content
stringlengths
7
2.61M
<reponame>deepanshu7007/Accounting-Software /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Master.Group.Presist; import Master.Account.Presist.*; public class DeletePanel extends javax.swing.JPanel { /** * Creates new form DeletePanel */ public DeletePanel() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jLabel3 = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); jTextField1 = new javax.swing.JTextField(); NameField = new javax.swing.JTextField(); SearchButton = new javax.swing.JButton(); DeleteButton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel1.setText("Name"); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel2.setText("Alias"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N jLabel3.setText("Delete Group Data"); jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL); SearchButton.setText("Search"); DeleteButton.setText("Delete"); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(NameField, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel2) .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(SearchButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(DeleteButton, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE) .addComponent(jTextField1)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 537, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(56, 56, 56) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(NameField, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(42, 42, 42) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(38, 38, 38) .addComponent(SearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(DeleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26)) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jSeparator2)) .addContainerGap()))) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton DeleteButton; private javax.swing.JTextField NameField; private javax.swing.JButton SearchButton; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
<reponame>messo/tictactoe package com.topdesk.cases.tictactoe.impl.rule; import com.topdesk.cases.tictactoe.Field; import com.topdesk.cases.tictactoe.impl.Board; /** * <p>The <b>Play Empty Corner</b> rule.</p> * <p><i>If</i> there is an empty corner,<br /> * <i>Then</i> move to the empty corner.</p> */ public class EmptyCorner extends AbstractRule { @Override public Field moveIfAvailable(Board board) { return moveIfEmpty(board, Field.TOP_LEFT, Field.TOP_RIGHT, Field.BOTTOM_LEFT, Field.BOTTOM_RIGHT); } }
A survey of pathogenic genes from diarrhea stool samples obtained in Nara prefecture. We conducted a survey of diarrhea stool samples in which no virulent agents had previously been detected at clinical laboratories. DNA extracted directly and purified from the diarrhea stool was tested for bacterial pathogenic genes by polymerase chain reaction. The test results for 85 specimens were as follows: one sample was positive for lt, ipaH, and eae; two were positive for aggR; and eight were positive for astA. Inoculation with the stool specimens led to the isolation of a strain of Escherichia coli possessing eae, three strains of E. coli possessing astA, and a strain of Klebsiella possessing astA.
package org.ros.tf2.insert_benchmark; import android.app.Activity; import android.os.Bundle; import android.os.AsyncTask; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.UUID; import java.util.Vector; import geometry_msgs.Quaternion; import geometry_msgs.Transform; import geometry_msgs.TransformStamped; import geometry_msgs.Vector3; import tf2_msgs.TFMessage; import org.ros.tf2_ros.Buffer; import org.ros.message.Duration; import org.ros.message.MessageFactory; import org.ros.message.Time; import org.ros.node.NodeConfiguration; public class BenchmarkActivity extends Activity { private volatile boolean mRunBenchmark = false; private TextView mTV; private volatile int mInsertionLoops = 1; private volatile int mNumberFrames = 100; private volatile int mBranchingFactor = 3; private class LongOperation extends AsyncTask<String, String, String> { public String generateString(Random rng, String characters, int length) { char[] text = new char[length]; for (int i = 0; i < length; i++) { text[i] = characters.charAt(rng.nextInt(characters.length())); } return new String(text); } String[] generateUniqueFrames(int nFrames){ String[] out = new String[nFrames]; Random r = new Random(); String chars = "abcdefghijklmnopqrstuvwxyz_"; for (int i = 0; i < nFrames; i++){ //out[i] = UUID.randomUUID().toString(); out[i] = generateString(r, chars, 25); } return out; } private int parentIndex(double childIndex, double branchFactor){ int ret = (int)(childIndex/(branchFactor+0.00001)); //Log.w("INDEX_PRINT", "Index of: " + Integer.toString(ret) + " for input: " + Double.toString(childIndex)); return ret; } private TFMessage createTF2Message(String[] uniqueFrames, Time stamp){ Random r = new Random(); NodeConfiguration mNodeConfiguration = NodeConfiguration.newPrivate(); MessageFactory mMessageFactory = mNodeConfiguration.getTopicMessageFactory(); TFMessage tfs = mMessageFactory.newFromType(TFMessage._TYPE); List<TransformStamped> tfl = tfs.getTransforms(); for(int i = 1; i < uniqueFrames.length; i++){ // Skip first frame TransformStamped ts = mMessageFactory.newFromType(TransformStamped._TYPE); ts.getHeader().setFrameId(uniqueFrames[parentIndex(i, mBranchingFactor)]); ts.getHeader().setStamp(stamp); ts.setChildFrameId(uniqueFrames[i]); Transform t = ts.getTransform(); Vector3 tr = t.getTranslation(); tr.setX(r.nextDouble()); tr.setY(r.nextDouble()); tr.setZ(r.nextDouble()); Quaternion q = t.getRotation(); double w = r.nextDouble(); double x = r.nextDouble(); double y = r.nextDouble(); double z = r.nextDouble(); double mag = Math.sqrt(w*w+x*x+y*y+z*z); if(mag < 1.e-5){ // Handle zero magnitude case w = 1.0; mag = 1.0; } q.setW(w/mag); q.setX(x/mag); q.setY(y/mag); q.setZ(z/mag); // Add to vector tfl.add(ts); } tfs.setTransforms(tfl); return tfs; } @Override protected String doInBackground(String... params) { Buffer mBuffer = new Buffer(); publishProgress("Generating TF2 Message Tree"); // Generate unique frames String[] uniqueFrames; int actual_frames = 0; if(mNumberFrames == 0){ // Use PR2 frame_ids uniqueFrames = mBuffer.getPR2FrameIds(); } else { // Random Strings uniqueFrames = generateUniqueFrames(mNumberFrames); } int actualNumberFrames = uniqueFrames.length; double dt = (20.0-10.0)/(double)mInsertionLoops; TFMessage[] tfArray = new TFMessage[mInsertionLoops]; for(int i = 0; i < mInsertionLoops; i++){ Time newTime = new Time(10.0+i*dt); // 10.0 to 20.0s tfArray[i] = createTF2Message(uniqueFrames, newTime); } String progressString = Integer.toString(mInsertionLoops) + " whole tree inserts - on " + Integer.toString(actualNumberFrames) + " total transforms" + " (" + Integer.toString(mInsertionLoops*actualNumberFrames) + " total inserts)."; publishProgress(progressString); String authority = "unknown"; boolean is_static = false; mBuffer.clear(); ; Time start = new Time().fromMillis(System.currentTimeMillis()); int aLength = tfArray.length; for(int i = 0; i < aLength; i++){ final List<TransformStamped> tfl = tfArray[i].getTransforms(); int lLength = tfl.size(); for(int j = 0; j < lLength; j++){ //Log.w("INSERT_BENCHMARK", tf.getHeader().getFrameId() + "::" + tf.getChildFrameId() + "::" + Double.toString(tf.getHeader().getStamp().toSeconds())); mBuffer.setTransform(tfl.get(j), authority, is_static); } } Time end = new Time().fromMillis(System.currentTimeMillis()); if(mRunBenchmark == false){ return "Benchmark did not completely finish."; } Duration diff = end.subtract(start); double diffs = (double)(diff.totalNsecs())/1.e9; progressString += "\n\nStart time: " + Double.toString(start.toSeconds()) + " \nEnd time: " + Double.toString(end.toSeconds()) + "\nDiff: " + Double.toString(diffs) + "\nAvg: " + Double.toString(diffs/(mInsertionLoops*actualNumberFrames)); mRunBenchmark = false; return progressString; } @Override protected void onPostExecute(String result) { mTV.setText(result); } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(String... values) { mTV.setText(values[0]); } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTV = (TextView)findViewById(R.id.outputText); final Button button = (Button) findViewById(R.id.startButton); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(mRunBenchmark == false){ new Thread(new Runnable() { public void run() { mRunBenchmark = true; EditText et = (EditText)findViewById(R.id.editNumLookups); mInsertionLoops = Integer.parseInt(et.getText().toString()); EditText et2 = (EditText)findViewById(R.id.editFrames); mNumberFrames = Integer.parseInt(et2.getText().toString()); EditText et3 = (EditText)findViewById(R.id.editBranching); mBranchingFactor = Integer.parseInt(et3.getText().toString()); new LongOperation().execute(""); } }).start(); } } }); } @Override public void onPause(){ mRunBenchmark = false; super.onPause(); } }
<gh_stars>1-10 import { Injectable, HttpService, HttpException } from '@nestjs/common'; import { AxiosResponse } from 'axios'; import { AuthorizeDto } from './dto/authorize.dto'; import { AccessTokenDto } from './dto/accessToken.dto'; @Injectable() export class OAuthService { constructor(private httpService: HttpService) {} async authorize(authorizeDto: AuthorizeDto): Promise<AxiosResponse> { try { const response = await this.httpService .get('/authorize', { params: authorizeDto, }) .toPromise(); return response.data; } catch (error) { const { status, statusText } = error.response; throw new HttpException(statusText, status); } } async accessToken(accessTokenDto: AccessTokenDto): Promise<AxiosResponse> { try { const response = await this.httpService .post('/access_token', { data: accessTokenDto, }) .toPromise(); return response.data; } catch (error) { const { status, statusText } = error.response; throw new HttpException(statusText, status); } } }
Ford Slashes Debt, Stays Ahead of GM and Chrysler Ford, the only of the Big Three automakers to so far refuse government bailout money, said this morning that it has slashed the debt in its automotive division, enabling it to save $500 million per year in interest expense. Ford used $2.4 billion in cash and 468 million shares of its common stock to buy down $9.9 billion in debt, reducing its leverage by 38 percent. "By substantially reducing our debt, Ford is taking another step toward creating an exciting, viable enterprise," Ford chief executive Alan Mulally said in a statement. Ford has so far been spared the wrath of the federal government and the administration's automotive restructuring team, headed by former investment banker Steve Rattner. The White House ousted GM chief executive Rick Wagoner last week. Last Wednesday, Ford reported that March vehicle sales were down 40.9 percent compared with March 2008, which beat forecasters' expectation of a 45 percent plunge for Ford. Ford sales were up 30 percent compared with February of this year. As recently as first quarter 2008, Ford was profitable. -- Frank Ahrens Sign up to get The Ticker on Twitter
Home-use preventive and therapeutic oral products. In our present-day climate, it is apparent that good healthcare is very much influenced by available resources and the provision of finances to underpin these resources. Governmental spending on health for many western nations has rocketed but always seems inadequate for the demands of the public, which has greater expectations, and, to some extent, this is influenced by ever-increasing age expectancy. It is not surprising therefore that we are expected to take some responsibility for our own health wellbeing, whether it is in preventing disease through changes in lifestyle or in purchasing products from retail outlets or pharmacies that may benefit us in some way or another. In these series of articles we look at various aspects of products of relevance to oral problems that can be used in a home setting and which may produce positive effects from a preventive, therapeutic or cosmetic point of view. As expected, the major products that are used, at least in the western world, for cleaning teeth are toothbrushes (manual and or electric), and various devices such as floss and interdental brushes, which are employed for cleaning between the teeth. Certainly, in terms of expenditure, toothbrushes and the accompanying toothpastes occupy the major slice of the pie when it comes to public money spent on oral hygiene products. In the first article of this volume of Periodontology 2000, by Claydon, various aspects of mechanical plaque control are reviewed. Topics covered include the prevention of periodontal diseases by the effective removal of plaque, the relevance of the frequency of brushing, toothbrushing methods, toothbrush design, electric (powered) toothbrushes and interdental cleaning aids. Finally, some conclusions on mechanical plaque control are provided that would be useful in providing appropriate and correct information to patients. Regarding toothpastes in particular, their cleaning potential by way of detergents and toothpaste abrasives has been recognized for years (possibly even producing detrimental effects such as abrasion) but they are now also considered to be an appropriate vehicle for the incorporation of chemicals that may have a preventive and or therapeutic role in oral disease. Immediately springing to mind has been the use of triclosan with the copolymer Gantrez in toothpaste, with reductions in plaque and gingivitis reported from a number of studies. It has also been suggested that these specific chemicals may be beneficial in reducing periodontitis. These possible beneficial effects are discussed at length, together with the use of other chemicals that may be incorporated into toothpastes. From a patient s perspective, oral discomfort and pain through dentine hypersensitivity remain major problems for many, if not most, individuals at some point in their lives, affecting about 15% of the population worldwide. The etiology of dentine hypersensitivity is multifactorial and can result from both tooth wear (erosion abrasion), and periodontal disease and treatment, exposing either coronal or radicular dentine, or indeed both. For dentine hypersensitivity to occur, the tubules must be about 1 lm in diameter and patent to the pulp. Without recourse to dentist hygienist-applied treatments, the use of chemicals, primarily in toothpaste, is the major method of controlling or eliminating symptoms. There are currently numerous products available from retail outlets that may help in this respect, the majority of which are thought to be effective through occlusion of the dentine tubules or nerve stabilization with potassium ions. In the article by West, dentine hypersensitivity is fully reviewed, and the information presented will hopefully help clinicians to understand and manage this common problem. Of the various oral hygiene products available, mouthrinses are also very popular in many
Cyclo-oligomerization of isocyanates with Na(PH2) or Na(OCP) as P anion sources Na(OCP) initiates the catalytic cyclo-trimerization of isocyanates involving the mutual formation of P-heterocycles and spiro phosphoranides (shown on the right) as reactive intermediates. (6 mL). The reaction mixture was stirred for 15 h at 50°C. The solvent was removed under reduced pressure and the obtained orange residue was washed with n-hexane to yield an orange-red powder, which was dried in vacuo. Yellow-orange crystals suitable for X-ray diffraction were obtained by slow concentration of a THF solution. Yield: 0.89 g (44%) (calculated for {Na(THF) 2 Reaction of sodium phosphide with two equivalents of 2,6-diisopropylphenyl isocyanate A solution of 2,6-diisopropylphenyl isocyanate (248 mg, 1.22 mmol) in DME (1 mL) was added drop wise at room temperature to a suspension of sodium phosphide NaPH 2 (50 mg, 0.61 mmol) in DME (1 mL). After refluxing for 5 min the reaction mixture was analyzed by 31 P NMR spectroscopy. 31 General procedure for the reaction of with phenyl (2b), cyclohexyl (2c) and n-butyl (2d) isocyanate in the ratio 1:8 A solution of isocyanate (8 eq., ca. 2.64 mmol) in THF (2 mL) was added drop-wise at room temperature to a solution of (0.10 g, 0.33 mmol) in THF (2 mL). The solution was stirred for 1 hour at room temperature and a color change to yellow was observed. Investigation of the reaction solutions by 31 P and 13 C NMR spectroscopy revealed the formation of compounds Na, Na and 7 and the characteristic data for these compounds are summarized in Table 8.1. In the reaction with 2b colorless crystals were formed, which were identified by single crystal X-ray diffraction analysis as 7b. Colorless single crystals of [(Na(DME)) ∞ ] and [(Na(THF)) ∞ ] suitable for X-ray diffraction were obtained by slow evaporation of the solvent at room temperature. The IR spectrum shows a very strong band in the carbonyl region at 1708 cm −1, which corresponds to that of triphenylisocyanurate (1710 cm −1 ). 5 No significant peaks were observed in the ranges 1800-1720 cm −1 and 1650-1600 cm −1. Note that the carbonyl shifts of the diphenyluretdione are at 1780 and 1760 cm −1, while those of diphenylmethyl iminooxadiazinedione are at 1620, 1680 and 1735 cm −1. 6,7 An X-ray diffraction analysis revealed the identity of 7b. The found cell parameters for 7b are in agreement with those reported in the literature 5 Additional Experiment: X-ray structure analyses Additional structures Refinement details X-ray structure determination of Single crystals (yellow blocks) were obtained by slow diffusion of diethyl ether into a pyridine solution of the crude reaction mixture. The X-ray data of a single crystal with the approximate dimensions of 0.100.120.2 mm was obtained at 150 K using an Oxford Diffraction Supernova dual-source diffractometer equipped with a 135 mm Atlas CCD area detector (Cu K radiation). X-ray structure determination of Single crystals (yellow blocks) were obtained by slow diffusion of diethyl ether into a pyridine solution of the crude reaction mixture. The X-ray data of a single crystal with the approximate dimensions of 0.300.600.70 mm was obtained at 150 K using an Enraf-Nonius kappa-CCD diffractometer equipped with a 95 mm CCD area detector (Mo K radiation). Crystal data and This means there is less positive charge localised on the P atom, which explains the difference in 31 P chemical shift and the lower magnitudes of the coupling constants. Computational details The computations reported in the paper were carried out with the Gaussian 09 program package. 8 In order to decrease the computation time, the larger Dipp, Ph, n-Bu and Cy groups were replaced by methyl substituents. All structures were optimized using the B3LYP functional with the 6-
Thailand's Khmer as invisible minority: Language, ethnicity and cultural politics in north-eastern Thailand Ethnic Khmer speakers in Thailand number over a million. Yet, despite their large numbers, they are regarded as an invisible minority, largely inconspicuous in the nation's arena of cultural politics. Their invisibility has, to some extent, to do with their overall cultural similarity with surrounding ethnic Lao speakers of Thailand's north-eastern Isan region; like Isan Lao, they are syncretic Theravada Buddhists, and their village life revolves around wet rice agriculture. Such similarity contrasts with the conspicuous differences marking other minorities of Thailand, such as the Muslims in the south, or highlanders in the north. But Khmer invisibility is also the result of cultural politics at the national level, and with the specific histories of these nation-states in the modern period. This paper examines the apathy towards Khmer identity in Thailand, both in the historical context of Thai nation-building and in specific language policies and practices.
// Set event // // Setting the event will cause all waiting threads to wakeup. And will let all future acquiring threads through until Baselib_EventSemaphore_Reset is called. // // Guaranteed to emit a release barrier. // // \returns number of woken threads. static inline uint16_t Baselib_EventSemaphore_Set(Baselib_EventSemaphore* semaphore) { Baselib_atomic_store_8_release(&semaphore->state, Detail_Baselib_EventSemaphore_SET); return Baselib_CappedSemaphore_Release(&semaphore->semaphore, UINT16_MAX); }
General practice is at breaking point with more than half (53.3 per cent) of GP practices in the South East saying the quality of service to patients has deteriorated in the past 12 months and almost seven out of 10 (65.3 per cent) practices say the current workload is unmanageable a lot or all of the time. This is the result of a rising workload, including increasing patient demand for appointments which is placing unsustainable pressure on GP services that have been starved of resources and staff, leaving patients waiting longer to see a GP. Across England, there were more than 600 GP trainee positions left unfilled in 2015, while a third of the workforce are considering retirement in the next five years. This comes at a time when GP practices across the country are seeing 150,000 more patients each day than in 2010, but have seen no extra resources to maintain effective, safe care to the public. Politicians have to realise that general practice is currently running on empty. GPs desperately want to provide the best possible service for patients, but we need improved resources and support to provide patients with the care they deserve.
<reponame>vyshuks/Leetcode-30-day-challenge """ You have a queue of integers, you need to retrieve the first unique integer in the queue. Implement the FirstUnique class: FirstUnique(int[] nums) Initializes the object with the numbers in the queue. int showFirstUnique() returns the value of the first unique integer of the queue, and returns -1 if there is no such integer. void add(int value) insert value to the queue. Example 1: Input: ["FirstUnique","showFirstUnique","add","showFirstUnique", "add","showFirstUnique","add","showFirstUnique"] [[[2,3,5]],[],[5],[],[2],[],[3],[]] Output: [null,2,null,2,null,3,null,-1] """ from typing import List from collections import OrderedDict, Counter class FirstUnique: def __init__(self, nums: List[int]): self._map = OrderedDict() self.counter = Counter(nums) for num in nums: if self.counter[num] == 1: self._map[num]=1 def showFirstUnique(self) -> int: if not self._map: return -1 return next(iter(self._map)) def add(self, value: int) -> None: if self.counter[value] > 1: return elif self.counter[value]==1: self._map.pop(value) else: self._map[value] = 1 self.counter[value] += 1 obj = FirstUnique([2,3,5]) obj.add(5) obj.add(2) print(obj.showFirstUnique()) obj.add(3) print(obj.showFirstUnique())
Speaking at a press conference at the end of the G7 summit, President Obama has urged Scottish voters to reject independence, saying that it is not in America’s interest to see Scotland independent from Britain. The comments mark the first direct US intervention in the upcoming referendum, and were quickly criticized by Scottish First Minister Alex Salmond, saying Scotland only wanted the same independence the US got hundreds of years ago, and that they are fortunate enough to be able to get it through a vote instead of a war of independence. Obama’s comments insisted the US has an “extraordinary partner” in the United Kingdom, and doesn’t want to see it risked. Salmond said the US could have two partners if Scotland is independent. The comments are unusually direct, as most nations have tried to avoid direct involvement in the Scottish independence movement, and Obama’s opposition is unlikely to change much, except giving it more publicity. Ah jeepers I don't know but, I think that Scotland independence is none of Obama's business. It is not in America’s interest that Obama remain president. It is in the habits of this gentlement to put his nose everywhere. We like to critze Putin. The international press in a hysteric anti russian campain made him the bad guy. Why Putin don't give lessons to Scotland ? Terrific but who is Lady Catherine de Burgh? Wtf…. Obama is just a terrorist crackpot, now. Transfer your funds to our joint account….to ensure prosperity…if you must ask. Here's hoping Scotland does secede and look to Russian and Chinese investment since Cameron and Great Britain have done nothing for Scotland. And if Britain exits the EU all the better. The EU needs to be less influenced by the US-Anglo cabal and the EU needs to loosen its integration to accommodate better its member nation needs. I favor Scottish secession. I hope they bail out, and chart their own course. That's what nations are supposed to do, aren't they? And Scotland had better be leery of any involvement with the U.S. Government, a government that's criminal and dishonorable. just what has it got to do with Obama? I hope that multitudes of the Scottish people give Obama a multitude of middle fingers. Better yet, how about they give him the three-finger salute? What business is it of Obozo if the (people) of Scotland vote for their independence? This guy appears to have given up smoking cigs in exchange for smoking crack. As Emperor of the World, Obama hasn't given his let or leave for the Province of Great Britain to be so subdivided. The subjects must bow before his will. If the English part of the UK were to displease His Imperial Excellency Obama, the UK would be punished. Scotland would be undermined to secede with a FedGov-approved regime, and Alex Salmond would quickly find himself declared a criminal and treated accordingly. Perhaps Obama is just using reverse psychology on the Scots. Maybe he secretly wants them to vote for independence. What other effect does he hope to achieve by opening his big mouth? If Scotland secedes from the UK, it might become the part of the UK that stays in the EU. All the more reason for Scotland to vote for independence from the NWO. Well, he really is a Tory then isn't he? Thinking like a king, he is, again. I'm pretty sure that Obama does not want Scotland to seceed from the UK because he's afraid they will put him on a "do not allow into the country" list and he won't be able to use all those great golf courses. "Obama said that it is not in America’s interest for Scotland to be independent" (the term "America" to Obama means the government. Its simply not in America's interest for Scotland nor anyone to be independent. After all, if someone or some entity is truly independent, then the sanctity of the state is threatened. Alex Salmond, you do not need to explain anything to this tyrant Obama. You and the Scottish people do what is in the interest of Scotland and screw Obama and the corrupt oligarchs he represents. He's just channeling the 'Great Emancipator'. No secession for YOU!!! Obama is probably mostly concerned about the nuclear-free stance of the proposed path to independence. Nuclear weapons would no longer be based at Faslane, for example. How Orwellian….Oceania is being set up…..Airstrip One will align itself with the US(yay) and The EU Superstate(Eurasia) will solidify….and in the East China(Eastasia) will centralize as the authority there… and we(the P.Elite) will finally have Perpetual War for Perpetual Peace…all linked together and always at "war"…with a "wartime" economy and a "wartime" State Security monitoring all for all…….. and in the US it will be BiPartisan and Patriotic….. We all know what happens if you turn down EU. Ukraine happens. O'bomber just needs to SHUT his dirty pie hole..
/** * This object contains factory methods for each Java content interface and Java * element interface generated in the gex.newsml.v12 package. * <p> * An ObjectFactory allows you to programatically construct new instances of the * Java representation for XML content. The Java representation of XML content * can consist of schema derived interfaces and classes representing the binding * of schema type definitions, element declarations and model groups. Factory * methods for each of these are provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME = new QName( "http://iptc.org/std/NewsML/2003-10-10/", "Origin"); /** * Create a new ObjectFactory that can be used to create new instances of * schema derived classes for package: gex.newsml.v12 * */ public ObjectFactory() { } /** * Create an instance of {@link NewsML } * */ public NewsML createNewsML() { return new NewsML(); } /** * Create an instance of {@link NewsComponentType } * */ public NewsComponentType createNewsComponentType() { return new NewsComponentType(); } /** * Create an instance of {@link NewsComponentType.ContentItem } * */ public NewsComponentType.ContentItem createNewsComponentTypeContentItem() { return new NewsComponentType.ContentItem(); } /** * Create an instance of * {@link NewsComponentType.ContentItem.Characteristics } * */ public NewsComponentType.ContentItem.Characteristics createNewsComponentTypeContentItemCharacteristics() { return new NewsComponentType.ContentItem.Characteristics(); } /** * Create an instance of {@link NewsComponentType.Metadata } * */ public NewsComponentType.Metadata createNewsComponentTypeMetadata() { return new NewsComponentType.Metadata(); } /** * Create an instance of {@link NewsComponentType.DescriptiveMetadata } * */ public NewsComponentType.DescriptiveMetadata createNewsComponentTypeDescriptiveMetadata() { return new NewsComponentType.DescriptiveMetadata(); } /** * Create an instance of * {@link NewsComponentType.DescriptiveMetadata.OfInterestTo } * */ public NewsComponentType.DescriptiveMetadata.OfInterestTo createNewsComponentTypeDescriptiveMetadataOfInterestTo() { return new NewsComponentType.DescriptiveMetadata.OfInterestTo(); } /** * Create an instance of * {@link NewsComponentType.DescriptiveMetadata.SubjectCode } * */ public NewsComponentType.DescriptiveMetadata.SubjectCode createNewsComponentTypeDescriptiveMetadataSubjectCode() { return new NewsComponentType.DescriptiveMetadata.SubjectCode(); } /** * Create an instance of {@link NewsComponentType.RightsMetadata } * */ public NewsComponentType.RightsMetadata createNewsComponentTypeRightsMetadata() { return new NewsComponentType.RightsMetadata(); } /** * Create an instance of {@link NewsComponentType.RightsMetadata.UsageRights * } * */ public NewsComponentType.RightsMetadata.UsageRights createNewsComponentTypeRightsMetadataUsageRights() { return new NewsComponentType.RightsMetadata.UsageRights(); } /** * Create an instance of {@link NewsComponentType.RightsMetadata.Copyright } * */ public NewsComponentType.RightsMetadata.Copyright createNewsComponentTypeRightsMetadataCopyright() { return new NewsComponentType.RightsMetadata.Copyright(); } /** * Create an instance of {@link NewsComponentType.AdministrativeMetadata } * */ public NewsComponentType.AdministrativeMetadata createNewsComponentTypeAdministrativeMetadata() { return new NewsComponentType.AdministrativeMetadata(); } /** * Create an instance of * {@link NewsComponentType.AdministrativeMetadata.Contributor } * */ public NewsComponentType.AdministrativeMetadata.Contributor createNewsComponentTypeAdministrativeMetadataContributor() { return new NewsComponentType.AdministrativeMetadata.Contributor(); } /** * Create an instance of {@link NewsComponentType.NewsLines } * */ public NewsComponentType.NewsLines createNewsComponentTypeNewsLines() { return new NewsComponentType.NewsLines(); } /** * Create an instance of {@link NewsComponentType.NewsLines.NewsLine } * */ public NewsComponentType.NewsLines.NewsLine createNewsComponentTypeNewsLinesNewsLine() { return new NewsComponentType.NewsLines.NewsLine(); } /** * Create an instance of {@link gex.newsml.v12.NewsItemType } * */ public gex.newsml.v12.NewsItemType createNewsItemType() { return new gex.newsml.v12.NewsItemType(); } /** * Create an instance of {@link gex.newsml.v12.NewsItemType.Update } * */ public gex.newsml.v12.NewsItemType.Update createNewsItemTypeUpdate() { return new gex.newsml.v12.NewsItemType.Update(); } /** * Create an instance of {@link gex.newsml.v12.NewsItemType.NewsManagement } * */ public gex.newsml.v12.NewsItemType.NewsManagement createNewsItemTypeNewsManagement() { return new gex.newsml.v12.NewsItemType.NewsManagement(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.NewsManagement.Instruction } * */ public gex.newsml.v12.NewsItemType.NewsManagement.Instruction createNewsItemTypeNewsManagementInstruction() { return new gex.newsml.v12.NewsItemType.NewsManagement.Instruction(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.NewsManagement.StatusWillChange } * */ public gex.newsml.v12.NewsItemType.NewsManagement.StatusWillChange createNewsItemTypeNewsManagementStatusWillChange() { return new gex.newsml.v12.NewsItemType.NewsManagement.StatusWillChange(); } /** * Create an instance of {@link gex.newsml.v12.NewsItemType.Identification } * */ public gex.newsml.v12.NewsItemType.Identification createNewsItemTypeIdentification() { return new gex.newsml.v12.NewsItemType.Identification(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.Identification.Label } * */ public gex.newsml.v12.NewsItemType.Identification.Label createNewsItemTypeIdentificationLabel() { return new gex.newsml.v12.NewsItemType.Identification.Label(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.Identification.NewsIdentifier } * */ public gex.newsml.v12.NewsItemType.Identification.NewsIdentifier createNewsItemTypeIdentificationNewsIdentifier() { return new gex.newsml.v12.NewsItemType.Identification.NewsIdentifier(); } /** * Create an instance of {@link NewsML.NewsEnvelope } * */ public NewsML.NewsEnvelope createNewsMLNewsEnvelope() { return new NewsML.NewsEnvelope(); } /** * Create an instance of {@link TopicSetType } * */ public TopicSetType createTopicSetType() { return new TopicSetType(); } /** * Create an instance of {@link TopicSetType.Topic } * */ public TopicSetType.Topic createTopicSetTypeTopic() { return new TopicSetType.Topic(); } /** * Create an instance of {@link CatalogType } * */ public CatalogType createCatalogType() { return new CatalogType(); } /** * Create an instance of {@link CatalogType.Resource } * */ public CatalogType.Resource createCatalogTypeResource() { return new CatalogType.Resource(); } /** * Create an instance of {@link OriginType } * */ public OriginType createOriginType() { return new OriginType(); } /** * Create an instance of {@link PropertyType } * */ public PropertyType createPropertyType() { return new PropertyType(); } /** * Create an instance of {@link CommentType } * */ public CommentType createCommentType() { return new CommentType(); } /** * Create an instance of {@link ContributionType } * */ public ContributionType createContributionType() { return new ContributionType(); } /** * Create an instance of {@link StatusType } * */ public StatusType createStatusType() { return new StatusType(); } /** * Create an instance of {@link DateAndTimeType } * */ public DateAndTimeType createDateAndTimeType() { return new DateAndTimeType(); } /** * Create an instance of {@link NewsComponentType.Role } * */ public NewsComponentType.Role createNewsComponentTypeRole() { return new NewsComponentType.Role(); } /** * Create an instance of {@link NewsComponentType.BasisForChoice } * */ public NewsComponentType.BasisForChoice createNewsComponentTypeBasisForChoice() { return new NewsComponentType.BasisForChoice(); } /** * Create an instance of {@link NewsComponentType.NewsItemRef } * */ public NewsComponentType.NewsItemRef createNewsComponentTypeNewsItemRef() { return new NewsComponentType.NewsItemRef(); } /** * Create an instance of {@link NewsComponentType.ContentItem.MediaType } * */ public NewsComponentType.ContentItem.MediaType createNewsComponentTypeContentItemMediaType() { return new NewsComponentType.ContentItem.MediaType(); } /** * Create an instance of {@link NewsComponentType.ContentItem.Format } * */ public NewsComponentType.ContentItem.Format createNewsComponentTypeContentItemFormat() { return new NewsComponentType.ContentItem.Format(); } /** * Create an instance of {@link NewsComponentType.ContentItem.MimeType } * */ public NewsComponentType.ContentItem.MimeType createNewsComponentTypeContentItemMimeType() { return new NewsComponentType.ContentItem.MimeType(); } /** * Create an instance of {@link NewsComponentType.ContentItem.Notation } * */ public NewsComponentType.ContentItem.Notation createNewsComponentTypeContentItemNotation() { return new NewsComponentType.ContentItem.Notation(); } /** * Create an instance of {@link NewsComponentType.ContentItem.Encoding } * */ public NewsComponentType.ContentItem.Encoding createNewsComponentTypeContentItemEncoding() { return new NewsComponentType.ContentItem.Encoding(); } /** * Create an instance of {@link NewsComponentType.ContentItem.DataContent } * */ public NewsComponentType.ContentItem.DataContent createNewsComponentTypeContentItemDataContent() { return new NewsComponentType.ContentItem.DataContent(); } /** * Create an instance of * {@link NewsComponentType.ContentItem.Characteristics.SizeInBytes } * */ public NewsComponentType.ContentItem.Characteristics.SizeInBytes createNewsComponentTypeContentItemCharacteristicsSizeInBytes() { return new NewsComponentType.ContentItem.Characteristics.SizeInBytes(); } /** * Create an instance of {@link NewsComponentType.Metadata.MetadataType } * */ public NewsComponentType.Metadata.MetadataType createNewsComponentTypeMetadataMetadataType() { return new NewsComponentType.Metadata.MetadataType(); } /** * Create an instance of * {@link NewsComponentType.DescriptiveMetadata.Language } * */ public NewsComponentType.DescriptiveMetadata.Language createNewsComponentTypeDescriptiveMetadataLanguage() { return new NewsComponentType.DescriptiveMetadata.Language(); } /** * Create an instance of {@link NewsComponentType.DescriptiveMetadata.Genre * } * */ public NewsComponentType.DescriptiveMetadata.Genre createNewsComponentTypeDescriptiveMetadataGenre() { return new NewsComponentType.DescriptiveMetadata.Genre(); } /** * Create an instance of * {@link NewsComponentType.DescriptiveMetadata.DateLineDate } * */ public NewsComponentType.DescriptiveMetadata.DateLineDate createNewsComponentTypeDescriptiveMetadataDateLineDate() { return new NewsComponentType.DescriptiveMetadata.DateLineDate(); } /** * Create an instance of * {@link NewsComponentType.DescriptiveMetadata.Location } * */ public NewsComponentType.DescriptiveMetadata.Location createNewsComponentTypeDescriptiveMetadataLocation() { return new NewsComponentType.DescriptiveMetadata.Location(); } /** * Create an instance of * {@link NewsComponentType.DescriptiveMetadata.TopicOccurrence } * */ public NewsComponentType.DescriptiveMetadata.TopicOccurrence createNewsComponentTypeDescriptiveMetadataTopicOccurrence() { return new NewsComponentType.DescriptiveMetadata.TopicOccurrence(); } /** * Create an instance of * {@link NewsComponentType.DescriptiveMetadata.OfInterestTo.Relevance } * */ public NewsComponentType.DescriptiveMetadata.OfInterestTo.Relevance createNewsComponentTypeDescriptiveMetadataOfInterestToRelevance() { return new NewsComponentType.DescriptiveMetadata.OfInterestTo.Relevance(); } /** * Create an instance of * {@link NewsComponentType.DescriptiveMetadata.SubjectCode.Subject } * */ public NewsComponentType.DescriptiveMetadata.SubjectCode.Subject createNewsComponentTypeDescriptiveMetadataSubjectCodeSubject() { return new NewsComponentType.DescriptiveMetadata.SubjectCode.Subject(); } /** * Create an instance of * {@link NewsComponentType.DescriptiveMetadata.SubjectCode.SubjectMatter } * */ public NewsComponentType.DescriptiveMetadata.SubjectCode.SubjectMatter createNewsComponentTypeDescriptiveMetadataSubjectCodeSubjectMatter() { return new NewsComponentType.DescriptiveMetadata.SubjectCode.SubjectMatter(); } /** * Create an instance of * {@link NewsComponentType.DescriptiveMetadata.SubjectCode.SubjectDetail } * */ public NewsComponentType.DescriptiveMetadata.SubjectCode.SubjectDetail createNewsComponentTypeDescriptiveMetadataSubjectCodeSubjectDetail() { return new NewsComponentType.DescriptiveMetadata.SubjectCode.SubjectDetail(); } /** * Create an instance of * {@link NewsComponentType.DescriptiveMetadata.SubjectCode.SubjectQualifier * } * */ public NewsComponentType.DescriptiveMetadata.SubjectCode.SubjectQualifier createNewsComponentTypeDescriptiveMetadataSubjectCodeSubjectQualifier() { return new NewsComponentType.DescriptiveMetadata.SubjectCode.SubjectQualifier(); } /** * Create an instance of * {@link NewsComponentType.RightsMetadata.UsageRights.UsageType } * */ public NewsComponentType.RightsMetadata.UsageRights.UsageType createNewsComponentTypeRightsMetadataUsageRightsUsageType() { return new NewsComponentType.RightsMetadata.UsageRights.UsageType(); } /** * Create an instance of * {@link NewsComponentType.RightsMetadata.UsageRights.Geography } * */ public NewsComponentType.RightsMetadata.UsageRights.Geography createNewsComponentTypeRightsMetadataUsageRightsGeography() { return new NewsComponentType.RightsMetadata.UsageRights.Geography(); } /** * Create an instance of * {@link NewsComponentType.RightsMetadata.UsageRights.RightsHolder } * */ public NewsComponentType.RightsMetadata.UsageRights.RightsHolder createNewsComponentTypeRightsMetadataUsageRightsRightsHolder() { return new NewsComponentType.RightsMetadata.UsageRights.RightsHolder(); } /** * Create an instance of * {@link NewsComponentType.RightsMetadata.UsageRights.Limitations } * */ public NewsComponentType.RightsMetadata.UsageRights.Limitations createNewsComponentTypeRightsMetadataUsageRightsLimitations() { return new NewsComponentType.RightsMetadata.UsageRights.Limitations(); } /** * Create an instance of * {@link NewsComponentType.RightsMetadata.UsageRights.StartDate } * */ public NewsComponentType.RightsMetadata.UsageRights.StartDate createNewsComponentTypeRightsMetadataUsageRightsStartDate() { return new NewsComponentType.RightsMetadata.UsageRights.StartDate(); } /** * Create an instance of * {@link NewsComponentType.RightsMetadata.UsageRights.EndDate } * */ public NewsComponentType.RightsMetadata.UsageRights.EndDate createNewsComponentTypeRightsMetadataUsageRightsEndDate() { return new NewsComponentType.RightsMetadata.UsageRights.EndDate(); } /** * Create an instance of * {@link NewsComponentType.RightsMetadata.Copyright.CopyrightHolder } * */ public NewsComponentType.RightsMetadata.Copyright.CopyrightHolder createNewsComponentTypeRightsMetadataCopyrightCopyrightHolder() { return new NewsComponentType.RightsMetadata.Copyright.CopyrightHolder(); } /** * Create an instance of * {@link NewsComponentType.RightsMetadata.Copyright.CopyrightDate } * */ public NewsComponentType.RightsMetadata.Copyright.CopyrightDate createNewsComponentTypeRightsMetadataCopyrightCopyrightDate() { return new NewsComponentType.RightsMetadata.Copyright.CopyrightDate(); } /** * Create an instance of * {@link NewsComponentType.AdministrativeMetadata.FileName } * */ public NewsComponentType.AdministrativeMetadata.FileName createNewsComponentTypeAdministrativeMetadataFileName() { return new NewsComponentType.AdministrativeMetadata.FileName(); } /** * Create an instance of * {@link NewsComponentType.AdministrativeMetadata.SystemIdentifier } * */ public NewsComponentType.AdministrativeMetadata.SystemIdentifier createNewsComponentTypeAdministrativeMetadataSystemIdentifier() { return new NewsComponentType.AdministrativeMetadata.SystemIdentifier(); } /** * Create an instance of * {@link NewsComponentType.AdministrativeMetadata.Provider } * */ public NewsComponentType.AdministrativeMetadata.Provider createNewsComponentTypeAdministrativeMetadataProvider() { return new NewsComponentType.AdministrativeMetadata.Provider(); } /** * Create an instance of * {@link NewsComponentType.AdministrativeMetadata.Creator } * */ public NewsComponentType.AdministrativeMetadata.Creator createNewsComponentTypeAdministrativeMetadataCreator() { return new NewsComponentType.AdministrativeMetadata.Creator(); } /** * Create an instance of * {@link NewsComponentType.AdministrativeMetadata.Source } * */ public NewsComponentType.AdministrativeMetadata.Source createNewsComponentTypeAdministrativeMetadataSource() { return new NewsComponentType.AdministrativeMetadata.Source(); } /** * Create an instance of * {@link NewsComponentType.AdministrativeMetadata.Contributor.Party } * */ public NewsComponentType.AdministrativeMetadata.Contributor.Party createNewsComponentTypeAdministrativeMetadataContributorParty() { return new NewsComponentType.AdministrativeMetadata.Contributor.Party(); } /** * Create an instance of {@link NewsComponentType.NewsLines.HeadLine } * */ public NewsComponentType.NewsLines.HeadLine createNewsComponentTypeNewsLinesHeadLine() { return new NewsComponentType.NewsLines.HeadLine(); } /** * Create an instance of {@link NewsComponentType.NewsLines.SubHeadLine } * */ public NewsComponentType.NewsLines.SubHeadLine createNewsComponentTypeNewsLinesSubHeadLine() { return new NewsComponentType.NewsLines.SubHeadLine(); } /** * Create an instance of {@link NewsComponentType.NewsLines.ByLine } * */ public NewsComponentType.NewsLines.ByLine createNewsComponentTypeNewsLinesByLine() { return new NewsComponentType.NewsLines.ByLine(); } /** * Create an instance of {@link NewsComponentType.NewsLines.ByLineTitle } * */ public NewsComponentType.NewsLines.ByLineTitle createNewsComponentTypeNewsLinesByLineTitle() { return new NewsComponentType.NewsLines.ByLineTitle(); } /** * Create an instance of {@link NewsComponentType.NewsLines.DateLine } * */ public NewsComponentType.NewsLines.DateLine createNewsComponentTypeNewsLinesDateLine() { return new NewsComponentType.NewsLines.DateLine(); } /** * Create an instance of {@link NewsComponentType.NewsLines.CreditLine } * */ public NewsComponentType.NewsLines.CreditLine createNewsComponentTypeNewsLinesCreditLine() { return new NewsComponentType.NewsLines.CreditLine(); } /** * Create an instance of {@link NewsComponentType.NewsLines.CopyrightLine } * */ public NewsComponentType.NewsLines.CopyrightLine createNewsComponentTypeNewsLinesCopyrightLine() { return new NewsComponentType.NewsLines.CopyrightLine(); } /** * Create an instance of {@link NewsComponentType.NewsLines.RightsLine } * */ public NewsComponentType.NewsLines.RightsLine createNewsComponentTypeNewsLinesRightsLine() { return new NewsComponentType.NewsLines.RightsLine(); } /** * Create an instance of {@link NewsComponentType.NewsLines.SeriesLine } * */ public NewsComponentType.NewsLines.SeriesLine createNewsComponentTypeNewsLinesSeriesLine() { return new NewsComponentType.NewsLines.SeriesLine(); } /** * Create an instance of {@link NewsComponentType.NewsLines.SlugLine } * */ public NewsComponentType.NewsLines.SlugLine createNewsComponentTypeNewsLinesSlugLine() { return new NewsComponentType.NewsLines.SlugLine(); } /** * Create an instance of {@link NewsComponentType.NewsLines.KeywordLine } * */ public NewsComponentType.NewsLines.KeywordLine createNewsComponentTypeNewsLinesKeywordLine() { return new NewsComponentType.NewsLines.KeywordLine(); } /** * Create an instance of * {@link NewsComponentType.NewsLines.NewsLine.NewsLineType } * */ public NewsComponentType.NewsLines.NewsLine.NewsLineType createNewsComponentTypeNewsLinesNewsLineNewsLineType() { return new NewsComponentType.NewsLines.NewsLine.NewsLineType(); } /** * Create an instance of * {@link NewsComponentType.NewsLines.NewsLine.NewsLineText } * */ public NewsComponentType.NewsLines.NewsLine.NewsLineText createNewsComponentTypeNewsLinesNewsLineNewsLineText() { return new NewsComponentType.NewsLines.NewsLine.NewsLineText(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.Update.InsertBefore } * */ public gex.newsml.v12.NewsItemType.Update.InsertBefore createNewsItemTypeUpdateInsertBefore() { return new gex.newsml.v12.NewsItemType.Update.InsertBefore(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.Update.InsertAfter } * */ public gex.newsml.v12.NewsItemType.Update.InsertAfter createNewsItemTypeUpdateInsertAfter() { return new gex.newsml.v12.NewsItemType.Update.InsertAfter(); } /** * Create an instance of {@link gex.newsml.v12.NewsItemType.Update.Replace } * */ public gex.newsml.v12.NewsItemType.Update.Replace createNewsItemTypeUpdateReplace() { return new gex.newsml.v12.NewsItemType.Update.Replace(); } /** * Create an instance of {@link gex.newsml.v12.NewsItemType.Update.Delete } * */ public gex.newsml.v12.NewsItemType.Update.Delete createNewsItemTypeUpdateDelete() { return new gex.newsml.v12.NewsItemType.Update.Delete(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.NewsManagement.NewsItemType } * */ public gex.newsml.v12.NewsItemType.NewsManagement.Type createNewsItemTypeNewsManagementNewsItemType() { return new gex.newsml.v12.NewsItemType.NewsManagement.Type(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.NewsManagement.FirstCreated } * */ public gex.newsml.v12.NewsItemType.NewsManagement.FirstCreated createNewsItemTypeNewsManagementFirstCreated() { return new gex.newsml.v12.NewsItemType.NewsManagement.FirstCreated(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.NewsManagement.ThisRevisionCreated } * */ public gex.newsml.v12.NewsItemType.NewsManagement.ThisRevisionCreated createNewsItemTypeNewsManagementThisRevisionCreated() { return new gex.newsml.v12.NewsItemType.NewsManagement.ThisRevisionCreated(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.NewsManagement.Urgency } * */ public gex.newsml.v12.NewsItemType.NewsManagement.Urgency createNewsItemTypeNewsManagementUrgency() { return new gex.newsml.v12.NewsItemType.NewsManagement.Urgency(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.NewsManagement.RevisionHistory } * */ public gex.newsml.v12.NewsItemType.NewsManagement.RevisionHistory createNewsItemTypeNewsManagementRevisionHistory() { return new gex.newsml.v12.NewsItemType.NewsManagement.RevisionHistory(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.NewsManagement.DerivedFrom } * */ public gex.newsml.v12.NewsItemType.NewsManagement.DerivedFrom createNewsItemTypeNewsManagementDerivedFrom() { return new gex.newsml.v12.NewsItemType.NewsManagement.DerivedFrom(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.NewsManagement.AssociatedWith } * */ public gex.newsml.v12.NewsItemType.NewsManagement.AssociatedWith createNewsItemTypeNewsManagementAssociatedWith() { return new gex.newsml.v12.NewsItemType.NewsManagement.AssociatedWith(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.NewsManagement.Instruction.RevisionStatus * } * */ public gex.newsml.v12.NewsItemType.NewsManagement.Instruction.RevisionStatus createNewsItemTypeNewsManagementInstructionRevisionStatus() { return new gex.newsml.v12.NewsItemType.NewsManagement.Instruction.RevisionStatus(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.NewsManagement.StatusWillChange.FutureStatus * } * */ public gex.newsml.v12.NewsItemType.NewsManagement.StatusWillChange.FutureStatus createNewsItemTypeNewsManagementStatusWillChangeFutureStatus() { return new gex.newsml.v12.NewsItemType.NewsManagement.StatusWillChange.FutureStatus(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.Identification.NameLabel } * */ public gex.newsml.v12.NewsItemType.Identification.NameLabel createNewsItemTypeIdentificationNameLabel() { return new gex.newsml.v12.NewsItemType.Identification.NameLabel(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.Identification.DateLabel } * */ public gex.newsml.v12.NewsItemType.Identification.DateLabel createNewsItemTypeIdentificationDateLabel() { return new gex.newsml.v12.NewsItemType.Identification.DateLabel(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.Identification.Label.LabelType } * */ public gex.newsml.v12.NewsItemType.Identification.Label.LabelType createNewsItemTypeIdentificationLabelLabelType() { return new gex.newsml.v12.NewsItemType.Identification.Label.LabelType(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.Identification.Label.LabelText } * */ public gex.newsml.v12.NewsItemType.Identification.Label.LabelText createNewsItemTypeIdentificationLabelLabelText() { return new gex.newsml.v12.NewsItemType.Identification.Label.LabelText(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.Identification.NewsIdentifier.ProviderId * } * */ public gex.newsml.v12.NewsItemType.Identification.NewsIdentifier.ProviderId createNewsItemTypeIdentificationNewsIdentifierProviderId() { return new gex.newsml.v12.NewsItemType.Identification.NewsIdentifier.ProviderId(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.Identification.NewsIdentifier.NewsItemId * } * */ public gex.newsml.v12.NewsItemType.Identification.NewsIdentifier.NewsItemId createNewsItemTypeIdentificationNewsIdentifierNewsItemId() { return new gex.newsml.v12.NewsItemType.Identification.NewsIdentifier.NewsItemId(); } /** * Create an instance of * {@link gex.newsml.v12.NewsItemType.Identification.NewsIdentifier.RevisionId * } * */ public gex.newsml.v12.NewsItemType.Identification.NewsIdentifier.RevisionId createNewsItemTypeIdentificationNewsIdentifierRevisionId() { return new gex.newsml.v12.NewsItemType.Identification.NewsIdentifier.RevisionId(); } /** * Create an instance of {@link NewsML.NewsEnvelope.TransmissionId } * */ public NewsML.NewsEnvelope.TransmissionId createNewsMLNewsEnvelopeTransmissionId() { return new NewsML.NewsEnvelope.TransmissionId(); } /** * Create an instance of {@link NewsML.NewsEnvelope.SentFrom } * */ public NewsML.NewsEnvelope.SentFrom createNewsMLNewsEnvelopeSentFrom() { return new NewsML.NewsEnvelope.SentFrom(); } /** * Create an instance of {@link NewsML.NewsEnvelope.SentTo } * */ public NewsML.NewsEnvelope.SentTo createNewsMLNewsEnvelopeSentTo() { return new NewsML.NewsEnvelope.SentTo(); } /** * Create an instance of {@link NewsML.NewsEnvelope.NewsService } * */ public NewsML.NewsEnvelope.NewsService createNewsMLNewsEnvelopeNewsService() { return new NewsML.NewsEnvelope.NewsService(); } /** * Create an instance of {@link NewsML.NewsEnvelope.NewsProduct } * */ public NewsML.NewsEnvelope.NewsProduct createNewsMLNewsEnvelopeNewsProduct() { return new NewsML.NewsEnvelope.NewsProduct(); } /** * Create an instance of {@link NewsML.NewsEnvelope.Priority } * */ public NewsML.NewsEnvelope.Priority createNewsMLNewsEnvelopePriority() { return new NewsML.NewsEnvelope.Priority(); } /** * Create an instance of {@link TopicSetType.TopicSetRef } * */ public TopicSetType.TopicSetRef createTopicSetTypeTopicSetRef() { return new TopicSetType.TopicSetRef(); } /** * Create an instance of {@link TopicSetType.Topic.TopicType } * */ public TopicSetType.Topic.TopicType createTopicSetTypeTopicTopicType() { return new TopicSetType.Topic.TopicType(); } /** * Create an instance of {@link TopicSetType.Topic.FormalName } * */ public TopicSetType.Topic.FormalName createTopicSetTypeTopicFormalName() { return new TopicSetType.Topic.FormalName(); } /** * Create an instance of {@link TopicSetType.Topic.Description } * */ public TopicSetType.Topic.Description createTopicSetTypeTopicDescription() { return new TopicSetType.Topic.Description(); } /** * Create an instance of {@link CatalogType.TopicUse } * */ public CatalogType.TopicUse createCatalogTypeTopicUse() { return new CatalogType.TopicUse(); } /** * Create an instance of {@link CatalogType.Resource.Urn } * */ public CatalogType.Resource.Urn createCatalogTypeResourceUrn() { return new CatalogType.Resource.Urn(); } /** * Create an instance of {@link CatalogType.Resource.Url } * */ public CatalogType.Resource.Url createCatalogTypeResourceUrl() { return new CatalogType.Resource.Url(); } /** * Create an instance of {@link CatalogType.Resource.DefaultVocabularyFor } * */ public CatalogType.Resource.DefaultVocabularyFor createCatalogTypeResourceDefaultVocabularyFor() { return new CatalogType.Resource.DefaultVocabularyFor(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.RightsMetadata.UsageRights.UsageType.class) public JAXBElement<OriginType> createNewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.RightsMetadata.UsageRights.UsageType.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.NewsLines.RightsLine.class) public JAXBElement<OriginType> createNewsComponentTypeNewsLinesRightsLineOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.NewsLines.RightsLine.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.NewsLines.HeadLine.class) public JAXBElement<OriginType> createNewsComponentTypeNewsLinesHeadLineOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.NewsLines.HeadLine.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.NewsLines.KeywordLine.class) public JAXBElement<OriginType> createNewsComponentTypeNewsLinesKeywordLineOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.NewsLines.KeywordLine.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.RightsMetadata.UsageRights.Geography.class) public JAXBElement<OriginType> createNewsComponentTypeRightsMetadataUsageRightsGeographyOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.RightsMetadata.UsageRights.Geography.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.NewsLines.CopyrightLine.class) public JAXBElement<OriginType> createNewsComponentTypeNewsLinesCopyrightLineOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.NewsLines.CopyrightLine.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.NewsLines.SeriesLine.class) public JAXBElement<OriginType> createNewsComponentTypeNewsLinesSeriesLineOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.NewsLines.SeriesLine.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.RightsMetadata.UsageRights.StartDate.class) public JAXBElement<OriginType> createNewsComponentTypeRightsMetadataUsageRightsStartDateOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.RightsMetadata.UsageRights.StartDate.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.NewsLines.ByLineTitle.class) public JAXBElement<OriginType> createNewsComponentTypeNewsLinesByLineTitleOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.NewsLines.ByLineTitle.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = OriginType.class) public JAXBElement<OriginType> createOriginTypeOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, OriginType.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.NewsLines.CreditLine.class) public JAXBElement<OriginType> createNewsComponentTypeNewsLinesCreditLineOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.NewsLines.CreditLine.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.NewsLines.ByLine.class) public JAXBElement<OriginType> createNewsComponentTypeNewsLinesByLineOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.NewsLines.ByLine.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.RightsMetadata.UsageRights.EndDate.class) public JAXBElement<OriginType> createNewsComponentTypeRightsMetadataUsageRightsEndDateOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.RightsMetadata.UsageRights.EndDate.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.RightsMetadata.UsageRights.Limitations.class) public JAXBElement<OriginType> createNewsComponentTypeRightsMetadataUsageRightsLimitationsOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.RightsMetadata.UsageRights.Limitations.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.NewsLines.SubHeadLine.class) public JAXBElement<OriginType> createNewsComponentTypeNewsLinesSubHeadLineOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.NewsLines.SubHeadLine.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.NewsLines.DateLine.class) public JAXBElement<OriginType> createNewsComponentTypeNewsLinesDateLineOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.NewsLines.DateLine.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.NewsLines.NewsLine.NewsLineText.class) public JAXBElement<OriginType> createNewsComponentTypeNewsLinesNewsLineNewsLineTextOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.NewsLines.NewsLine.NewsLineText.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.RightsMetadata.Copyright.CopyrightHolder.class) public JAXBElement<OriginType> createNewsComponentTypeRightsMetadataCopyrightCopyrightHolderOrigin( OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.RightsMetadata.Copyright.CopyrightHolder.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.NewsLines.SlugLine.class) public JAXBElement<OriginType> createNewsComponentTypeNewsLinesSlugLineOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.NewsLines.SlugLine.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.RightsMetadata.Copyright.CopyrightDate.class) public JAXBElement<OriginType> createNewsComponentTypeRightsMetadataCopyrightCopyrightDateOrigin(OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.RightsMetadata.Copyright.CopyrightDate.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OriginType } * {@code >}} * */ @XmlElementDecl(namespace = "http://iptc.org/std/NewsML/2003-10-10/", name = "Origin", scope = NewsComponentType.RightsMetadata.UsageRights.RightsHolder.class) public JAXBElement<OriginType> createNewsComponentTypeRightsMetadataUsageRightsRightsHolderOrigin( OriginType value) { return new JAXBElement<OriginType>(_NewsComponentTypeRightsMetadataUsageRightsUsageTypeOrigin_QNAME, OriginType.class, NewsComponentType.RightsMetadata.UsageRights.RightsHolder.class, value); } }
Promotion of Sorghum Callus Growth by the s-Triazine Herbicides. Growth-promoting action of simazine and other s-triazine herbicides was detected by the use of sorghum (Sorghum bicolor . Moench) callus tissue and the chlorophyll retention test. Soil application of simazine at sublethal levels nearly doubled the growth-promoting action of sorghum root exudates. Treated plants yielded up to 26% more total protein than untreated plants. This indicated that the level of callus growth-promoting action in the root exudate of the plant has a positive effect on its final total protein yield and confirms a positive effect of simazine on total protein content in certain instances. The results may provide a new understanding of the mode of action of s-triazines applied at sublethal levels in increasing protein content and certain enzymic activities of treated plants. It is speculated that the growth-promoting action of these herbicides is hormonal in nature and most likely kinetin-like.
Russia should not be punished for missing the deadline to grant access to data at the Moscow Laboratory providing the information recovered from the facility is credible, World Anti-Doping Agency (WADA) Presidential candidate Philippe Muyters has claimed. The Flemish Sports Minister, also a member of the WADA Foundation Board, told insidethegames "finding a solution for the future" was "more important" than Russia failing to meet the December 31 deadline. WADA has repeatedly insisted, however, that the suspension on the Russian Anti-Doping Agency (RUSADA) would be reimposed if the country did not comply with the ultimatum. The deadline set by WADA when it controversially reinstated the Russian Anti-Doping Agency (RUSADA) in September lapsed without the organisation being able to extract the data from the laboratory. A smaller delegation was granted access to the facility last week and began its work on Thursday (January 10), which is still proceeding but is taking longer than expected. The Compliance Review Committee (CRC) was due to at least partly assess the data at its meeting on Monday (January 14) and yesterday but it was likely that this was not possible owing to the delay, which WADA claim is because of the outdated systems and servers at the laboratory. "The only thing we can do is follow the procedures," Muyters said. "Not having the deadline is important but more important is having a solution for the future. "Let's wait and see what the CRC says - if this is the only thing which is wrong, being a fortnight too late, then it is up to the Executive Committee to decide whether this should be punished. "If the point of view is that they are a fortnight too late they should be given an extra punishment, I don't think this is a good thing." The CRC is due to provide a recommendation to the WADA Executive Committee, which will hold a key meeting by teleconference on Tuesday (January 22). This comes despite the fact that the CRC meeting was likely to focus on Russia's failure to adhere to the deadline as WADA has publicly admitted a full analysis of the data obtained from the laboratory could take months. "I was really disappointed that Russia did not provide the access before the end of 2018 and I really hope that we can clear up the position of Russia and of Russian athletes for the future," Muyters added. "Perhaps it would have been better to come together with the CRC faster but okay if it is January 2 or January 15, a fortnight won't change anything. "In my opinion, the Executive Committee has to make its decision very fast." Muyters is one of four candidates to succeed Sir Craig Reedie as WADA President. The 57-year-old Belgian politician is battling WADA vice-president Linda Helleland and Polish Sports Minister Witold Bańka for the European nomination. The Council of Europe is set to decide which of the three to put forward at a meeting on January 30. Dominican Republic's Marcos Diaz is also in the running, while it is likely another candidate will emerge from Asia.
Cache-Aware Matrix Polynomials Efficient solvers for partial differential equations are among the most important areas of algorithmic research in high-performance computing. In this paper we present a new optimization for solving linear autonomous partial differential equations. Our approach is based on polynomial approximations for exponential time integration, which involves the computation of matrix polynomial terms () in every time step. This operation is very memory intensive and requires targeted optimizations. In our approach, we exploit the cache-hierarchy of modern computer architectures using a temporal cache blocking approach over the matrix polynomial terms. We develop two single-core implementations realizing cache blocking over several sparse matrix-vector multiplications of the polynomial approximation and compare it to a reference method that performs the computation in the traditional iterative way. We evaluate our approach on three different hardware platforms and for a wide range of different matrices and demonstrate that our approach achieves time savings of up to 50% for a large number of matrices. This is especially the case on platforms with large caches, significantly increasing the performance to solve linear autonomous differential equations. Introduction Solving time-depending partial differential equations (PDEs) on large-scale supercomputers is extremely resource demanding, yet applications demand the ability to operate on increasingly larger and more complex systems. Consequently, the development of efficient parallel PDE solvers from the mathematical side, as well as their efficient implementation on high-performance computing (HPC) systems is an active area of research. In this work, we investigate optimizations along the time dimension combining new approaches from mathematics and HPC research. Our main application focus lies on linear autonomous PDEs that occur frequently, e.g., in full waveform inversion problems or as part of splitting methods that incorporate non-linear parts in a separate way. In general, such PDEs are given by ∂U(t) ∂t = LU (t) with L being the linear operator and U (t) the solution at time t. In order to solve such systems numerically for a given initial condition U, we must apply a discretization. In particular, our presented HPC algorithms target commonly used discretization methods leading to a linear operator directly and explicitly given by a sparse matrix L. This is, e.g., the case when using discretizations based on finite differences or radial basis functions. Furthermore, the discrete state of the solution at time t is given by U (t), leading to ∂U (t) ∂t = LU (t). Such a discretization typically results in sparse matrices that are then used in matrix-vector-like computations LU, as it is common in off-the-shelf time integration methods. To provide an example, explicit Runge-Kutta (RK) methods rely on computations of the form k i = L t n + tc i, U n + t j a i,j k j with U n being the approximated solution at time t n, k j related to the j-th RK stage, a i,j an entry in the Butcher table (e.g., see ) and t the time step size as part of the time discretization. However, such a formulation targets non-autonomous systems with the assumption of L(t) varying over time, e.g., by external time-varying forces, hence involving the dependency on time via t n + tc i. In contrast, the linear PDEs we target in this paper do not involve any timedepending terms and this is indeed the case for many other PDEs (Seismic waves, Tsunami simulations, etc.). This opens up a new branch of matrix-polynomialbased time integration methods of the form U (t + t) = n n (tL) n U (t), which we explore in this paper as the target for our algorithmic HPC optimizations. Similarly to the RK-based methods, these methods rely on matrix-vector products. For their efficient implementation, though, we need to take modern HPC architectures into account, in particular their cache and memory hierarchy. We, therefore, design and implement a novel temporal cache-blocking scheme over the linear operators L as part of such a matrix polynomial computation. This increases both spatial and temporal locality and leads to a high utilization of the cache resources, leading to a speed-up of up to 50% on some architectures. Our main contributions are the development of these caching strategies in Sect. 3, an analytical performance model which is presented in Sect. 4 as well as the performance assessment in Sect. 5. Related Work The growing gap between computational performance and memory access latencies and bandwidth, commonly referred to as the memory wall, is one of the fundamental bottlenecks in modern computer architectures. Caches are commonly used to mitigate this problem, but require careful algorithm design to achieve the needed temporal and spatial locality that makes their use efficient. This is particularly true for PDE solvers, which we target in this paper. Algorithm design and optimization is, therefore, an active and wide field of research. In the following we point out the most relevant related work and contrast it to our approach. We first discuss very common optimization approaches for spatial dimensions. For matrix-vector and matrix-matrix multiplications, cache-blocking is a well established technique and considered an essential optimization on today's architectures with deep memory hierarchies. For regular grid structures, this technique can be combined with tiling approaches, like spatial tiling, to further increase its efficiency. However, so far such optimizations only targeted the execution of a single operation, ignoring potential optimizations across multiple operators. When considering the time dimension, temporal tiling and wavefront computations, as a generalization of it, has been shown to provide significantly improved performance on modern architectures. In our work we build on this approach of temporal tiling, used for individual SpMvs, and apply it to a series of successive SpMvs, as they occur during the calculation of the matrix potentials M p v needed for our class of targeted PDEs. Contrary to stencil computations, our algorithms do not perform blocking over several time steps, but rather several sparse matrix-vector multiplications (SpMvs) computing the polynomial terms (vectors) in every time step. Furthermore, our approach can also be applied out-of-the-box to non-uniform grids. For temporal tiling, this would pose new requirements on data dependencies, as it is based on the explicit use of the regular grid structure. Within the scope of the project to develop "communication-avoiding Krylov subspace methods" several publications focus on comparable approaches (see Hoemmen and references therein). One particular difference of our work is the application of this technique in polynomial time integration. We also provide two different implementations of this technique, which enable the cache blocking naturally with a very small preprocessing overhead. Cache-Aware Matrix Polynomials In this section we present two cache-aware algorithms for the calculation of the matrix polynomial terms M p v: the Forward Blocking Method (FBM) and the Backward Blocking Method (BBM). In particular, matrix-polynomial-based time integration demands not only the vector M p v to be calculated, but rather all vectors M k v, k ∈ {1,, p}, which makes it infeasible to explicitly precompute the matrices M k before multiplying them with v. Therefore, these vectors are computed by typically successive matrix-vector multiplications with the same matrix M. With y n denoting the result vector of the calculation of M n v, the vector y n+1 is derived as y n+1 = M n+1 v = M y n. This leads to the intuitive way to calculate M p v by successive matrix-vector multiplications, i.e., the vectors y 1 to y p are calculated one after the other. We refer to this as the naive approach. However, for sufficiently large problem sizes this results in no data reuse between the matrix-vector products, as the data is already evicted from the cache before it can be used again in the next multiplication. To avoid this situation our two methods use a blocking technique that enables the reuse of data over multiple matrix-vector calculations, which borrows some ideas from wavefront strategies in stencil computations. We interpret the vectors y 1 to y p as one-dimensional domains at time steps 1 to p, similar to one-dimensional stencil computations. While in such stencil computations the dependencies between the time steps are given by the defined stencil. for our calculations these dependencies are defined by the positions of nonzero entries in every row of the matrix. For matrices arising from finite differences or radial basis function discretizations, these positions are usually regionally similar in neighboring rows. Based on this observation, we apply a blocking scheme to the matrix to describe dependencies between whole blocks of the vectors. Our algorithms then construct two-dimensional spacetime tiles over the vectors that fit into cache, while simultaneously respecting the dependencies between all blocks of the vectors. To achieve this, our two methods use two different concepts: FBM starts at the first vector y 1 and calculates successive blocks of a vector y n until the dependencies for a block on the next vector y n+1 are fulfilled. BBM, on the other hand, starts at the last vector y p and is stepping backwards through the dependency graph in a recursive way to calculate exactly the blocks needed to resolve the dependencies for the current block of y p. To realize these two concepts, both methods demand distinct information about the dependencies between the vector blocks. Therefore, we use different data structures for the FBM and BBM, as discussed next. Extended CSR Matrix Formats As a basis for our cache-aware matrix polynomial scheme, we extended the CSR matrix storage format to provide additional information about the non-zero block structure of the matrix. The CSR format uses three arrays: the non-zero entries of the matrix in the array val, the corresponding column indices in the array colInd and the row information as pointers into the two other arrays in the array rowPtr. We extended this format by (conceptually) partitioning the matrix into blocks of size B B, while keeping the underlying data layout of the CSR format. The information about the non-zero block structure is then stored in additional arrays. However, we use different formats for the two methods: while we store the positions of all non-zero blocks for the BBM, only the position of one non-zero block per blockRow has to be stored for FBM. Therefore, for FBM the CSR format is extended by only one additional array of size n B for an M nm matrix. In this array the maximum block-column index of every block-row is stored (see maxBlockColInd array in Fig. 1). Hence, only a relatively small overhead of additional data has to be stored and loaded. The format used by BBM, on the other hand, provides the full information about the non-zero block structure of the matrix. This information is stored in two arrays similarly to the colInd and rowPtr arrays of the CSR format, but by dealing with all block rows and columns instead of single ones (see Fig. 2). Thus, the blockRowPtr array consists of offsets into the blockColumnIndex array, indicating the start of a block row. The blockColumnIndex array contains the for i = p0 to p do 5: while lastBlockOf( yi−1 ) ≥ neededBlockFor(yi) and not (i + 1 <= p and lastBlockOf(yi) >= neededBlockFor(yi+1)) do 6: SpMv(yi, lastBlockOf(yi)+1) 7: lastBlockOf(yi)++ 8: if lastBlockOf(yi) < numBlocks −1 then 9: neededBlockFor(yi) = maxBlockColInd 10: else 11: p0 + + 12: neededBlockFor(yi)=-1 13: break block-column indices of non-zero blocks in a block-row. If B r denotes the number of non-zero B B blocks of an M nm matrix, the size of the two arrays is given by n B and B r. The Forward Blocking Method We implemented FBM according to the pseudo code in Algorithm 1. For a better understanding of the underlying concept of this method, we present an example in Fig. 1. Based on this example we describe the algorithm while referring to the corresponding lines of code. For each vector y 1, y 2 and y 3 we track the information about its last calculated block (starting at −1) and the maximum index of the block of the predecessor vector that is needed to calculate the next block. For simplicity, in Algorithm 1 we compute these values by the function calls lastBlockOf(y n ) and neededBlockFor(y n ), respectively. Starting at y 1, FBM loops through the vectors (Line 2 & 3), thereby calculating blocks of vector y n by an arbitrary SpMv kernel (Line 5) until one of the following two conditions is reached (Line 4): -The forward pointer in the last calculated block points to an unfilled block of y n+1 : this indicates that the currently calculated data can be used to calculate a block of vector y n+1 and, therefore, the loop jumps to the next vector to propagate the new data forward. -The forward pointer to the next block of y n to be calculated originates from an unfilled block of y n−1 : this indicates that there are more blocks of the previous vector(s) needed, so the loop starts again at vector y 1. When a block of vector y n with index B i is calculated, the value of lastBlockOf(y n ) has to be incremented (Line 7) and the new value of neededBlockFor(y n ) can be read from maxBlockColInd (Line 9). Completely filled vectors are excluded from the loop (Line 11). This loop is repeated until the last block of y 3 is filled (Line 1). The numbers in the vectors in Fig. 1 illustrate the order in which the blocks of the vectors would be calculated by FBM in this example. This order exhibits improved temporal locality on both the matrix and the vectors, compared to successive matrix-vector products, as it traverses the dimp-plane of the vectors in wavefronts with a certain (constant) wavefront angle, resembling those in stencil computation. It can be observed that the minimum tile size is dependent on the distances between the lowest and highest column index in every row. Hence, for very large distances FBM produces large space-time tiles to respect these dependencies, which impedes cache usage and, among other issues, excludes periodic boundary problems from the application domain of this method. Figure 2 shows the concept of BBM. It loops over the blocks of the final result vector y p (y 3 in our example) and calculates the necessary blocks of the previous vectors recursively by calling the functions shown in Algorithm 2. As input parameters, this function takes a vector y n and the index B i of the block of this vector that will be calculated.. When all necessary blocks are filled, y n can finally be calculated using a SpMv kernel (Line 10). The algorithm is effectively stepping backwards through the dependence graph in a depth first traversal to reach the needed filled blocks and is calculating exactly the required data on the way backtracking forward through the dependence graph. As above, the correct order of the calculations of the vector blocks improves the temporal locality of the data accesses. For the shown example of a regular grid, BBM calculates blocks of vectors (after a short initialization phase) in the same order as FBM. However, the additional information of the dependencies between the blocks leads to a decisive advantage. As discussed above FBM degenerates to nearly successive SpMv calculations for large distances between non-zeros in one or multiple rows. BBM can "compensate" a small number of such rows, if for a majority of rows these distances are small enough for the space-time tiles to fit into cache. For such cases, BBM breaks the wavefront analogy and only calculates exactly the needed data blocks. This is contrary to FBM, which calculates all blocks of a vector up to the maximum needed block. Analytical Best-Case Performance Model In order to understand the quality of our proposed solution, we derive an analytical model showing the upper bound for the performance improvements possible with our blocking methods. When calculating M p v for large problem sizes without cache blocking, the values of the matrix and vectors have to be loaded from memory for every matrix-vector multiplication. Thus, the time for the naive calculation is given by T naive (p) = p T mem, where T mem denotes the time needed for an SpMv with no values cached. Our approaches use cache blocking, hence-in the ideal case-the matrix and vector values are only loaded once from memory and then reside in cache for the rest of the computation. Following this observation, we model the computation time as T blocked (p) = T mem + (p − 1) T cache, where T cache is the time needed for in-cache SpMvs. The time savings through blocking can then be calculated as T save (p) = 1 − T blocked (p) Tnaive(p). Consequently, for increasing exponents of the matrix (p), the expected time savings through blocking converge to Tmem. The size of the data that has to fit into the cache to achieve full cache blocking (S C ) is heavily dependent on the specific matrix structure and the exponent of the matrix. I.e., the relation can be described as S C ∝ R nz B w p, where R nz is the number of nonzero values per row, B w the distance between the lowest and highest column index per row and p the exponent of the matrix. For regular grid based matrices, the computation order in which the two methods compute the blocks lead to a more accurate approximation of S C ≈ Bw 2 (p(R nz (S val + S ind ) + 3S val + S ind ) + S val ), where S val is the size of the data type of the matrix/vector values and S ind the size of the data type used for the index and pointer array of the CSR format. Targeted Hardware Architectures To analyze the effectiveness of our approach, we evaluate our approaches on three different hardware platforms: XeonBronze, XeonSilver and AMD. Both XeonBronze and XeonSilver are based on the Intel Skylake Architecture; the XeonBronze platform features an Intel Xeon Bronze 3106 8-core processor with a total of 80 GiB of DRAM, and the XeonSilver platform is equipped with two Intel Xeon Silver 4116 12-core processors and a total of 96 GiB of DRAM, arranged equally across all available memory slots to allow for optimal bandwidth. Our AMD platform is built with a single AMD Ryzen Threadripper 2990WX 32-core processor. It is based on the 2nd-generation AMD Zen architecture and features a total of 64 GiB of main memory. The Intel Skylake features a classical 3-layer cache design (L1I/D, L2 and L3), with each of the layers (L1I/D, L2 and L3) being non-inclusive. L1D and L1I caches are 32 KiB large and 8-way associative, the L2 cache has a size of 1 MiB and is 4-way associative, and all three caches are exclusive to a particular core. The L3, on the other hand, is a shared cache and has a size of 1.375 MiB per core on our reference systems, resulting in a total of 11 MiB (Xeon Bronze) and 16.5 MiB (Xeon Silver) L3 cache shared between the cores of a processor. On AMD's 2nd-generation Zen architecture (Zen+) the L1I caches are 64 KiB and the L1D are 32 KiB per core and each core also has its own 256 KiB L2 cache. Unlike on Skylake, the L1 caches are full inclusive with respect to the L2 caches. A special design of Zen+ is the so-called CCX consisting of a cluster of 4 cores, which each shares an 8 MiB L3 cache. Two CCXs are located on one die and our reference platform (2990WX) features a total of 4 dies in its package. The dies are interconnected with a high-speed interconnect named Infinity Fabric. On the 2990WX, two memory controllers are attached to two of the dies, resulting in 4 NUMA domains, in which two of the domains do not have direct memory access and need to route accesses through another core. Matrix Test Suite The structure of the generated matrices depends on the particular grid, the finite difference order and the boundary condition. To identify the interplay between these parameters and our developed algorithms, we construct two matrix test suites that cover a wide range of combinations of these parameters. We give an overview of these matrices we used for our tests in Tables 1 and 2. Benchmark Description and Configuration We investigate the behavior of our two methods for matrices of TS 1a and 1b. As FBM is not suited for problems with periodic boundary conditions (see Sect. 3.2), we test only BBM for matrices of TS 2. We run tests using SSE4.2, AVX, AVX2 and AVX512 on the Intel systems and an AVX2 implementation on the AMD system, using block sizes of B = 2 i, i ∈ {6,, 12}. We further use an affinity of the single-threaded program to the core closest to the memory controller on each architecture. Our findings show that the differences in the vector instruction sets and the underlying micro architecture realizing them have a great impact on the performance of SpMvs with the matrices of our test suites: using AVX512 consistently leads to lower performance. Further, the performance of SSE, AVX and AVX2 instructions seem to be highly dependent on the specific matrix, making it difficult to get to a general conclusion on which vector extensions to use. Hence, if not further specified, we use the results of the best performing vector extension for our implementation and the reference method, respectively. We compare the results of our approaches to an implementation of the naive approach, which performs the matrix-vector multiplications sequentially (see Sect. 3). For this, we use the best performing block size evaluated per matrix and exponent. For all occurrences of SpMv calculations, we use the routine mkl sparse d mv() of the Intel Math Kernel Library (MKL). We also use the same library on the AMD processor, although it often is reported to not reach high performance on non-Intel CPU types. Several factors led to this decision: by setting the environment variable MKL DEBUG CPU TYPE=5, the library can be forced to choose the AVX2 code path instead of the default SSE path to which it normally falls back to on non-Intel CPUs. Comparing the performance of the AVX2 code path to other libraries on our AMD architecture, e.g., OSKI, we found that for our cases the optimal library is dependent on the specific problem type and size. Moreover, this paper focuses on exploring the general potential of cache-aware algorithms for this type of calculation, rather than achieving overall maximum performance in using SpMvs directly, motivated further by the results in the following section. We therefore stick with MKL on all architectures. Results In this section we present our results of FBM and BBM introduced in Sect. 3. We measure the time needed for the calculation of M p v, p ∈ {2, 3, 4, 5} and compare it to the reference implementation without cache blocking. Our results show improved performance of our blocking methods on all three architectures for a large number of matrices in the test suites. For the matrices of TS 1a and 1b, both FBM and BBM produce quite similar performance behavior; consequently, these results are shown interchangeably in Fig. 3. For most of the matrices in TS 1a, our approaches outperform the reference method. We achieve time savings of up to 25%/15% on the Intel Xeon Bronze/Silver, respectively, and up to 50% on the AMD Ryzen Threadripper. The matrices in TS 1b lead to slightly less improvements on the Intel processors, but still produced time savings of up to ±15% and ±5%, respectively. On the AMD, we measure greater performance improvements of 40% to 50% for many of these matrices. Regarding the periodic boundary problems of TS 2, BBM still achieves the same kind of performance improvements as for some matrices resulting from 2D FD grids (Figs. 4). Evaluation Compared to the Analytical Model On all three hardware platforms, we measure the in-L2/L3-cache and in-memory performance for SpMvs with matrices similar to those in the test suites and then use these values in our analytical model as described in Sect. 4. The upper bounds for the time savings of our blocking approach derived from the model are 20%/12% on Intel Xeon Silver, 30%/15% on Intel Xeon Bronze and 55%/50% on the AMD Ryzen Threadripper, which closely resembles our real measured performance. The performance of our approaches depends on size and structure of the matrix as discussed in Sect. 4. Using cache blocking, these algorithms naturally can only provide significant performance improvements if the matrix itself does not fit into cache. Moreover, the matrix properties B w and R nz have to be small enough such that the space-time tiles do fit into cache. This explains the poor performance of the methods for very small matrices (e.g., matrices 0, 1 and 2) and matrices with large B w and R nz (e.g., matrices 53, 54 and 55), while they perform well for large sparse matrices. Summary and Discussion In this paper we investigated the potential of using cache aware algorithms to increase the performance of matrix polynomials in the context of higher-order time integration of linear autonomous PDEs. We introduced two algorithms: the Forward Blocking Method (FBM) and the Backward Blocking Method (BBM), both using a cache blocking technique to allow data reuse during the calculation of M p v. Our evaluation on three different architectures showed both methods profit from larger and faster caches. Further, our approaches showed improved performance for a large number of matrices of our test suites. These are matrices not fitting into cache, while the generated space-time tiles do. We showed that the ratio of in-cache and in-memory SpMv is a good indicator for upper bounds of the performance improvements of our method to be expected on a specific architecture. This is also the deciding factor, why better results can be observed especially on AMD by blocking for the L3 cache. Our experiments showed that BBM is the more flexible approach. While FBM is (by design) not suited for periodic boundary problems, our results showed BBM also achieved improved performance for such matrices. Overall, our results showed promising time savings of both methods compared to the standard approach of successive sparse matrix-vector multiplications. Therefore, our approach is a significant step towards further reducing the wallclock time of higher-order time integrators for linear autonomous partial differential equations. Future work will extend these algorithms to exploit multi-core architectures. Here, various new challenges will arise, such as possible data races, which ultimately show up for such unstructured problems. However, also opportunities such as the exploitation of additional caches can lead to further performance boosts. Additionally, future work will leverage the performance boosts of the presented algorithms in the context of time integrating PDEs.
def compute_floor_offsets_with_indices(y_source, x_source, y_target=None, x_target=None): y_source_floored = tf.floor(y_source) x_source_floored = tf.floor(x_source) source_shape = shape_utils.combined_static_and_dynamic_shape(y_source) if y_target is None and x_target is None: y_target = y_source x_target = x_source else: target_shape = shape_utils.combined_static_and_dynamic_shape(y_target) if len(source_shape) == 2 and len(target_shape) == 1: _, num_neighbors = source_shape y_target = tf.tile( tf.expand_dims(y_target, -1), multiples=[1, num_neighbors]) x_target = tf.tile( tf.expand_dims(x_target, -1), multiples=[1, num_neighbors]) elif source_shape != target_shape: raise ValueError('Inconsistent source and target shape.') y_offset = y_target - y_source_floored x_offset = x_target - x_source_floored y_source_indices = tf.cast(y_source_floored, tf.int32) x_source_indices = tf.cast(x_source_floored, tf.int32) indices = tf.stack([y_source_indices, x_source_indices], axis=-1) offsets = tf.stack([y_offset, x_offset], axis=-1) return offsets, indices
A new raw material in the production of biodiesel: purple pinion seeds. Biodiesel is an alternative fuel that is produced through oil plants or animal fat. It is a renewable energy source, with biodegradable characteristics, to emit less pollutant than diesel. Thus, this work aims to show the production of biodiesel from the purple-pinion (Jatropha gossypiifolia L.) seeds. In addition to the synthesis, the physical-chemical characterization of both the raw material and the final product was carried out. The biodiesel synthetic route was performed by the basic catalytic transesterification reaction, using potassium hydroxide (KOH) in the presence of methanol (CH3OH) in the molar ratio of 1: 3 (oil: methanol). As a result, it was observed that the mass conversion of the biodiesel was 22.05 g. The physical-chemical analyzes carried out were acid index of 0.106 mgKOH / g, according to ANP technical resolution. The peroxide index of 1.03 meqO2 / kg, the kinematic viscosity of 20 ° C to 40 ° C, obtained was 6.455 mm2/s and 3.5343 mm2/s, the values are close to the ANP technique resolutions. Stability was 0.26 hours, and the biodiesel burning test was executed for approximately 3 hours. Therefore, there is a high viability of biodiesel production through the purple pinion seeds.
Characterization, Purity Determination and Decomposition Kinetics of Ezetimibe Under Non-Isothermal Conditions Ezetimibe is a lipid-lowering agent used therapeutically alone or in combination of other drugs. The properties of the solid-state of drugs are critical factors in the pharmaceutical formulation development. Several instrumental techniques can be employed in the analysis of new formulations, but the thermoanalytical techniques, provide a fast and careful evaluation of physicochemical properties of a compound. Objective: To carry out the physicochemical characterization, purity evaluation and non-isothermal kinetic studies of ezetimibe raw material.A combination of the following different analytical technics was employed: Differential Scanning Calorimetry, Thermogravimetric, Scanning Electron Microscopy, X-ray powder diffraction.The results evidenced the crystalline characteristic of ezetimibe. The sample purity was 99.06 % ± 0.02 and the thermal decomposition followed a zero order kinetic, with activation energy of 96.56 kJ mol1 and Arrhenius frequency factor of 3,442 x 109 min-1.The characterization of ezetimibe together with the non-isothermal kinetic degradation represents important studies for the pharmaceutical area, since it provides crucial information for the pharmacotechnical/quality control/production areas that should establish the specifications necessary to standardize the requirements of the raw material acquire to ensure the batch-to-batch reproducibility.
Catalytic synthesis and structural characteristics of high-quality tetrapod-like ZnO nanocrystals by a modified vapor transport process High-quality tetrapod-like ZnO (T-ZnO) nanocrystals were synthesized by a modified vapor transport process. NiO nanocrystals were prepared on a Si substrate as a catalyst. High-yield zinc vapor was produced by a carbothermal reduction of zinc carbonate to promote the synthesis of T-ZnO nanocrystals. The as-grown T-ZnO nanocrystals are assembled by four hexagonal prismatic nanorods, whose diameters and lengths are 80−100 and 600−1000 nm, respectively. In the center of a T-ZnO nanocrystal, a tetrahedral core and several irregular patches were found among the nanorods. As a whole, T-ZnO nanocrystals are preferentially arranged along the 〈001〉 direction of ZnO. The photoluminescence spectrum of T-ZnO nanocrystals showed two emission bands, a strong ultraviolet emission at around 390 nm and a weak blue emission at 440 nm. The green light emission that is related to the existence of the defects in ZnO crystals cannot be distinguished. It implies that the high crystal integrity of T-ZnO nanocrystals has been obt...
// Copyright 2020 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package query_frontend import ( "fmt" "emperror.dev/errors" "github.com/banzaicloud/operator-tools/pkg/merge" "github.com/banzaicloud/operator-tools/pkg/reconciler" "github.com/banzaicloud/operator-tools/pkg/utils" "github.com/banzaicloud/thanos-operator/pkg/resources" "github.com/banzaicloud/thanos-operator/pkg/sdk/api/v1alpha1" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" ) func (q *QueryFrontend) deployment() (runtime.Object, reconciler.DesiredState, error) { if q.Thanos.Spec.QueryFrontend != nil { queryFrontend := q.Thanos.Spec.QueryFrontend deployment := &appsv1.Deployment{ ObjectMeta: queryFrontend.MetaOverrides.Merge(q.getMeta(q.getName())), Spec: appsv1.DeploymentSpec{ Replicas: utils.IntPointer(1), Selector: &metav1.LabelSelector{ MatchLabels: q.getLabels(), }, Template: corev1.PodTemplateSpec{ ObjectMeta: q.getMeta(q.getName()), Spec: corev1.PodSpec{ Containers: []corev1.Container{ { Name: "query-frontend", Image: fmt.Sprintf("%s:%s", v1alpha1.ThanosImageRepository, v1alpha1.ThanosImageTag), Args: []string{ "query-frontend", }, Ports: []corev1.ContainerPort{ { Name: "http", ContainerPort: resources.GetPort(queryFrontend.HttpAddress), Protocol: corev1.ProtocolTCP, }, }, ImagePullPolicy: corev1.PullIfNotPresent, LivenessProbe: q.GetCheck(resources.GetPort(queryFrontend.HttpAddress), resources.HealthCheckPath), ReadinessProbe: q.GetCheck(resources.GetPort(queryFrontend.HttpAddress), resources.ReadyCheckPath), }, }, }, }, }, } // Set up args deployment.Spec.Template.Spec.Containers[0].Args = q.setArgs(deployment.Spec.Template.Spec.Containers[0].Args) if queryFrontend.DeploymentOverrides != nil { if err := merge.Merge(deployment, queryFrontend.DeploymentOverrides); err != nil { return deployment, reconciler.StatePresent, errors.WrapIf(err, "unable to merge overrides to base object") } } return deployment, reconciler.StatePresent, nil } delete := &appsv1.Deployment{ ObjectMeta: q.getMeta(q.getName()), } return delete, reconciler.StateAbsent, nil }
The casting of a two-component, clear polyurethane resin upon a substrate to produce a decorative emblem is well known in the art. Cast polyurethane, when cured, gives a lens effect to the surface applied as described in U.S. Pat. Nos. 4,100,010 and RE 33,175. These cast polyurethane resins are commonly referred to as “doming” or “lensing” resins. Doming or lensing resins are typically clear, colorless, high gloss, room temperature or elevated temperature curing, thermosetting systems developed to provide aesthetic enhancement and environmental protection to objects such as, but not limited to, paper, plastic, wood, metal, labels, decals, plaques, badges, name plates, lapel pins, automotive ornamentation, and automotive dashboards to form a durable three-dimensional coating or dome. In order for a liquid doming resin to achieve the required appearance on an object once it is cured, it preferably has a number of characteristics intrinsic to both the liquid components and the cured resin. First, the formulation should be a clear, colorless, low viscosity liquid. It should flow sufficiently to cover the entire surface to which it is applied. It should produce a coating from approximately 20 mils (0.5 mm) to 100 mils (2.5 mm) high. It should fully cure within forty-eight hours at 25° C. & 50% R.H. The curing of the coating resin formulation should not cause shrinkage, wrinkles, surface defects, curling, or other deviations from a clear, transparent, smooth, high gloss surface. It should not contain volatile solvents (less than 1%). Once cured, the coating should maintain its initial hardness and flexibility after heat and environmental aging. Doming resins typically have an application viscosity of about 100 to 5000 cps, are generally clear and colorless, and cure to a smooth, defect free, flexible or rigid coating. In addition to protecting the substrate surface from the environment, the resins are usually transparent providing an aesthetically appealing lensing effect to the pattern, design, or scripting on or near the substrate surface over which the resins are placed. Currently, conventional doming resins are practically applied as two-component, 100% solids, polyurethane systems, which may be room temperature cured or cured with heat. Two-component epoxy systems are sometimes used in indoor applications. However, they cannot be used outdoors or in applications where they will be exposed to a high concentration of UV light, as they will yellow. Polyurethane systems, based primarily on aliphatic diisocyanates, are used for most indoor and outdoor applications. There are major disadvantages with these two-component conventional systems. They need specialized two-component metering-mixing and dispensing systems to accurately dispense and mix the two reactive components. The curing of these resins must be made sufficiently slow so that the resin does not cure in the mixing unit. However, the resins then cure slowly once dispensed onto the desired substrate. Smaller parts cure slower than larger parts. Tack-free times are usually greater than six hours at ambient temperatures with full cure taking up to five days. Vacuum tables are often used to keep the substrate flat until the resin thickens sufficiently so that it will not flow off of the part. This can take hours at ambient temperatures. Special safety precautions are also necessary due to the inherent toxicity of isocyanate and epoxy resin components in these formulations. Additionally, in isocyanate-functional systems, outgassing can occur when the isocyanate component undesirably reacts with a source of water or carboxyl groups and not the hydroxyl groups present in the first component. This will cause carbon dioxide bubbles to generated & become entrapped in the cured product, essentially ruining the appearance and protective properties of the coating. Compounds based on the heavy metals; especially mercury and lead, are commonly used as catalysts in these polyurethane based systems. These compounds present both safety and environmental concerns. Phenyl mercuric acetate is one example of such a catalyst. Furthermore, polyurethane-based systems cannot be made softer than about 70 Shore A. Thus, they cannot be used on pressure sensitive adhesive labels for applications requiring a very soft, flexible dome, such as on highly curved surfaces, unless very strong adhesives are used. These two-component polyurethane and epoxy systems are also used in molding applications to produce molded designs, nameplates, and lettering and in scripting and design applications. Here again these systems are limited by their long curing times and usually must be left to cure at least twenty-four hours before they can be packaged. Heat curing systems to accelerate the curing process are available. However they are expensive and require at least twenty minutes at 60° C. for the epoxies and polyurethanes to reach a tack free state. After that, they again must sit for at least twenty-four hours before the molded parts and letters can be packaged. One-component, thin coatings that cure by actinic radiation are extensively used for thin coatings. These coatings are usually applied at less than 5 mils thick (0.13 mm). High build (>10 mils) UV curable coatings are severely limited because of high shrinkage during the curing process. Because of this high shrinkage these coatings have poor flexibility and poor adhesion to many substrates. This high shrinkage also limits the use of these UV curing doming resins to very small parts, usually less than 3 cm diameter. If placed on larger parts, such as flexible labels or decals, the shrinking would cause the part to curl on curing. Furthermore, these systems yellow on exposure to UV light and cannot be used in outdoor applications. Furthermore, acrylic monomers are very expensive and these systems contain high acrylic monomer contents. There are also health concerns over the toxicity and sensitizing properties of the acrylate based functional monomers. Co-pending application Ser. No. 11/124,077 describes one-component silylated, high build coatings that can also be used in doming resin applications. These silylated systems have many advantages over two-component systems. They do not require two-component, meter-mix-dispensing systems, they do not produce carbon dioxide bubbles on exposure to moisture and they do not contain heave metals. Although the application is useful for many applications, the tack-free times are in the area of thirty minutes to two hours. Dual cure compositions have been used for structural adhesives such as described in EP 646632A1, WO 0105846 and WO 98/53008. A photocurable resin composition for use in coatings comprising a component with dual functionality, acrylate and silane, is described in EP 0549228B1. There is a need for a curing system that can be used in doming, scripting, and molding applications that cures quickly or instantly, does not shrink, has good UV light and weathering resistance, and can be packaged as soon as it has been cured.
<gh_stars>10-100 import lxml.html from bs4 import BeautifulSoup # soup soup = BeautifulSoup(data,'lxml') ele = soup.select(css_select) # lxml html = lxml.html.fromstring(data) ele = html.cssselect(css_select) ##examples def get_hrefs(data,css_select): # soup = BeautifulSoup(data,'lxml') # ele = soup.select(css_select) html = lxml.html.fromstring(data) ele = html.cssselect(css_select) hrefs = [e for e in ele] cell = (hrefs[0].text,hrefs[1].get('href')) return cell ## lxml 速度是soup的4倍 # re import re # s = 'title=(.*)>(.*)</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;下载地址:<a href=\'(.*)\' target' pattern = re.compile(s.encode('gb2312')) # href = pattern.search(data) href = href.groups()[1:] # strings = [k.decode('gb2312') + ' ' + v.decode('gb2312') + '\n' for k,v in total_hrefs] ### 单纯匹配 re比lxml快15倍 100MB/s # 时间差异,主要是高级库做了额外工作,对少量元素效率不高。 # 少量元素re是合适,解析大多数元素lxml是合适的。 # soup:22*4s lxml:22s re:1.45s
/* * Copyright 2017 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.web.vo.stat.chart; import com.navercorp.pinpoint.web.util.TimeWindow; import com.navercorp.pinpoint.web.vo.stat.chart.Point.UncollectedPointCreater; import java.util.ArrayList; import java.util.List; /** * @author minwoo.jung */ public class TimeSeriesChartBuilder { private final TimeWindow timeWindow; private final List<Point> pointList; public TimeSeriesChartBuilder(TimeWindow timeWindow, UncollectedPointCreater uncollectedPointCreater) { if (timeWindow.getWindowRangeCount() > Integer.MAX_VALUE) { throw new IllegalArgumentException("range yields too many timeslots"); } this.timeWindow = timeWindow; int numTimeslots = (int) this.timeWindow.getWindowRangeCount(); this.pointList = new ArrayList<>(numTimeslots); for (long timestamp : this.timeWindow) { this.pointList.add(uncollectedPointCreater.createUnCollectedPoint(timestamp)); } } public Chart build(List<Point> pointList) { for (Point point : pointList) { int timeslotIndex = this.timeWindow.getWindowIndex(point.getxVal()); if (timeslotIndex < 0 || timeslotIndex >= timeWindow.getWindowRangeCount()) { continue; } this.pointList.set(timeslotIndex, point); } return new Chart(this.pointList); } }
export type MetaTypeConfig = { relationModel: string, type: 'Relation' } export type FieldConfig = { name: string, label: string, typeMeta?: MetaTypeConfig, type: string } export type ModelConfig = { name: string, label: string, fields: FieldConfig[], module: string, type?: string , aggregateRoot?: boolean; aggregateModelKey: string; belongAggregate: string; } export type ModuleConfig = { name: string, label: string, } export type SysConfig = { search: string, currentModel: string, currentModule: string, checkedKeys: string[], showNameOrLabel: boolean, tabOrTree: boolean, height: number } export type IComponentConfig = { Tree? : React.ComponentType, Input?: React.ComponentType, Button?:React.ComponentType, Dropdown?:React.ComponentType, Menu?:React.ComponentType, Select?:React.ComponentType, Tooltip?: React.ComponentType } export type TData = { models : ModelConfig[], modules :ModuleConfig[] }
A struggle for dominance over the browsers that run on wireless handsets appears to be shaping up that could rival the browser wars in the personal computer market. As more companies enter the market for mini-browsers, confusion and fragmentation will likely hit the wireless Internet market. In the U.S., Openwave Systems, formerly called Phone.com, dominates mini-browsers for wireless handsets. But in January, America Online said it was developing a Netscape-branded mini-browser with Nokia. The move threw a wrench in the mini-browser market. Microsoft, whose PC browser experiences prompted the U.S. governments massive antitrust case, has developed a mini-browser in use in Korea. The company did not have a spokesperson available to elaborate on its strategy. Mini-browsers play a vital role in the evolving wireless Internet. Openwave, for example, offers enhanced features to improve users experiences, said Tim Hyland, director of product marketing at Openwave. Users must use an Openwave gateway to take advantage of those enhancements. Most companies see mini-browsers as a way to sell other products. "Anybody out there trying to build a business around a browser wont be in business long," said Felix Lin, chairman and co-founder of AvantGo. His company has a mini-browser thats part of its server software platform designed to enable access to enterprise and Internet information from a variety of devices. "The real value isnt in the browser itself; its in the applications and services," he said. But differences between mini-browsers can cause problems, as they do in the more mature European market. In Europe, Nokia has the largest share of gateways and mini-browsers in the market. So most developers there build applications that work best on Nokias product. As a result, the 7 percent of wireless Internet users in Europe who have phones with Openwave browsers may have a less optimal experience. But users with a browser that doesnt work correctly are most likely to decide the app doesnt work well or blame the operator. "I think the danger is that it will hurt or slow the growth of content available and then slow the growth of the wireless Internet," Hyland said. Openwave is working to educate developers in the U.S. and Europe about creating their apps to work ideally on multiple mini-browsers. Unlike with browsers on PCs, wireless handset users dont have a choice. Mini-browsers must be built into the handset. That puts the onus on service providers to choose the one that will handle the most content. But in the future, users may get to choose to download different mini-browsers, which may make things easier for consumers. "With Sun and the J2ME downloadable software, users can download all kinds of stuff," said Andy Fox, chairman and co-founder of iConverse, which offers a platform that lets apps run on any device with any browser.
<reponame>dcblack/systemc-complete #ifndef SC_CXX11_HPP #define SC_CXX11_HPP #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <systemc> #pragma clang diagnostic pop #pragma GCC diagnostic pop #if __cplusplus >= 201103L // The following allows for easy bigint's: 123456789ABCDEF0123456789_BIGINT #ifndef SC_MAX_NBITS #define SC_MAX_NBITS 17*30 #endif inline sc_dt::sc_bigint<SC_MAX_NBITS> operator "" _BIGINT( const char* literal_string ) { return sc_dt::sc_bigint<SC_MAX_NBITS>( literal_string ); } inline sc_dt::sc_bigint<SC_MAX_NBITS> operator "" _BIGUINT( const char* literal_string ) { return sc_dt::sc_bigint<SC_MAX_NBITS>( literal_string ); } #endif #endif
This invention relates to hair styling tools, and more particularly to hair rollers that can be heated during a hair styling process. In the field of hair styling, it is conventional to roll hair about a plurality of cylindrically-shaped rollers while the hair is damp and then dry the hair while it is still in its rolled state. The object of the process is to obtain a hair style having a fuller appearance and enhanced body. Currently, there are two principal methods for rolling and drying hair. The first involves the use of a hairbrush with a hair dryer to brush the hair strands, while lifting the hair and rolling it over the brush head. Another method involves rolling strands of hair on a plurality of cylindrical rollers and allowing the hair to dry either under a hair dryer or while using a blow dryer. However, each of these methods has its drawbacks, one of the principal being difficulty in coordinating rolling and blow drying, particularly when not done by a hairdresser. Often times, the result of home styling is less than satisfactory particularly in the back of the head, when a person has to use an additional mirror. A person has to hold a brush in one hand, a blow dryer—in another and also manipulate the mirror for better view of the back of the head. As to the hair rollers, it is well known that most conventional hair rollers are formed from plastic with no hair bristles, which makes it difficult in achieving “natural” curls and waves. Conventional clips, when left on the hair roller for long periods of time during drying of the hair tend to leave a wave line where the clip compresses the hair. As a result, the task of properly styling hair becomes frustrating and time-consuming. The present invention contemplates elimination of drawbacks associated with the prior art and provision of a hair roller and hairbrush assembly that can be used by a person while styling hair at home to achieve professional results.
Q. I am 53 years old and reached 30 years of government service earlier this month. I work for the Environmental Protection Agency and am preparing for the possibility of being offered VERA/VSIP. I am trying to determine if it is possible to make a partial withdrawal from my TSP under VERA. My thinking is that a partial withdrawal would enable me to, at a minimum, have funding to bridge me to the start of receiving the FERS supplement at my minimum retirement age of 56. The only thing that I’ve been able to find is that I have the option of purchasing a TSP annuity or by starting monthly payments based on life expectancy. Is that correct? 1. Fail to repay an outstanding TSP loan. 2. Request a once-in-a-lifetime partial lump-sum withdrawal using form TSP-77. 3. Request a lump-sum withdrawal as part of a mixed full withdrawal using form TSP-79. If done in that order, you may do all three. Keep in mind that retirement under a VERA does not create an exception to the IRS withdrawal penalty to distributions received before you reach age 59½.
The iconic Louvre in Paris was forced to close its doors to the public today after staff staged a walk out in protest at the increasing number of pickpocket thefts by Romanian immigrant children at the museum. Hundreds of staff refused to work because of the increasing number of thieves targeting tourists at the city's famous landmark, which normally attracts up to 30,000 visitors a day. Many of the thieves are said to be the children of Romanian immigrants who get into the museum for free and then start asking tourists for money. They usually ask their victims whether they speak English before surrounding them and taking money and other possessions. Although the problem of pickpocketing is said to be a widespread problem throughout the city, the Louvre seems to have become a particularly popular target for thieves. The museum had asked for extra help from the police at the end of last year, but the problem has persisted. One member of staff, who did not wish to be named, said: 'The children are tough and very well organised. 'They stop at nothing to get what they want, and work in gangs. 'We can only do so much, but arrests are usually impossible because of their young age. Members of museum staff trade unions visited the Ministry of Culture following today's walk-out to demand action. Two years ago, France's then Interior Minister said that the vast majority of street robberies in Paris were being carried out by the children of Romanian immigrants. Claude Gueant said the notoriously poor and corrupt eastern European state was responsible for exporting some of the most notorious sneak thieves in the world. Many operated in gangs around the Gare du Nord Eurostar station, preying on British travellers as they arrived by high-speed train from London. France has shut down illegal Roma camps full of Romanian immigrants which have sprung up around the French capital, but Romanian crime remains a huge problem. Romania joined the EU in 2007 but faced restrictions on immigration which are set to be lifted next year, leading to an expected influx into countries like Britain. Around eight million people a year visit the Louvre, which is full of artistic treasures including the Mona Lisa.
Unattached radon progeny as an experimental tool for dosimetry of nanoaerosols: Proposed method and research strategy In this paper the authors discuss a method using 1-nm particulate radon decay products as an experimental tool in the study of local lung deposition and dosimetry for nanoaerosols. The study of aerosol exposure and dosimetry measurements, and related quantitative assessment of health effects, are important to the understanding of the consequences of air pollution, and are discussed widely in the scientific literature. During the last 10 years the need to correlate aerosol exposure and biological effects has become especially important due to rapid development of a new, revolutionary industrynanotechnology. Quantitative assessment of aerosol particle behavior in air, in lung deposition, and dosimetry in different parts of the lung, particularly for nanoaerosols, remains poor despite several decades of study. Direct nanoparticle dose measurements on humans are still needed in order to validate the hollow cast, animal studies, and lung deposition modeling. The issue of the safe use of radon progeny in such measurements is discussed. One of the properties of radon progeny is that they consist partly of 1-nm radioactive particles called unattached activity; having extremely small size and high diffusion coefficients, these particles can be potentially useful as radioactive tracers in the study of nanometer-sized aerosols.
# %% # Setup ## Packages import pandas as pd import numpy as np import torch from transformers import RobertaForSequenceClassification, TrainingArguments, Trainer, RobertaTokenizer, RobertaConfig from datasets import load_metric, load_dataset from sklearn.metrics import precision_recall_fscore_support, accuracy_score, classification_report from tqdm import tqdm ## Cuda device = torch.device("cuda" if torch.cuda.is_available() else "cpu") n_gpu = torch.cuda.device_count() ####### Model Config ############ ## Modelname model_to_use = "roberta-base" trained_model_name = "ManiBERT_v2" ## Max Sequence Length max_lengh_parameter = 512 ## Anzahl Labels label_count = 56 ## Anzahl Epochs if n_gpu > 1 : epoch_count = 5 else: epoch_count = 1 ## Batch Size if n_gpu > 1 : batch_size = 16 else: batch_size = 4 ## warmup_steps warmup_ratio_parameter = 0.05 ## weight_decay weight_decay_parameter = 0.1 ## learning_rate learning_rate_parameter = 5e-05 ## Log file log_name = '01_Report/log_manibert.json' ## Report validatipon_report_name = '01_Report/validation_report_manibert.txt' test_report_name = '01_Report/test_report_manibert.txt' ####### Data Config ############ ## Train Data train_data = "00_Data_intern/01_data/trainingsdaten_manibert_27022022.csv" ## Valid Data valid_data = "00_Data_intern/01_data/validierungsdaten_manibert_27022022.csv" ## Test Data test_data = "00_Data_intern/01_data/testdaten_manibert_27022022.csv" ## Delimeter delimeter_char = "," ## Label Names label_names = [ "Foreign Special Relationships: Positive", "Foreign Special Relationships: Negative", "Anti-Imperialism", "Military: Positive", "Military: Negative", "Peace", "Internationalism: Positive", "European Community/Union or Latin America Integration: Positive", "Internationalism: Negative", "European Community/Union or Latin America Integration: Negative", "Freedom and Human Rights", "Democracy", "Constitutionalism: Positive", "Constitutionalism: Negative", "Decentralisation: Positive", "Centralisation: Positive", "Governmental and Administrative Efficiency", "Political Corruption", "Political Authority", "Free Market Economy", "Incentives: Positive", "Market Regulation", "Economic Planning", "Corporatism/ Mixed Economy", "Protectionism: Positive", "Protectionism: Negative", "Economic Goals", "Keynesian Demand Management", "Economic Growth: Positive", "Technology and Infrastructure: Positive", "Controlled Economy", "Nationalisation", "Economic Orthodoxy", "Marxist Analysis: Positive", "Anti-Growth Economy and Sustainability", "Environmental Protection", "Culture: Positive", "Equality: Positive", "Welfare State Expansion", "Welfare State Limitation", "Education Expansion", "Education Limitation", "National Way of Life: Positive", "National Way of Life: Negative", "Traditional Morality: Positive", "Traditional Morality: Negative", "Law and Order", "Civic Mindedness: Positive", "Multiculturalism: Positive", "Multiculturalism: Negative", "Labour Groups: Positive", "Labour Groups: Negative", "Agriculture and Farmers", "Middle Class and Professional Groups", "Underprivileged Minority Groups", "Non-economic Demographic Groups" ] ## Config Dicts id2label_parameter = { "0": "Foreign Special Relationships: Positive", "1": "Foreign Special Relationships: Negative", "2": "Anti-Imperialism", "3": "Military: Positive", "4": "Military: Negative", "5": "Peace", "6": "Internationalism: Positive", "7": "European Community/Union or Latin America Integration: Positive", "8": "Internationalism: Negative", "9": "European Community/Union or Latin America Integration: Negative", "10": "Freedom and Human Rights", "11": "Democracy", "12": "Constitutionalism: Positive", "13": "Constitutionalism: Negative", "14": "Decentralisation: Positive", "15": "Centralisation: Positive", "16": "Governmental and Administrative Efficiency", "17": "Political Corruption", "18": "Political Authority", "19": "Free Market Economy", "20": "Incentives: Positive", "21": "Market Regulation", "22": "Economic Planning", "23": "Corporatism/ Mixed Economy", "24": "Protectionism: Positive", "25": "Protectionism: Negative", "26": "Economic Goals", "27": "Keynesian Demand Management", "28": "Economic Growth: Positive", "29": "Technology and Infrastructure: Positive", "30": "Controlled Economy", "31": "Nationalisation", "32": "Economic Orthodoxy", "33": "Marxist Analysis: Positive", "34": "Anti-Growth Economy and Sustainability", "35": "Environmental Protection", "36": "Culture: Positive", "37": "Equality: Positive", "38": "Welfare State Expansion", "39": "Welfare State Limitation", "40": "Education Expansion", "41": "Education Limitation", "42": "National Way of Life: Positive", "43": "National Way of Life: Negative", "44": "Traditional Morality: Positive", "45": "Traditional Morality: Negative", "46": "Law and Order", "47": "Civic Mindedness: Positive", "48": "Multiculturalism: Positive", "49": "Multiculturalism: Negative", "50": "Labour Groups: Positive", "51": "Labour Groups: Negative", "52": "Agriculture and Farmers", "53": "Middle Class and Professional Groups", "54": "Underprivileged Minority Groups", "55": "Non-economic Demographic Groups" } label2id_parameter = { "Foreign Special Relationships: Positive": 0, "Foreign Special Relationships: Negative": 1, "Anti-Imperialism": 2, "Military: Positive": 3, "Military: Negative": 4, "Peace": 5, "Internationalism: Positive": 6, "European Community/Union or Latin America Integration: Positive": 7, "Internationalism: Negative": 8, "European Community/Union or Latin America Integration: Negative": 9, "Freedom and Human Rights": 10, "Democracy": 11, "Constitutionalism: Positive": 12, "Constitutionalism: Negative": 13, "Decentralisation: Positive": 14, "Centralisation: Positive": 15, "Governmental and Administrative Efficiency": 16, "Political Corruption": 17, "Political Authority": 18, "Free Market Economy": 19, "Incentives: Positive": 20, "Market Regulation": 21, "Economic Planning": 22, "Corporatism/ Mixed Economy": 23, "Protectionism: Positive": 24, "Protectionism: Negative": 25, "Economic Goals": 26, "Keynesian Demand Management": 27, "Economic Growth: Positive": 28, "Technology and Infrastructure: Positive": 29, "Controlled Economy": 30, "Nationalisation": 31, "Economic Orthodoxy": 32, "Marxist Analysis: Positive": 33, "Anti-Growth Economy and Sustainability": 34, "Environmental Protection": 35, "Culture: Positive": 36, "Equality: Positive": 37, "Welfare State Expansion": 38, "Welfare State Limitation": 39, "Education Expansion": 40, "Education Limitation": 41, "National Way of Life: Positive": 42, "National Way of Life: Negative": 43, "Traditional Morality: Positive": 44, "Traditional Morality: Negative": 45, "Law and Order": 46, "Civic Mindedness: Positive": 47, "Multiculturalism: Positive": 48, "Multiculturalism: Negative": 49, "Labour Groups: Positive": 50, "Labour Groups: Negative": 51, "Agriculture and Farmers": 52, "Middle Class and Professional Groups": 53, "Underprivileged Minority Groups": 54, "Non-economic Demographic Groups": 55 } ####### Functions ############ def tokenize_function(examples): return tokenizer(examples["text"], padding="max_length", truncation=True) ## Neue Metrics function: https://huggingface.co/transformers/v3.0.2/training.html#trainer def compute_metrics(pred): labels = pred.label_ids preds = pred.predictions.argmax(-1) precision, recall, f1_micro, _ = precision_recall_fscore_support(labels, preds, average='micro') precision2, recall3, f1_macro, _ = precision_recall_fscore_support(labels, preds, average='macro') precision3, recall4, f1_weighted, _ = precision_recall_fscore_support(labels, preds, average='weighted') acc = accuracy_score(labels, preds) return { 'accuracy': acc, 'f1-micro': f1_micro, 'f1-macro': f1_macro, 'f1-weighted': f1_weighted, 'precision': precision, 'recall': recall } # %% # Daten laden raw_datasets = load_dataset('csv',data_files={'train':[train_data],'validation':[valid_data],'test': [test_data]},delimiter=delimeter_char) # %% # Tokenizer RobertaTokenizer.from_pretrained( model_to_use, model_max_length=max_lengh_parameter ).save_pretrained(trained_model_name) tokenizer = RobertaTokenizer.from_pretrained( model_to_use, model_max_length=max_lengh_parameter ) tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) # %% # Trainer Argumente training_args = TrainingArguments( output_dir=trained_model_name, warmup_ratio=warmup_ratio_parameter, weight_decay=weight_decay_parameter, learning_rate=learning_rate_parameter, fp16 = True, evaluation_strategy="epoch", num_train_epochs=epoch_count, per_device_train_batch_size=batch_size, overwrite_output_dir=True, per_device_eval_batch_size=batch_size, save_strategy="no", logging_dir='logs', logging_strategy= 'steps', logging_steps=10, push_to_hub=True, hub_strategy="end") # %% # Modell laden model = RobertaForSequenceClassification.from_pretrained( model_to_use, num_labels=label_count, id2label=id2label_parameter, label2id=label2id_parameter ) # %% # Trainer definieren trainer = Trainer( model=model, args=training_args, train_dataset=tokenized_datasets["train"], eval_dataset=tokenized_datasets["validation"], compute_metrics=compute_metrics, ) # %% # Trainieren trainer.train() # %% # Evaluate for Classification Report ## Validation predictions, labels, _ = trainer.predict(tokenized_datasets["validation"]) predictions = np.argmax(predictions, axis=1) with open(validatipon_report_name,'w',encoding='utf-8') as f: f.truncate(0) # Vorher File leeren f.write(classification_report(y_pred=predictions,y_true=labels,target_names=label_names)) # %% # Evaluate for Classification Report ## Test predictions, labels, _ = trainer.predict(tokenized_datasets["test"]) predictions = np.argmax(predictions, axis=1) with open(test_report_name,'w',encoding='utf-8') as f: f.truncate(0) # Vorher File leeren f.write(classification_report(y_pred=predictions,y_true=labels,target_names=label_names)) # %% # Abspeichern ## Log speichern with open(log_name, 'w',encoding='utf-8') as f: f.truncate(0) # Vorher File leeren for obj in trainer.state.log_history: f.write(str(obj)+'\n') ## Modell speichern trainer.save_model(trained_model_name) tokenizer.save_pretrained(trained_model_name, push_to_hub=True) # %%
//----------------------------------------------------------------------------- // Purpose: Given a vector of possible attributes, roll to see which ones are // chosen. We allocate memory for these new attributes, so it's the // responsibility of the caller to free these attributes when they're // done with them! //----------------------------------------------------------------------------- void CEconLootListDefinition::RollRandomAttributes( CUtlVector< static_attrib_t >& vecAttributes, const CEconGameAccount *pGameAccount ) const { for ( int i=0; i<m_RandomAttribs.Count(); ++i ) { const random_attrib_t* rattr = m_RandomAttribs[i]; rattr->RollRandomAttributes( vecAttributes, pGameAccount ); } }
<gh_stars>1-10 package com.pattern.tutor.syntax.database.util; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import lombok.extern.slf4j.Slf4j; @Slf4j public class SqlHelper { private String prefix; private String suffix; private String separator; private volatile LinkedHashSet<String> data = new LinkedHashSet<>(); private static final String OUTPUT = "src/main/resources/database/_result"; private static final String GROUP_OUTPUT = "src/main/resources/database/_groupby"; public void loadData(String pathname) { try (BufferedReader reader = new BufferedReader(new FileReader(new File(pathname)))) { this.data = reader.lines().map(String::trim).filter(StringUtils::isNotEmpty) .collect(Collectors.toCollection(LinkedHashSet::new)); } catch (IOException e) { e.printStackTrace(); } } public String launch() { final String pre = Optional.ofNullable(prefix).orElse(""); final String suf = Optional.ofNullable(suffix).orElse(""); return data.stream().distinct().map(loginid -> pre + loginid + suf).collect(Collectors.joining(",")); } public void fire() { final String pre = Optional.ofNullable(prefix).orElse(""); final String suf = Optional.ofNullable(suffix).orElse(""); String result = data.stream().distinct().map(loginid -> pre + loginid + suf).collect(Collectors.joining(",")); log.info("result size is {}.", result.split(",").length); try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(OUTPUT)))) { outputStream.write(result.getBytes()); } catch (IOException e) { e.printStackTrace(); } } public void groupBy() { ConcurrentHashMap<String, Long> map = new ConcurrentHashMap<>(); for (Iterator<String> iter = this.data.iterator(); iter.hasNext();) { String key = iter.next(); map.putIfAbsent(key, map.getOrDefault(key, 1L) + 1L); } log.info("groupby size is {}.", map.size()); try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(GROUP_OUTPUT)))) { map.entrySet().stream().filter(entry -> entry.getValue() > 1) .map(entry -> entry.getKey() + "," + entry.getValue()).forEach(res -> { try { outputStream.write((res + "\n").getBytes()); } catch (Exception e) { e.printStackTrace(); } }); } catch (IOException e) { e.printStackTrace(); } } public void setPrefix(String prefix) { this.prefix = prefix; } public void setSuffix(String suffix) { this.suffix = suffix; } public String getPrefix() { return prefix; } public String getSuffix() { return suffix; } public String getSeparator() { return separator; } public void setSeparator(String separator) { this.separator = separator; } }
/* * Copyright (C) <NAME> AS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package no.digipost.security; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import java.security.cert.X509Certificate; /** * Utilities for working with certificates in secure (https) requests. * The class requires the Servlet API, i.e: * <pre>{@code * <dependency> * <groupId>javax.servlet</groupId> * <artifactId>javax.servlet-api</artifactId> * <version>3.1.0</version> * </dependency> * }</pre> * */ public class Https { /** * The attribute key for retrieving the client {@link X509Certificate} set by a servlet container for secure * (https) requests. * * @see ServletRequest#getAttribute(String) */ public static final String REQUEST_CLIENT_CERTIFICATE_ATTRIBUTE = "javax.servlet.request.X509Certificate"; public static X509Certificate extractClientCertificate(ServletRequest request) { if (!request.isSecure()) { String resourceDescription; if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; resourceDescription = httpRequest.getMethod() + ": " + httpRequest.getRequestURI(); } else { resourceDescription = request.toString(); } throw new NotSecure(ServletRequest.class, resourceDescription); } Object certObj = request.getAttribute(REQUEST_CLIENT_CERTIFICATE_ATTRIBUTE); if(certObj instanceof Object[] && ((Object[]) certObj).length > 0) { certObj = ((Object[])certObj)[0]; } if (certObj instanceof X509Certificate) { return (X509Certificate) certObj; } else { throw new IllegalCertificateType(certObj); } } private Https() {} }
The company sent notifications to its Massachusetts-based sellers that it will start handing over their federal tax ID numbers along with the estimated value of inventory they have stored in Amazon’s Massachusetts warehouses, reports CNBC. Amazon initially refused to turn over seller tax data, but said it is doing so now due to a “valid and binding legal demand.” The move could set a precedent for other states to follow. States miss up to $13 billion in tax revenue annually because of sellers that refuse to come forward with taxes owed.
Multilinear Map Layer: Prediction Regularization by Structural Constraint In this paper we propose and study a technique to impose structural constraints on the output of a neural network, which can reduce amount of computation and number of parameters besides improving prediction accuracy when the output is known to approximately conform to the low-rankness prior. The technique proceeds by replacing the output layer of neural network with the so-called MLM layers, which forces the output to be the result of some Multilinear Map, like a hybrid-Kronecker-dot product or Kronecker Tensor Product. In particular, given an"autoencoder"model trained on SVHN dataset, we can construct a new model with MLM layer achieving 62\% reduction in total number of parameters and reduction of $\ell_2$ reconstruction error from 0.088 to 0.004. Further experiments on other autoencoder model variants trained on SVHN datasets also demonstrate the efficacy of MLM layers. Introduction To the human eyes, images made up of random values are typically easily distinguishable from those images of real world. In terms of Bayesian statistics, a prior distribution can be constructed to describe the likelihood of an image being a natural image. An early example of such "image prior" is related to the frequency spectrum of an image, which assumes that lower-frequency components are generally more important than high-frequency components, to the extent that one can discard some high-frequency components when reducing the storage size of an image, like in JPEG standard of lossy compression of images. Another family of image prior is related to the so called sparsity pattern (,,, which refers to the phenomena that real world data can often be constructed from a handful of exemplars modulo some negligible noise. In particular, for data represented as vector d ∈ F m that exhibits sparsity, we can construct the following approximation: where D ∈ F mn is referred to as dictionary for d and x is the weight vector combining rows of the dictionary to reconstruct d. In this formulation, sparsity is reflected by the phenomena that number of non-zeros in x is often much less than its dimension, namely: The sparse representation x may be derived in the framework of dictionary learning (Olshausen andField, 1997, ) by the following optimization: where D i is a component in dictionary, f is used to induce sparsity in x, with 1 being a possible choice. Low-Rankness as Sparse Structure in Matrices When data is represented as a matrix M, the formulation of 3 is related to the rank of M by Theorem ?? in the following sense: Hence a low rank matrix M always has a sparse representation w.r.t. some rank-1 orthogonal bases. This unified view allows us to generalize the sparsity pattern to images by requiring the underlying matrix to be low-rank. When an image has multiple channels, it may be represented as a tensor T ∈ F CHW of order 3. Nevertheless, the matrix structure can still be recovered by unfolding the tensor along some dimension. In Figure 1, it is shown that the unfolding of the RGB image tensor along the width dimension can be well approximated by a low-rank matrix as energy is concentrated in the first few components. In particular, given Singular Value Decomposition of a matrix M = UDV *, where U, V are unitary matrices and D is a diagonal matrix with the diagonal made up of singular values of M, a rank-k approximation of M ∈ F mn is: where and are the first k-columns of the U and V respectively, andD is a diagonal matrix made up of the largest k entries of D. In this case approximation by SVD is optimal in the sense that the following holds (Horn and Johnson, 1991): and An important variation of the SVD-based low rank approximation is to also model the 1 noise in the data: This norm which we tentatively call "RPCA-norm" (), is well-defined as it is infimal convolution of two norms. Low Rank Structure for Tensor Above, we have used the low-rank structure of the unfolded matrix of a rank-3 tensor corresponding to RGB values of an image to reflect the low rank structure of the tensor. However, there are multiple ways to construct of matrix D ∈ R m3n, e.g., by stacking R, G and B together horizontally. An emergent question is if we construct a matrix D ∈ R 3mn by stacking R, G and B together vertically. Moreover, it would be interesting to know if there is a method that can exploit both forms of constructions. It turns out that we can deal with the above variation by enumerating all possible unfoldings. For example, the nuclear norm of a tensor may be defined as: Definition 1 Given a tensor E, let E (i) = fold −1 i (E) be unfolding of E to matrices. The nuclear norm of E is defined w.r.t. some weights i (satisfying i ≥ 0) as a weighted sum of the matrix nuclear norms of unfolded matrices E (i) as: Consequently, minimizing the tensor nuclear norm will minimize the matrix nuclear norm of all unfoldings of tensor. Further, by adjusting the weights used in the definition of the tensor nuclear norm, we may selectively minimize the nuclear norm of some unfoldings of the tensor. Stronger Sparsity for Tensor by Kronecker Product Low Rank When an image is taken as matrix, the basis for low rank factorizations are outer products of row and column vectors. However, if data exhibits Principle of Locality, then only adjacent rows and columns can be meaningfully related, meaning the rank in this decomposition will not be too low. In contrast, local patches may be used as basis for low rank structure (Elad and Aharon, 2006,, Schaeffer and Osher, 2013, b,. Further, patches may be grouped before assumed to be of low-rank (,, Kwok, 2015. A simple method to exploit the low-rank structure of the image patches is based on Kronecker Product SVD of matrix M ∈ F mn : where R(A) is the operator defined in (Van Loan, 2000, Van which shuffles indices. Note that outer product is a special case of Kronecker product when A ∈ F m1 and B ∈ F 1n, hence we have SVD as a special case of KPSVD. The choice of shapes of A and B, however, affects the extent to which the underlying sparsity assumption is valid. Below we give an empirical comparison of a KPSVD with SVD. The image is of width 480 and height 320, and we approximate the image with KPSVD and SVD respectively for different ranks. To make the results comparable, we let B ∈ F 16x20 to make the number of parameters in two approach equal. We may extend Kronecker product to tensors as Kronecker Tensor Product as: Definition 2 Kronecker tensor product ((Phan et al.,, 2012 is defined for two tensors of the same order k. I.e., for two tensors: and we define Kronecker product of tensor as With the help of Kronecker Tensor Product, ((Phan et al.,, 2012 is able to extend KPSVD to tensors as: where R(T ) is a matrix. (a) Original image selected from BSD500 dataset () (b) SVD approximations with rank 1, 2, 5, 10, 20 respectively from left to right (c) KPSVD approximations with right matrix having shape 16x20 and with rank 1, 2, 5, 10, 20 respectively from left to right Figure 2: This figures visually compares the results of KPSVD and SVD approximation given the same number of parameters. For this example, it can be seen that KPSVD with right matrix shape 16x20 is considerably better than SVD in approximation. Prediction Regularization by Structural Constraint In a neural network like If f (X; ), the prediction of the network, is known to be like an image, it is desirable to use the image priors to help improve the prediction quality. An example of such a neural network is the so-called "Autoencoder" (,,, Ng, 2011, which when presented with a possibly corrupted image, will output a reconstructed image that possibly have the noise suppressed. One method to exploit the prior information is to introduce an extra cost term to regularize the output as The regularization technique is well studied in the matrix and tensor completion literature (,,,,,. For example, nuclear norm Z *, which is sum of singular values, or logarithm of determinant log(det( I + ZZ )) (), may be used to induce low-rank structure if Z is a matrix. It is even possible to use RPCA-norm to better handle the possible sparse non-low-rank components in Z by letting r(Z) = Z RP CA. However, using extra regularization terms also involve a few subtleties: 1. The training of neural network incurs extra cost of computing the regularizer terms, which slows down training. This impact is exacerbated if the regularization terms cannot be efficiently computed in batch, like when using the nuclear norm or RPCA-norm regularizers together with the popular mini-batch based Stochastic Gradient Descent training algorithm. 2. The value of is application-specific and may only be found through grid search on validation set. For example, when r reflects low-rankness of the prediction, larger value of may induce result of lower-rank, but may cause degradation of the reconstruction quality. We take an alternative method by directly restricting the parameter space of the output. Assume in the original neural network, the output is given by a Fully-Connected (FC) layer as: It can be seen that the output L a ∈ F mn has mn number of free parameters. However, noting that the product of two matrices A ∈ F mr and B ∈ F rn will have the property when m ≥ r and n ≥ r. Hence we may enforce that rank(L a ) ≤ r by the following construct for example: when we have: In a Convolutional Neural Network where intermediate data are represented as tensors, we may enforce the low-rank image prior similarly. In fact, by proposing a new kind of output layer to explicitly encode the low-rankness of the output based on some kinds of Multilinear Map, like a hybrid of Kronecker and dot product, or Kronecker tensor product, we are able to increase the quality of denoising and reduce amount of computation at the same time. We outline the two formulations below. Assume each output instance of a neural network is an image represented by a tensor of order 3: where C, H and W are number of channels, height and width of the image respectively. KTP layer In KTP layers, we approximate T by Kronecker Tensor Product of two tensors. T ≈ A ⊗ B. As by applying the shuffle operator defined in (Van Loan, 2000, Van, 28 is equivalent to: hence we are effectively doing rank-1 approximation of the matrix R(T ). A natural extension would then be to increase the number of components in approximation as: We may further combine the multiple shape formulation of 29 to get the general form of KTP layer: where {A ij } K i=1 and {B i,j } K i=1 are of the same shape respectively. HKD layer In HKD layers, we approximate T by the following multilinear map between A ∈ F C1H1W1 and B ∈ F C1C2H2W2, which is a hybrid of Kronecker product and dot product: where h = h 1 h 2, w = w 1 w 2. The rationale behind this construction is that the Kronecker product along the spatial dimension of H and W may capture the spatial regularity of the output, which enforces low-rankness; while the dot product along C would allow combination of information from multiple channels of A and B. In the framework of low-rank approximation, the formulation 31 is by no means unique. One could for example improve the precision of approximation by introducing multiple components as: c1,h2,w2 B k,c,c1,h1,w1. Hereafter we would refer to layers constructed following 31 as HKD layers. The general name of MLM layers will refer to all possible kinds of layers that can be constructed from other kinds of multilinear map. General MLM layer A Multilinear map is a function of several variables that is linear separately in each variable as: where V 1,..., V n and W are vector spaces with the following property: for each i, if all of the variables but v i are held constant, then f (v 1,..., v n ) is a linear function of v i. It is easy to verify that Kronecker product, convolution, dot product are all special cases of multilinear map. Figure 3 gives a schematic view of general structure of the MLM layer. The left factor and right factor are produced from the same input, which are later combined by the multilinear map to produce the output. Depending on the type of multilinear map used, the MLM layer will become HKD layer or KTP layer. We note that it is also possible to introduce more factors than two into an MLM layer. Empirical Evaluation of Multilinear Map Layer We next empirically study the properties and efficacy of the Multilinear Map layers and compare it with the case when no structural constraint is imposed on the output. To make a fair comparison, we first train a covolutional autoencoder with the output layer being a fully-connected layer as a baseline. Then we replace the fully-connected layer with different kinds of MLM layers and train the new network until quality metrics stabilizes. For example, Figure 4 gives a subjective comparison of HKD layer with the original model on SVHN dataset. We then compare MLM layer method with the baseline model in terms of number of parameters and prediction quality. We do the experiments based on implementation of MLM layers in Theano (, framework. Table 4 shows the performance of MLM layers on training an autoencoder for SVHN digit reconstruction. The network first transforms the 40 40 input image to a bottleneck feature vector through a traditional ConvNet consisting of 4 convolutional layers, 3 max pooling layers and 1 fully connected layer. Then, the feature is transformed again to reconstruct the image through 4 convolutional layers, 3 un-pooling layers and the last fully-connected layer or its alternatives as output layer. The un-pooling operation is implemented with the same approach used in (), by simply setting the pooled value at the top-left corner of the pooled region, and leaving other as zero. The fourth column of the table is the number of parameters in fully-connected layer or its alternative MLM layer. By varying the length of bottleneck feature and using different alternatives for FC layer, we can observe that both HKD and KTP layer are good alternatives for FC layer as output layer, and they also both significantly reduce the number of parameters. We also tested the case with convolutional layer as output layer, and the result still shows the efficacy of MLM layer. The second row contains the output of an Autoencoder "A1". The third row contains the output of an Autoencoder "A2", which has smaller number of hidden units in the bottleneck layer. The fourth row contains the output of an Autoencoder "A3" constructed from "A2" by replacing the output FC layer with a HKD layer. It can be seen that "A3", though with smaller number of hidden units in bottleneck layer, visually performs better than "A1" and "A2" in reconstruting the input images. As the running time may depend on particular implementation details of the KFC and the Theano framework, we do not report running time. However, the complexity analysis suggests that there should be significant reduction in amount of computation. Related Work In this section we discuss related work not covered in previous sections. Low rank approximation has been a standard tool in restricting the space of the parameters. Its application in linear regression dates back to. In (,,, b,, low rank approximation of fully-connected layer is used; and (,, b,a, also considered low rank approximation of convolution layer. (a) considered approximation of multiple layers with nonlinear activations. To our best knowledge, these methods only consider applying low-rank approximation to weights of the neural network, but not to the output of the neural network. As structure is a general term, there are also other types of structure that exist in the desired prediction. Neural network with structured prediction also exist for tasks other than autoencoder, like edge detection (Dollr and Zitnick, 2013), image segmentation (,, super resolution (a), image generation (). The structure in these problem may also exhibit low-rank structure exploitable by MLM layers. Conclusion and Future Work In this paper, we propose and study methods for incorporating the low-rank image prior to the predictions of the neural network. Instead of using regularization terms in the objective function of the neural network, we directly encode the low-rank constraints as structural constraints by requiring the output of the network to be the result of some kinds of multilinear map. We consider a few variants of multilinear map, including a hybrid-Kronecker-dot product and Kronecker tensor product. We have found that using the MLM layer can significantly reduce the number of parameters and amount of computation for autoencoders on SVHN. As future work, we note that when using 1 norm as objective together with the structural constraint, we could effectively use the norm defined in Robust Principal Value Analysis as our objective, which would be able to handle the sparse noise that may otherwise degrade the low-rankness property of the predictions. In addition, it would be interesting to investigate applying the structural constraints outlined in this paper to the output of intermediate layers of neural networks.
#-------------------------------------------------------------------------# #! Python3 # Author : NK # Desc : Insertion Sort Implementation # Info : Creating a sublist of smaller numbers on the start # and Inserting each new accordingly, # so named Insertion Sort. #-------------------------------------------------------------------------# def sort_insertion(user_input): l = len(user_input) for i in range(1,l): current_value = user_input[i] index_position = i while index_position > 0 and user_input[index_position-1] > current_value: user_input[index_position] = user_input[index_position-1] index_position = index_position -1 user_input[index_position] = current_value return user_input if __name__ == '__main__': final_sorted = [] get_user_input = [int(x) for x in input('\nEnter numbers to be sorted [seperated by ","]:').split(',')] #int(x) is import as we are looking forward to integers and not string value print('\nUser Input before Sorting:\t',get_user_input) final_sorted = sort_insertion(get_user_input) print('\nUser Input after Bubble Sort:\t',get_user_input)
Research status and development trend of concrete spiral distributor Concrete distributor is one of the key equipment for the industrial production of concrete product parts. Its performance directly affects the product quality and production efficiency of precast concrete components, which in turn affects the level of architecture industrialization of China. At present, the domestic concrete distributor has a low degree of automation and a simple mechanical structure. There is too much manual intervention in the production. It is impossible to achieve a real automatic distribution. Also, BIM data cannot be shared with the control system, resulting in low production efficiency. This paper summarized these problems which are in the context of big data, internet of things and intelligence, and proposed the upgrade ideas for precast concrete components production equipment. In order to break through the bottleneck that restricts the stability, refinement and intelligent development of precast concrete components distribution. The research and exploration in BIM data analysis mechanical structure optimization and control system upgrade were conducted. Then the overall development of mechanical equipment that meets construction standards of China will be promoted. Introduction With the proposal and implementation of Made-in-China 2025, the concept of assembly building has become a hot topic in the construction industry. The Guidelines on Developing Assembly Buildings are issued by the State Council, that pointed out that in the future. We will vigorously promote Assembly Buildings which is making up 30% of the new building area. As a modern building technology of energy saving, high efficiency and environmental protection. Assembly building is gradually accepted by major countries all over the world which puts forward higher requirements for building industrial equipment. Concrete distributor is the core equipment of precast concrete components production line in assembly building (see figure 1). Its performance will directly affect the precision and production efficiency of precast concrete components. The new generation of artificial intelligence is represented by big data and in-depth learning, will have a subversive impact on manufacturing industry which will be an inevitable trend for factories to realize information and intelligent production in the future. International Conference CIBv2019 Civil Engineering and Building Services IOP Conf. Series: Materials Science and Engineering 789 012071 IOP Publishing doi:10.1088/1757-899X/789/1/012071 2 The research of concrete distributor in developed countries is early. Users, manufacturers and designers are represented by the famous international enterprises such as German Ebawe Company, Avermann Company, Vollert Company and Soma Company. They are mainly studied the modern technology of scientific use, optimum design and intelligent control of concrete distributor. Ebawe's concrete distributor has a disposable width of 3000 mm. It can extract and transform the drawing information of concrete product parts, transmit it to the distribution system before production, also guide the distribution path planning and realize automatic and accurate distribution. The concrete distributor of Vollert Company has two ways: screw forced discharge and star-shaped axle-slip valve discharge. They can adapt to different concrete consistency and realize manual or automatic control functions. Soma has studied the seamless connection between the production information of precast concrete components and Building Information Modeling (BIM). It can optimize the data processing ability of the main control computer and developed the equipment interface for NC data exchange and feedback. In China, the designers and the researchers of concrete distributor mainly study the mechanical structure, automatic control and operation efficiency of the distributor. At present, the distributor can be controlled manually according to the size of the components only through manual intervention. Most domestic concrete distributors can be realized:  automatic weighing and judging whether feeding is needed;  the hopper of the distributor can be vertical lifting, adjusting the height of the material according to the thickness of the product. Also adjusting the distance between the material receiving and the feeding trolley to prevent concrete splashing.  Manual and wireless control mode are adopted to operate the distributor. High degree of automation can also achieve interlocking control with feeding trolley, die table walking and vibration equipment etc, that can ensure that the production process of the distributing station is reasonable and reliable. However, there are many phenomena such as inaccurate blanking quantity of concrete distributor and excessive manual participation, which have not really realized automatic and accurate distribution. It is obviously that there is still a big gap between domestic concrete distributors and developed countries' automation and intellectualization. While foreign equipment can achieve refined distribution, but it cannot meet the domestic production status (such as the problem of steel bar). At present, the technologies of data exchange between the distributor system and BIM system which are path planning before concrete product parts manufacturing, precise control of distributor and intelligent production of concrete product parts, have become the key technologies that restrict the development of concrete distributor towards modernization, automation, precision and intellectualization. Mechanical structure and operation principle of concrete distributor The concrete distributor includes the distributing system and the walking system. The distributing system includes hopper, scatter device, spiral conveying appliance, gate assembly and bottom plate assembly. The walking system includes steel structure bracket, trolley walking device and cart walking device. The walking device of the cart is a frame structure which can move forward and backward in the Y direction. It is driven by dual variable frequency motor. Also, its parallel track acts as the wheel tread of the walking device of the trolley. The walking device of the trolley can move along the X direction on the walking device of the cart. It is generally driven by a single variable-frequency moto. The hydraulic cylinder is vertically mounted lifting. It can realize Z direction movement of the hopper. A weighing sensor is installed on the frame of the hopper and trolley walking so that it can device to monitor the concrete weight in the hopper. The hopper is a component which is used to undertake concrete and complete the distribution. The dispersing device mixes the concrete in the hopper forcibly. In this way it can ensure the good fluidity of the concrete. The spiral conveying appliance uses screw to discharge material forcibly. It arranges multiple screw rods in the width of material distribution. Each screw is driven by a separate variable frequency motor. It can be driven and controlled speed independently so that meet the requirements of fine distribution. The structure of the concrete distributor shows in figure 2. The working process are as follows: concrete is dumped into hopper of distributor through torpedo tank; starting of scatter device; opening of gate corresponding to distributor area according to component shape; starting of screw drive motor to distribute material. Through the movement of the walking device of the cart and trolley, the concrete is evenly laid on the die table. The switch of the gate and the start and stop of the screw motor completed during the traveling process. After the distributing finished. In order to prevent the residual concrete from solidifying inside the hopper, the bottom plate assembly is opened. Also, the hopper is quickly washed. Control system and operation principle of concrete distributor The computer is connected with the basic automation controller. The instructions are downloaded to the controller through PLC programming. The controller sends instructions to the variable frequency motors that can drive the cart and the trolley to the starting point of the material distribution. Then the controller generates instructions to start the scatter motor and sends instructions to open the gate of the corresponding material distribution area. Finally it drives the variable frequency motor of the corresponding spiral conveying appliance and also distribute concrete material. A weighing sensor is installed at the joint of hopper and trolley that can detect the concrete weight in hopper. The weighing sensor transmits data with the PLC controller. When the concrete content in the distribution equipment is insufficient, the PLC controller will send out alarm instructions to remind the operator. Distribution control system belongs to primary control (see figure 3). In the production, it is impossible to realize the operation of automatic control equipment. It needs to be controlled by human through external wireless remote control for the distribution. According to the size information of the component, the operator can determine the distribution path and the numbers of openings by himself. Research direction and development trend of spiral distributor As a big construction country, China is moving towards strongly. The extensive construction mode needs to be upgraded and transformed. It needs to be supported by industrialization and informatization as the core. The full life cycle of the product, the digitization of the entire manufacturing process and the modular integration of ICTs will result in a production model of highly flexible, personalized products and services. Under this new production mode, the assembly-type construction equipment will be promoted for information fusion and intelligent production. The spiral distributor is the core equipment in the production line of precast components. The importance of product optimization and upgrading is self-evident. Optimization and upgrade of the mechanical structure of the spiral distributor The wheel-rail structure is adopted in the walking device of the distributor traditionally. The walking wheel driven by the variable frequency motor that travels along the track in the direction of X and Y. Slipping and creeping will inevitably occur. The precise positioning cannot be achieved, resulting in inaccurate blanking point and uneven blanking volume. Adding a rack and pinion mechanism to the cart and the trolley. Using the servo motor to drive. Changing the gear to the active part. Driving the walking wheel to walk on the track. Walking wheels play only support and guide roles, gear and rack drive which can effectively avoid skidding, creeping and other problems. The rotor speed of the servo motor is controlled by the input signal which can respond quickly and has high positional accuracy. It can also ensure the smooth running of the low speed and heavy load for the cart and trolley. The spiral conveying appliance is driven by a variable frequency motor. The discharge amount is adjusted by frequency conversion speed regulation. But there is a gap between the actual speed and the theoretical speed of the screw, resulting in inaccurate discharge. Especially in the later stage of screw wear. The difference between the theoretical discharge amount and the actual discharge amount is larger, it cannot achieve fine distribution. The relationship between screw blade diameter, screw shaft diameter, pitch, screw speed, power consumption and wear are vague. It needs further study and optimization. Wear-resistant material is needed for the helical blade in the design. It can effectively increase the service life of the screw. The encoder is added to each screw variable-frequency motor so that the motor can achieve closed-loop control in speed regulation. It can keep the actual speed consistent with the theoretical speed. The screw is optimized by discrete element method, computational fluid dynamics, lightweight structure design and experimental method. The power consumption and wear are minimal when the materials output is satisfied then. In the later stage of screw wear, the screw speed is compensated by predicted life model that ensure the blanking amount stable. Optimal upgrade of control system of spiral distributor Usually the control strategy of the distributor control system is simple. There is even no control strategy. It is impossible to achieve intelligent and accurate distribution. Component BIM information cannot be transmitted to the control system through the interface, which requires manual conversion and low efficiency. Lacking of positioning sensors, the distributor cannot locate quickly and accurately. The control system has no prediction model of the materials output and cannot accurately control the materials output; in the later stage of screw wear. There is no rotational speed compensation control model to ensure uniform materials output. Heavy sensors become detection components which do not play a role in the control system. Lacking of production process monitoring and prediction result in the distributor cannot operate reliably and accurately. On the basis of the lower computer programming controller, the upper computer industrial control system is added to the distribution control system. The programming controller mainly realizes the multi-direction motion control of the distributor, the control of the spiral conveying motor and the control of the gate cylinder. The function of the upper computer reads the graphical data of the components parsed by BIM, divide, process the distributor area in the upper computer software and transmit the distributor area data to the PLC controller. The controller controls the work of the executing mechanism. The encoder added to the screw motor and the weighing sensor provided by the distributor are used to collect the signals in the process of distribution. The collected data are fed back to the control system to form a closed-loop PID regulation. The programmable controller is implemented in the form of main program calling subroutine, which is convenient for system debugging and upgrading. A control algorithm is added to the program to ensure the stability of the motor starting and stopping stages. BIM is an important technology to promote the development of new industrialization and construction industry informatization. Based on BIM technology, the BIM-compatible information parsing interface is designed by using data compatibility extraction, symbol recognition of building components and topological relationship tree building method. The component is identified by vector graph symbols so that the component has its own "ID number". The component data parameters are transmitted to the distribution control system through the corresponding interface. The optimization theory is adopted in the system in order to the generation and calculation of the distribution path. It can realize the automatic distribution path planning and guide the automatic distribution of the distributor. The visual control interface of the distributor is shown in figure 4. For the automated intelligent distribution system, the detection module is indispensable. The component thickness information and positioning information of the distributor need to be extracted and fed back through the detection technology. In the process of distributing material, the pre-calibrated position of the distributor can be measured by laser displacement sensor. The thickness information of the component can be measured by ranging method. The information can be fed back to the control system. Through the feedback information, the position compensation and quality compensation can be carried out by the control system. It ensures the distributor can deliver material accurately. Before the distribution production, the concrete distribution machine is driven by the distribution cart and the distribution trolley. It locates the pre-production starting such as the end point of the edge touching. According to the BIM analysis of the concrete component information to calculate the required concrete quality, distribution path, spiral speed and other production process information for distribution production. The distribution trolley is equipped with the distribution machine. According to the calculated distribution path, it moves in the corresponding position in the side touch on the distribution crane beam. At the same time, the screw of each distribution port rotates at a certain speed. It pushes out the concrete in the hopper. Finally pour it into the distribution area surrounded by the side formwork of the bottom formwork tray. When the distribution trolley moves to the side mold of the door and window hole, the corresponding screw stops rotating. The prediction quality of concrete materials transported by screw. The quality is detected by the weighing sensor of the distributor. The quality of materials is analyzed by BIM information are applied to the distribution control system that achieve closed-loop accurate discharge. Conclusion With the rapid development of computer technology and artificial intelligence technology, driven by the national manufacturing 2025 policy. The era of intelligent production is on the way. Digital, automated, refined and intelligent distribution technology can liberate the labor force to the greatest extent, realize automatic, accurate and stable operation of the distribution machine. Also, it improves production efficiency comprehensively.
Alastair Donaldson Alastair Donaldson (27 April 1955, in Edinburgh – 18 June 2013, in Edinburgh) was a Scottish multi-instrumentalist, and was the bass guitar player for the Scottish punk/pop band The Rezillos, for whom he played under the stage name of William Mysterious. He was a formative member of the folk ensemble Silly Wizard prior to his involvement with The Rezillos, and appears on many of their recordings under his real name. He appears on the Rezillos' second single for Sire Records, a double A-side featuring the songs "Flying Saucer Attack" and "My Baby (Does Good Sculptures)" and also on their first studio album Can't Stand The Rezillos. He took over the bass slot in the Rezillos whilst working as their saxophonist. He left The Rezillos after a British tour supporting The Ramones, although he did make a guest appearance at the Rezillos' final gig at the Glasgow Apollo, where he returned to his original role of saxophone player alongside his replacement on bass guitar, Simon Templar (born Simon Broomfield). This performance was captured on The Rezillos' live album, Mission Accomplished (But The Beat Goes On). He also appeared on the B-side of the single version of "Top of The Pops", playing saxophone on the instrumental track, "20,000 Rezillos under the Sea". This track itself was a re-imagining of the "William Tell Overture" by the classical composer Rossini. After leaving the Rezillos, he released one single in 1982 as William Mysterious with Alastair Donaldson on the independent Mezzanine label, "Security of Noise" b/w "Alright". After The Rezillos split up for the first time in 1978, former members became The Revillos, and Donaldson rejoined them in 1979 for the Rev Up LP where he once again played bass. After this final outing with The Rezillos he retired from recording and touring, but was still semi active in live work in his native Edinburgh up until his death on 18 June 2013. He is survived by a daughter, Ailsa, and a son, John, as well as his wife Ksenija Horvat.
<reponame>dhanin/friendly-bassoon<filename>src/sim/tcLauncherState.cpp /** ** @file tcLauncherState.cpp */ /* ** Copyright (c) 2014, GCBLUE PROJECT ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: ** ** 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from ** this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT ** NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ** COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING ** IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "stdwx.h" #include "tcLauncherState.h" #include "tcLauncher.h" #include "tcDatabase.h" #include "tcBallisticDBObject.h" #include "tcPlatformDBObject.h" #include "tcLauncherDBObject.h" #include "tcMissileDBObject.h" #include "tcTorpedoDBObject.h" #include "tcRadar.h" #include "tcOpticalSensor.h" #include "tcSimState.h" #include <iostream> #include "common/tcObjStream.h" #include "tcGameStream.h" #include "Game.h" #ifdef _DEBUG #define new DEBUG_NEW #endif tcDatabase* tcLauncherState::mpDatabase = 0; tcSimState* tcLauncherState::simState = 0; /** * @param anKey, key of launcher database object in database * @param azimuth_rad mount angle of (fixed) launcher in radians relative to bow/nose * @param displayName name to display in GUI controls, e.g. "Tube 1" */ void tcLauncherState::AddFullLauncher(long anKey, float azimuth_rad, float elevation_rad, float fov_deg, const std::string& displayName, bool isReloadable) { wxASSERT(mpDatabase); tcLauncherDBObject* ldata = dynamic_cast<tcLauncherDBObject*>(mpDatabase->GetObject(anKey)); if (ldata == 0) { fprintf(stderr, "Error - tcLauncherState::AddFullLauncher - Not found in db (%d)\n", anKey); return; } if (mnCount >= tcPlatformDBObject::MAXLAUNCHERS) { fprintf(stderr, "Error - tcLauncherState::AddFullLauncher - full\n"); return; } // add new launcher wxASSERT(parent); tcLauncher* new_launcher = new tcLauncher(ldata, parent); new_launcher->pointingAngle = azimuth_rad; new_launcher->mountPointingAngle = azimuth_rad; new_launcher->pointingElevation = elevation_rad; new_launcher->SetFOV(fov_deg); new_launcher->displayName = displayName; new_launcher->isReloadable = isReloadable; // hack to get flares and chaff mix on default if (((mnCount % 2) == 1) && (ldata->mzClass == "CM Ejector")) { wxString childClass(ldata->GetConfigurationClass(1).c_str()); if ((childClass.Find('?') == wxNOT_FOUND) && (childClass.Find('*') == wxNOT_FOUND)) { new_launcher->SetChildClass(childClass.ToStdString()); new_launcher->SetChildQuantity(ldata->GetConfigurationCapacity(1)); } } wxASSERT((new_launcher->mpChildDBObj != 0) || (ldata->mzClass == "Test Launcher")); launchers.push_back(new_launcher); mnCount = (int)launchers.size(); } /** * @return approximate intercept time for target track * For missiles this is assumes 600 kts velocity for now. * For guns the range and speed are estimated using ballistics. */ float tcLauncherState::EstimateInterceptTimeForLauncher(unsigned nLauncher, tcTrack& track) { tcLauncher* launcher = GetLauncher(nLauncher); if (!launcher) { fprintf(stderr, "EstimateInterceptTimeForLauncher - bad launcher\n"); return 0; } tcDatabaseObject* child = launcher->mpChildDBObj; tcKinematics kin = parent->mcKin; float heading_rad = 0; float tti_s = 0; if (tcMissileDBObject* missileInfo = dynamic_cast<tcMissileDBObject*>(child)) { kin.mfSpeed_kts = 600; kin.GetInterceptData2D(track, heading_rad, tti_s); } else if (tcBallisticDBObject* ballInfo = dynamic_cast<tcBallisticDBObject*>(child)) { float targetAlt_m = track.GetOrGuessAltitude(); float range_km = kin.RangeToKm(track); ballInfo->GetGunneryElevation(1000 * range_km, targetAlt_m, tti_s); tcKinematics launcherKin(parent->mcKin); } else if (tcTorpedoDBObject* torpedo = dynamic_cast<tcTorpedoDBObject*>(child)) { if (!track.IsBearingOnly() && (track.IsHeadingValid() && track.IsSpeedValid())) { kin.mfSpeed_kts = 0.5f * torpedo->maxSpeed_kts + 0.5f * launcher->preEnableSpeed_kts; kin.GetInterceptData2D(track, heading_rad, tti_s); } } else { fprintf(stderr, "EstimateInterceptTimeForLauncher - unhandled data type\n"); } return tti_s; } tcLauncher* tcLauncherState::GetLauncher(unsigned int nLauncher) { if (nLauncher >= (unsigned int)mnCount) return 0; return launchers[nLauncher]; } const tcLauncher* tcLauncherState::GetLauncher(unsigned nLauncher) const { if ((int)nLauncher >= mnCount) return 0; return launchers[nLauncher]; } std::string tcLauncherState::GetLauncherChildClass(unsigned nLauncher) const { wxASSERT((int)nLauncher < mnCount); return launchers[nLauncher]->GetChildClassName(); } /** * @return number of launchers */ unsigned int tcLauncherState::GetLauncherCount() const { return (mnCount >= 0) ? (unsigned int)mnCount : 0; } int tcLauncherState::GetLauncherQuantity(unsigned anLauncher) const { if (anLauncher > launchers.size()) {return -1;} return launchers[anLauncher]->mnUncommitted; } /** * @return LAUNCHER_READY if launcher is ready to launch. Launch readiness * @return conditions depend on meLaunchMode for the launcher. * @return Otherwise return error code * @see teWeaponLaunchMode * @see tcLauncherState::teLauncherStatus * This method needs to be separated into smaller pieces. */ int tcLauncherState::GetLauncherStatus(unsigned nLauncher) { using namespace database; if (nLauncher > launchers.size()) { std::cerr << "Bad launcher index" << std::endl; return tcLauncher::BAD_LAUNCHER; } tcLauncher* ldata = launchers[nLauncher]; wxASSERT(ldata); return ldata->GetLauncherStatus(); } bool tcLauncherState::IsDatumLaunch(unsigned anLauncher) { if (anLauncher > launchers.size()) {return false;} return launchers[anLauncher]->meLaunchMode == DATUM_ONLY; } bool tcLauncherState::IsSeekerLaunch(unsigned anLauncher) { if (anLauncher > launchers.size()) {return false;} return launchers[anLauncher]->meLaunchMode == SEEKER_TRACK; } /** * sets key to database id of object to launch, otherwise NULL_INDEX * nLauncher is set to launcher idx of launching launcher * This only handles one launch per call (not efficient for simultaneous launches) */ void tcLauncherState::Launch(long& key, unsigned& nLauncher) { for (int n=0; n<mnCount; n++) { tcLauncher* pLauncher = launchers[n]; if ((pLauncher->mbActive)&&((int)pLauncher->mnCurrent > pLauncher->mnUncommitted)) { bool bLaunch = (pLauncher->mnCurrent > 0)&&(pLauncher->mfTimeToReady <= 0); if (bLaunch) { int statusCode = GetLauncherStatus(n); if (statusCode == tcLauncher::LAUNCHER_READY) { pLauncher->mnCurrent--; key = pLauncher->mnChildDBKey; nLauncher = n; pLauncher->mfTimeToReady = pLauncher->GetCycleTime(); if (pLauncher->mnCurrent > 0) { if ((pLauncher->mnUncommitted == pLauncher->mnCurrent) && (pLauncher->AutoLaunchAgain())) { pLauncher->mnUncommitted--; // queue another launch pLauncher->repeatShots--; } } else // (pLauncher->mnCurrent == 0) { pLauncher->QueueAutoReload(); // moved reload AFTER child is launched to avoid screwing up datum, etc. // pLauncher->Reload(); } return; } else { pLauncher->mnUncommitted = pLauncher->mnCurrent; // reset } } } else { } } key = NULL_INDEX; nLauncher = 0; } /** * @param nLauncher launcher index * @param sesnor pointer to tcRadar or tcOpticalSensor object that acts as fire control sensor * @param sensorIdx index of sensor object on parent platform */ void tcLauncherState::SetFireControlSensor(unsigned nLauncher, tcSensorState* sensor, unsigned sensorIdx) { wxASSERT(sensor); tcRadar* radar = dynamic_cast<tcRadar*>(sensor); tcOpticalSensor* optical = dynamic_cast<tcOpticalSensor*>(sensor); if ((radar == 0) && (optical == 0)) { fprintf(stderr, "tcLauncherState::SetFireControlSensor - Only radar and laser fire control supported\n"); return; } if (nLauncher > launchers.size()) {return;} launchers[nLauncher]->fireControlSensor = sensor; launchers[nLauncher]->fireControlSensorIdx = sensorIdx; // Launchers with fireControlSensor must have a FC track to launch // SEEKER_TRACK already requires a fire control track (and a seeker track) so do not change // added DATUM_ONLY too so that dumb bombs don't require laser designator (kind of a mess!) if ((launchers[nLauncher]->meLaunchMode != SEEKER_TRACK) && (launchers[nLauncher]->meLaunchMode != DATUM_ONLY)) { launchers[nLauncher]->meLaunchMode = FC_TRACK; } } /** * If launcher is ready, decrement mnUncommitted of nLauncher by quantity. * This method does not support targeting multiple targets. * @return tcLauncherState::teLauncherStatus error code, LAUNCHER_READY = 0 for success */ int tcLauncherState::SetLaunch(int nLauncher, int quantity) { int statusCode; tcLauncher* pLauncher = launchers[nLauncher]; pLauncher->ActivateFireControl(); statusCode = GetLauncherStatus(nLauncher); if (statusCode != tcLauncher::LAUNCHER_READY) { return statusCode; } pLauncher->mnUncommitted -= quantity; if (pLauncher->mnUncommitted < 0) { pLauncher->mnUncommitted = 0; // don't set new cmd here since this is an error case #ifdef _DEBUG fprintf(stderr, "Warning - tcLauncherState::SetLaunch - request exceeds capacity\n"); #endif } else { commandObj.SetNewCommand(GetLauncherFlag(nLauncher)); } pLauncher->SetRepeatShotsForType(); return statusCode; } /** * @return true if success */ bool tcLauncherState::SetLauncherDatum(unsigned nLauncher, double lon_rad, double lat_rad, float alt_m) { size_t nLaunchers = launchers.size(); if (nLauncher > nLaunchers) { std::cerr << "Bad launcher index" << std::endl; return false; } bool nullTarget = (lon_rad == 0) && (lat_rad == 0) && (alt_m == 0); // do not set datum if not in range of launcher (only check for guns for now) if (!nullTarget) { if (tcBallisticDBObject* ballDB = dynamic_cast<tcBallisticDBObject*> (launchers[nLauncher]->mpChildDBObj)) { float maxRange_km = ballDB->GetMaxLevelGunRangeKm(); if (maxRange_km <= 0) { maxRange_km = 20.0f; // hack for non-guns for now wxASSERT(false); } if (parent->mcKin.RangeToKm(lon_rad, lat_rad) > maxRange_km) { /*if (!tcSimState::Get()->IsMultiplayerServer()) { wxString msg = wxString::Format("%s gun out of range (%.1f km)", parent->GetName(), maxRange_km); tcGame::DisplayMessage(msg.c_str()); }*/ return false; } } } launchers[nLauncher]->SetDatum(lon_rad, lat_rad, alt_m); commandObj.SetNewCommand(GetLauncherFlag(nLauncher)); return true; } /** * @return true if success */ bool tcLauncherState::SetLauncherTarget(unsigned nLauncher, long targetID) { size_t nLaunchers = launchers.size(); if (nLauncher > nLaunchers) { std::cerr << "Bad launcher index" << std::endl; return false; } tcLauncher* launcher = launchers[nLauncher]; launcher->mnTargetID = targetID; launcher->msDatum.Set(0, 0, 0); // clear datum launcher->ClearPendingLaunch(); commandObj.SetNewCommand(GetLauncherFlag(nLauncher)); return true; } /** * Converts launcher status code into string. */ std::string tcLauncherState::TranslateLauncherStatus(int status) { return tcLauncher::TranslateStatus(status); } /** * */ tcCommandStream& tcLauncherState::operator<<(tcCommandStream& stream) { for (int n = 0; n < mnCount; n++) { *launchers[n] << stream; } return stream; } /** * Save launcher state to command stream */ tcCommandStream& tcLauncherState::operator>>(tcCommandStream& stream) { for(int n = 0; n < mnCount; n++) { *launchers[n] >> stream; } return stream; } /** * Loads state from update stream */ tcUpdateStream& tcLauncherState::operator<<(tcUpdateStream& stream) { for(int n = 0; n < mnCount; n++) { tcLauncher& ldata = *launchers[n]; int oldStatus = ldata.GetLauncherStatus(); ldata << stream; int launcherStatus = ldata.GetLauncherStatus(); if ((launcherStatus != 0) && (launcherStatus != oldStatus) && (ldata.mnUncommitted < ldata.mnCurrent)) { ldata.ClearPendingLaunch(); // set the new command flag to allow the launch request to be cleared commandObj.SetNewCommand(GetLauncherFlag(n)); tcGame::DisplayMessage(TranslateLauncherStatus(launcherStatus).c_str()); } } // update damage unsigned short launcherDamage; stream >> launcherDamage; unsigned short damageFlag = 0x0001; size_t nLaunchers = launchers.size(); wxASSERT(nLaunchers <= 8*sizeof(launcherDamage)); for (size_t k=0; k<nLaunchers; k++) { bool damageState = (launcherDamage & damageFlag) != 0; launchers[k]->SetDamaged(damageState); damageFlag = damageFlag << 1; } return stream; } /** * Saves state to update stream */ tcUpdateStream& tcLauncherState::operator>>(tcUpdateStream& stream) { unsigned short launcherDamage = 0; unsigned short damageFlag = 0x0001; wxASSERT(mnCount <= 8*sizeof(launcherDamage)); for(int n = 0; n < mnCount; n++) { tcLauncher& ldata = *launchers[n]; ldata >> stream; // update damage flag if (launchers[n]->IsDamaged()) { launcherDamage |= damageFlag; } damageFlag = damageFlag << 1; } stream << launcherDamage; return stream; } /** * Loads state from game stream */ tcGameStream& tcLauncherState::operator<<(tcGameStream& stream) { commandObj << stream; for(size_t n=0; n<launchers.size(); n++) { tcLauncher& ldata = *launchers[n]; ldata << stream; } return stream; } /** * Saves state to game stream */ tcGameStream& tcLauncherState::operator>>(tcGameStream& stream) { commandObj >> stream; for(size_t n=0; n<launchers.size(); n++) { tcLauncher& ldata = *launchers[n]; ldata >> stream; } return stream; } void tcLauncherState::ClearNewCommand() { commandObj.ClearNewCommand(); } bool tcLauncherState::HasNewCommand() const { return commandObj.HasNewCommand(); } /** * */ void tcLauncherState::Serialize(tcFile& file, bool abLoad) { if (abLoad) { file.Read(&mnCount,sizeof(mnCount)); for(int i=0;(i<mnCount)&&(i<tcPlatformDBObject::MAXLAUNCHERS);i++) { /* file.Read(&ma[i],sizeof(tcLauncher)); // replace serialized pointer tcDatabaseObject *pDatabaseObj = mpDatabase->GetObject(ma[i].mnDBKey); ma[i].mpLauncherDBObj = dynamic_cast<tcLauncherDBObject*>(pDatabaseObj); ma[i].mpChildDBObj = mpDatabase->GetObject(ma[i].mnChildDBKey); */ } } else { /* file.Write(&mnCount,sizeof(mnCount)); for(int i=0;(i<mnCount)&&(i<tcPlatformDBObject::MAXLAUNCHERS);i++) { file.Write(&ma[i],sizeof(tcLauncher)); } */ } } /** * */ std::string tcLauncherState::GetLaunchMode(unsigned anLauncher) { std::string s; if (anLauncher > launchers.size()) { s = "err"; return s; } teWeaponLaunchMode lm = launchers[anLauncher]->meLaunchMode; if (lm == DATUM_ONLY) { s = "Datum"; } else if (lm == SEEKER_TRACK) { s = "Seeker"; } else { s = "Unknown"; } return s; } /** * update launcher state (reload time) */ void tcLauncherState::Update(float dt_s) { for(int n=0; n<mnCount; n++) { tcLauncher* launcher = launchers[n]; if (simState->IsMultiplayerServer()) { launcher->UpdateStatus(); } if ((launcher->mbActive) && (launcher->mfTimeToReady > 0)) { launcher->mfTimeToReady -= dt_s; } } } /** * */ tcLauncherState::tcLauncherState() : mnCount(0), parent(0) { } tcLauncherState::tcLauncherState(tcPlatformObject* parentObj) : parent(parentObj), mnCount(0) { } /** * */ tcLauncherState::tcLauncherState(tcLauncherState& lstate) : parent(0) { for(unsigned i=0;i<lstate.launchers.size();i++) { launchers.push_back(lstate.launchers[i]); } mnCount = (int)launchers.size(); } /** * */ tcLauncherState::~tcLauncherState() { for (size_t n=0; n<launchers.size(); n++) { delete launchers[n]; } }
<reponame>Praggya17/HacktoberFestContribute //Works for negative costs, but does not work for negative cycles //Complexity: O(min(E^2 *V log V, E logV * flow)) struct edge { int to, flow, cap, cost, rev; }; struct MinCostMaxFlow { int nodes; vector<int> prio, curflow, prevedge, prevnode, q, pot; vector<bool> inqueue; vector<vector<edge> > graph; MinCostMaxFlow() {} MinCostMaxFlow(int n): nodes(n), prio(n, 0), curflow(n, 0), prevedge(n, 0), prevnode(n, 0), q(n, 0), pot(n, 0), inqueue(n, 0), graph(n) {} void addEdge(int source, int to, int capacity, int cost) { edge a = {to, 0, capacity, cost, (int)graph[to].size()}; edge b = {source, 0, 0, -cost, (int)graph[source].size()}; graph[source].push_back(a); graph[to].push_back(b); } void bellman_ford(int source, vector<int> &dist) { fill(dist.begin(), dist.end(), INT_MAX); dist[source] = 0; int qt=0; q[qt++] = source; for(int qh=0;(qh-qt)%nodes!=0;qh++) { int u = q[qh%nodes]; inqueue[u] = false; for(auto &e : graph[u]) { if(e.flow >= e.cap) continue; int v = e.to; int newDist = dist[u] + e.cost; if(dist[v] > newDist) { dist[v] = newDist; if(!inqueue[v]) { inqueue[v] = true; q[qt++ % nodes] = v; } } } } } pair<int, int> minCostFlow(int source, int dest, int maxflow) { bellman_ford(source, pot); int flow = 0; int flow_cost = 0; while(flow < maxflow) { priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > q; q.push({0, source}); fill(prio.begin(), prio.end(), INT_MAX); prio[source] = 0; curflow[source] = INT_MAX; while(!q.empty()) { int d = q.top().first; int u = q.top().second; q.pop(); if(d != prio[u]) continue; for(int i=0;i<graph[u].size();i++) { edge &e=graph[u][i]; int v = e.to; if(e.flow >= e.cap) continue; int newPrio = prio[u] + e.cost + pot[u] - pot[v]; if(prio[v] > newPrio) { prio[v] = newPrio; q.push({newPrio, v}); prevnode[v] = u; prevedge[v] = i; curflow[v] = min(curflow[u], e.cap - e.flow); } } } if(prio[dest] == INT_MAX) break; for(int i=0;i<nodes;i++) pot[i]+=prio[i]; int df = min(curflow[dest], maxflow - flow); flow += df; for(int v=dest;v!=source;v=prevnode[v]) { edge &e = graph[prevnode[v]][prevedge[v]]; e.flow += df; graph[v][e.rev].flow -= df; flow_cost += df * e.cost; } } return {flow, flow_cost}; } };
<filename>packages/wrap/src/generateProxyingResolvers.ts import { GraphQLSchema, GraphQLFieldResolver, GraphQLObjectType } from 'graphql'; import { Transform, Operation, getResponseKeyFromInfo, getErrors, applySchemaTransforms } from '@graphql-tools/utils'; import { delegateToSchema, getSubschema, handleResult, SubschemaConfig, isSubschemaConfig, CreateProxyingResolverFn, ICreateProxyingResolverOptions, } from '@graphql-tools/delegate'; export function generateProxyingResolvers( subschemaOrSubschemaConfig: GraphQLSchema | SubschemaConfig, transforms: Array<Transform> ): Record<string, Record<string, GraphQLFieldResolver<any, any>>> { let targetSchema: GraphQLSchema; let schemaTransforms: Array<Transform> = []; let createProxyingResolver: CreateProxyingResolverFn; if (isSubschemaConfig(subschemaOrSubschemaConfig)) { targetSchema = subschemaOrSubschemaConfig.schema; createProxyingResolver = subschemaOrSubschemaConfig.createProxyingResolver ?? defaultCreateProxyingResolver; if (subschemaOrSubschemaConfig.transforms != null) { schemaTransforms = schemaTransforms.concat(subschemaOrSubschemaConfig.transforms); } } else { targetSchema = subschemaOrSubschemaConfig; createProxyingResolver = defaultCreateProxyingResolver; } if (transforms != null) { schemaTransforms = schemaTransforms.concat(transforms); } const transformedSchema = applySchemaTransforms(targetSchema, schemaTransforms); const operationTypes: Record<Operation, GraphQLObjectType> = { query: targetSchema.getQueryType(), mutation: targetSchema.getMutationType(), subscription: targetSchema.getSubscriptionType(), }; const resolvers = {}; Object.keys(operationTypes).forEach((operation: Operation) => { const resolveField = operation === 'subscription' ? 'subscribe' : 'resolve'; const rootType = operationTypes[operation]; if (rootType != null) { const typeName = rootType.name; const fields = rootType.getFields(); resolvers[typeName] = {}; Object.keys(fields).forEach(fieldName => { const proxyingResolver = createProxyingResolver({ schema: subschemaOrSubschemaConfig, transforms, transformedSchema, operation, fieldName, }); const finalResolver = createPossiblyNestedProxyingResolver(subschemaOrSubschemaConfig, proxyingResolver); resolvers[typeName][fieldName] = { [resolveField]: finalResolver, }; }); } }); return resolvers; } function createPossiblyNestedProxyingResolver( subschemaOrSubschemaConfig: GraphQLSchema | SubschemaConfig, proxyingResolver: GraphQLFieldResolver<any, any> ): GraphQLFieldResolver<any, any> { return (parent, args, context, info) => { if (parent != null) { const responseKey = getResponseKeyFromInfo(info); const errors = getErrors(parent, responseKey); // Check to see if the parent contains a proxied result if (errors != null) { const subschema = getSubschema(parent, responseKey); // If there is a proxied result from this subschema, return it // This can happen even for a root field when the root type ia // also nested as a field within a different type. if (subschemaOrSubschemaConfig === subschema && parent[responseKey] !== undefined) { return handleResult(parent[responseKey], errors, subschema, context, info); } } } return proxyingResolver(parent, args, context, info); }; } export function defaultCreateProxyingResolver({ schema, transforms, transformedSchema, }: ICreateProxyingResolverOptions): GraphQLFieldResolver<any, any> { return (_parent, _args, context, info) => delegateToSchema({ schema, context, info, transforms, transformedSchema, }); }
Spot size, distance and emissivity errors in field applications of infrared thermography Infrared thermography is increasingly emerging as an analytical approach within the thermal ecology research community, providing unique and rapid temperature information crucial to understanding how plants and animals exchange heat with their environment. What is difficult to appreciate are the numerous ways in which thermography may still yield inaccurate (i.e. deviation from the correct value) information if certain tenets are not followed. In this paper, we examine, demonstrate and discuss these tenets with an aim to provide methodological advice to ecologists interested in employing thermography. We found that spot size and distance strongly influenced the surface temperature estimates of known, calibrated temperature sources, with similar results observed in maximum eye temperature measurements in wild birds. We also report on how the angle of incidence affects the apparent emissivity of various biological surfaces (fur, feather, skin, leaves), another source of uncertainty in thermography. The variation in temperature caused by variation in distance and uncertainty in emissivity are large enough to raise flags for field applications of thermography where accuracy is necessary but control over study subjects is limited. Since accurate emissivity and distance parameters are crucial to thermography calculations, our results should serve as a framework to assist ecologists in better experimental design with respect to the use of thermography.
/* * Janino - An embedded Java[TM] compiler * * Copyright (c) 2001-2010 <NAME>. All rights reserved. * Copyright (c) 2015-2016 TIBCO Software Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.codehaus.janino.util.iterator; import java.util.Iterator; /** * An {@link java.util.Iterator} that transforms its elements on-the-fly. * * @param <T1> The element type of the delegate iterator * @param <T2> The element type of this iterator */ public abstract class TransformingIterator<T1, T2> implements Iterator<T2> { private final Iterator<? extends T1> delegate; public TransformingIterator(Iterator<? extends T1> delegate) { this.delegate = delegate; } @Override public boolean hasNext() { return this.delegate.hasNext(); } @Override public final T2 next() { return this.transform(this.delegate.next()); } @Override public void remove() { this.delegate.remove(); } /** * Derived classes must implement this method such that it does the desired transformation. */ protected abstract T2 transform(T1 o); }
<filename>record/record.go package record import ( "bufio" "bytes" "encoding/base64" "errors" "fmt" "regexp" "strings" ) const ( // index number of record N_HostName = 0 N_IP = 1 N_Score = 2 N_Ping = 3 N_Speed = 4 N_CountryLong = 5 N_CountryShort = 6 N_NumVPNGateSessions = 7 N_Uptime = 8 N_TotalUsers = 9 N_TotalTraffic = 10 N_LogType = 11 N_Operator = 12 N_Message = 13 N_OpenVPNGate_ConfigData_Base64 = 14 ) var ( reSpace = regexp.MustCompile(`\s+`) ) var ( ConfigKeys = []string{ "dev", "proto", "remote", "resolv-retry", "nobind", "persist-key", "persist-tun", "cipher", "auth", "verb", } ) type Record struct { record []string config map[string][]string } // Len func (r Record) Len() int { return len(r.record) } // Get func (r Record) Get(index int) string { return r.record[index] } // Config get the value of given key. See var ConfigKeys for a list of valid keys func (r Record) Config(key string) ([]string, bool) { v, ok := r.config[key] return v, ok } // Data return the decoded data from base64 to be the contents of the .ovpn file. func (r Record) Data() []byte { data, _ := decodeBase64([]byte(r.record[N_OpenVPNGate_ConfigData_Base64])) return data } // Record return the items of CSV in slice func (r Record) Record() []string { return r.record } // FileName return the file name create based on config data func (r Record) FileName() string { hostname := "unknown" if v := r.record[N_HostName]; len(v) > 0 { hostname = v } filename := "vpngate_" + hostname + ".opengw.net" if v, ok := r.config["proto"]; ok { if len(v) > 0 && len(v[0]) > 0 { filename += "_" + v[0] } } if v, ok := r.config["remote"]; ok { if len(v) > 1 && len(v[1]) > 0 { filename += "_" + v[1] } } return filename + ".ovpn" } // New func New(row []string) (*Record, error) { if len(row) < N_OpenVPNGate_ConfigData_Base64+1 { return nil, errors.New("insufficient csv row") } r := &Record{ record: row, config: make(map[string][]string, len(ConfigKeys)), } for _, k := range ConfigKeys { r.config[k] = nil } if err := r.mapping(); err != nil { return nil, fmt.Errorf("mapping: %v", err) } return r, nil } func decodeBase64(src []byte) ([]byte, error) { data := make([]byte, base64.StdEncoding.DecodedLen(len(src))) n, err := base64.StdEncoding.Decode(data, []byte(src)) if err != nil { return nil, err } return data[:n], nil } func (r *Record) mapping() error { data, err := decodeBase64([]byte(r.record[N_OpenVPNGate_ConfigData_Base64])) if err != nil { return fmt.Errorf("decodeBase64: %v", err) } s := bufio.NewScanner(bytes.NewReader(data)) // <ca></ca> // <cert></cert> // <key></key> for i := 0; s.Scan(); i++ { t := strings.TrimSpace(s.Text()) if t == "" || strings.HasPrefix(t, "#") { continue } for _, k := range ConfigKeys { if strings.HasPrefix(t, k) { a := reSpace.Split(t, -1) if len(a) > 1 { r.config[k] = a[1:] } } } } return s.Err() }
Notes on Contributors Hlne Bowen Raddeker is the author of Treacherous Women of Imperial Japan and Sceptical History: Feminist and Postmodern Approaches in Practice. She is based in the School of History and Philosophy at University of New South Wales where she teaches premodern and modern Japanese history, world gender history, and the history of feminism; and also often convenes the Womens and Gender Studies program.
Aggregatibacter aphrophilus infective endocarditis confirmed by broad-range PCR diagnosis: A case report Highlights Case of infective endocarditis caused by a rare pathogen, Aggregatibacter aphrophilus is presented. Aggregatibacter aphrophilus cant be detected by common culture methods. Br-PCR testing is a useful tool to identify pathogens of culture negative endocarditis. Serum PR3-ANCA can be positive in Aggregatibacter aphrophilus endocarditis. Introduction For the successful treatment of infective endocarditis (IE), identification of the causative pathogens is crucial. However, conventional culture methods often fail to reveal the correct diagnosis in patients with IE because of prophylactic use of antibiotics before diagnosis or because the pathogen is difficult to culture. Among the organisms that cause IE, 3%-10% are reportedly culture-negative. A molecular technique that combines broad-range polymerase chain reaction (br-PCR) amplification and direct sequencing is useful for detecting pathogens in patients with culture-negative endocarditis. Aggregatibacter aphrophilus is one of the typical culture-negative species that can cause IE. Due to the rarity of the organism and the difficulty of identification, the clinical features and outcomes of Aggregatibacter aphrophilus IE are not fully understood, leading to incorrect diagnoses. Here, we report a case of IE caused by Aggregat-Abbreviations: IE, infective endocarditis; br-PCR, broad-range polymerase chain reaction; PR3-ANCA, serum proteinase 3 anti-neutrophil cytoplasmic antibody. * ibacter aphrophilus that was detected with br-PCR and successfully treated with surgical repair and appropriate antibiotic therapy. Presentation of case A 72-year-old woman was admitted to a community hospital with a persistent high fever. She also had hematuria with rapidly deteriorating renal function for which hemodialysis had been performed. Renal biopsy revealed crescentic glomerulonephritis and serum proteinase 3 anti-neutrophil cytoplasmic antibody (PR3-ANCA) testing was positive. ANCA-associated vasculitis was therefore suspected as the cause of renal dysfunction and oral prednisolone was initiated. However, the patent developed heart failure soon afterward. Echocardiography showed vegetation near the anterior commissure of the mitral valve as well as a perforation in part of the anterior leaflet, with severe regurgitation (Fig. 1). In addition, brain MRI revealed mycotic cerebral embolism with accompanying hemorrhage, although the patient did not display obvious neurological symptoms (Fig. 2). Laboratory testing revealed an increased peripheral leukocyte count of 19,800 cells/mm 3 and an elevated C-reactive protein level of 10.8 mg/dL. At this point, IE appeared to be the probable diagnosis. However, no pathogen was detected in repeated blood cultures. Administration of broad-spectrum antibiotics (vancomycin hydrochloride and ceftriaxone sodium) was therefore started empirically. After the patient was referred to our hospital, mitral valve repair was performed. During surgery, a 1-cm diameter of spherical vegetation was found attached to the anterior commissure of the mitral leaflet (Fig. 3). The anterior commissure leaflet was resected, together with the vegetation, followed by patch repair with autologous pericardium and mitral annuloplasty using a 28-mm prosthetic ring (Physio II ring, Carpentier Edwards). Intraoperative transesophageal echocardiography showed no mitral regurgitation after the repair. Because cultures of the removed mitral valve and vegetation were negative, we performed br-PCR to identify microorganisms based on partial sequences of divergent regions of the 16S rRNA gene for bacteria, as follows (Fig. 4). Total DNA was purified from the tissue with the QIAamp DNA Mini Kit (Qiagen, Hilden, Germany). We used 10F/800R primers to analyze a former part of 16S rRNA for bacteria and then performed 30 amplification cycles at 94 C for 30 s, 55 C for 60 s, and 72 C for 60 s. This process amplified 772 bp DNA fragments. The PCR products were labeled with sequencing reagents and placed in the DNA sequencer. The nucleotide sequences of the PCR products were read and compared with the DNA Data Bank of Japan (http://www.ddbj.nig.ac. jp/), which revealed that the PCR products significantly matched the nucleotide sequences of Aggregatibacter aphrophilus. Vancomycin administration was discontinued after identification of the pathogen; ceftriaxone was continued intravenously for 4 weeks after surgery to prevent recurrence of infection. The patient was transferred to the referring hospital without any complications to continue rehabilitation. Serum PR3-ANCA was negative at the time of transfer and the patient's renal function had recovered. No sign of recurrence of endocarditis has been detected to date. Discussion Aggregatibacter aphrophilus was first described in 1940 by Khairat and colleagues and is currently categorized as a member of the HACEK group of bacteria (Haemophilus species, Aggregatibacter species, Cardiobacterium hominis, Eikenella corrodens, and Kingella species). HACEK bacteria are commonly recognized as part of normal oral flora, but are relatively rare as a cause of IE, accounting for only 1% to 3% of IE cases. Aggregatibacter aphrophilus IE is especially rare, limited to a few case reports. HACEK bacteria are one cause of culture-negative endocarditis because the species are difficult to identify with normal blood culture methods. Given these circumstances, the clinical features and outcomes of Aggregatibacter aphrophilus endocarditis have not been fully described. Chambers and colleagues reported 77 cases of HACEK endocarditis; cerebral embolism occurred in 19 of these patients, including cerebral hemorrhage in eight. They concluded that the rate of cerebral complications was higher in HACEK endocarditis than in non-HACEK endocarditis. The reasons for this difference are not clear. However, glomerulonephritis and positive rheumatoid factor are more frequently observed in HACEK endocarditis, suggesting that a more frequent microvascular/immunological response in these patients might contribute to the development of cerebral microbleeds and subsequent intracranial hemorrhage. Cerebral embolism accompanied by hemorrhage did occur in our patent. PR3-ANCA are important diagnostic markers for small-vessel vasculitic syndromes (e.g. granulomatosis with polyangiitis, microscopic polyangiitis, eosinophilic granulomatosis and polyangiitis), which are commonly referred to as ANCA-associated vasculitis. However, several infectious diseases, particularly IE, may have positive ANCA tests and mimic ANCA-associated vasculitis, leading to potential misdiagnosis and inappropriate treatment. To date, no report has described the pathogenicity of ANCA in IE. However, Ying et al. reported that ANCA reflects systemic inflammation rather than IE activity. In that report, white blood cell counts tended to be higher and LDH levels were higher in those with ANCApositive IE than in those with ANCA-negative IE. In another study, serum levels of rheumatoid factor and IgG were higher in patients with ANCA-positive IE than in those with ANCA-negative IE. These reports suggest that ANCA-positive IE is likely an atypical immune response to infection. Similarly, the serum PR3-ANCA test was positive in our patient, but this did not indicate ANCAassociated vasculitis. It is rare that PR3-ANCA testing is positive in patients with culture-negative endocarditis. To the best of our knowledge, there has been no previous report of positive PR3-ANCA in a patient with IE caused by Aggregatibacter aphrophilus. These rare circumstances may have made the correct diagnosis more difficult at the referring hospital. Typically Aggregatibacter aphrophilus is part of the normal oral flora, frequently found in dental plaque and gingival scrapings. Dental procedures, tongue piercings, use of tongue scrapers, and recent upper respiratory tract infection are known causes of bacterial entry into the bloodstream. Our patient did not report any of these factors. However, she had poor dental condition, including tooth decay, which possibly induced transient bacteremia. We speculate that this is the most plausible source of infection in her case. Our treatment method for Aggregatibacter aphrophilus endocarditis was similar to the treatment of endocarditis caused by other organisms. The patient received antibiotic treatment with ceftriaxone for a total of 8 weeks in accordance with antibiotic susceptibility and published guidelines. Identification of the causative pathogen is very important for successful treatment of IE. However, blood cultures can some-times be negative because of preceding antibiotic treatment or pathogens such as HACEK bacteria that are difficult to detect with common culture methods. The br-PCR method, which overcomes these problems, has recently been reported to be helpful in the diagnosis of IE and can improve antibiotic treatment, particularly in cases of culture-negative IE. The method includes universal PCR for the 16S rRNA gene, with subsequent sequence analysis of the amplicons and comparison with the DNA database. Our patient's repeated blood cultures were negative despite echocardiographic evidence of a mobile mass and valve destruction, which strongly suggested active IE. We therefore decided to identify the causative bacterium using the br-PCR method and successfully diagnosed IE caused by Aggregatibacter aphrophilus. In suspected cases of culture-negative IE, br-PCR tests should be immediately performed because correct identification of the causative pathogen helps determine an appropriate management plan and can lead to better outcomes. In this case, however, there was a time lag between the diagnosis of IE and the identification of the causative pathogen because an initial diagnosis of ANCA-associated vasculitis was made and steroid therapy was initiated at the community hospital. Fortunately, ceftriaxone, to which Aggregatibacter aphrophilus shows sensitivity, had already been administered empirically before surgery, which also contributed to a positive outcome. Conclusion In summary, Aggregatibacter aphrophilus endocarditis was successfully treated with excision of the vegetation followed by mitral valve repair and ceftriaxone infusion. Aggregatibacter aphrophilus endocarditis can cause positive PR3-ANCA tests and can mimic ANCA-associated vasculitis. Br-PCR analysis can help to diagnose IE and to identify causative pathogens such as Aggregatibacter aphrophilus, which are rare and difficult to detect with normal culture methods. Conflict of interest None. Funding None. Ethical approval The case report was approved by the ethics committee at Japan Red Cross Ise Hospital. Consent Written informed consent was obtained from the patient for publication of this case report and accompanying images. A copy of the written consent is available for review by the Editor-in-Chief of this journal on request. Author contribution KH and TT conceived of this case presentation and drafted the manuscript. MI, TF, YM and HT participated in the treatment of this case. All authors read and approved the final manuscript. Guarantor Koji Hirano have acceptful responsibility for this work and controlled the decision to publish.
import debug from 'debug'; import plimit from 'p-limit'; import { ElectronVersions, Installer, Runner as FiddleRunner, } from 'fiddle-core'; import { Runner } from './runner'; const d = debug('runner'); async function prefetch() { const installer = new Installer(); const ev = await ElectronVersions.create(); const { versions } = ev; const limit = plimit(5); await Promise.allSettled( versions.map((version) => limit(() => installer.ensureDownloaded(version.version)), ), ); } async function main() { if (process.argv.some((arg) => arg === '--prefetch')) return void prefetch(); try { const fiddleRunner = await FiddleRunner.create({}); const bugbotRunner = new Runner({ fiddleRunner }); await bugbotRunner.start(); } catch (err) { d('encountered an error: %O', err); console.error('execution stopped due to a critical error', err); process.exit(1); } } void main();
n = int(raw_input()) L = [True for i in range(n)] L[0] = False I = [None]*n for i in range(n-1): c = int(raw_input()) L[c-1] = False I[i+1] = c-1 leaf = [] parent = [] for i in range(n): if L[i] : leaf.append(i) else: parent.append(i) cnt = [0 for i in range(n)] for i in leaf: cnt[I[i]] += 1 ans = True for i in parent: if cnt[i] < 3 : ans = False if ans : print "Yes" else: print "No"
Analysis of Micro-grid power supply reliability Micro-grid is the technique which could access the utility grid with combined renewable energy generation resources, loads, energy storage devices and control devices. It is generally agreed that, Micro-grid could reduce or avoid the impact of wide range failure to the users and improves the power supply reliability. This paper proposed a Monte Carlo method to evaluate the reliability of Micro-grid. A Micro-grid example which includes energy storage devices, distributed wind turbines, solar arrays and time-varying loads is built in this paper and the corresponding reliability indices are calculated.
/** * Wrap a previously initialised repository in an ObjectRepository. */ public ObjectRepository createRepository(ObjectRepositoryConfig config, Repository delegate) throws RepositoryConfigException, RepositoryException { ObjectRepository repo = getRepository(config, delegate.getValueFactory()); repo.setDelegate(delegate); return repo; }
declare const fromHexString: (hexString: string) => Uint8Array; declare const toHexString: (byteArray: Uint8Array) => string; export { fromHexString, toHexString };
Dispute Resolution in the Islamic Finance Industry A unique and independent legal framework is important to effectively adjudicate Islamic finance disputes, Sukuk bankruptcies, and Takaful disputes. Currently, these disputes are being adjudicated in common law courts or ineffective arbitration centres where often the Islamic finance transaction is inadvertently converted into a conventional transaction due to the common law nature of the dispute adjudication. In this chapter, a framework is proposed for Islamic finance dispute resolution in the form of the Dubai World Islamic Finance Arbitration Centre (DWIFAC), DWIFAC Jurisprudence Office, the Sukuk Bankruptcy Tribunal (SBT) and the Takaful Tribunal (TT).<br>
<gh_stars>1-10 heroes_dict = {h: {"Items": [], "Cost": 0} for h in input().split(', ')} while True: line = input() if line == 'End': break hero, item, cost = line.split('-') cost = int(cost) if item not in heroes_dict[hero]['Items']: heroes_dict[hero]['Items'].append(item) heroes_dict[hero]['Cost'] += cost for h, h_dict in heroes_dict.items(): print(f'{h} -> Items: {len(h_dict["Items"])}, Cost: {h_dict["Cost"]}')
Patterns of injuries and predictors of inhospital mortality in trauma patients in Saudi Arabia Background The aim of this study was to describe the pattern of traumatic injuries and determine the predictors of inhospital mortality in patients admitted to the emergency department. Patients and methods This is a retrospective cohort study of 3,786 patients with traumat injuries admitted to the emergency department of King Abdulaziz Medical City, Riyadh, Saudi Arabia, between January 2012 and December 2014. Data on patient characteristics, trauma characteristics and outcomes were extracted from medical records. A negative binomial regression model was utilized to identify significant predictors of inhospital mortality. Results Of all injured patients, 77.5% were male, 29.8% were aged 1525 years and 25.7% were aged 2645 years. Blunt trauma was the main mechanism of injury, including motor vehicle crashes (MVCs) in 52.0% and falls in 25.8% of patients. Most patients had injuries to the extremities (61.3%), followed by the head (32.2%), chest (16.9%) and abdomen (8.9%). Injuries were mild in 49.7% of patients, moderate in 30.2% and severe in 20.1%. The sex of the patients was significantly associated with the mechanism of injury (p<0.001), severity (p<0.001), anatomical site of injury (p<0.001), admission to the intensive care unit (p<0.001), need for trauma team activation (p<0.001) and type of transportation to hospital (p<0.001). The predictors of inhospital mortality were age (rate ratio for each 10-year increase=1.174; p<0.001), falls and burns (RR=2.337 and 1.728; p<0.001) and moderate and severe injuries (RR=6.438 and 181.780; p<0.001). Conclusion Our results suggest different patterns of trauma injuries according to patient age and sex. MVCs were the leading cause of injuries, but falls and burns had the highest inhospital mortality. This suggests the need for a comprehensive national education and prevention programs that address all causes of injuries. Introduction Injuries result in 16,000 deaths per day and more than 5 million deaths per year. 1,2 They are one of the major causes of death worldwide and result in temporary or permanent disability with consequential social and economic impact. The leading causes of injury-related deaths include road traffic injuries (RTIs), interpersonal and self-inflicted violence, drowning, burns, poisoning and falls. 2 Over the past decade, there has been a decline in traumatic injuries; however, the patterns vary widely by cause, age, sex and region. 3 This decline is due to major efforts in tailored preventive programs that have been developed to address major underlying causes of injuries. For instance, US has made tremendous progress in reducing falls and traffic-related injuries and fatality in recent decades. 4 This was possible via successful implementation and execution of preventive strategies and programs such as Stopping Elderly Accidents, Deaths and Injuries (STEADI) deployed by the US Center for Disease Control. 5 In Saudi Arabia, RTIs account for more than 80% of all trauma admissions. 6 In 2010, RTIs ranked second in the main causes of daily adjusted life years in Kingdom of Saudi Arabia (KSA), after major depressive disorder, and the third leading cause of death, accounting for 11.75% of total mortality. 7 The Ministry of Health, in collaboration with the Ministry of Interior, launched a road safety program called Saher in 2009, 8 which is an automated system developed to manage traffic via electronic systems in major cities in Saudi Arabia. This system uses a digital camera network connected to the National Information Center to track any violations and to control traffic. Alghnam et al 9 reported significant reductions in the severity and mortality of motor vehicle crash (MVC)-related injury following the implementation of this system. Saudi Arabia has also enforced seat belt law from December 5, 2000, making its use compulsory for all drivers and front seat passengers. 10,11 Despite this remarkable progress on combating RTI, unfortunately there have been very few programs addressing other causes of injuries such as falls, burns and intentional injuries. The burden of injuries in terms of morbidity, disability and mortality is augmented by injuries other than RTIs. This is especially important given the fact that the life expectancy of Saudi population is in a dramatic increase during the past few decades. This change in population structure is likely to lead to changes in patterns of trauma injuries and mortality. 12,13 To properly plan for comprehensive education and prevention programs to combat trauma of causes other than MVCs, studies are needed to understand their patterns. Thus, the aim of this study was to describe the pattern of traumatic injuries and predictors of in-hospital mortality in patients admitted to the emergency department of King Abdulaziz Medical City (KAMC), Riyadh, Saudi Arabia, between January 2012 and December 2014. Patients and methods The study was carried out at the Emergency Care Center (ECC) of KAMC, a 900-bed tertiary-care Joint Commission International-accredited academic center. The ECC of KAMC is the largest in Riyadh and has 132 beds. The ECC provides free, high-quality emergency care for National Guard employees, their families and anyone who is critically ill or injured and seeks care. The ECC receives approximately 32,000 visits per year and also serves as a referral trauma center for patients across the entire KSA. This study was approved by the institutional review board (IRB) of the Ministry of National Guard-Health Affairs (MNG-HA) in Riyadh, Saudi Arabia (ref no. RSS15/003). Study design This is a retrospective cohort study of 3,786 patients with trauma injuries who were admitted to the ECC between January 2012 and December 2014. Data collection Data were extracted from electronic medical records and patient charts. Patient characteristics included age and sex. Trauma characteristics included the type and mechanism of injury, Injury Severity Score (ISS), adult trauma score and trauma team activation. Outcomes included inhospital mortality, hospital disposition, emergency room (ER) disposition and length of stay (LOS). Injuries were assessed and classified according to the ISS, Glasgow Coma Scale (GCS) 17,18 and Revised Trauma Score (RTS). 19 The injury type was classified as blunt, burn/ scald or penetrating (gunshot/stab wound or others). The injury mechanism was classified into one of the five groups: motor-vehicle-related injuries (including MVCs and injuries to pedestrians and motorcycle riders), burns (either from fire, flame or liquid), falls, intentional injuries (comprising selfinflicted and suicidal injuries, and injuries purposely inflicted by others, such as homicidal injuries) and other injuries. This last group included drowning/submersion, suffocation and foreign body-mediated injuries. In our hospital, trauma activation is based on a complex algorithm that involves the sequential assessment of several criteria of physiological, anatomical, mechanism of injury and logistical domains. The ER LOS was defined as the time spent from the patient's arrival at the ER until disposition to the intensive care unit (ICU), burn unit, morgue, operating room or ward. The hospital LOS was the time from ER disposition until discharge. The ICU LOS was the time spent in the ICU following disposition from the ER. All data were collected after obtaining the approval of the IRB of the MNG-HA (ref no. RSS15/003). Consent was deemed not applicable by IRB due to the fact that all data utilized in this study were extracted retrospectively from the hospital health information system. Statistical analyses All categorical variables were summarized and reported in terms of frequency and proportion, and continuous variables were summarized and reported in terms of mean and SD. 91 Traumatic injuries in trauma patients in Saudi Arabia Categorical variables were compared using Chi-square and Fisher's exact tests, as appropriate. Continuous variables, including ISS, GCS score, RTS and LOS, were compared using Student's t-tests. To determine the predictors of inhospital mortality, we analyzed mortality by generalized linear models with log link function and negative binomial distribution. Mortality was included as the dependent variable, and age in years, ISS, sex and mechanism of injury were included as independent variables. The results were reported in terms of rate ratio (RR) and the corresponding 95% CI. Statistical significance was determined at a type I error rate of 0.05. All analyses were performed with SPSS version 21 (IBM Corporation, Armonk, NY, USA). Results The study population consisted of 3,786 patients presenting with injuries during a period of 3 years, 77.5% of whom were male. A little less than one third (29.8%) of patients were aged 15-25 years and 25.7% were aged 26-45 years. The mean age of female patients (33.7 years) was significantly higher than that of male patients (28.4 years, t=5.39, p<0.001; Table 1). The majority of traumatic injuries were from blunt trauma in the form of MVCs (52.0%) and falls (25.8%). Injuries from MVCs made up a higher proportion of all injuries in males (57.1%) than in females (34.4%), whereas injuries from falls among females (42.7%) were double that of males (20.9%). Burn/scald injuries have only accounted for 6.8% of all injuries, equally distributed between burns due to fire flames (n=134, 51.9%) and burns due to liquid (n=124, 48.1%). Intentional injuries accounted for 5.1% of all injuries in the form of homicide injuries and injuries purposely inflicted by others (4.8%) and suicide and self-inflicted injuries (0.3%; Table 1). The injuries were affecting a total of 4,519 anatomical sites, as they could affect more than one site in each patient. Injuries to the extremities affected 61.3% of patients, followed by injuries to the head (32.2%), chest (16.9%) and abdomen (8.9%). The proportions of males affected by head, chest and abdomen injuries were significantly higher than those of females (p<0.001 each; Table 1). The distribution of different types of traumatic injury according to sex and age of the patients is shown in Figure 1. Injuries resulting from MVCs were the main type overall in males, whereas fall-related injuries were most common among females. In the 0-4-year age group, injuries were distributed fairly evenly between four types (MVCs, falls, burns and others). Injuries resulting from MVCs made up progressively higher proportions of the total as age increased, up to maximum rates in the 15-25-year age group (70.3% in men and 59.8% in women); the rates then fell as age increased further. The proportions of injuries resulting from falls decreased as age increased up to the 15-25-year age group, then increased through all higher age groups, reaching maximum rates in individuals aged ≥65 years (53.3% in men and 87.0% in women). Injuries from burns and scalding formed a much higher proportion of all injuries in the 0-4year age group than in other groups ( Table 1). As summarized in Table 1, 49.7% of all injuries were mild in severity, 30.2% were moderate and 20.1% were severe. The proportions were significantly different in males and females with higher rates of severe injuries in males and higher rates of mild injuries in females (p<0.001). Among all injured patients, 56.3% were disposed from ER to the wards. The patterns of disposition were significantly different in males and females (p<0.001). The sex of the patients was also significantly associated with the requirement for trauma team activation, the need for ICU admission and the mode of transportation to the ER (all p<0.001). The pattern of severity was different across the mechanism of injury by sex, where severity was significantly higher in males than in females, in injuries caused by MVCs (p=0.009) and in intentional injuries (p=0.004), as shown in Figure 2. As summarized in Table 2, 178 patients (4.8%) died in hospital, with 32.0% of those deaths occurring in patients aged 26-45 years, 89.3% in patients with severe injuries, 69.7% in patients with head, neck and face injuries, 97.0% in patients who required ICU admission, 69.1% in patients transported by ambulance and 65.2% in patients who required trauma team activation. Inhospital mortality (as a percentage of patients in each age group) increased significantly with age (Chi-square for linear trend=17.51, p<0.004). The difference in mortality rate between males and females was only significant in the 26-45-year age group (p=0.029). The highest rates of mortality were among patients with head, neck or face injuries (10.2%), burn injuries (9.7%) or severe injuries (20.9%) and those who needed trauma team activation (13.9%), transportation by Medevac (13.5%) or ICU admission (12.6%). In a multivariable regression model, age, severity of injury and mechanism of injury were the significant predictors of inhospital mortality ( Discussion In the current study, of 3,786 injured patients admitted to ER during the period of 3 years, the majority were injured 93 Traumatic injuries in trauma patients in Saudi Arabia by MVCs, accounting for more than one-half of all injuries, followed by falls, accounting for one-fourth of all injuries. Other injuries were due to burn/scald as well as intentional injuries. Inhospital mortality rate in the current study was 4.8%, a figure that is lower than that of the National Center for Technology Planning (NCTP) population (9.5%) 20 and that reported by Abbasi et al 21 24 Inhospital mortality from trauma is influenced by the cause of injury, age and injury body areas. In our study, the predictors of inhospital deaths in trauma patients were as follows: age, mechanism of injury and severity. Injuries were more prevalent among young subjects aged 15-45 years, yet the incidence of mortality was the highest in geriatric subjects, where it reached threefold. In our study, controlling for sex, severity and mechanism of injury, age was independently associated with increased fatality, where every 10 years of age resulted in 17% increase in fatality rate. This could be attributed to the presence of comorbidities and post-injury complications, 29 which were not measured in our study. However, it has been reported that the presence of multiple comorbidities is not necessarily an indicator of poor outcome. 30,31 MVCs were the leading cause of injuries, in our study, being responsible for 52% of all injuries. This figure is five times higher than the global figure of 12% reported by Haagsma et al. 3 Underlying reasons leading to such high figures are not clear, but several studies have implicated 96 Abolfotouh et al high speed, driver errors and lack of basic skills for safe driving and lack of law enforcement. These injuries were significantly higher among males than females, possibly due to their greater exposure of driving and other risk-taking behaviors. 35,36 Injuries due to MVCs in our study accounted for two-thirds of inhospital deaths, which is more than double the global figure of 31%, 3 but consistent with those of other studies in the region. The case fatality from MVCs is twofold to threefold higher in males than in females in developing countries. 41 Yet, in our study, there was no sex difference in case fatality from MVCs, in spite of the fact that severity in male patients with MVC-related injuries was higher than in females. This is probably due to the fact that females were older than males. In our study, falls trail MVCs as the second major mechanism of injury, responsible for one-fourth of all injuries, with the highest rates among younger children and older females. This figure is 57% higher than the global reported figure of 16%. In a previous study, 42 men and women were at equal risk of fall-related injuries, irrespective of age groups and regions. However, in our study, the percentage of falls in females was double that of males. It has been reported that mortality rates from fall-related injuries were higher among males in the low-and middle-income countries. 43 However, in our study, there was no significant sex difference in mortality rate from these injuries. Women and young children are at greater risk of domestic burns. 42 Burn, in our study, was responsible for only 6.8% of all injuries; yet, it was the cause of 14% of all deaths, with its highest case fatality rate of 9.7%. Burn-related injuries, in our study, were higher among children aged 0-4 years, with no sex difference. Several studies have reported higher mortality rates from burn injuries among females than males. However, no such sex difference was shown in our study. On the other hand, intentional injuries accounted for 5.1% of all injuries, yet it accounted for only 1.2% of injuries among females with the highest case fatality rate of 22.2%, reflecting the higher severity of intentional injuries among females, as compared to males (p=0.004). Globally, most traumatic injuries are minor and the most patients are discharged directly from the emergency department. In the current study, minor injuries constituted onehalf of all injuries, while severe injuries constituted 20.1%. Injuries in the current study were significantly more severe among males than females, specifically in MVC-related injuries, and this may explain the significantly higher need, by males, for ambulance transportation, disposition from ER to OR as well as ICU admission. Severity was independently associated with higher rates of inhospital mortality which is consistent with findings from other studies. In our study, controlling for age, sex, severity of injury, victims of falls and burns/scalds had higher inhospital mortality rates than victims of MVCs. This finding is inconsistent with results reported from other studies. 13 This finding is alarming and may highlight potential differences in the care provided to those patients. Our results may be explained by the fact that ISS score does not capture inherent features of fatality induced by different mechanisms of injury in our setting. Head injuries are one of the most common injuries sustained by patients after MVCs in adults 51,52 and children. 53,54 Head injuries in our study accounted for 32.2% of all injuries. However, they were the cause of death in 70% of all deaths. This finding was even higher than a figure of 54.4% in Greece, 55 which has one of the highest death rates after MVCrelated injuries in the European Union. 56 Head injuries were significantly higher in males than in females, possibly due to higher rate of MVCs among males. Moreover, in MVCs, women are at a greater risk of injuries to lower extremities due to their smaller stature. 57 In our study, head, chest and abdomen injuries were significantly higher among males than among females, but injuries of the extremities showed no sex difference. Female sex was an independent predictor of mortality in isolated severe traumatic brain injury 58 due to differential response of nervous system toward this injury. 59 However, in our study, case fatality rate in head injuries was not different in males and females, and this finding is in agreement with the findings of others. 60 Further studies are necessary to delineate sex-related factors that contribute to these disparities. 97 Traumatic injuries in trauma patients in Saudi Arabia Limitations Our study has some limitations due to its retrospective design. First, the setting of our study is one of the largest referral trauma centers in the KSA, therefore, the observed trauma severity pattern in our study might not reflect the pattern in the whole kingdom. Second, the standard of care provided in this tertiary center might differ from that in other health care settings in Saudi Arabia. Third, we did not have access to information such as time to arrival which is a possible predictor of inhospital mortality. Therefore, our study might not reflect the full spectrum of the inhospital mortality predictors. Finally, although mortality is an important indicator of the magnitude of the trauma burden, for each death due to injury, many more survivors are left with permanent disabling sequelae. This is especially important given that about 85% of our study population were of mild-to-moderate severity with low mortality rates. We did not have access to long-term outcomes to depict the full picture of the trauma burden. Further studies are needed to look into the long-term outcome of trauma patients especially in these groups. Conclusion This study highlights the different patterns of traumatic injuries across age and sex. RTIs are the major contributor to injuries in middle age, while falls dominate the young and old age. Inhospital mortality varies by the pattern of injury with the highest among victims of falls and burns. This suggests the need for a comprehensive national education and prevention programs that address all causes of injuries. Data sharing statement Most of the data supporting our findings is contained within the manuscript, and all others, excluding identifying/confidential respondent data will be shared upon request from the corresponding author.
RIGA - There are around 1,400 foreign NATO soldiers serving in Latvia at the moment, and the number is expected to further increase. The Canada-led multinational NATO battle group is 1,300 strong. The battle group, stationed at Adazi military base, is made up of Canadian, Albanian, Czech, Italian, Polish, Slovakian, Slovenian and Spanish soldiers. The battalion is supported by different fighting vehicles and tanks, the Defense Ministry's Press Department told LETA. Following the annexation of Crimea in 2014, the United States was sending, on a rotational basis, different units to Latvia, including with heavy equipment. After the multinational NATO battalion arrived in Latvia, the United States' presence was reduced and at the moment there are 70 U.S. soldiers with five Black Hawk helicopters serving at Lielvarde Air Force Base, the ministry said. NATO Force Integration Unit in Riga was established in 2015. Half of 40 positions at the unit are filled by representatives from 12 NATO countries - Belgium, Canada, Denmark, Germany, Netherlands, Norway, Poland, Spain, Turkey, Great Britain and the United States, and the other half by Latvian personnel. The number of allied troops deployed to Latvia is expected to further increase in the future. As reported, Canadian Prime Minister Justin Trudeau said during a visit to Riga in early July that Canada would extend its leadership of the NATO battle group based in Latvia for another four years until March 2023, and increase the number of Canadian troops in Latvia from 455 to 540. The defense ministers of Latvia, Denmark, Estonia, Canada, Great Britain and Lithuania earlier this month signed a letter of intent on the establishment of the headquarters of NATO Multinational Division North. The headquarters' framework nations are Denmark, Estonia and Latvia. The division headquarters will be tasked with having a continuous operational overview of the developments in the region, commanding the brigades subordinated to it, coordinating, planning and synchronizing training exercises and operations with different authorities and neighboring units. It will be also tasked with conducting the training of the units subordinated to it and ensuring comprehensive support for them.
Emotional geographies of irregular transmigrants journeys Migrants journeys involve geopolitical, corporeal, and emotional dimensions. Yet, emotions, which are fundamental to understand the migrant experience, are usually overlooked. Following the emotional geographies approach, this article analyses the spatial contextualisation of the affective and emotional experiences of irregular migrants in transit. Cognitive mapping methodology is proposed as a means to address the spatial and subjective dimensions of migrants experiences. The testimonial maps of two Central American transmigrants in Mexico are explored. The emotional geographies of irregular transmigration underscore the emotional turmoil associated with the irregular migratory process(es). They shed light to the familiar arrangements made before the journey, the natural landscape as part of the control, the encounters with agents of the state and criminal actors, the sanctuary places, the acquaintances and fortuitous friendships, the resilience and adaptability needed for endure the journey, and, beneath all this, the multi-emotional dimension of the journey: love, sorrow, shame, courage, anxiety, fear, trust, kindness, and hope.
def load_component(component_clz, context, config): if component_clz is not None: load_args = fill_args(component_clz.load_args(), context, config) return component_clz.load(*load_args) else: return None
Performance Analysis and Uplink Scheduling for QoS-Aware NB-IoT Networks in Mobile Computing Low-power wide-area (LPWA) communication has gained increasing attention in recent years with the rapid growth of fifth generation evolution (5G), the Internet of Things (IoT), and mobile computing. Narrowband Internet of Things (NB-IoT) is one kind of LPWA technology based on cellular IoT, which supports massive connections, wide area coverage, ultra-low power consumption, and ultra-low cost. Research on NB-IoT communication is increasingly attractive. Network calculus theory facilitates the performance analysis and network optimization of the NB-IoT system. We aim to analyze and optimize the NB-IoT networks. In this paper, we construct a random access traffic model including the NB-IoT user equipment (UE) arrival process and eNB service process. Then, we utilize the stochastic network calculus (SNC) to analyze the network delay in NB-IoT traffic model. Random latency bounds in different arrival processes are derived. Simulations show that SNC can evaluate the system delay under different distributions effectively. For the condition that numerous UEs access simultaneously following the Beta distribution, we first propose an improved K-means algorithm to cluster the NB-IoT terminals. Then, we raise the scheduling strategy on the basis of priority. It consists of the priority generation algorithm IPGNTQ and the NB-IoT task scheduling algorithm SANTQ. The extensive experiment results verify that our proposed optimized strategy can alleviate the network congestion effectually. Moreover, we compare our proposed optimized scheme with four existing uplink traffic scheduling schemes, showing that ours outperforms all of them.
<reponame>juslee/boost-svn // Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 <NAME>, Amsterdam, the Netherlands. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_EXTENSIONS_ALGORITHMS_REMOVE_MARKED_HPP #define BOOST_GEOMETRY_EXTENSIONS_ALGORITHMS_REMOVE_MARKED_HPP #include <boost/range.hpp> #include <boost/geometry/multi/core/tags.hpp> #include <boost/geometry/core/coordinate_type.hpp> #include <boost/geometry/core/cs.hpp> #include <boost/geometry/core/interior_rings.hpp> #include <boost/geometry/geometries/concepts/check.hpp> #include <boost/geometry/util/math.hpp> #include <boost/geometry/algorithms/area.hpp> #include <boost/geometry/algorithms/distance.hpp> #include <boost/geometry/algorithms/perimeter.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace remove_marked { template <typename Range, typename MarkMap> struct range_remove_marked { typedef typename strategy::side::services::default_strategy < typename cs_tag<Range>::type >::type side_strategy_type; typedef typename coordinate_type<Range>::type coordinate_type; static inline void apply(Range const& range_in, ring_identifier id, Range& range_out, MarkMap const& mark_map) { typename MarkMap::const_iterator mit = mark_map.find(id); if (mit == mark_map.end()) { range_out = range_in; return; } typedef typename MarkMap::mapped_type bit_vector_type; if (boost::size(range_in) != boost::size(mit->second)) { throw std::runtime_error("ERROR in size of mark_map"); return; } range_out.clear(); typename boost::range_iterator<bit_vector_type const>::type bit = boost::begin(mit->second); for (typename boost::range_iterator<Range const>::type it = boost::begin(range_in); it != boost::end(range_in); ++it, ++bit) { bool const& marked = *bit; if (! marked) { range_out.push_back(*it); } } } }; template <typename Polygon, typename MarkMap> struct polygon_remove_marked { static inline void apply(Polygon const& polygon_in, ring_identifier id, Polygon& polygon_out, MarkMap const& mark_map) { typedef typename geometry::ring_type<Polygon>::type ring_type; typedef range_remove_marked<ring_type, MarkMap> per_range; id.ring_index = -1; per_range::apply(exterior_ring(polygon_in), id, exterior_ring(polygon_out), mark_map); typename interior_return_type<Polygon const>::type rings_in = interior_rings(polygon_in); typename interior_return_type<Polygon>::type rings_out = interior_rings(polygon_out); rings_out.resize(boost::size(interior_rings(polygon_in))); BOOST_AUTO_TPL(out, boost::begin(rings_out)); for (BOOST_AUTO_TPL(it, boost::begin(rings_in)); it != boost::end(rings_in); ++it, ++out) { id.ring_index++; per_range::apply(*it, id, *out, mark_map); } } }; template <typename MultiGeometry, typename MarkMap, typename SinglePolicy> struct multi_remove_marked { static inline void apply(MultiGeometry const& multi_in, ring_identifier id, MultiGeometry& multi_out, MarkMap const& mark_map) { id.multi_index = 0; multi_out.resize(boost::size(multi_in)); typename boost::range_iterator<MultiGeometry>::type out = boost::begin(multi_out); for (typename boost::range_iterator<MultiGeometry const>::type it = boost::begin(multi_in); it != boost::end(multi_in); ++it, ++out) { SinglePolicy::apply(*it, id, *out, mark_map); id.multi_index++; } } }; }} // namespace detail::remove_marked #endif // DOXYGEN_NO_DETAIL #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { template < typename Tag, typename Geometry, typename MarkMap > struct remove_marked { static inline void apply(Geometry const&, ring_identifier, Geometry&, MarkMap const&) {} }; template <typename Ring, typename MarkMap> struct remove_marked<ring_tag, Ring, MarkMap> : detail::remove_marked::range_remove_marked<Ring, MarkMap> {}; template <typename Polygon, typename MarkMap> struct remove_marked<polygon_tag, Polygon, MarkMap> : detail::remove_marked::polygon_remove_marked<Polygon, MarkMap> {}; template <typename MultiPolygon, typename MarkMap> struct remove_marked<multi_polygon_tag, MultiPolygon, MarkMap> : detail::remove_marked::multi_remove_marked < MultiPolygon, MarkMap, detail::remove_marked::polygon_remove_marked < typename boost::range_value<MultiPolygon>::type, MarkMap > > {}; } // namespace dispatch #endif /*! \ingroup remove_marked \tparam Geometry geometry type \param geometry the geometry to make remove_marked */ template <typename Geometry, typename MarkMap> inline void remove_marked(Geometry const& geometry_in, Geometry& geometry_out, MarkMap const& mark_map) { concept::check<Geometry>(); ring_identifier id; dispatch::remove_marked < typename tag<Geometry>::type, Geometry, MarkMap >::apply(geometry_in, id, geometry_out, mark_map); } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_EXTENSIONS_ALGORITHMS_REMOVE_MARKED_HPP
package org.softuni.residentevil.web.converters; import org.softuni.residentevil.domain.enums.Creator; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import java.util.Objects; @Component public class StringToCreatorConverter implements Converter<String, Creator> { @Override public Creator convert(String label) { return Creator.fromLabel(Objects.requireNonNull(label)); } }
"""passbook core authentication views""" from typing import Dict, Optional from django.contrib import messages from django.contrib.auth import login, logout from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.forms.utils import ErrorList from django.http import HttpRequest, HttpResponse from django.shortcuts import get_object_or_404, redirect, reverse from django.utils.translation import ugettext as _ from django.views import View from django.views.generic import FormView from structlog import get_logger from passbook.core.forms.authentication import LoginForm, SignUpForm from passbook.core.models import Invitation, Nonce, Source, User from passbook.core.signals import invitation_used, user_signed_up from passbook.factors.password.exceptions import PasswordPolicyInvalid from passbook.factors.view import AuthenticationView, _redirect_with_qs from passbook.lib.config import CONFIG LOGGER = get_logger() class LoginView(UserPassesTestMixin, FormView): """Allow users to sign in""" template_name = "login/form.html" form_class = LoginForm success_url = "." # Allow only not authenticated users to login def test_func(self): return self.request.user.is_authenticated is False def handle_no_permission(self): if "next" in self.request.GET: return redirect(self.request.GET.get("next")) return redirect(reverse("passbook_core:overview")) def get_context_data(self, **kwargs): kwargs["config"] = CONFIG.y("passbook") kwargs["title"] = _("Log in to your account") kwargs["primary_action"] = _("Log in") kwargs["show_sign_up_notice"] = CONFIG.y("passbook.sign_up.enabled") kwargs["sources"] = [] sources = ( Source.objects.filter(enabled=True).order_by("name").select_subclasses() ) for source in sources: ui_login_button = source.ui_login_button if ui_login_button: kwargs["sources"].append(ui_login_button) return super().get_context_data(**kwargs) def get_user(self, uid_value) -> Optional[User]: """Find user instance. Returns None if no user was found.""" for search_field in CONFIG.y("passbook.uid_fields"): # Workaround for E-Mail -> email if search_field == "e-mail": search_field = "email" users = User.objects.filter(**{search_field: uid_value}) if users.exists(): LOGGER.debug("Found user", user=users.first(), uid_field=search_field) return users.first() return None def form_valid(self, form: LoginForm) -> HttpResponse: """Form data is valid""" pre_user = self.get_user(form.cleaned_data.get("uid_field")) if not pre_user: # No user found return self.invalid_login(self.request) self.request.session[AuthenticationView.SESSION_PENDING_USER] = pre_user.pk return _redirect_with_qs("passbook_core:auth-process", self.request.GET) def invalid_login( self, request: HttpRequest, disabled_user: User = None ) -> HttpResponse: """Handle login for disabled users/invalid login attempts""" LOGGER.debug("invalid_login", user=disabled_user) messages.error(request, _("Failed to authenticate.")) return self.render_to_response(self.get_context_data()) class LogoutView(LoginRequiredMixin, View): """Log current user out""" def dispatch(self, request): """Log current user out""" logout(request) messages.success(request, _("You've successfully been logged out.")) return redirect(reverse("passbook_core:auth-login")) class SignUpView(UserPassesTestMixin, FormView): """Sign up new user, optionally consume one-use invitation link.""" template_name = "login/form.html" form_class = SignUpForm success_url = "." # Invitation instance, if invitation link was used _invitation = None # Instance of newly created user _user = None # Allow only not authenticated users to login def test_func(self): return self.request.user.is_authenticated is False def handle_no_permission(self): return redirect(reverse("passbook_core:overview")) def dispatch(self, request, *args, **kwargs): """Check if sign-up is enabled or invitation link given""" allowed = False if "invitation" in request.GET: invitations = Invitation.objects.filter(uuid=request.GET.get("invitation")) allowed = invitations.exists() if allowed: self._invitation = invitations.first() if CONFIG.y("passbook.sign_up.enabled"): allowed = True if not allowed: messages.error(request, _("Sign-ups are currently disabled.")) return redirect(reverse("passbook_core:auth-login")) return super().dispatch(request, *args, **kwargs) def get_initial(self): if self._invitation: initial = {} if self._invitation.fixed_username: initial["username"] = self._invitation.fixed_username if self._invitation.fixed_email: initial["email"] = self._invitation.fixed_email return initial return super().get_initial() def get_context_data(self, **kwargs): kwargs["config"] = CONFIG.y("passbook") kwargs["title"] = _("Sign Up") kwargs["primary_action"] = _("Sign up") return super().get_context_data(**kwargs) def form_valid(self, form: SignUpForm) -> HttpResponse: """Create user""" try: self._user = SignUpView.create_user(form.cleaned_data, self.request) except PasswordPolicyInvalid as exc: # Manually inject error into form # pylint: disable=protected-access errors = form._errors.setdefault("password", ErrorList()) for error in exc.messages: errors.append(error) return self.form_invalid(form) self.consume_invitation() messages.success(self.request, _("Successfully signed up!")) LOGGER.debug("Successfully signed up", email=form.cleaned_data.get("email")) return redirect(reverse("passbook_core:auth-login")) def consume_invitation(self): """Consume invitation if an invitation was used""" if self._invitation: invitation_used.send( sender=self, request=self.request, invitation=self._invitation, user=self._user, ) self._invitation.delete() @staticmethod def create_user(data: Dict, request: HttpRequest = None) -> User: """Create user from data Args: data: Dictionary as returned by SignUpForm's cleaned_data request: Optional current request. Returns: The user created Raises: PasswordPolicyInvalid: if any policy are not fulfilled. This also deletes the created user. """ # Create user new_user = User.objects.create( username=data.get("username"), email=data.get("email"), name=data.get("name"), ) new_user.is_active = True try: new_user.set_password(data.get("password")) new_user.save() request.user = new_user # Send signal for other auth sources user_signed_up.send(sender=SignUpView, user=new_user, request=request) return new_user except PasswordPolicyInvalid as exc: new_user.delete() raise exc class SignUpConfirmView(View): """Confirm registration from Nonce""" def get(self, request, nonce): """Verify UUID and activate user""" nonce = get_object_or_404(Nonce, uuid=nonce) nonce.user.is_active = True nonce.user.save() # Workaround: hardcoded reference to ModelBackend, needs testing nonce.user.backend = "django.contrib.auth.backends.ModelBackend" login(request, nonce.user) nonce.delete() messages.success(request, _("Successfully confirmed registration.")) return redirect("passbook_core:overview") class PasswordResetView(View): """Temporarily authenticate User and allow them to reset their password""" def get(self, request, nonce): """Authenticate user with nonce and redirect to password change view""" # 3. (Optional) Trap user in password change view nonce = get_object_or_404(Nonce, uuid=nonce) # Workaround: hardcoded reference to ModelBackend, needs testing nonce.user.backend = "django.contrib.auth.backends.ModelBackend" login(request, nonce.user) nonce.delete() messages.success( request, _(("Temporarily authenticated, please change your password")), ) return redirect("passbook_core:user-change-password")
<gh_stars>1-10 /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <StdAfx.h> #include "AWSBehaviorHTTP.h" #include <aws/core/http/HttpClient.h> #include <aws/core/http/HttpClientFactory.h> #include <AzCore/Jobs/JobContext.h> #include <AzCore/Jobs/JobFunction.h> #include <AzCore/Jobs/JobManagerBus.h> #include <LmbrAWS/IAWSClientManager.h> #include <LmbrAWS/ILmbrAWS.h> /// To use a specific AWS API request you have to include each of these. #pragma warning(disable: 4355) // <future> includes ppltasks.h which throws a C4355 warning: 'this' used in base member initializer list #include <aws/lambda/LambdaClient.h> #include <aws/lambda/model/ListFunctionsRequest.h> #include <aws/lambda/model/ListFunctionsResult.h> #include <aws/lambda/model/InvokeRequest.h> #include <aws/lambda/model/InvokeResult.h> #include <aws/core/utils/Outcome.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #pragma warning(default: 4355) namespace CloudGemAWSScriptBehaviors { AWSBehaviorHTTP::AWSBehaviorHTTP() : m_url() { } void AWSBehaviorHTTP::ReflectSerialization(AZ::SerializeContext* serializeContext) { if (serializeContext) { serializeContext->Class<AWSBehaviorHTTP>() ->Field("URL", &AWSBehaviorHTTP::m_url) ->Version(1); } } void AWSBehaviorHTTP::ReflectBehaviors(AZ::BehaviorContext* behaviorContext) { behaviorContext->Class<AWSBehaviorHTTP>("AWSBehaviorHTTP") ->Method("Get", &AWSBehaviorHTTP::Get, nullptr, "HTTP GET operation on AWS") ->Property("URL", nullptr, BehaviorValueSetter(&AWSBehaviorHTTP::m_url)); behaviorContext->EBus<AWSBehaviorHTTPNotificationsBus>("AWSBehaviorHTTPNotificationsBus") ->Handler<AWSBehaviorHTTPNotificationsBusHandler>(); } void AWSBehaviorHTTP::ReflectEditParameters(AZ::EditContext* editContext) { editContext->Class<AWSBehaviorHTTP>("AWSBehaviorHTTP", "Wraps AWS HTTP functionality") ->DataElement(AZ::Edit::UIHandlers::Default, &AWSBehaviorHTTP::m_url, "URL", "URL to get"); } void AWSBehaviorHTTP::Get() { if (m_url.empty()) { EBUS_EVENT(AWSBehaviorHTTPNotificationsBus, OnError, "AWS HTTP Get: No URL provided"); return; } AZ::Job* httpGetJob = CreateHttpGetJob(m_url); if (httpGetJob) { httpGetJob->Start(); } } AZ::Job* AWSBehaviorHTTP::CreateHttpGetJob(const AZStd::string& url) const { AZ::JobContext* jobContext{ nullptr }; EBUS_EVENT_RESULT(jobContext, AZ::JobManagerBus, GetGlobalContext); AZ::Job* job{ nullptr }; job = AZ::CreateJobFunction([url]() { std::shared_ptr<Aws::Http::HttpClient> httpClient = Aws::Http::CreateHttpClient(Aws::Client::ClientConfiguration()); Aws::String requestURL{ url.c_str() }; auto httpRequest(Aws::Http::CreateHttpRequest(requestURL, Aws::Http::HttpMethod::HTTP_GET, Aws::Utils::Stream::DefaultResponseStreamFactoryMethod)); auto httpResponse(httpClient->MakeRequest(*httpRequest, nullptr, nullptr)); if (!httpResponse) { EBUS_EVENT(AWSBehaviorHTTPNotificationsBus, OnError, "No Response Received from request! (Internal SDK Error)"); return; } int responseCode = static_cast<int>(httpResponse->GetResponseCode()); auto headerMap = httpResponse->GetHeaders(); AZStd::unordered_map<AZStd::string, AZStd::string> stdHeaderMap; for (auto headerContent : headerMap) { stdHeaderMap.emplace(headerContent.first.c_str(), headerContent.second.c_str()); } AZStd::string contentType = httpResponse->GetContentType().c_str(); AZStd::string returnString; auto& body = httpResponse->GetResponseBody(); Aws::StringStream readableOut; readableOut << body.rdbuf(); returnString = readableOut.str().c_str(); EBUS_EVENT(AWSBehaviorHTTPNotificationsBus, OnSuccess, AZStd::string("Success!")); EBUS_EVENT(AWSBehaviorHTTPNotificationsBus, GetResponse, responseCode, stdHeaderMap, contentType, returnString); }, true, jobContext); return job; } }
Cole County sheriff’s deputies have gotten to an inmate of the county jail in time to keep him from hanging himself. The sheriff says he had used a sheet to form a noose but deputies got to him before he lost consciousness. The inmate has been taken to a psychiatric center in Columbia.
/** * A DropSequenceNode represents a DROP SEQUENCE statement. */ public class DropSequenceNode extends DDLStatementNode { private TableName dropItem; /** * Initializer for a DropSequenceNode * * @param dropSequenceName The name of the sequence being dropped * @throws StandardException */ public void init(Object dropSequenceName) throws StandardException { dropItem = (TableName) dropSequenceName; initAndCheck(dropItem); } public String statementToString() { return "DROP ".concat(dropItem.getTableName()); } /** * Bind this DropSequenceNode. * * @throws StandardException Thrown on error */ public void bindStatement() throws StandardException { DataDictionary dataDictionary = getDataDictionary(); String sequenceName = getRelativeName(); SequenceDescriptor seqDesc = null; SchemaDescriptor sd = getSchemaDescriptor(); if (sd.getUUID() != null) { seqDesc = dataDictionary.getSequenceDescriptor (sd, sequenceName); } if (seqDesc == null) { throw StandardException.newException(SQLState.LANG_OBJECT_DOES_NOT_EXIST, statementToString(), sequenceName); } // Statement is dependent on the SequenceDescriptor getCompilerContext().createDependency(seqDesc); } // inherit generate() method from DDLStatementNode /** * Create the Constant information that will drive the guts of Execution. * * @throws StandardException Thrown on failure */ public ConstantAction makeConstantAction() throws StandardException { return getGenericConstantActionFactory().getDropSequenceConstantAction(getSchemaDescriptor(), getRelativeName()); } }
Showtime has set June 26 as the premiere date for “Roadies,” the hourlong comedy from Warner Bros TV that marks the first TV series created by Cameron Crowe. The ensembler led by Luke Wilson and Carla Gugino revolves around the backstage lives of the road crew for an arena-rock band. Production on the first season’s 10-episode order is set to begin in Los Angeles next month. Crowe created the series and directed the pilot. He exec produces with J.J. Abrams and Winnie Holzman, who is showrunner. Bad Robot’s Bryan Burk and Len Goldstein also exec produce. The large ensemble cast also includes Imogen Poots, Rafe Spall, Keisha Castle-Hughes, Peter Cambor, Colson Baker a.k.a. Machine Gun Kelly and Ron White. Luis Guzman, Jacqueline Byers, Finesse Mitchell, Branscombe Richmond and Tanc Sade are guest stars.
HIV-1 Drug Resistance in the iPrEx Preexposure Prophylaxis Trial Background.The iPrEx study demonstrated that combination oral emtricitabine and tenofovir disoproxil fumarate (FTC/TDF) as preexposure prophylaxis (PrEP) protects against HIV acquisition in men who have sex with men and transgender women. Selection for drug resistance could offset PrEP benefits. Methods.Phenotypic and genotypic clinical resistance assays characterized major drug resistant mutations. Minor variants with FTC/TDF mutations K65R, K70E, M184V/I were measured using 454 deep sequencing and a novel allele-specific polymerase chain reaction (AS-PCR) diagnostic tolerant to sequence heterogeneity. Results.Control of primer-binding site heterogeneity resulted in improved accuracy of minor variant measurements by AS-PCR. Of the 48 on-study infections randomized to FTC/TDF, none showed FTC/TDF mutations by clinical assays despite detectable drug levels in 8 participants. Two randomized to FTC/TDF had minor variant M184I detected at 0.53% by AS-PCR or 0.75% by deep sequencing, only 1 of which had low but detectable drug levels. Among those with acute infection at randomization to FTC/TDF, M184V or I mutations that were predominant at seroconversion waned to background levels within 24 weeks after discontinuing drug. Conclusions.Drug resistance was rare in iPrEx on-study FTC/TDF-randomized seroconverters, and only as low-frequency minor variants. FTC resistance among those initiating PrEP with acute infection waned rapidly after drug discontinuation. Clinical Trials Registration.NCT00458393. Antiretroviral drugs have demonstrated efficacy when used as preexposure prophylaxis (PrEP) for preventing human immunodeficiency virus (HIV) acquisition through sexual or intravenous exposure in uninfected men, women, and transgendered women. A consistent finding among reported randomized, placebocontrolled trials testing oral and topical PrEP strategies is that efficacy is associated with drug exposure. In the iPrEx study, where the safety and efficacy of daily oral dosing of combination nucleoside/nucleotide reverse-transcriptase inhibitors (nRTI) emtricitabine (FTC) and tenofovir disoproxil fumarate (TDF) was tested in men and transgender women who have sex with men, a 44% reduction in infection incidence was seen in participants randomized to FTC/TDF compared with placebo, and a 99% reduction among those with blood FTC/TDF levels commensurate with daily dosing. In contrast, in the Fem-PrEP and VOICE trials where product adherence was low, the use of oral TDF, TDF/FTC, or tenofovir (TFV) 1% vaginal gel did not significantly reduce HIV infections. Decades of experience with therapeutic use of antiretroviral drugs have accumulated an extensive understanding of the causes and consequences of HIV drug resistance (DR), which emerges with suboptimal antiretroviral therapy (ART), including the dual nRTI regimens such as that recommended for PrEP. If HIV infection occurred during suboptimal PrEP use, DR could be selected early in infection. In rhesus macaque studies investigating oral FTC/TDF PrEP, breakthrough infections following rectal exposure showed FTC-selected DR mutations M184V/I. In people with unrecognized infection, antiretroviral use intended as PrEP is functionally postexposure prophylaxis (PEP), where DR can occur in breakthrough systemic infection. Additionally, initial efforts administering single-dose nevirapine to mothers at birth for prevention of mother-to-child-transmission (MTCT) resulted in rapid emergence of drug-selected mutations in infected infants measured by population sequencing. Ultrasensitive diagnostic assays revealed a substantially higher frequency of mothers and infants with minor variant DR. These findings demonstrate that the use of antiretrovirals to prevent infection can select for DR when breakthrough infections occur, and warrant thorough and sensitive monitoring in PrEP studies. We report the results from comprehensive viral DR testing and drug exposure measurements in iPrEx seroconverters in a clinical trial setting. Clinical genotype and phenotype assays were performed to detect resistance in viral populations. We quantified minor variant FTC/TDF-selected mutations by deep sequencing and a novel allele-specific polymerase chain reaction (AS-PCR)-based assay that controls for target sequence polymorphisms and yields improved performance when testing isolates from diverse geographic locations. The nature and frequency of DR mutations are presented in the context of concurrent systemic FTC/TDF exposure. Study Design and Sample Selection The iPrEx study design, conduct, and primary analysis results through 1 May 2010 are described. The protocol was approved by institutional review boards at all participating sites. All study participants provided written informed consent. Participants were monitored for HIV infection by antibody testing at monthly visits. Study drug was discontinued with confirmed seroconversion (SC) and subjects monitored prospectively for plasma HIV-1 RNA levels. Retrospective HIV-1 RNA testing was performed on archived specimens from visits at and prior to SC to define the infection window (last RNA negative to first RNA positive). Plasma HIV RNA was tested for DR at the first SC visit or if unavailable, a pre-SC RNA positive, or proximal post-SC sample. Participants randomized to FTC/TDF with any drug-associated resistance mutation by genotype were monitored for DR longitudinally. Sample Preparation and HIV Resistance Testing Blood plasma HIV RNA was assessed for DR by HIV-1 pol population sequencing with mixed base detection at approximately 20% (TRUGENE, Siemens Healthcare Diagnostics, Inc, Tarrytown, NY); the Phenosense assay (Monogram Biosciences, Inc. South San Francisco CA) for drug susceptibility profiles; an AS-PCR-based quantitative minor variant assay (qMVA) as the primary analysis targeting rt K65R, K70E, M184V, and M184I; and 454 GS-FLX Titanium single-amplicon deep sequencing (Roche Applied Sciences, Pleasanton, CA) for confirmatory analysis. Population and 454 sequences are available in GenBank (Accession numbers KJ585857-KJ586124 and SRP037739, respectively). Cell-free virions were concentrated from 1 mL ethylenediaminetetraacetic acid blood plasma by centrifugation at 52 800 g for 60 minutes at 4°C. RNA was extracted using the QIAamp viral RNA kit (QIAGEN, Inc, Valencia, CA). For nonsubtype C viruses, minor variant DR was quantified directly from the 1.3 kilobase (kb) sequencing amplicon generated by 1-step reverse transcription (RT)-PCR. For subtype C viruses, a 692 base-pair (bp) amplicon (homebrew amplicon, HBA) was generated using high-fidelity conditions to minimize base misincorporation in homopolymer regions adjacent to and within the rt 65 codon during template generation, which decreased the background mutation frequency measured by both qMVA and deep-sequencing assays (Supplementary Methods). Quantitative Minor Variant Assay The qMVA combines an initial "cure" PCR of the rt amplicon followed by AS-PCR using sybr-green master mix (AnaSpec, Fremont, CA) in parallel reactions with primers specific for wild-type (WT) and mutant (Mut) codons. The cure step is an 8-cycle PCR that normalizes AS-PCR primer target sites to consensus sequences, while maintaining the single-nucleotide polymorphism (SNP) conferring resistance. The percent minor variant was determined by extrapolating the participant sample Ct (Ct minus Ct ) from AS-PCR reactions against a 6-point standard curve. In samples where Mut or WT/Mut mixtures were detected by population sequencing, primers designated as major or minor variant were adjusted accordingly. Detailed assay conditions, primers, and assay performance characteristics are described in Supplementary Methods. Sequencing The 1.3 kb or 692 bp HIV rt amplicon containing FTC/TDF DR sites were further amplified to generate a 517 or 535 bp amplicon, including 25-base Titanium adapter and 10-base multiplex identifier sequences. Following purification and quantification, amplicons were pooled, diluted to 1.0 10 6 molecules/L, and further amplified by emulsion PCR using the Roche 454 emPCR Kit (Lib A) (Roche Applied Sciences, Indianapolis, IN) according to the manufacturer's instructions. Recovered DNA beads were sequenced using a 454 GS FLX+ with Titanium sequencing chemistry (Supplementary Methods). The Roche Amplicon Variant Analysis software (version 2.6) was used for determining codon variant frequencies by employing predefined codon changes at resistance sites. Subtypematched consensus sequences (http://www.hiv.lanl.gov) were used as alignment references. Biological Cut-off Values for Minor Variant Frequencies The biological cut-off (BCO) was determined to define the natural frequency of DR mutations in the absence of drug exposure, and above which a sample was considered positive. We defined the BCO for each DR site, template (TRUGENE or HBA), and assay primer set (qMVA and 454 sequencing) using panels of 12 subtype B and 9 subtype C samples from individuals infected prior to the general availability of antiretroviral drugs, selecting for K65R, K70E, and M184V/I (Supplementary Methods). The BCO was defined as the highest value measured plus 3 SD, or 0.50%, whichever was higher. BCO values ranged from 0.50% to 0.60% for the qMVA, and 0.50% to 1.70% for 454 assays. HIV-1 Subtype and Surveillance Drug Resistance Mutation Assignment HIV-1 subtypes were assigned from population sequences of HIV-1 protease codons 10-99 and reverse transcriptase codons 40-247 using the Recombinant Identification Program (RIP, http://www.hiv.lanl.gov/content/sequence/RIP/RIP.html) with consensus alignment, 300 nucleotide (nt) window size, 90% confidence threshold in regions of significant match between query and consensus sequence. Surveillance DR mutations (SDRM) were derived from a consensus genotypic definition for identifying transmitted mutations and were assigned from population sequences by the Stanford HIV DR Database CPR tool (v6.0) (http://cpr.stanford.edu). Statistical Methods Between-group comparisons were performed using a 2-sample t test with unequal variances. Accurate Minor Variant Quantification With Tolerance to Sequence Polymorphisms Viral sequence diversity presents challenges for quantitative target sequence-based diagnostics, especially in homopolymer regions adjacent to DR codons such as subtype C K65R. To increase the specificity and accuracy of AS-PCR strategies for minor variant quantification across multiple subtypes, we developed the quantitative minor variant assay (qMVA), which includes a "cure" PCR step before the AS-PCR to normalize the primer target sites adjacent to the SNP conferring resistance to defined, consensus-based sequences ( Figure 2). To evaluate the diagnostic impact conferred by viral sequence polymorphisms in minor variant quantification by AS-PCR in the presence and absence of a cure-PCR, we measured mixtures of K65R (aga vs aaa for WT and Mut, respectively) at 0%, 0.5%, 1.0%, and 10% Mut in a consensus B background template, with or without 4 polymorphic bases in both discriminatory and universal primer-binding regions. The percent mutant was measured by the qMVA using the matched and mismatched panels in the presence and absence of a cure-PCR step (Supplementary Table 1). In the absence of a cure-PCR, the homologous AS-PCR primer:template accurately quantified minor variant DR mixtures, yielding values of 0%, 0.48%, 1.02%, and 10.38% Mut for the panel. However, when the same primers were used with a mismatched template, mutant frequencies at levels <1.0% were overestimated, while those at 10% target levels were underestimated. Addition of a cure step prior to the AS-PCR reaction restored the accurate measurement of mutant frequencies with mismatched AS-PCR primer and template (0 = 0.04%, 0.5 = 0.44%, 1 = 0.94%, and 10 = 9.5%). These results demonstrate the potentially deleterious effects of sequence polymorphisms when present within the AS-PCR primer targets, resulting in inaccurate minor variant frequency estimates. Genotypic, Phenotypic, and Minor Variant Drug Resistance Among the 131 participants with incident infections, none had FTC-or TDF-selected mutations or reduced phenotypic susceptibility ( Figure 1). As previously reported, DR was detected exclusively in those initiating PrEP during unrecognized acute infection at study entry. Of these, genotypic and phenotypic resistance to FTC was seen in 2 of 2 participants randomized to FTC/TDF and 1 of 8 randomized to placebo with mutations M184V and I, with maximally increased fold change half maximal inhibitory concentration (IC 50 ) values for FTC. Both FTC-resistant viruses from participants randomized to FTC/ TDF were hypersusceptible to TDF and zidovudine (ZDV; Figure 1. Genotype, phenotype, and minor variant drug resistance in iPrEx seroconverters by randomization arm. Genotype and phenotype results from a subset of iPrEx participants were described previously in the interim analysis report and are included here for a cumulative assessment. Of the 131 participants with incident infection (48 FTC/TDF, 83 placebo), drug resistance assays were performed on specimens collected at first evidence of seroconversion (n = 128) or if unavailable, the HIV RNA-positive visit prior to (n = 2) or following (n = 1) seroconversion. Minor variant drug resistance testing by qMVA was performed on all participants at 1 or more drug resistance mutations. The number of mutation sites ineligible for testing based on preestablished criteria regarding cure primer 3 end match with viral target sequence among the 131 samples possible are as follows: K65R: n = 2 (1.5%); K70E: n = 11 (8.4%); M184V: n = 5 (3.8%); and M184I: n = 4 (3.0%). Plasma virus from 1 participant was not available for analysis by 454 sequencing (FTC/TDF arm). Abbreviations: 3TC, lamivudine; BCO, biological cut-off; FC IC 50, fold change half maximal inhibitory concentration; FTC, emtricitabine; HIV, human immunodeficiency virus; MAX, maximal FC IC 50 ; PCR, polymerase chain reaction; qMVA, quantitative minor variant assay; TDF, tenofovir disoproxil fumarate; ZDV, zidovudine. where the mutant sequence is undetectable by population sequencing. B, Cure PCR step. The cure PCR step is performed prior to the AS-PCR step to normalize possible sequence heterogeneity in the AS-PCR primer target sites that can reduce PCR efficiency and result in inaccurate quantification of the minor variant population. The example portrays a virus that differs from the discriminatory AS-PCR primer at 2 sites upstream from the SNP conferring resistance. A low-stringency PCR with limited cycle number is performed on the mixed WT (99%) and Mut (1%) DNA amplicons, using a consensus sequence-based primer pair covering the AS-PCR target sites adjacent to but not including the SNP conferring resistance. When paired with another consensus primer, AS-PCR target amplicons are generated representing the original WT:Mut SNP mixtures, but with AS-PCR target sequences M184V virus showed fold change IC 50 of 0.46 and 0.36; M184I showed fold change IC 50 of 0.44 and 0.22, respectively). Viruses from 6 participants (3 FTC/TDF, 3 placebo) had other single nucleoside reverse-transcriptase inhibitor (NRTI; M41L), nonnucleoside reverse-transcriptase inhibitor (NNRTI; K103N/E), or protease inhibitor (PI)-selected (I85V) SDRM ( Table 1). The participant with acute infection who was randomized to placebo had multiclass resistance mutations M184V, T215Y, K103N, and P225H. These mutations, appearing in the absence of drug exposure, likely result from acquisition of resistant virus from a treatment-experienced source. Of the seroconverters randomized to FTC/TDF, none showed minor variant mutations above the BCO at K65R or K70E. Two subjects showed the FTC-associated resistance mutation M184I at <1.0%, one by 454 sequencing exclusively (0.75%), and another by qMVA (0.53%). Repeat testing by qMVA using an independent amplification product yielded a value just below the BCO of 0.5% (0.43%), most likely reflecting normal variation bracketing the established cutoff rather than selected resistance. Among those randomized to placebo, 1 participant had 0.69% K65R by qMVA and 1.64% by deep sequencing. Another subject showed minor variant M184V by both qMVA (1.26%) and 454 sequencing (2.75%). In summary, minor variant DR mutations were rare, and when detected, were measured at very low frequencies. Longitudinal Monitoring of FTC-resistance Mutations The proportion of contemporaneous Mut:WT species was monitored over time in both participants with unrecognized infection prior to FTC/TDF randomization (Figure 3). Minor variant frequencies by qMVA and 454 sequencing were highly concordant. At study entry, the subject in Figure 3 The genotype revealed mixed M184M/V, with predominance of the Mut codon (84% by qMVA, 85% by 454 sequencing), consistent with selection by FTC. Following study drug withdrawal at the SC visit, plasma viral load increased to 5.42 log 10 cps/mL, and M184V waned to <0.5% within 14 weeks, remaining at background levels through 52 weeks of follow-up. Drug Exposure Levels Among Seroconverters The absence of PrEP-selected DR in subjects with postrandomization infection, and the rare occurrence of minor variant DR may reflect the low adherence reported in iPrEx. To address drug resistance in the context of measured drug exposure, we examined the plasma FTC and TFV and intracellular PBMC FTC-TP and TFV-DP levels in all participants with incident infection where at least 1 measurement was detectable within 90 days prior to or including the seroconversion visit ( Figure 4). Eight of 48 (17%) subjects had detectable drug within 90 days of seroconversion. Four of 48 (8.3%) participants had detectable drug prior to, but not at the SC visit, and 3/48 (6.3%) had detectable drug only at SC, indicating intermittent dosing. One subject (Figure 4, orange symbols) had detectable drug prior to and at the SC visit. The participant with minor variant M184I (0.53% by qMVA, open symbols) had undetectable plasma drug levels, and low but detectable PBMC drug levels prior to SC (FTC-TP 2.62 pmol/10 6 cells; TFV-DP 3.58 fmol/10 6 cells). Intracellular FTC-TP concentrations ranged from 0.15 to 8.55 pmol/10 6 cells, and TFV-DP concentrations ranged from 3.58 to 34.0 fmol/10 6 cells, values consistent with nondaily oral dosing. DISCUSSION We have performed a comprehensive analysis of FTC/TDFselected DR in 131 participants who seroconverted postrandomization in the iPrEx study, and in 2 participants with exposure to FTC/TDF during unrecognized acute infection. Overall, detection of PrEP-selected DR mutations was infrequent. Bulk genotypic and phenotypic resistance assays revealed FTC-associated mutations (M184V or I) exclusively in participants exposed to FTC/TDF during acute infection, of which 1 had confirmed WT virus at entry. TDF-selected mutations were not observed in PrEP recipients. Of the 48 infected participants randomized to FTC/TDF, minor variant FTC-selected DR (M184I) was detected in 2 participants, 1 by qMVA (0.53%) and another by deep sequencing (0.75%), of which only the former had detectable FTC within the estimated infection window. Taken together, clinically significant DR selected by PrEP was limited to those who initiated drug after established infection, and was associated with FTC exposure. The emergence of PrEP-associated viral mutations where PrEP was initiated during acute infection was also reported for men and women in the TDF2 study and HIV serodiscordant couples in Partners PrEP, respectively. Consistent with the findings in iPrEx, and the Bangkok Tenofovir study, PrEPselected mutations were absent among seroconverters infected postrandomization. This may reflect drug concentrations or exposure duration that were insufficient to prevent infection and select for drug resistance. In all PrEP study reports, efficacy significantly increases when measured drug exposure is taken into account. By contrast, in the Fem-PrEP trial, PrEP-associated DR in SC randomized to the FTC/TDF arm was noted exclusively in those infected postrandomization. Seroconversion in 3 of 4 women occurred within 8 weeks of study entry, raising the possibility of emergent infection during PrEP initiation. Taken together, these results underscore the importance of recognizing the rare individual with acute seronegative infection, through sensitive HIV RNA testing, or 4th generation antigen-antibody combination enzyme immunoassays. Other potential strategies where such diagnostic testing is impractical To the right of (B), the estimated dosing frequency corresponding to TFV-TP concentration is shown (median, IQR) as reported from the STRAND trial. BLQ values for TFV, FTC = 10 ng/mL; TFV-DP = 2.5 fmol/10 6 PBMCs; FTC-TP = 0.1 pmol/10 6 PBMCs. Abbreviations: BLQ, below the limit of quantitation; FTC, emtricitabine; FTC-TP, FTC triphosphate FTC; IQR, interquartile range; PBMC, peripheral blood mononuclear cell; SC, seroconversion; TDF, tenofovir disoproxil fumarate; TFV, tenofovir; TFV-DP, TFV diphospate. include delaying PrEP initiation in individuals with symptoms consistent with acute viral infection syndromes. In the absence of continued drug selection, the FTC-resistant viruses proportionately waned within the infected host over time, reaching background levels by 24 weeks. This is consistent with our findings measuring the time-course of transmitted M184V reversion and WT outgrowth in ARV-naive subjects, and reflects the impaired replication capacity in viruses carrying FTC-selected mutations. The contribution of archived, low-frequency M184V/I in the proviral DNA reservoir to treatment response is not known. Long-term persistence of K103N is detected as minor variants in untreated infants exposed to single-dose nevirapine at birth. In a meta-analysis, there is increased risk of treatment failure with preexisting NNRTI minor variant resistance, but reduced risk is noted with minor variant NRTI resistance comparable to frequencies seen in our study (approximately 1%). The FTC-resistant viruses associated with PrEP exposure had phenotypic susceptibility profiles predicting durable suppression with current second-line regimens based on World Health Organization recommendations. The response to regimens containing FTC or lamivudine (3TC) for viruses harboring isolated M184VI mutations is difficult to predict, although use of a boosted PI is an option to minimize the risk of virological failure. The mutations M184VI confer hypersusceptibility to ZDV and TDF, raising the possibility of successful ZDV-or TDF-based dual NRTI regimens combined with a fully active NNRTI or integrase inhibitor, thus sparing 2nd-line boosted PI-based regimens. In iPrEx, antiretrovirals were withdrawn at first evidence of infection, with clinical follow-up consistent with the in-country standard of care. However, recent insights into the potential clinical benefit of very early treatment initiation warrants reconsideration of this strategy, as therapy intensification during hyperacute infection might attenuate the course of HIV spread and decrease viral reservoir size. Indeed, the decreased frequency of seroconversions in subjects undergoing acute infection at randomization detected in the active arms compared with placebo in iPrEx (2 vs 8) and CAPRISA 004 (1 vs 7) may reflect attenuated infection when antiretrovirals are started during the Fiebig 1 infection stage or earlier. A better understanding of the FTC/TDF dose and dosing patterns that are associated with prophylactic effects and selection for drug resistance is important for evaluating risk-benefit ratios of PrEP. In a case-control substudy of iPrEx participants, the frequency of drug detection in infected participants within a 90-day infection window was significantly lower (11%) than that seen in uninfected controls (51%), but equivalent at time points farther from infection, indicating increased risk of infection during periods of low drug exposure. We find that such periods of low drug exposure were not sufficient for selection of drug resistance. One subject who had detectable HIV-1 RNA when starting PrEP rapidly developed FTC resistance; his drug concentrations were TFV-DP 18.7 fmol/10 6 PBMCs and FTC-TP 0.95 pmol/10 6 PBMCs at the seroconversion visit 4 weeks later, by which time M184V was selected. This indicates that these concentrations of drug were sufficient to select for resistance, while being in the prophylactic range for those who are uninfected when starting PrEP. This case, and the lack of FTC or TDF resistance among those with incident infections, suggests that concentrations of drug required to overcome viral fitness barriers to DR selection are also sufficient to prevent HIV infection. There are limitations in directly extrapolating our findings to other settings of PrEP use. The iPrEx study design included monthly serologic monitoring of PrEP recipients and termination of PrEP at seroconversion. Current guidelines for PrEP in clinical settings indicate HIV-1 monitoring at at least 3-month intervals, potentially increasing drug exposure duration and risk of DR if infection occurs. The absence K65R or K70E in iPrEx may be due to insufficient duration of TDF exposure. Among PrEP users with preexisting infection in other trials, K65R appeared after 4 weeks of TDF PrEP in 1 person, and after 7 months of FTC/TDF PrEP in another. In GS-934, a randomized study of FTC/TDF/efavirenz (EFV) versus 3TC/TDF/EFV in infected ART-naive subjects, 2/19 developed M184V or I while none developed K65R or K70E after treatment for a median of 16 weeks postvirologic failure. In clinical practice, PrEP may be used intermittently, started, and stopped as people change their sexual practices; the frequency and nature of DR in these or other settings may differ from that reported here. In summary, we found DR in iPrEx SC was limited to those initiating PrEP with unrecognized infection. In 8 participants with measurable systemic drug levels near the infection window, PrEP-selected DR with a potential clinical impact was absent, due to insufficient levels or exposure duration. Continued surveillance of PrEP exposure and DR in seroconverters from ongoing PrEP demonstration projects will extend these findings from randomized controlled trials. Supplementary Data Supplementary materials are available at The Journal of Infectious Diseases online (http://jid.oxfordjournals.org/). Supplementary materials consist of data provided by the author that are published to benefit the reader. The posted materials are not copyedited. The contents of all supplementary data are the sole responsibility of the authors. Questions or messages regarding errors should be addressed to the author.
. Identifying risk factors affecting the formation of the musculoskeletal system (MSS) in children and adolescents is considered by the author as a necessary condition for the implementation of prevention, timely diagnosis and adequate correction of the MSS disorders and diseases. Introduction in the educational process developed by the author for the first time a conceptual model of prevention and correction of the MSS disorders and diseases in schoolchildren allowed significantly reduce the prevalence of functional disorders and early forms of the MSS diseases in students of a number of comprehensive schools in Moscow by 50%.
<gh_stars>100-1000 /* * Copyright 2012 AT&T * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.att.aro.model; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import org.jsoup.Jsoup; import com.att.aro.bp.fileorder.FileOrderAnalysis; import com.att.aro.bp.asynccheck.AsyncCheckAnalysis; import com.att.aro.pcap.TCPPacket; import com.att.aro.util.Util; /** * Encapsulates information about an HTTP request or response. This class was * converted from struct HTTP_REQUEST_RESPONSE */ public class HttpRequestResponseInfo implements Comparable<HttpRequestResponseInfo> { /** * Returns HTTP version 1.0. */ public static final String HTTP10 = "HTTP/1.0"; /** * Returns HTTP version 1.1. */ public static final String HTTP11 = "HTTP/1.1"; /** * Returns UTF-8. */ public static final String UTF8 = "UTF-8"; /** * Returns the GET HTTP type. */ public static final String HTTP_GET = "GET"; /** * Returns the PUT HTTP type.pe. */ public static final String HTTP_PUT = "PUT"; /** * Returns the POST HTTP type. */ public static final String HTTP_POST = "POST"; public static final String HTTP_SCHEME = "HTTP"; private static final String CONTENT_ENCODING_GZIP = "gzip"; private static final String CONTENT_ENCODING_COMPRESS = "compress"; private static final String CONTENT_ENCODING_DEFLATE = "deflate"; private static final String CONTENT_ENCODING_NONE = Util.RB.getString("rrview.http.compression.no"); private static final String CONTENT_ENCODING_NA = ""; private static final Date BEGINNING_OF_TIME = new Date(0); private static final Logger LOGGER = Logger.getLogger(HttpRequestResponseInfo.class.getName()); private static final Map<String, Integer> WELL_KNOWN_PARTS = new HashMap<String, Integer>(5); private static final Pattern TEXT_CONTENT_TYPE_TEXT = Pattern.compile("^text/.*"); private static final Pattern TEXT_CONTENT_TYPE_XML = Pattern.compile("^application/.*xml"); private static final CharSequence IMAGE = Util.RB.getString("fileChooser.contentType.image"); static { WELL_KNOWN_PARTS.put(HTTP_SCHEME, 80); WELL_KNOWN_PARTS.put("HTTPS", 443); WELL_KNOWN_PARTS.put("RTSP", 554); } private PacketInfo.Direction packetDirection; private TCPSession session; private Direction direction; // REQUEST or RESPONSE private String scheme; private int port; private String version; private String statusLine; private String requestType; // e.g., HTTP_POST, HTTP_GET private int statusCode; // e.g., 200 private String hostName; // e.g., a57.foxnews.com private String contentType; // image/jpeg private String charset; private String objName; // e.g., /static/managed/img/.../JoePerry640.jpg private String objNameWithoutParams; private String fileName; private URI objUri; private String responseResult; private boolean chunked; private boolean chunkModeFinished; private boolean rangeResponse; private boolean ifModifiedSince; private boolean ifNoneMatch; private int rangeFirst; private int rangeLast; private long rangeFull; private int contentLength; private String contentEncoding; private int rrStart; private int rawSize; // Includes headers private boolean ssl; private TextFileCompression textFileCompression; // Map of the content offset/ private SortedMap<Integer,Integer> contentOffsetLength; // packets private PacketInfo firstDataPacket; private PacketInfo lastDataPacket; // Cache info private Date date; private boolean hasCacheHeaders; private boolean pragmaNoCache; private boolean noCache; private boolean noStore; private boolean publicCache; private boolean privateCache; private boolean mustRevalidate; private boolean proxyRevalidate; private boolean onlyIfCached; private String etag; private Long age; private Date expires; private URI referrer; private Date lastModified; private Long maxAge; private Long sMaxAge; private Long minFresh; private Long maxStale; private HttpRequestResponseInfo assocReqResp; private RequestResponseTimeline waterfallInfos; private String allHeaders; /** * The HttpRequestResponseInfo.Direction Enumeration specifies constant * values that describe the direction of an HTTP request/response. The * direction indicates whether an HttpRequestResponseInfo object contains a * request (up link) or a response (downlink). This enumeration is part of * the HttpRequestResponseInfo class. */ public enum Direction { /** * A Request traveling in the up link direction. */ REQUEST, /** * A Response traveling in the down link direction. */ RESPONSE; } public enum TextFileCompression { GZIP(CONTENT_ENCODING_GZIP), COMPRESS(CONTENT_ENCODING_COMPRESS), DEFLATE(CONTENT_ENCODING_DEFLATE), NONE(CONTENT_ENCODING_NONE), NOT_APPLICABLE(CONTENT_ENCODING_NA); private String type; TextFileCompression(String type) { this.type = type; } @Override public String toString() { return type; } } /** * This is a synchronized request/response builder class */ private static class RequestResponseBuilder { /** * Date format pattern used to parse HTTP date headers in RFC 1123 * format. */ private static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; /** * Date format pattern used to parse HTTP date headers in RFC 1036 * format. */ private static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz"; /** * Date format pattern used to parse HTTP date headers in ANSI C * <code>asctime()</code> format. */ private static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy"; private static final String PATTERN_ASCTIME2 = "EEE MMM d HH:mm:ss zzz yyyy"; private static final String CHARSET = "charset"; private static final String CHUNKED = "chunked"; private static final String NOCACHE = "no-cache"; private static final String NOSTORE = "no-store"; private static final String PUBLIC = "public"; private static final String PRIVATE = "private"; private static final String MUSTREVALIDATE = "must-revalidate"; private static final String PROXYREVALIDATE = "proxy-revalidate"; private static final String ONLYIFCACHED = "only-if-cached"; private static final Object HEADERS_SEPARATOR = " "; private static Pattern strReRequestType = Pattern .compile("(\\S*)\\s* \\s*(\\S*)\\s* \\s*(HTTP/1\\.[0|1]|RTSP/1\\.[0|1])"); private static Pattern strReRequestHost = Pattern.compile("[H|h]ost:"); private static Pattern strReResponseContentLength = Pattern .compile("[C|c]ontent-[L|l]ength:"); private static Pattern strReTransferEncoding = Pattern .compile("[T|t]ransfer-[E|e]ncoding:"); private static Pattern strReResponseContentType = Pattern .compile("[C|c]ontent-[T|t]ype:"); private static Pattern strReResponseContentEncoding = Pattern .compile("[C|c]ontent-[E|e]ncoding:"); private static Pattern strReResponseResults = Pattern .compile("(HTTP/1\\.[0|1]|RTSP/1\\.[0|1])\\s* \\s*(\\d++)\\s* \\s*(.*)"); private static Pattern strReResponseEtag = Pattern .compile("ETag\\s*:\\s*(W/)?\"(.*)\""); private static Pattern strReResponseAge = Pattern .compile("Age\\s*:\\s*(\\d*)"); private static Pattern strReResponseExpires = Pattern .compile("Expires\\s*:(.*)"); private static Pattern strReResponseReferer = Pattern .compile("Referer\\s*:(.*)"); private static Pattern strReResponseLastMod = Pattern .compile("Last-Modified\\s*:(.*)"); private static Pattern strReResponseDate = Pattern .compile("Date\\s*:(.*)"); private static Pattern strReResponsePragmaNoCache = Pattern .compile("Pragma\\s*:\\s*no-cache"); private static Pattern strReResponseCacheControl = Pattern .compile("Cache-Control\\s*:(.*)"); private static Pattern strReCacheMaxAge = Pattern .compile("max-age\\s*=\\s*(\\d++)"); private static Pattern strReCacheSMaxAge = Pattern .compile("s-maxage\\s*=\\s*(\\d++)"); private static Pattern strReCacheMinFresh = Pattern .compile("min-fresh\\s*=\\s*(\\d++)"); private static Pattern strReCacheMaxStale = Pattern .compile("max-stale\\s*(?:=\\s*(\\d*))?"); private static Pattern strReContentRange = Pattern .compile("Content-Range\\s*:\\s*bytes (\\d*)\\s*-\\s*(\\d*)\\s*/\\s*(\\d*)"); private static Pattern strReIfModifiedSince = Pattern .compile("If-Modified-Since\\s*:"); private static Pattern strReIfNoneMatch = Pattern .compile("If-None-Match\\s*:"); private TCPSession session; private ArrayList<HttpRequestResponseInfo> result = new ArrayList<HttpRequestResponseInfo>(); private int counter; private byte[] input; private DateFormat rfc1123 = new SimpleDateFormat(PATTERN_RFC1123); private DateFormat rfc1036 = new SimpleDateFormat(PATTERN_RFC1036); private DateFormat asctime = new SimpleDateFormat(PATTERN_ASCTIME); private DateFormat asctime2 = new SimpleDateFormat(PATTERN_ASCTIME2); private DateFormat[] dateFormats = { rfc1123, rfc1036, asctime, asctime2 }; public RequestResponseBuilder(TCPSession session) throws IOException { this.session = session; extractHttpRequestResponseInfo(PacketInfo.Direction.UPLINK); extractHttpRequestResponseInfo(PacketInfo.Direction.DOWNLINK); Collections.sort(result); result.trimToSize(); if(!session.isUDP()){/* By pass for UDP packets*/ if (result.size() > 0) { // Get DNS info for waterfall Double dns = null; if (session.getDnsRequestPacket() != null && session.getDnsResponsePacket() != null) { dns = session.getDnsRequestPacket().getTimeStamp(); } // Find syn and ack packets for session Double synTime = null; for (PacketInfo p : session.getPackets()) { if (p.getPacket() instanceof TCPPacket) { TCPPacket tcp = (TCPPacket) p.getPacket(); if (tcp.isSYN()) { synTime = p.getTimeStamp(); break; } } } Double sslNegTime = null; PacketInfo handshake = session.getLastSslHandshakePacket(); if (handshake != null) { sslNegTime = handshake.getTimeStamp(); } // Associate requests/responses List<HttpRequestResponseInfo> reqs = new ArrayList<HttpRequestResponseInfo>( result.size()); for (HttpRequestResponseInfo rr : result) { if (rr.direction == Direction.REQUEST) { reqs.add(rr); } else if (rr.direction == Direction.RESPONSE) { if (!reqs.isEmpty()) { rr.assocReqResp = reqs.remove(0); rr.assocReqResp.assocReqResp = rr; } } } // Build waterfall for each request/response pair for (HttpRequestResponseInfo rr : result) { if (rr.getDirection() != Direction.REQUEST || rr.getAssocReqResp() == null) { // Only process non-HTTPS request/response pairs continue; } double startTime = -1; //check firstDataPacket and lastDataPacket if(rr.firstDataPacket != null && rr.lastDataPacket != null) { double firstReqPacket = rr.firstDataPacket.getTimeStamp(); double lastReqPacket = rr.lastDataPacket.getTimeStamp(); HttpRequestResponseInfo resp = rr.getAssocReqResp(); // check getAssocReqResp firstDataPacket and lastDataPacket packet if(resp != null && resp.firstDataPacket !=null && resp.lastDataPacket != null) { double firstRespPacket = resp.firstDataPacket.getTimeStamp(); double lastRespPacket = resp.lastDataPacket.getTimeStamp(); // Add DNS and initial connect to fist req/resp pair only Double dnsDuration = null; if (dns != null) { startTime = dns.doubleValue(); if (synTime != null) { dnsDuration = synTime.doubleValue() - dns.doubleValue(); } else { LOGGER.warning("Found DNS connection with no initial session connection"); dnsDuration = firstReqPacket - dns.doubleValue(); } // Prevent from being added again dns = null; } Double initConnDuration = null; if (synTime != null) { initConnDuration = firstReqPacket - synTime; if (startTime < 0.0) { startTime = synTime.doubleValue(); } // Prevent from being added again synTime = null; } // Calculate request time if (startTime < 0.0) { startTime = firstReqPacket; } // Store waterfall in request/response if (sslNegTime != null) { rr.waterfallInfos = new RequestResponseTimeline(startTime, dnsDuration, initConnDuration, sslNegTime - firstReqPacket, 0, 0, lastRespPacket - sslNegTime); } else { if (firstRespPacket >= lastReqPacket) { rr.waterfallInfos = new RequestResponseTimeline(startTime, dnsDuration, initConnDuration, null, lastReqPacket - firstReqPacket, firstRespPacket - lastReqPacket, lastRespPacket - firstRespPacket); } else { rr.waterfallInfos = new RequestResponseTimeline(startTime, dnsDuration, initConnDuration, null, 0, 0, lastRespPacket - firstReqPacket); } } }// if null check end }// rr check end } } } /* by pass for UDP sessions.*/ } /** * Returns the HTTP request/response result list. * * @return The result The list object containing the requests and * responses. */ public List<HttpRequestResponseInfo> getResult() { return Collections.unmodifiableList(result); } /** * Returns a list of HTTP requests and responses from the specified TCP * session. * * @param direction * The direction i.e. uplink/downlink. * @throws IOException * * @return A List of HttpRequestResponseInfo objects that contain the * request/response data from a TCP session. */ public synchronized void extractHttpRequestResponseInfo( PacketInfo.Direction direction) throws IOException { SortedMap<Integer, PacketInfo> packetOffsets; switch (direction) { case DOWNLINK: this.input = session.getStorageDl(); packetOffsets = session.getPacketOffsetsDl(); break; case UPLINK: this.input = session.getStorageUl(); packetOffsets = session.getPacketOffsetsUl(); break; default: throw new IllegalArgumentException("Direction argument invalid"); } this.counter = 0; HttpRequestResponseInfo rrInfo = findNextRequestResponse(direction, packetOffsets); String line; while ((line = readLine()) != null && rrInfo != null) { if (line.length() == 0) { if (rrInfo.contentLength > 0) { //rrInfo.contentOffsetLength = new TreeMap<Integer, Integer>(); rrInfo.contentOffsetLength = new TreeMap<Integer,Integer>(); rrInfo.contentOffsetLength.put(counter, rrInfo.contentLength); // Skip content counter = Math.min(input.length, counter + rrInfo.contentLength); if (counter < 0) { counter = input.length; } } else if (rrInfo.chunked) { rrInfo.contentOffsetLength = new TreeMap<Integer,Integer>(); while (true) { // Read each chunk line = readLine(); if (line != null) { String[] s = line.split(";"); int size = Integer.parseInt(s[0].trim(), 16); if (size > 0) { // Save content offsets rrInfo.contentOffsetLength.put(counter, size); rrInfo.contentLength += size; for (int i = 0; i < size; ++i) { readInput(); } // CRLF at end of each chunk line = readLine(); if (line != null && line.length() > 0) { LOGGER.warning("Unexpected end of chunk: " + line); } } else { rrInfo.chunkModeFinished = true; // End of chunks line = readLine(); if (line != null && line.length() > 0) { LOGGER.warning("Unexpected end of chunked data: " + line); } break; } } else { break; } } } mapPackets(packetOffsets, rrInfo.rrStart, counter - 1, direction, rrInfo); rrInfo.rawSize = counter - rrInfo.rrStart; // Build an absolute URI if possible if (rrInfo.objUri != null && !rrInfo.objUri.isAbsolute()) { try { int port = Integer.valueOf(rrInfo.port).equals(WELL_KNOWN_PARTS.get(rrInfo.scheme)) ? -1 : rrInfo.port; rrInfo.objUri = new URI(rrInfo.scheme.toLowerCase(), null, rrInfo.hostName, port, rrInfo.objUri.getPath(), rrInfo.objUri.getQuery(), rrInfo.objUri.getFragment()); } catch (URISyntaxException e) { // Just log fine message LOGGER.log(Level.FINE, "Unexpected exception creating URI for request: " + e.getMessage()+ ". Scheme=" + rrInfo.scheme.toLowerCase() +",Host name="+ rrInfo.hostName +",Path=" + rrInfo.objUri.getPath() + ",Fragment="+ rrInfo.objUri.getFragment()); } } result.add(rrInfo); if (rrInfo.getDirection() == null) { LOGGER.warning("Request/response object has unknown direction"); } rrInfo = findNextRequestResponse(direction, packetOffsets); } else { parseHeaderLine(line, rrInfo); } } // end: while } /** * Process of map the packets with its direction. * * @param packetOffsets * The collection of packets with ids. * @param start * The begin id. * @param end * The end id. * @param direction * The packet direction i.e. uplink/downlink. * @param rrInfo * The request/response info associated with the packet. */ private void mapPackets(SortedMap<Integer, PacketInfo> packetOffsets, int start, int end, PacketInfo.Direction direction, HttpRequestResponseInfo rrInfo) { // Determine the packets that make up the request/response rrInfo.firstDataPacket = determineDataPacketAtIndex(packetOffsets, start, direction); rrInfo.lastDataPacket = determineDataPacketAtIndex( packetOffsets, counter - 1, direction); // Removed because this logic is not totally correct and is currently not needed // long startSeq = ((TCPPacket) rrInfo.firstDataPacket.getPacket()) // .getSequenceNumber(); // long endSeq = ((TCPPacket) lastDataPacket.getPacket()) // .getSequenceNumber(); // ArrayList<PacketInfo> rrPackets = new ArrayList<PacketInfo>(); // for (PacketInfo p : session.getPackets()) { // TCPPacket tcp = (TCPPacket) p.getPacket(); // if (p.getDir() == direction) { // if (tcp.getSequenceNumber() >= startSeq // && tcp.getSequenceNumber() <= endSeq // + lastDataPacket.getPayloadLen()) { // rrPackets.add(p); // p.setRequestResponseInfo(rrInfo); // } // } // } // rrPackets.trimToSize(); // rrInfo.packets = rrPackets; } /** * Determine the packets that make up the request/response * * @param packetOffsets * @param index * @return Success case PacketInfo which creates a request/response; * else null. */ private PacketInfo determineDataPacketAtIndex( SortedMap<Integer, PacketInfo> packetOffsets, int index, PacketInfo.Direction direction) { // Determine the packets that make up the request/response for (SortedMap.Entry<Integer, PacketInfo> entry : packetOffsets .entrySet()) { int packetOffset = entry.getKey().intValue(); if (index >= packetOffset && index < packetOffset + entry.getValue().getPayloadLen()) { return entry.getValue(); } } if(direction == PacketInfo.Direction.UPLINK && this.session.getStorageUlEx() != null) { index = this.session.getStorageUlEx().length - 1; } else if(direction == PacketInfo.Direction.DOWNLINK && this.session.getStorageDlEx() != null) { index = this.session.getStorageDlEx().length - 1; } for (SortedMap.Entry<Integer, PacketInfo> entry : packetOffsets .entrySet()) { int packetOffset = entry.getKey().intValue(); if (index >= packetOffset && index < packetOffset + entry.getValue().getPayloadLen()) { return entry.getValue(); } } return null; } /** * Read a line of text from the HTTP request/response stream * * @param input * the request/response stream * @return Next line of text in stream or null if end of stream reached * @throws IOException */ private synchronized String readLine() throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); int b; try { // Look for CRLF while ((b = readInput()) != -1) { switch (b) { case '\r': b = readInput(); if (b == '\n') { // Return found line of text return new String(output.toByteArray(), UTF8); } else { output.write('\r'); output.write(b); } break; default: output.write(b); } } // End of stream return output.size() > 0 ? new String(output.toByteArray(), UTF8) : null; } finally { output.close(); } } /** * process to detect the next HttpRequestResponseInfo. * * @param direction * indicates the HTTP transaction direction with server. * REQUEST/RESPONSE. * @param packetOffsets * range of packet info. * @return next HttpRequestResponseInfo object. * @throws IOException */ private synchronized HttpRequestResponseInfo findNextRequestResponse( PacketInfo.Direction direction, SortedMap<Integer, PacketInfo> packetOffsets) throws IOException { int index = counter; String line = readLine(); while (line != null && line.length() == 0) { index = counter; line = readLine(); } HttpRequestResponseInfo rrInfo = null; if (line != null) { Matcher matcher; rrInfo = new HttpRequestResponseInfo(session, direction); rrInfo.rrStart = index; // Check for request type matcher = strReRequestType.matcher(line); if (matcher.lookingAt()) { rrInfo.statusLine = line; rrInfo.requestType = matcher.group(1); rrInfo.direction = Direction.REQUEST; rrInfo.objName = matcher.group(2); try { rrInfo.objUri = new URI(rrInfo.objName); if (rrInfo.objUri.getHost() != null) { rrInfo.hostName = rrInfo.objUri.getHost(); } } catch (URISyntaxException e) { // Ignore since value does not have to be a URI } rrInfo.version = matcher.group(3); rrInfo.scheme = rrInfo.version.split("/")[0]; switch (direction) { case UPLINK: rrInfo.port = session.getRemotePort(); break; case DOWNLINK: rrInfo.port = session.getLocalPort(); break; } } // Get response matcher = strReResponseResults.matcher(line); if (matcher.lookingAt()) { rrInfo.statusLine = line; rrInfo.direction = Direction.RESPONSE; rrInfo.version = matcher.group(1); rrInfo.scheme = rrInfo.version.split("/")[0]; rrInfo.statusCode = Integer.parseInt(matcher.group(2)); rrInfo.responseResult = matcher.group(3); } if (rrInfo.direction == null) { // Check for HTTPS if (session.isSsl()) { rrInfo.ssl = true; } while ((line = readLine()) != null && line.length() > 0) { ; } rrInfo.rawSize = counter - index; switch (direction) { case UPLINK: rrInfo.direction = Direction.REQUEST; break; case DOWNLINK: rrInfo.direction = Direction.RESPONSE; // Actual content length is unknown so headers are // included rrInfo.contentOffsetLength = new TreeMap<Integer, Integer>(); rrInfo.contentOffsetLength.put(index, rrInfo.rawSize); break; } mapPackets(packetOffsets, index, counter - 1, direction, rrInfo); result.add(rrInfo); } } return rrInfo; } /** * Parse data from the line of text * * @param headerLine * @param rrInfo */ private synchronized void parseHeaderLine(String headerLine, HttpRequestResponseInfo rrInfo) { appendHeaderToHttpRequestResponseInfo(headerLine, rrInfo); Matcher matcher; String[] s; // Get request host matcher = strReRequestHost.matcher(headerLine); if (matcher.lookingAt()) { String hostName = headerLine.substring(matcher.end()).trim(); // Strip port info if included int i = hostName.indexOf(':'); if (i >= 0) { hostName = hostName.substring(0, i); } rrInfo.hostName = hostName; return; } // Get request content length matcher = strReResponseContentLength.matcher(headerLine); if (matcher.lookingAt() && rrInfo.contentLength == 0) { try{ rrInfo.contentLength = Integer.parseInt(headerLine.substring(matcher.end()).trim()); }catch(NumberFormatException e) { /* The value exceeds the Interger.MAX_VALUE i.e 2^31-1=2147483647*/ LOGGER.log(Level.FINE, "Cannot parse the string to int for contentLength,because" + " The value to parse is :" + (headerLine.substring(matcher.end()).trim()) + " which is greater than the Integer.MAX_VALUE (2^31-1=2147483647)."); } return; } // Get request transfer encoding matcher = strReTransferEncoding.matcher(headerLine); if (matcher.lookingAt()) { rrInfo.chunked = CHUNKED.equals(headerLine.substring(matcher.end()) .trim()); return; } // Get request transfer encoding matcher = strReResponseContentEncoding.matcher(headerLine); if (matcher.lookingAt()) { rrInfo.contentEncoding = headerLine.substring(matcher.end()).trim().toLowerCase(); return; } // Get content type matcher = strReResponseContentType.matcher(headerLine); if (matcher.lookingAt()) { s = headerLine.substring(matcher.end()).trim().split(";"); rrInfo.contentType = s[0].trim().toLowerCase(); for (int i = 1; i < s.length; ++i) { int index = s[i].indexOf("="); if (index >= 0) { String attr = s[i].substring(0, index - 1).trim(); if (CHARSET.equals(attr)) { rrInfo.charset = s[i].substring(index).trim(); } } } return; } // Date matcher = strReResponseDate.matcher(headerLine); if (matcher.lookingAt()) { rrInfo.date = readHttpDate(matcher.group(1), false); return; } // Pragma: no-cache matcher = strReResponsePragmaNoCache.matcher(headerLine); if (matcher.lookingAt()) { rrInfo.hasCacheHeaders = true; rrInfo.pragmaNoCache = true; return; } // Cache-Control matcher = strReResponseCacheControl.matcher(headerLine); if (matcher.lookingAt()) { s = matcher.group(1).split(","); if (s.length > 0) { rrInfo.hasCacheHeaders = true; } for (int i = 0; i < s.length; ++i) { String directive = s[i].trim(); if (NOCACHE.equals(directive)) { rrInfo.noCache = true; continue; } else if (NOSTORE.equals(directive)) { rrInfo.noStore = true; continue; } // max-age matcher = strReCacheMaxAge.matcher(directive); if (matcher.lookingAt()) { rrInfo.maxAge = Long.valueOf(matcher.group(1)); continue; } if (rrInfo.direction == Direction.REQUEST) { if (ONLYIFCACHED.equals(directive)) { rrInfo.onlyIfCached = true; continue; } // min-fresh matcher = strReCacheMinFresh.matcher(directive); if (matcher.lookingAt()) { rrInfo.minFresh = Long.valueOf(matcher.group(1)); continue; } // max-stale matcher = strReCacheMaxStale.matcher(directive); if (matcher.lookingAt()) { rrInfo.maxStale = matcher.group(1) != null ? Long .valueOf(matcher.group(1)) : Long.MAX_VALUE; continue; } } else if (rrInfo.direction == Direction.RESPONSE) { if (PUBLIC.equals(directive)) { rrInfo.publicCache = true; continue; } else if (PRIVATE.equals(directive)) { rrInfo.privateCache = true; continue; } else if (MUSTREVALIDATE.equals(directive)) { rrInfo.mustRevalidate = true; continue; } else if (PROXYREVALIDATE.equals(directive)) { rrInfo.proxyRevalidate = true; continue; } // s-maxage matcher = strReCacheSMaxAge.matcher(directive); if (matcher.lookingAt()) { rrInfo.sMaxAge = Long.valueOf(matcher.group(1)); continue; } } } return; } if (rrInfo.direction == Direction.RESPONSE) { // ETag matcher = strReResponseEtag.matcher(headerLine); if (matcher.lookingAt()) { rrInfo.etag = matcher.group(2); return; } // Age matcher = strReResponseAge.matcher(headerLine); if (matcher.lookingAt()) { rrInfo.age = Long.valueOf(matcher.group(1)); return; } // Expires matcher = strReResponseExpires.matcher(headerLine); if (matcher.lookingAt()) { rrInfo.expires = readHttpDate(matcher.group(1), true); return; } // Last modified matcher = strReResponseLastMod.matcher(headerLine); if (matcher.lookingAt()) { rrInfo.lastModified = readHttpDate(matcher.group(1), false); return; } // Content-Range matcher = strReContentRange.matcher(headerLine); if (matcher.lookingAt()) { rrInfo.rangeResponse = true; rrInfo.rangeFirst = Integer.parseInt(matcher.group(1)); try{ rrInfo.rangeLast = Integer.parseInt(matcher.group(2)); }catch(NumberFormatException e) { /* The value exceeds the Interger.MAX_VALUE i.e 2^31-1=2147483647. * Continue.*/ LOGGER.log(Level.FINE, "Cannot parse the string to int for rangeLast,because" + " The value to parse is :" + matcher.group(2) + " which is greater than the Integer.MAX_VALUE (2^31-1=2147483647)."); } rrInfo.rangeFull = Long.parseLong(matcher.group(3)); if (rrInfo.contentLength == 0) { rrInfo.contentLength = rrInfo.rangeLast - rrInfo.rangeFirst + 1; } return; } } else if (rrInfo.direction == Direction.REQUEST) { // Referrer matcher = strReResponseReferer.matcher(headerLine); if (matcher.lookingAt()) { try { rrInfo.referrer = new URI(matcher.group(1).trim()); } catch (URISyntaxException e) { LOGGER.fine("Invalid referrer URI: " + matcher.group(1)); } return; } // If-Modified-Since matcher = strReIfModifiedSince.matcher(headerLine); if (matcher.lookingAt()) { rrInfo.ifModifiedSince = true; return; } // If-None-Match matcher = strReIfNoneMatch.matcher(headerLine); if (matcher.lookingAt()) { rrInfo.ifNoneMatch = true; return; } } LOGGER.log(Level.FINEST, "found a line that was not parsed: {0}", headerLine); } private void appendHeaderToHttpRequestResponseInfo(String line, HttpRequestResponseInfo rrInfo) { if (rrInfo != null) { StringBuilder headersBuilder; if (rrInfo.allHeaders == null) { headersBuilder = new StringBuilder(); } else { headersBuilder = new StringBuilder(rrInfo.allHeaders); } headersBuilder.append(HEADERS_SEPARATOR).append(line); rrInfo.allHeaders = headersBuilder.toString(); } } /** * Reads from input stream keeping counter of how much has been read * * @return * @throws IOException */ private synchronized int readInput() throws IOException { int result; if (counter < input.length) { result = input[counter]; ++counter; } else { result = -1; } return result; } /** * Parses HTTP date formats. Synchronized because DateFormat objects are * not thread-safe. If defaultForExpired is true and value is an invalid * dateFormat (such as -1 or 0 meaning already expired), the returned * Date will be "beginning of time" Jan 1 1970. * * @param value * @param defaultForExpired * boolean - true/false provide default "beginning of time" * Jan 1 1970 GMT Date * @return formated Date value else null. */ private synchronized Date readHttpDate(String value, boolean defaultForExpired) { if (value != null) { for (DateFormat dateFormat : dateFormats) { try { return dateFormat.parse(value.trim()); } catch (ParseException e) { // Ignore for now } } } if (defaultForExpired) { return BEGINNING_OF_TIME; } LOGGER.fine("Unable to parse HTTP date: " + value); return null; } } /** * Builds the request/response list from the specified TCP session * * @param session * The tcp session object. * @return The list of requests/responses that were found in the specified * tcp session. * @throws IOException */ public static List<HttpRequestResponseInfo> extractHttpRequestResponseInfo( TCPSession session) throws IOException { return new RequestResponseBuilder(session).getResult(); } /** * Constructor */ private HttpRequestResponseInfo(TCPSession session, PacketInfo.Direction direction) { if (session == null || direction == null) { throw new IllegalArgumentException( "Neither session nor direction may be null"); } this.session = session; this.packetDirection = direction; // Initialize session remote host this.hostName = session.getRemoteHostName(); } /** * Compares the specified HttpRequestResponseInfo object to this one. * * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(HttpRequestResponseInfo o) { return Double.valueOf(getTimeStamp()).compareTo( Double.valueOf(o.getTimeStamp())); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj instanceof HttpRequestResponseInfo) { HttpRequestResponseInfo oHttp = (HttpRequestResponseInfo)obj; return Double.valueOf(getTimeStamp()) == oHttp.getTimeStamp(); } else { return false; } } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return (int)Double.doubleToLongBits(getTimeStamp()); } /** * Returns the TCP session. * * @return A TCPSession object containing the TCP session. */ public TCPSession getSession() { return session; } /** * Returns the associated HTTP request/response. For instance, if this * object contains an HTTP request, then this method will return the HTTP * response associated with that request. * * @return An HttpRequestResponseInfo object containing the associated * request/response. */ public HttpRequestResponseInfo getAssocReqResp() { return assocReqResp; } /** * Returns the waterfall information for this request/response pair. This * is only set when the direction is "REQUEST" and there is an associated * response. * @return */ public RequestResponseTimeline getWaterfallInfos() { return waterfallInfos; } /** * Returns the timestamp of the first packet associated with this * HttpRequestResponseInfo . This is the offset of the request/response * within the current trace. * * @return A double that is the first packet timestamp associated with this * HttpRequestResponseInfo. If the first packet is null, then this * method returns 0. */ public double getTimeStamp() { return firstDataPacket != null ? firstDataPacket.getTimeStamp() : 0.0; } /** * Gets the real Date (the first packet Date) for the request/response. * * @return The first packet Date associated with the * HttpRequestResponseInfo. If the first packet is null, then this * method returns null. */ public Date getAbsTimeStamp() { return firstDataPacket != null ? new Date(Math.round(firstDataPacket .getPacket().getTimeStamp() * 1000)) : null; } /** * Returns the direction (request or response). * * @return An HttpRequestResponseInfo.Direction enumeration value that * indicates the direction. */ public Direction getDirection() { return direction; } /** * @return the statusLine */ public String getStatusLine() { return statusLine; } /** * The HTTP requestType. * * @return A string containing the HTTP requestType. */ public String getRequestType() { return requestType; } /** * Returns the HTTP object name. * * @return A string containing the object name. */ public String getObjName() { return objName; } /** * Returns the HTTP object URL. * * @return The HTTP object URL. */ public URI getObjUri() { return objUri; } /** * Returns the HTTP object name without parameters. * * @return A string containing the object name without parameters. */ public String getObjNameWithoutParams() { if (objName != null && objNameWithoutParams == null) { int index = objName.indexOf('?'); if (index > 0) { objNameWithoutParams = objName.substring(0, index); } else { objNameWithoutParams = objName; } } return objNameWithoutParams; } /** * Returns the file name that was accessed by this request * @return */ public String getFileName() { if (objName != null && fileName == null) { String s = getObjNameWithoutParams(); int index = s.lastIndexOf('/'); if (index == s.length() - 1) { --index; } fileName = index >= 0 ? s.substring(index + 1) : s; } return fileName; } /** * Returns the host name. * * @return A string containing the host name. */ public String getHostName() { return hostName; } /** * Returns the status code. * * @return An int that is the status code. */ public int getStatusCode() { return statusCode; } /** * Returns the content type. * * @return A string that describes the content type. */ public String getContentType() { return contentType; } /** * Returns the content length. * * @return The content length in bytes. */ public int getContentLength() { return contentLength; } /** * Returns the raw size in bytes. * * @return The raw size in bytes. */ public int getRawSize() { return rawSize; } /** * Returns the raw size in kilobytes. * * @return The raw size in kilobytes. */ public double getRawSizeInKB() { return (double) rawSize / 1024; } /** * @return the encrypted */ public boolean isSsl() { return ssl; } /** * Returns the protocol used (e.g http) * @return the scheme */ public String getScheme() { return scheme; } /** * Returns the HTTP request/response version. * * @return A string that is the HTTP request/response version. */ public String getVersion() { return version; } /** * Returns the HTTP response result. * * @return A string containing the HTTP response result. */ public String getResponseResult() { return responseResult; } /** * Returns the HTTP request/response ContentEncoding. * * @return A string containing the ContentEncoding. */ public String getContentEncoding() { return contentEncoding; } /** * Returns the first data packet associated with the request/response. * * @return A PacketInfo object containing the first data packet. */ public PacketInfo getFirstDataPacket() { return firstDataPacket; } /** * Returns the HTTP request/response date. * * @return The date. */ public Date getDate() { return date; } /** * Returns the HTTP CacheHeaders state. * * @return A boolean value that is true if the request/response has * CacheHeaders, and is false otherwise. */ public boolean isHasCacheHeaders() { return hasCacheHeaders; } /** * Returns the HTTP PragmaNoCache state. * * @return A boolean value that is true if the request/response has * PragmaNoCache, and is false otherwise. */ public boolean isPragmaNoCache() { return pragmaNoCache; } /** * Returns the HTTP NoCache state. * * @return A boolean value that is true if the request/response has NoCache, * and is false otherwise. */ public boolean isNoCache() { return noCache; } /** * Returns the HTTP NoStore state. * * @return A boolean value that is true if the request/response has NoStore, * and is false otherwise. */ public boolean isNoStore() { return noStore; } /** * Returns the HTTP PublicCache state. * * @return A boolean value that is true if the request/response has * PublicCache, and is false otherwise. */ public boolean isPublicCache() { return publicCache; } /** * Returns the HTTP PrivateCache state. * * @return A boolean value that is true if the request/response has * PrivateCache, and is false otherwise. */ public boolean isPrivateCache() { return privateCache; } /** * Returns the HTTP MustRevalidate state. * * @return A boolean value that is true if the request/response has * MustRevalidate, and is false otherwise. */ public boolean isMustRevalidate() { return mustRevalidate; } /** * Returns the HTTP ProxyRevalidate state. * * @return A boolean value that is true if the request/response has * ProxyRevalidate, and is false otherwise. */ public boolean isProxyRevalidate() { return proxyRevalidate; } /** * Returns the HTTP OnlyIfCached state. * * @return A boolean value that is true if the request/response has * OnlyIfCached, and is false otherwise. */ public boolean isOnlyIfCached() { return onlyIfCached; } /** * Returns the HTTP etag. * * @return A string containing the HTTP etag. */ public String getEtag() { return etag; } /** * Returns the HTTP request/response age. * * @return The HTTP request/response age. */ public Long getAge() { return age; } /** * Returns the HTTP request/response expire date. * * @return The HTTP request/response expire date. */ public Date getExpires() { return expires; } /** * Returns the URI referrer. * * @return The URI referrer. */ public URI getReferrer() { return referrer; } /** * Returns the HTTP request/response LastModified date. * * @return The HTTP request/response LastModified date. */ public Date getLastModified() { return lastModified; } /** * Returns the HTTP request/response MaxAge. * * @return The HTTP request/response MaxAge. */ public Long getMaxAge() { return maxAge; } /** * Returns the HTTP request/response sMaxAge. * * @return The HTTP request/response sMaxAge. */ public Long getsMaxAge() { return sMaxAge; } /** * Returns the HTTP request/response minFresh. * * @return The HTTP request/response minFresh. */ public Long getMinFresh() { return minFresh; } /** * Returns the HTTP request/response maxStale. * * @return The HTTP request/response maxStale. */ public Long getMaxStale() { return maxStale; } /** * To know the packet direction * * @return direction */ public PacketInfo.Direction getPacketDirection() { return packetDirection; } /** * Returns all headers. * * @return Headers as a long string. */ public String getAllHeaders() { return allHeaders; } /** * Returns the binary content of the request/response body. * * @return An array of bytes containing the binary content of the * request/response body, or Null if no content is found. * * @throws ContentException * - When part of the content is not available. */ public byte[] getContent() throws ContentException, IOException { if (contentOffsetLength != null) { byte[] buffer = getStorageBuffer(); if (buffer == null) { return null; } ByteArrayOutputStream output = null; for (Map.Entry<Integer, Integer> entry : contentOffsetLength .entrySet()) { int start = entry.getKey(); int size = entry.getValue(); if( start + size < 0) { throw new ContentException("The content may be too big."); } else if (buffer.length < start + size) { throw new ContentException("The content may be corrupted."); } for (int i = start; i < start + size; ++i) { if (output == null) { output = new ByteArrayOutputStream((int) getActualByteCount()); } output.write(buffer[i]); } } if (CONTENT_ENCODING_GZIP.equals(contentEncoding) && output != null) { // Decompress gzipped content GZIPInputStream gzip=null; try{ gzip = new GZIPInputStream( new ByteArrayInputStream(output.toByteArray())); output.reset(); buffer = new byte[2048]; int len; while ((len = gzip.read(buffer)) >= 0) { output.write(buffer, 0, len); } }catch(IOException ioe){ if (gzip != null) { try{ gzip.close(); }catch (IOException ex){ throw ex; } } if (output != null) { try{ output.close(); }catch (IOException ex){ throw ex; } } LOGGER.log(Level.FINE, " IOException !!.The file may be corrupt." + ioe.getMessage()); } } if (output != null) { return output.toByteArray(); } else { return new byte[0]; } } else { return null; } } /** * Saves the binary content of the request/response body to the specified * file. * * @throws ContentException * - When part of content is not available. */ public void saveContentToFile(File file) throws IOException { if (contentOffsetLength != null) { FileOutputStream fos = new FileOutputStream(file); try { fos.write(getContent()); } catch (ContentException e) { // If we get a ContentException, just save the bytes we have byte[] buffer = getStorageBuffer(); if (buffer == null) { buffer = new byte[0]; } for (Map.Entry<Integer, Integer> entry : contentOffsetLength .entrySet()) { int start = entry.getKey(); int len = Math.min(entry.getValue(), buffer.length - start); fos.write(buffer, start, len); } } finally { fos.close(); } } } /** * Gets the number of bytes in the request/response body. The actual byte * count. * * @return The total number of bytes in the request/response body. If * contentOffsetLength is null, then this method returns 0. */ public long getActualByteCount() { if (contentOffsetLength != null) { byte[] buffer = getStorageBuffer(); int bufferSize = buffer != null ? buffer.length : 0; long result = 0; for (Map.Entry<Integer, Integer> entry : contentOffsetLength .entrySet()) { int start = entry.getKey(); int size = entry.getValue(); if (bufferSize < start + size) { // Only include what was actually downloaded. size = bufferSize - start; } result += size; } return result; } else { return 0; } } /** * Determines whether the same content is contained in this request/response as in * the specified request/response * @param rr The request to compare to * @return true if the content is the same */ public boolean isSameContent(HttpRequestResponseInfo rr) { // Check specified content length if (contentLength > 0 && contentLength != rr.contentLength) { return false; } long count = getActualByteCount(); if (count == rr.getActualByteCount()) { // If not data then they are the same if (count == 0) { return true; } // Otherwise do byte by byte compare byte[] b1 = getStorageBuffer(); byte[] b2 = rr.getStorageBuffer(); Iterator<Map.Entry<Integer, Integer>> it1 = contentOffsetLength.entrySet().iterator(); Iterator<Map.Entry<Integer, Integer>> it2 = rr.contentOffsetLength.entrySet().iterator(); if (it1.hasNext() && it2.hasNext()) { Map.Entry<Integer, Integer> e1 = it1.next(); Map.Entry<Integer, Integer> e2 = it2.next(); int i1 = e1.getKey(); int i2 = e2.getKey(); do { if (b1[i1] != b2[i2]) { return false; } ++i1; ++i2; if (i1 >= b1.length || i2 >= b2.length) { break; } if (i1 >= e1.getKey() + e1.getValue()) { if (it1.hasNext()) { e1 = it1.next(); i1 = e1.getKey(); } else { break; } } if (i2 >= e2.getKey() + e2.getValue()) { if (it2.hasNext()) { e2 = it2.next(); i2 = e2.getKey(); } else { break; } } } while (true); } return true; } else { return false; } } /** * Returns the HTTP rangeResponse state. * * @return A boolean value that is true if the request/response has * rangeResponse, and is false otherwise. */ public boolean isRangeResponse() { return rangeResponse; } /** * Returns the HTTP request/response rangeFirst value. * * @return An int that is the HTTP request/response rangeFirst value. */ public int getRangeFirst() { return rangeFirst; } /** * Returns the HTTP request/response rangeLast value. * * @return An int that is the HTTP request/response rangeLast value. */ public int getRangeLast() { return rangeLast; } /** * Returns the HTTP request/response rangeFull value. * * @return The HTTP request/response rangeFull. */ public long getRangeFull() { return rangeFull; } /** * Returns the HTTP request/response IfModifiedSince state. * * @return A boolean value that is true if the request/response has * IfModifiedSince, and is false otherwise */ public boolean isIfModifiedSince() { return ifModifiedSince; } /** * Returns the HTTP request/response ifNoneMatch state. * * @return A boolean value that is true if the request/response has * ifNoneMatch, and is false otherwise. */ public boolean isIfNoneMatch() { return ifNoneMatch; } /** * Returns the HTTP request/response chunked state. * * @return A boolean value that is true if the request/response is chunked, * and is false otherwise. */ public boolean isChunked() { return chunked; } /** * Returns the HTTP request/response chunkModeFinished state. * * @return A boolean value that is true if the request/response has * chunkModeFinished, and is false otherwise. */ public boolean isChunkModeFinished() { return chunkModeFinished; } /** * Returns the request/response body as a text string. The returned text may * not be readable. * * @return The content of the request/response body as a string, or null if * the method does not execute successfully. * * @throws ContentException * - When part of the content is not available. */ public String getContentString() throws ContentException, IOException { byte[] content = getContent(); return content != null ? new String(content, charset != null ? charset : UTF8) : null; } /** * Returns the entire request/response including headers as a UTF-8 string. * No decompression of the content is done. * @return UTF-8 string or null if an error occurred */ public String getRequestResponseText() { byte[] storage = getStorageBuffer(); if (storage == null) { return null; } try { return new String(storage, rrStart, rawSize, UTF8); } catch (UnsupportedEncodingException e) { // This should not happen because UTF-8 is valid encoding LOGGER.log(Level.SEVERE, "Unexpected error creating request/response string", e); return null; } } /** * Convenience method that gets the storage array in the session where this request/ * response is located. * @return */ private byte[] getStorageBuffer() { switch (packetDirection) { case DOWNLINK: return session.getStorageDl(); case UPLINK: return session.getStorageUl(); default: // This should not happen because value is checked on construction LOGGER.severe("Packet direction for request/response is has unexpected value"); return null; } } /** * Indicates whether the HTTP content is image or not. * * @return Returns true when the content is image otherwise returns false. */ public boolean isImageContent() { if (this.getContentType() != null && this.getContentType().contains(IMAGE)) { return true; } return false; } /** * Indicates whether the server response containing text payload is * compressed or not. * * @return Returns "none" string if the server response with a text payload is not * compressed. Otherwise returns a string representation of the compression type used. */ public String getHttpCompression() { return textFileCompression.toString(); } /** * Indicates whether the server response containing text payload is * compressed or not. * * @param textFileCompressionAnalysis * - Text file compression analysis. * * @return Returns true when the text file payload is not compressed. * Otherwise returns false. */ public boolean setHttpCompression(TextFileCompressionAnalysis textFileCompressionAnalysis) { boolean rsp = false; if (packetDirection == PacketInfo.Direction.DOWNLINK && contentLength != 0 && contentType != null && isTextContent(contentType)) { if (CONTENT_ENCODING_GZIP.equals(contentEncoding)) { textFileCompression = TextFileCompression.GZIP; textFileCompressionAnalysis.incrementNoOfCompressedFiles(); } else if (CONTENT_ENCODING_COMPRESS.equals(contentEncoding)) { textFileCompression = TextFileCompression.COMPRESS; textFileCompressionAnalysis.incrementNoOfCompressedFiles(); } else if (CONTENT_ENCODING_DEFLATE.equals(contentEncoding)) { textFileCompression = TextFileCompression.DEFLATE; textFileCompressionAnalysis.incrementNoOfCompressedFiles(); } else { // the content should be compressed but is not textFileCompression = TextFileCompression.NONE; if(contentLength > TextFileCompressionAnalysis.FILE_SIZE_THRESHOLD_BYTES) { textFileCompressionAnalysis.incrementNoOfUncompressedFiles(); textFileCompressionAnalysis.addToTotalUncompressedSize(contentLength); rsp = true; } else { textFileCompressionAnalysis.incrementNoOfCompressedFiles(); } } } else { textFileCompression = TextFileCompression.NOT_APPLICABLE; } return rsp; } /** * Indicates whether the packet is a response packet and the content type is * text/html. * * @param AsyncCheckAnalysis * - Script loading asynchronous analysis. * * @return Returns true when there are no asynchronously loaded files or the * packet's content type is not text/html. Otherwise returns false. */ public boolean checkAsyncAttributeInHead( AsyncCheckAnalysis asyncCheckAnalysis) { // Checking the content length and content type (only text/html). if (contentLength != 0 && contentType != null && isContentTypeTextHtml(contentType)) { return asyncCheckAnalysis.parseHtmlToFindSyncLoadingScripts(this); } else { return true; } } /** * Indicates whether the content type is text/html or not. * * @return Returns true if the content type is text/html otherwise return false; */ boolean isContentTypeTextHtml(String contentType){ return (contentType.equalsIgnoreCase("text/html")); } public org.jsoup.nodes.Document parseHtml(FileOrderAnalysis fileOrderAnalysis){ org.jsoup.nodes.Document doc = null; String packetContent = null; try { if (this.getContentString() != null) { if ((contentLength != 0) && (contentType != null) && (isContentTypeTextHtml(contentType))) { try { packetContent = this.getContentString(); } catch (ContentException e) { LOGGER.log(Level.FINE, "ContentException in parseHtml()"); } catch (IOException e) { LOGGER.log(Level.FINE, "IOExecption in parseHtml()"); } if (packetContent != null) { doc = Jsoup.parse(packetContent); } } } } catch (ContentException e) { LOGGER.log(Level.FINE,"ContentException in parseHtml()"); } catch (IOException e) { LOGGER.log(Level.FINE,"IOExecption in parseHtml()"); } if (doc != null) { return doc; } else { return null; } } /** * Indicates whether the content type is text or not. * * The following content types are considered as text: * - any type starting with 'text/' * - any type starting with 'application/' and followed by 'xml', for example: 'application/atom+xml' * - application/ecmascript * - application/json * - application/javascript * - message/http * * @return Returns true if the content type is text otherwise return false; */ public static boolean isTextContent(String contentType) { if (contentType.equals("application/ecmascript") || contentType.equals("application/json") || contentType.equals("application/javascript") || contentType.equals("message/http")) { return true; } else { Matcher m = TEXT_CONTENT_TYPE_TEXT.matcher(contentType); if (m.matches()) { return true; } m = TEXT_CONTENT_TYPE_XML.matcher(contentType); if (m.matches()) { return true; } return false; } } /** * Indicates whether the content type is JavaScript or not. * * The following content types are considered as JavaScript: * * - application/ecmascript * - application/javascript * - text/javascript * * @return returns true if the content type is JavaScript otherwise return false * */ public static boolean isJavaScript(String contentType) { return (contentType.equals("application/ecmascript") || contentType.equals("application/javascript") || contentType.equals("text/javascript")); } /** * Indicates whether the content type is CSS or not. * * The following content types are considered as CSS: * * - text/css * * @return returns true if the content type is CSS otherwise return false * */ public static boolean isCss(String contentType) { return contentType.equals("text/css") ? true : false; } /** * Indicates whether the content type is HTML or not. * * The following content types are considered as HTML: * * - text/html * * @return returns true if the content type is HTML otherwise return false * */ public static boolean isHtml(String contentType) { return contentType.equals("text/html") ? true : false; } public static boolean isJSON(String contentType) { return contentType.equals("application/json") ? true : false; } }
Nearly every other country in the world yearns for the deep relationship that India has with Silicon Valley, Boston, New York, Austin and all the other entrepreneurship hubs in the United States. Everywhere you go in the world, cities and nations are trying to recreate Silicon Valley. But they do it from a distance because they lack insider access to Silicon Valley and its tight-knit community of technologists, coders, entrepreneurs, innovators and investors. But India has it. Around 25% of startups in America’s entrepreneurial hubs have an Indian American co-founder or executive, according to research by Duke University. America’s leading technology companies, including Google, Microsoft and Adobe, have CEO’s that were born and raised in India. Nearly every American company has a major presence in India – to access India’s technical talent for back-office tasks, R&D and product development, or eventually, to reach India’s growing middle class. And Silicon Valley spawned the Indus Entrepreneurs – an organization of South Asian entrepreneurs that annually hosts the largest entrepreneurship conference in the Bay Area, and has been the driver of American investment in Indian startups. Unfortunately, India hasn’t done nearly enough to take advantage of this incredible resource. The Indian government has been slow to recognize the role of innovation and entrepreneurship in achieving the countries development goals. The Indian private sector has been slow to adopt many of the best practices of their peers in the United States technology community. The result is that, while India is a world leader in technology services, it was late to join the “apps economy” and its startup sector continues to be focused mostly on IT – even though that includes Big Data, mobile apps and e-commerce. On the one hand, the Modi Government has shown itself adept at courting Silicon Valley – most recently by participating in a live town hall with Mark Zuckerberg at Facebook. But recent policies announced by the Modi government have generally not placed innovation and entrepreneurship as integral to India’s development. The Prime Minister did announce a “Startup India, Standup India” policy in January. But the policy itself did little but provide basic streamlining of government services for startups and provide tax holidays to startups (who don’t make any money, and therefore, don’t pay taxes anyway) and seemed geared to appease India’s investor class and influential Indian Americans trying to recreate the American regulatory environment in India. Far more indicative was the release of the Government of India’s budget, which provided few incentives to integrate R&D, innovation and entrepreneurship into broader policy goals. On the one hand, the Prime Minister has launched ambitious programs to improve quality of life in India. There is Jan Dhan Yojna, which has created bank accounts for 150 million Indians in the hopes moving them to the formal economy and maximizing mobile banking opportunities. There is “Make In India” to attract manufacturing to India. And there is “Swachh Bharat”, a national program to improve hygiene and water usage. Unfortunately, India has been struggling with these challenges for most of its history as an independent nation. And existing government programs have never been enough to solve problems like water scarcity, access to capital or the lack of local manufacturing. But the solution is not to double-down on those same programs, or offer incentives to large multinationals to build automated factories in India that won’t actually create a lot of low-skilled jobs. The solution is to scour the world – far and wide, for innovations that are relevant to India and encourage entrepreneurs to commercialize and scale those solutions – in India. An informal survey I did of leading American accelerators last year revealed that about 10-20% of the participating entrepreneurs were building technologies for the developing world. A similar informal survey of entrepreneurship at Indian universities revealed that nearly 50% of their startup ideas were focused on India’s development challenges. So the solutions are there, and the entrepreneurs are there. There are countless innovations focused on climate change – data analytics for monitoring the environment, clean tech and sustainable water and agriculture. There is an emerging breed of Indian entrepreneurs in the fields of 3D printing, synthetic biology and next generation agriculture. And India is already home to the world’s largest community of social entrepreneurs and social enterprises seeking scalable business models to solve societal challenges. The Government of India, along with the private sector, can do two important things to connect these impressive innovators and entrepreneurs with the larger agenda of development First, they can expand the startup culture beyond Bangalore, Hyderabad and Delhi. While lip service has been paid to this in the form of funding for accelerators and startup tax policy, the government has not looked to seed innovation and build organizations that it can partner with. Instead of “Startup India”, I have advocated for a policy of “Silicon Swadesh”. You can pick whatever name you like, but the focus should make high-growth entrepreneurship an option across India – and specifically in the 52 Tier II and III cities in India that have populations over 1 million. These cities should be nurturing entrepreneurship with all the well-known tools practiced by accelerators and entrepreneurship programs worldwide. But it should be done in the context of the ecosystem, which in India is a growing private sector, Public Sector Enterprises (PSE) and the Government. Corporate philanthropy and government can support entrepreneurship programs beyond the best universities. Organizations like the Deshpande Foundation, Wadhwani Foundation, TiE and the Sankalp Forum have already supported contextual innovation and entrepreneurship across India. The missing connection is integration with policy objectives. The Indian government can also build local capacity for the industries of the future. While technologies 3D printing, synthetic biology or hydroponics may not make a big impact in India for 10-15 years, the investment must start today. This is a traditional role for government – to invest in emerging industries before the private sector has the ability to. One area in which the government has made limited progress is related to climate change. But even here, policies are geared towards incumbent firms, rather than the best performing, low-cost technologies. Secondly, India’s private sector must use its significant capabilities and clout to support entrepreneurship. They can target their corporate philanthropy to support entrepreneurship programs, or invest directly in innovation in areas like education and agriculture. Innovative philanthropic organizations like the Michael & Susan Dell Foundation, along with Sunil Wadhwani’s WISH Foundation, are already changing the way philanthropy uses private sector levers – such as financing and corporate restructuring techniques, to rapidly improve NGO’s and government programs. Ironically, India has a legion of successful Indian-origin entrepreneurs, financiers and philanthropists in Silicon Valley, Boston and around the world, that are willing to help. No other country has access to such a level of talent for such a low cost. Instead of taking it for granted or simply celebrating it – use it.
Optimal therapy of epilepsy by measuring serum concentration of antiepileptic drugs with least adverse effects. The study comprised 150 epileptic patients treated at the Institute of Neurology of the Clinical Centre Novi Sad. The optimal therapy with least adverse effects and seizures was achieved in patients in whom measurement of serum concentration of antiepileptic drugs was performed. Patients were divided into five groups with respect to the therapy they received: I--carbamazepane; II--valproic acid; III--polytherapy with phenobarbitone and diphenylhydantoin; IV--phenobarbitone and valproic acid; and V--phenobarbitone, valproic acid and carbamazepine. No adverse effects were recorded in over 60% of patients on monotherapy, 35% of patients who received two anticonvulsants, and 30% of patients who received three anticonvulsants. Significant correlation between drug dosage and blood drug concentration (r > 0.5) was found in polytherapy with phenobarbitone, carbamazepine and valproic acid (r = 0.66); and phenobarbitone and diphenylhydantoin (r = 0.53).
Off-Design Prediction of Transonic Axial Compressors: Part 1 Mean-Line Code and Tuning Factors With yearly advances in CFD techniques and methodologies, and the increased capacity and capabilities of computer CPU, GPU, and information storage, CFD has become a powerful design tool. However, despite its vast strengths, a CFD analysis is still based on the sound development of the 1D mean-line analysis methodology. This paper (part 1 of 2) describes an off-design axial compressor mean-line code, tested in a specialized engineering software for the development and analysis of a whole gas turbine engine, and the various tuning factors used to obtain an off-design performance match. It will be shown that, to obtain a proper match of the off-design performance of single-stage transonic axial compressors, both the rotor and stage pressure ratio, and the rotor temperature ratio are required to be converged upon. To do so, the off-design mean-line analysis requires the incorporation of a set of inlet & exit blockage factors and deviation angles that vary with the compressor performance conditions. This approach differs from the literature-based procedural assumptions (or rule-of-thumb) of fixed inlet and exit blockage factors of approximately 0.98, and the use of a unique deviation angle based on Carters rule. The results obtained in this paper are then used to develop a generalized off-design mean-line loss modelling methodology (part 2 of 2) capable of predicting the off-design performance of four well documented NASA transonic axial compressors.
<filename>source/projects/ar.spiral_tilde/ar.spiral_tilde.cpp #include "c74_min.h" using namespace c74::min; class spiral : public object<spiral>, public vector_operator<> { public: MIN_DESCRIPTION {"smooth distortion"}; MIN_TAGS {"distortion"}; MIN_AUTHOR {"<NAME>"}; inlet<> in1 {this, "(signal) Input1"}; inlet<> in2 {this, "(signal) Input2"}; outlet<> out1 {this, "(signal) Output1", "signal"}; outlet<> out2 {this, "(signal) Output2", "signal"}; message<> dspsetup {this, "dspsetup", MIN_FUNCTION { fpd = 17; //this is reset: values being initialized only once. Startup values, whatever they are. return {}; } }; void operator()(audio_bundle _input, audio_bundle _output) { double* in1 = _input.samples(0); double* in2 = _input.samples(1); double* out1 = _output.samples(0); double* out2 = _output.samples(1); long sampleFrames = _input.frame_count(); while (--sampleFrames >= 0) { long double inputSampleL = *in1; long double inputSampleR = *in2; if (fabs(inputSampleL)<1.18e-43) inputSampleL = fpd * 1.18e-43; if (fabs(inputSampleR)<1.18e-43) inputSampleR = fpd * 1.18e-43; //clip to 1.2533141373155 to reach maximum output inputSampleL = sin(inputSampleL * fabs(inputSampleL)) / ((fabs(inputSampleL) == 0.0) ?1:fabs(inputSampleL)); inputSampleR = sin(inputSampleR * fabs(inputSampleR)) / ((fabs(inputSampleR) == 0.0) ?1:fabs(inputSampleR)); //begin 64 bit stereo floating point dither int expon; frexp((double)inputSampleL, &expon); fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5; inputSampleL += static_cast<int32_t>(fpd) * 1.110223024625156e-44L * pow(2,expon+62); frexp((double)inputSampleR, &expon); fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5; inputSampleR += static_cast<int32_t>(fpd) * 1.110223024625156e-44L * pow(2,expon+62); //end 64 bit stereo floating point dither *out1 = inputSampleL; *out2 = inputSampleR; *in1++; *in2++; *out1++; *out2++; } } private: uint32_t fpd; //default stuff }; MIN_EXTERNAL(spiral);
Transcriptome-wide analysis of alternative splicing events in bladder cancer: Novel biomarkers discovery for early diagnosis. 483Background: Cystoscopy, an invasive, painful and expensive method, is currently the main clinical tool for new diagnosis and disease recurrence detection of bladder cancer (BCa). The need for new biomarkers discovery that is costless, sensitive and specific is urgent. This project aims to study and compare alternative splicing events (ASE) in BCa tissues and normal bladder tissues and ultimately, identify specific spliced events coding for proteins detectable in urine by liquid chromatographymass spectrometry. Methods: In this study, alterations to the global RNA splicing landscape of cellular genes were investigated in a large-scale screen from 408 BCa tissues and 19 normal tissues provided by The Cancer Genome Atlas (TCGA). Three statistical thresholds were used to determine substantial modifications. All events showing a p-value<0.05 and a level of expression ≥ 50 transcripts per million; -10 ≥ percent splice index ≤10; and a q-value<0.05 were conserved. Next, mRNA expression levels between cance...
<reponame>coac-gmbh/okuna-web export class UserVisibility { static public = new UserVisibility('P'); static okuna = new UserVisibility('O'); static private = new UserVisibility('T'); static _values: UserVisibility[] = [ UserVisibility.private, UserVisibility.public, UserVisibility.okuna, ]; static values() { return UserVisibility._values.slice(0); } static parse(val: string): UserVisibility | undefined { let badgeKeyword; for (let i = 0; i < UserVisibility._values.length; i++) { const value = UserVisibility._values[i]; if (val == value.code) { badgeKeyword = value; break; } } if (!badgeKeyword) { console.error(`Unsupported userVisibility type ${val}`); } return badgeKeyword; } constructor(public code: string) { }; toString(): string { return this.code; } }
// newServer creates a new network server. func newServer(n *net, enablePubSub bool, opts ...grpc.DialOption) (*server, error) { var ( s = &server{ net: n, conns: make(map[peer.ID]*grpc.ClientConn), } defaultOpts = []grpc.DialOption{ s.getLibp2pDialer(), grpc.WithInsecure(), } ) s.opts = append(defaultOpts, opts...) if enablePubSub { ps, err := pubsub.NewGossipSub( n.ctx, n.host, pubsub.WithMessageSigning(false), pubsub.WithStrictSignatureVerification(false)) if err != nil { return nil, err } s.ps = NewPubSub(n.ctx, n.host.ID(), ps, s.pubsubHandler) ts, err := n.store.Threads() if err != nil { return nil, err } for _, id := range ts { if err := s.ps.Add(id); err != nil { return nil, err } } } return s, nil }
The military said its initial investigation revealed that a 35-year-old Palestinian from a village near Hebron tried to run over an officer with a Bobcat tractor. The U.S. vetoed an Arab-backed resolution that sought to explore ways to ensure “international protection” for Palestinian civilians, and there wasn’t enough support to pass a U.S. resolution to condemn Hamas. The United States has strongly indicated during negotiations on the resolution that it would veto the measure. “If it will be quiet, we will respond with quiet. We’ve given Hamas a chance to prove that we can return to routine ... If they release the reins there will be a very painful strike,” Israeli Cabinet minister Arieh Deri said. The sudden burst of violence follows weeks of mass Palestinian protests along the Gaza border with Israel. The step was sure to worsen the already troubled relations between the internationally backed Palestinian Authority and Israeli Prime Minister Benjamin Netanyahu’s government. Izzeldin Abuelaish lost three daughters and a neice in the Gaza conflict. Now he calls on Prime Minister Justin Trudeau to live up to his promises and help injured children there. International protests and boycotts are necessary to rein in the toxic tendencies of Israel’s Netanyahu and Donald Trump, writes Tony Burman. Countries such as Iran and Saudi Arabia are vying for regional control, while Israel is seeking maintain a military supremacy of its own. The prime minister is adding his voice to the calls for an independent investigation into the shootings by Israeli soldiers on the Gaza border that killed 59 Palestinians and wounded hundreds more during Monday’s mass protests. Show based on Mideast antagonism has become a global hit for Netflix. Season 2 debuts May 24. Tarek Loubani, an emergency physician from London, Ont., was testing 3D-printed tourniquets when he was wounded by Israeli sniper fire during Monday’s violence in Gaza. A crowd of more than 50 gathered in front of the Halifax Public Gardens a day after 59 protesters were killed at the Gaza border. Fifty-nine were killed Monday in what was the single deadliest day in Gaza since 2014. About 2,700 were injured. Moving the U.S. embassy to Jerusalem has damaged, not helped, the cause of peace and progress in the Middle East.
import {structureType} from "../_utils"; import {Method} from "../../../src/abap/3_structures/structures"; const cases = [ {abap: ` METHOD get_lines. result = VALUE ztimem_line_t( FOR part IN parts FOR line IN part-lines ( line ) ). ENDMETHOD.`}, ]; structureType(cases, new Method());
<gh_stars>1-10 package im.cave.ms.connection.packet; import im.cave.ms.client.MapleClient; import im.cave.ms.client.character.Macro; import im.cave.ms.client.character.MapleCharacter; import im.cave.ms.client.character.Stat; import im.cave.ms.client.character.items.Equip; import im.cave.ms.client.character.items.InventoryOperation; import im.cave.ms.client.character.items.Item; import im.cave.ms.client.character.items.ScrollUpgradeInfo; import im.cave.ms.client.character.potential.CharacterPotential; import im.cave.ms.client.character.skill.Skill; import im.cave.ms.client.character.temp.TemporaryStatManager; import im.cave.ms.client.field.Effect; import im.cave.ms.client.field.Portal; import im.cave.ms.client.field.movement.MovementInfo; import im.cave.ms.connection.crypto.TripleDESCipher; import im.cave.ms.connection.netty.OutPacket; import im.cave.ms.connection.netty.Packet; import im.cave.ms.connection.packet.opcode.RecvOpcode; import im.cave.ms.connection.packet.opcode.SendOpcode; import im.cave.ms.connection.packet.result.FameResult; import im.cave.ms.connection.packet.result.InGameDirectionEvent; import im.cave.ms.enums.*; import im.cave.ms.tools.DateUtil; import im.cave.ms.tools.Position; import im.cave.ms.tools.Randomizer; import java.util.*; import static im.cave.ms.constants.ServerConstants.DES_KEY; import static im.cave.ms.constants.ServerConstants.MAX_TIME; import static im.cave.ms.enums.InventoryType.EQUIPPED; /** * @author fair * @version V1.0 * @Package im.cave.ms.net.packet.opcode * @date 11/29 22:25 */ public class UserPacket { public static final Map<Stat, Long> EMPTY_STATUS = Collections.emptyMap(); public static OutPacket enableActions() { return statChanged(EMPTY_STATUS, true, null); } public static OutPacket statChanged(Map<Stat, Long> stats, MapleCharacter chr) { return statChanged(stats, false, chr); } public static OutPacket statChanged(Map<Stat, Long> stats, boolean enableActions, MapleCharacter chr) { OutPacket out = new OutPacket(SendOpcode.STAT_CHANGED); out.write(enableActions ? 1 : 0); out.write(0); //unk long mask = 0; for (Stat stat : stats.keySet()) { mask |= stat.getValue(); } out.writeLong(mask); Comparator<Stat> comparator = Comparator.comparingLong(Stat::getValue); TreeMap<Stat, Long> sortedStats = new TreeMap<>(comparator); sortedStats.putAll(stats); for (Map.Entry<Stat, Long> entry : sortedStats.entrySet()) { Stat stat = entry.getKey(); long value = entry.getValue(); switch (stat) { case SKIN: out.write((byte) value); break; case FACE: case HAIR: case HP: case MAXHP: case MP: case MAXMP: case FAME: case CHARISMA: case CHARM: case WILL: case SENSE: case INSIGHT: case CRAFT: case LEVEL: case ICE_GAGE: case JOB: out.writeInt((int) value); break; case STR: case DEX: case INT: case LUK: case AVAILABLEAP: case FATIGUE: out.writeShort((int) value); break; case AVAILABLESP: chr.encodeRemainingSp(out); break; case EXP: case MESO: out.writeLong(value); break; case TODAYS_TRAITS: out.writeZeroBytes(21); //限制 break; } } out.write(chr != null ? chr.getCharLook().getHairColorBase() : -1); out.write(chr != null ? chr.getCharLook().getHairColorMixed() : 0); out.write(chr != null ? chr.getCharLook().getHairColorProb() : 0); out.write(0); out.write(0); out.write(0); return out; } public static OutPacket inventoryOperation(boolean exclRequestSent, InventoryOperationType type, short oldPos, short newPos, int bagPos, Item item) { InventoryOperation inventoryOperation = new InventoryOperation(type); inventoryOperation.setItem(item); inventoryOperation.setBagPos(bagPos); inventoryOperation.setNewPos(newPos); inventoryOperation.setOldPos(oldPos); List<InventoryOperation> operations = Collections.singletonList(inventoryOperation); return inventoryOperation(exclRequestSent, operations); } public static OutPacket move(MapleCharacter player, MovementInfo movementInfo) { OutPacket out = new OutPacket(SendOpcode.REMOTE_MOVE); out.writeInt(player.getId()); movementInfo.encode(out); return out; } public static OutPacket setStandAloneMode(boolean enable) { OutPacket out = new OutPacket(SendOpcode.SET_STAND_ALONE_MODE); out.writeBool(enable); return out; } public static OutPacket setInGameDirectionMode(boolean lockUI, boolean blackFrame, boolean forceMouseOver, boolean showUI) { OutPacket out = new OutPacket(SendOpcode.SET_IN_GAME_DIRECTION_MODE); out.writeBool(lockUI); out.writeBool(blackFrame); if (lockUI) { out.writeBool(forceMouseOver); out.writeBool(showUI); } return out; } public static OutPacket updateMaplePoint(MapleCharacter chr) { OutPacket out = new OutPacket(SendOpcode.UPDATE_MAPLE_POINT); out.writeInt(chr.getId()); out.writeInt(chr.getAccount().getPoint()); return out; } /* 角色乘坐地图固定椅子或者起身离开移动椅子时 */ public static OutPacket sitResult(int charId, short id) { OutPacket out = new OutPacket(SendOpcode.SIT_RESULT); out.writeInt(charId); if (id != -1) { out.write(1); out.writeShort(id); } else { out.write(0); } return out; } public static OutPacket userSit() { OutPacket out = new OutPacket(SendOpcode.USER_SIT); out.writeInt(0); return out; } public static OutPacket sendRebirthConfirm(boolean onDeadRevive, boolean onDeadProtectForBuff, boolean onDeadProtectBuffMaplePoint, boolean onDeadProtectExpMaplePoint, boolean anniversary, int reviveType, int protectType) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.OPEN_DEAD_UI.getValue()); int reviveMask = 0; if (onDeadRevive) { reviveMask |= 0x1; } if (onDeadProtectForBuff) { reviveMask |= 0x2; } if (onDeadProtectBuffMaplePoint) { reviveMask |= 0x4; } if (onDeadProtectExpMaplePoint) { reviveMask |= 0x8; } out.writeInt(reviveMask); out.writeBool(anniversary); out.writeInt(reviveType); if (onDeadProtectForBuff || onDeadProtectExpMaplePoint) { out.writeInt(protectType); } return out; } public static OutPacket changeSkillRecordResult(Skill skill) { List<Skill> skills = new ArrayList<>(); skills.add(skill); return changeSkillRecordResult(skills, true, false, false, false); } public static OutPacket changeSkillRecordResult(List<Skill> skills, boolean exclRequestSent, boolean showResult , boolean removeLinkSkill, boolean sn) { OutPacket out = new OutPacket(SendOpcode.CHANGE_SKILL_RECORD_RESULT); out.writeBool(exclRequestSent); out.writeBool(showResult); out.writeBool(removeLinkSkill); out.writeShort(skills.size()); for (Skill skill : skills) { out.writeInt(skill.getSkillId()); out.writeInt(skill.getCurrentLevel()); out.writeInt(skill.getMasterLevel()); out.writeLong(MAX_TIME); } out.writeBool(sn); return out; } public static OutPacket setSkillCoolTime(int skillId, int cdMS) { Map<Integer, Integer> cds = new HashMap<>(); cds.put(skillId, cdMS); return setSkillCoolTime(cds); } public static OutPacket setSkillCoolTime(MapleCharacter chr) { Map<Integer, Long> skillCooltimes = chr.getSkillCooltimes(); if (skillCooltimes == null || skillCooltimes.size() == 0) { return null; } long now = System.currentTimeMillis(); HashMap<Integer, Integer> cds = new HashMap<>(); skillCooltimes.forEach((skillId, time) -> cds.put(skillId, Math.min((int) (time - now), 0)) ); return setSkillCoolTime(cds); } public static OutPacket setSkillCoolTime(Map<Integer, Integer> cooltimes) { OutPacket out = new OutPacket(SendOpcode.SKILL_COOLTIME_SET); out.writeInt(cooltimes.size()); cooltimes.forEach((id, cooltime) -> { out.writeInt(id); out.writeInt(cooltime); }); return out; } public static OutPacket skillCoolDown(int skillId) { HashMap<Integer, Integer> skills = new HashMap<>(); skills.put(skillId, 0); return setSkillCoolTime(skills); } public static OutPacket removeBuff(TemporaryStatManager tsm, boolean demount) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.REMOVE_BUFF.getValue()); out.writeInt(0); out.write(1); out.write(1); for (int i : tsm.getRemovedMask()) { out.writeInt(i); } tsm.getRemovedStats().forEach((characterTemporaryStat, options) -> out.writeInt(0)); if (demount) { out.writeBool(true); } return out; } public static OutPacket giveBuff(TemporaryStatManager tsm) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.GIVE_BUFF.getValue()); out.writeZeroBytes(8); tsm.encodeForLocal(out); return out; } public static OutPacket effect(Effect effect) { OutPacket out = new OutPacket(SendOpcode.EFFECT); effect.encode(out); return out; } public static OutPacket teleport(int type, Position position, Portal portal) { OutPacket out = new OutPacket(SendOpcode.TELEPORT); out.writeBool(false);// excl request out.write(type); /* TODO: import the enum enum USER_TELEPORT_CALLING_TYPE { TELEPORT_CALLING_TYPE_DEFAULT = 0x0, TELEPORT_CALLING_TYPE_GUILD = 0x1, TELEPORT_CALLING_TYPE_FLAMEWIZARD_FLAREBLINK = 0x2, TELEPORT_CALLING_TYPE_BYSCRIPT = 0x3, }; */ switch (type) { case 0x00: out.writeInt(portal.getId()); out.write(0); break; case 0xCD: out.writeInt(1);//charId out.writePosition(position); break; } return out; } public static OutPacket incMoneyMessage(int amount) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.MESSAGE.getValue()); out.write(MessageType.INC_MONEY_MESSAGE.getVal()); out.writeInt(amount); out.writeInt(-1); out.writeInt(amount > 0 ? 0 : -1); return out; } public static OutPacket message(MessageType mt, int i, String string, byte type) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.MESSAGE.getValue()); out.write(mt.getVal()); switch (mt) { case CASH_ITEM_EXPIRE_MESSAGE: case INC_POP_MESSAGE: case INC_GP_MESSAGE: case GIVE_BUFF_MESSAGE: out.writeInt(i); break; case INC_COMMITMENT_MESSAGE: out.writeInt(i); out.write(i < 0 ? 1 : i == 0 ? 2 : 0); // gained = 0, lost = 1, cap = 2 break; case SYSTEM_MESSAGE: out.writeMapleAsciiString(string); break; case QUEST_RECORD_EX_MESSAGE: case WORLD_SHARE_RECORD_MESSAGE: case COLLECTION_RECORD_MESSAGE: out.writeInt(i); out.writeMapleAsciiString(string); break; case INC_HARDCORE_EXP_MESSAGE: out.writeInt(i); //You have gained x EXP out.writeInt(i); //Field Bonus Exp break; case BARRIER_EFFECT_IGNORE_MESSAGE: out.write(type); //protection/shield scroll pop-up Message break; } return out; } public static OutPacket stylishKillMessage(long exp, int count) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.MESSAGE.getValue()); out.write(MessageType.STYLISH_KILL_MESSAGE.getVal()); out.write(0); out.writeLong(exp); out.writeInt(0); //unk out.writeInt(count); out.writeInt(1); //unk return out; } public static OutPacket comboKillMessage(int objId, int combo) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.MESSAGE.getValue()); out.write(MessageType.STYLISH_KILL_MESSAGE.getVal()); out.write(1); out.writeInt(combo); out.writeInt(objId); out.writeInt(0); //unk out.writeInt(1); //unk return out; } public static OutPacket inventoryRefresh(boolean excl) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.INVENTORY_OPERATION.getValue()); out.writeBool(excl); out.writeShort(0); return out; } public static OutPacket scrollUpgradeDisplay(boolean feverTime, List<ScrollUpgradeInfo> scrolls) { OutPacket out = new OutPacket(SendOpcode.EQUIPMENT_ENCHANT); out.write(EquipmentEnchantType.ScrollUpgradeDisplay.getVal()); out.writeBool(feverTime); out.write(scrolls.size()); scrolls.forEach(scrollUpgradeInfo -> scrollUpgradeInfo.encode(out)); return out; } public static OutPacket showScrollUpgradeResult(boolean feverTime, int result, String desc, Equip prevEquip, Equip equip) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.EQUIPMENT_ENCHANT.getValue()); out.write(EquipmentEnchantType.ShowScrollUpgradeResult.getVal()); out.writeBool(feverTime); out.writeInt(result); out.writeMapleAsciiString(desc); prevEquip.encode(out); equip.encode(out); return out; } public static OutPacket macroSysDataInit(MapleCharacter chr) { OutPacket out = new OutPacket(SendOpcode.MACRO_SYS_DATA_INIT); out.write(chr.getMacros().size()); for (Macro macro : chr.getMacros()) { macro.encode(out); } return out; } public static OutPacket characterPotentialSet(CharacterPotential cp) { return characterPotentialSet(true, true, cp.getKey(), cp.getSkillID(), cp.getSlv(), cp.getGrade(), true); } public static OutPacket characterPotentialSet(CharacterPotential cp, boolean updatePassive) { return characterPotentialSet(true, true, cp.getKey(), cp.getSkillID(), cp.getSlv(), cp.getGrade(), updatePassive); } public static OutPacket characterPotentialSet(boolean exclRequest, boolean changed, short pos, int skillID, short skillLevel, short grade, boolean updatePassive) { OutPacket out = new OutPacket(SendOpcode.CHARACTER_POTENTIAL_SET); out.writeBool(exclRequest); out.writeBool(changed); if (changed) { out.writeShort(pos); out.writeInt(skillID); out.writeShort(skillLevel); out.writeShort(grade); out.writeBool(updatePassive); //全部重置的话第三条就是true } return out; } public static OutPacket noticeMsg(String msg) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.NOTICE_MSG.getValue()); out.writeMapleAsciiString(msg); out.write(1); return out; } public static OutPacket damageSkinSaveResult(DamageSkinType req, DamageSkinType res, MapleCharacter chr) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.DAMAGE_SKIN_SAVE_RESULT.getValue()); out.write(req.getVal()); if (req.getVal() <= 2) { out.write(res.getVal()); if (res == DamageSkinType.DamageSkinSave_Success) { chr.encodeDamageSkins(out); } } else if (req == DamageSkinType.DamageSkinSaveReq_SendInfo) { chr.encodeDamageSkins(out); } return out; } public static OutPacket resurrectionCountdown(int time1, int time2, boolean opt) { OutPacket out = new OutPacket(SendOpcode.RESURRECTION_COUNTDOWN); out.writeInt(time1); //20s out.writeInt(time2); //20s out.writeBool(opt); //false return out; } public static OutPacket updateHonerPoint(int honerPoint) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.CHARACTER_HONOR_POINT.getValue()); out.writeInt(honerPoint); return out; } public static OutPacket keymapInit(MapleCharacter character) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.KEYMAP_INIT.getValue()); character.getKeyMap().encode(out); return out; } public static OutPacket quickslotInit(MapleCharacter player) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.QUICKSLOT_INIT.getValue()); boolean edited = player.getQuickSlots() != null && player.getQuickSlots().size() == 32; out.writeBool(edited); if (player.getQuickSlots() != null) { for (Integer key : player.getQuickSlots()) { out.writeInt(key); } } return out; } public static OutPacket progress(int progress) { OutPacket out = new OutPacket(SendOpcode.PROGRESS); out.writeInt(progress); return out; } public static OutPacket openWorldMap() { OutPacket out = new OutPacket(SendOpcode.OPEN_WORLDMAP); out.writeInt(0); return out; } public static OutPacket initOpCodeEncryption(MapleClient client) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.INIT_OPCODE_ENCRYPTION.getValue()); out.writeInt(4); //block size List<Integer> used = new ArrayList<>(); StringBuilder sOpcodes = new StringBuilder(); for (int i = RecvOpcode.BEGIN.getValue(); i < RecvOpcode.END.getValue(); i++) { int opcode = Randomizer.rand(RecvOpcode.BEGIN.getValue(), 9999); while (used.contains(opcode)) { opcode = Randomizer.rand(RecvOpcode.BEGIN.getValue(), 9999); } String sOpcode = String.format("%04d", opcode); if (!used.contains(opcode)) { client.mEncryptedOpcode.put(opcode, i); used.add(opcode); sOpcodes.append(sOpcode); } } used.clear(); TripleDESCipher tripleDESCipher = new TripleDESCipher(DES_KEY); try { byte[] buffer = new byte[Short.MAX_VALUE + 1]; byte[] encrypt = tripleDESCipher.Encrypt(sOpcodes.toString().getBytes()); System.arraycopy(encrypt, 0, buffer, 0, encrypt.length); for (int i = encrypt.length; i < buffer.length; i++) { buffer[i] = 0; } out.writeInt(buffer.length); out.write(buffer); } catch (Exception e) { e.printStackTrace(); client.close(); } return out; } public static OutPacket updateEventNameTag() { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.CANCEL_TITLE_EFFECT.getValue()); for (int i = 0; i < 5; i++) { out.writeShort(0); out.write(-1); } return out; } public static OutPacket fameResponse(FameResult fameResult) { OutPacket out = new OutPacket(SendOpcode.FAME_RESPONSE); out.write(fameResult.getAction().getVal()); switch (fameResult.getAction()) { case Add: out.writeMapleAsciiString(fameResult.getStr()); out.write(fameResult.getArg1()); out.writeInt(fameResult.getArg2()); break; case Receive: out.writeMapleAsciiString(fameResult.getStr()); out.write(fameResult.getArg1()); break; case AlreadyAddInThisMonth: break; } return out; } public static OutPacket inventoryOperation(boolean exclRequestSent, List<InventoryOperation> operations) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.INVENTORY_OPERATION.getValue()); out.writeBool(exclRequestSent); out.writeShort(operations.size()); byte equipMove = 0; boolean addMovementInfo = false; for (InventoryOperation operation : operations) { Item item = operation.getItem(); short newPos = operation.getNewPos(); short oldPos = operation.getOldPos(); int bagPos = operation.getBagPos(); InventoryOperationType type = operation.getType(); InventoryType invType = item.getInvType(); if ((oldPos > 0 && newPos < 0 && invType == EQUIPPED) || (invType == EQUIPPED && oldPos < 0)) { invType = item.isCash() ? InventoryType.CASH_EQUIP : InventoryType.EQUIP; } out.write(type.getVal()); out.write(invType.getVal()); out.writeShort(oldPos); switch (type) { case ADD: item.encode(out); addMovementInfo = true; break; case UPDATE_QUANTITY: out.writeShort(item.getQuantity()); break; case MOVE: out.writeShort(newPos); if ((invType == InventoryType.EQUIP || invType == InventoryType.CASH_EQUIP) && (oldPos < 0 || newPos < 0)) { addMovementInfo = true; if (oldPos > 0) { equipMove += 2; } else { equipMove += 1; } } break; case REMOVE: if ((invType == InventoryType.EQUIP || invType == InventoryType.CASH_EQUIP) && (oldPos < 0 || newPos < 0)) { addMovementInfo = true; } break; case ITEM_EXP: out.writeLong(((Equip) item).getExp()); break; case UPDATE_BAG_POS: out.writeInt(bagPos); break; case UPDATE_BAG_QUANTITY: out.writeShort(newPos); break; case UNK_1: case UNK_3: break; case UNK_2: out.writeShort(bagPos); break; case UPDATE_ITEM_INFO: item.encode(out); break; } } if (addMovementInfo) { out.write(equipMove); } return out; } public static OutPacket inventoryGrow(InventoryType type, byte slots) { OutPacket out = new OutPacket(); out.write(type.getVal()); out.write(slots); return out; } public static OutPacket gatherItemResult(byte val) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.GATHER_ITEM_RESULT.getValue()); out.write(1); out.write(val); return out; } public static OutPacket sortItemResult(byte val) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.SORT_ITEM_RESULT.getValue()); out.write(1); out.write(val); return out; } public static OutPacket finalAttack(MapleCharacter chr, int weapon, int skillId, int finalSkillId) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.FINAL_ATTACK.getValue()); out.writeInt(chr.getTick()); out.writeInt(finalSkillId > 0); out.writeInt(skillId); out.writeInt(finalSkillId); out.writeInt(weapon); out.writeInt(0); return out; } public static OutPacket invExpandResult(int i, int point, boolean cash) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.SLOT_EXPAND_RESULT.getValue()); out.writeInt(i); out.writeInt(0); out.writeInt(point); out.write(2); out.writeShort(cash ? 1 : 0); return out; } public static OutPacket characterModified(MapleCharacter player) { OutPacket out = new OutPacket(); out.writeShort(SendOpcode.CHARACTER_MODIFIED.getValue()); out.write(1); out.writeLong(1); //mask out.write(0); player.encode(out, CharMask.Character); return out; } public static OutPacket openLimitBreakUI(MapleCharacter player, boolean success, Item item, long incALB, Equip equip) { OutPacket out = new OutPacket(SendOpcode.LIMIT_BREAK_UI); out.writeInt(player.getId()); out.writeBool(success); out.writeInt(item.getItemId()); out.writeInt(item.getPos()); out.writeInt(equip.getPos()); out.writeInt(1000); out.writeLong(equip.getLimitBreak()); out.writeLong(incALB); equip.encode(out); return out; } public static OutPacket hyperUpgradeDisplay(Equip equip, boolean downgradable, long stars, int successChance, int destroyChance, boolean chanceTime) { OutPacket out = new OutPacket(SendOpcode.EQUIPMENT_ENCHANT); out.write(EquipmentEnchantType.HyperUpgradeDisplay.getVal()); out.writeBool(downgradable); out.writeLong(stars); out.writeZeroBytes(18); out.writeInt(successChance); out.writeInt(destroyChance); out.writeBool(chanceTime); out.writeLong(0); TreeMap<EnchantStat, Integer> vals = equip.getHyperUpgradeStats(); int mask = 0; for (EnchantStat es : vals.keySet()) { mask |= es.getVal(); } out.writeInt(mask); vals.forEach((es, val) -> out.writeInt(val)); return out; } public static OutPacket showUnknownEnchantFailResult(byte type) { OutPacket outPacket = new OutPacket(SendOpcode.EQUIPMENT_ENCHANT); outPacket.write(EquipmentEnchantType.ShowUnknownFailResult.getVal()); outPacket.write(type); return outPacket; } public static OutPacket miniGameDisplay() { OutPacket outPacket = new OutPacket(SendOpcode.EQUIPMENT_ENCHANT); outPacket.write(EquipmentEnchantType.MiniGameDisplay.getVal()); outPacket.write(0); outPacket.writeInt(DateUtil.getTime()); return outPacket; } public static OutPacket showUpgradeResult(Equip oldEquip, Equip equip, boolean succeed, boolean boom, boolean canDegrade) { OutPacket out = new OutPacket(SendOpcode.EQUIPMENT_ENCHANT); out.write(EquipmentEnchantType.ShowHyperUpgradeResult.getVal()); out.writeInt(boom ? 2 : succeed ? 1 : canDegrade ? 0 : 3); out.write(0); oldEquip.encode(out); equip.encode(out); return out; } public static OutPacket additionalCubeResult(int charId, boolean upgrade, Item item, Equip equip) { OutPacket out = new OutPacket(SendOpcode.ADDITIONAL_CUBE_RESULT); out.writeInt(charId); out.writeBool(upgrade); out.writeInt(item.getItemId()); out.writeInt(equip.getPos()); out.writeInt(item.getQuantity()); equip.encode(out); return out; } public static OutPacket memorialCubeResult(Item item, Equip equip) { OutPacket out = new OutPacket(SendOpcode.MEMORIAL_CUBE_RESULT); out.writeLong(equip.getId()); out.writeBool(true); //equip!=null equip.encode(out); out.writeInt(item.getItemId()); out.writeInt(equip.getPos()); out.writeInt(item.getQuantity()); out.writeInt(item.getPos()); return out; } public static OutPacket blackCubeResult(Item item, Equip equip) { OutPacket out = new OutPacket(SendOpcode.BLACK_CUBE_RESULT); out.writeLong(equip.getId()); out.writeBool(true); equip.encode(out); out.writeInt(item.getItemId()); out.writeInt(equip.getPos()); out.writeInt(item.getQuantity()); out.writeInt(item.getPos()); return out; } public static Packet hexagonalCubeModifiedResult() { OutPacket out = new OutPacket(SendOpcode.HEXAGONAL_CUBE_RESULT); out.writeShort(1); out.writeInt(0); return out; } public static Packet reflectionCubeResult(Item item, Equip equip, MapleCharacter chr) { OutPacket out = new OutPacket(SendOpcode.REFLECTION_CUBE_RESULT); out.writeInt(chr.getId()); out.write(0); out.writeInt(item.getItemId()); out.writeInt(equip.getPos()); equip.encode(out); return out; } public static OutPacket hexagonalCubeResult(int level, List<Integer> options) { OutPacket out = new OutPacket(SendOpcode.HEXAGONAL_CUBE_RESULT); out.writeShort(0); out.writeInt(0); out.writeInt(level); out.writeInt(options.size()); for (Integer option : options) { out.writeInt(option); } return out; } public static OutPacket uniqueCubeResult(int line) { OutPacket out = new OutPacket(SendOpcode.UNIQUE_CUBE_RESULT); out.writeShort(0); out.writeInt(0); out.writeInt(line); return out; } public static OutPacket uniqueCubeModifiedResult(int line) { OutPacket out = new OutPacket(SendOpcode.UNIQUE_CUBE_RESULT); out.writeShort(1); out.writeInt(0); out.writeInt(line); return out; } public static OutPacket memorialCubeModified() { OutPacket out = new OutPacket(SendOpcode.MEMORIAL_CUBE_MODIFIED); out.writeBool(false); return out; } public static OutPacket miracleCirculatorResult(Set<CharacterPotential> potentials, Item item) { OutPacket out = new OutPacket(SendOpcode.MIRACLE_CIRCULATOR_RESULT); out.writeInt(potentials.size()); for (CharacterPotential potential : potentials) { out.writeInt(potential.getSkillID()); out.write(potential.getSlv()); out.write(potential.getKey()); out.write(potential.getGrade()); } out.writeInt(item.getItemId()); out.writeInt(0); out.writeInt(0); out.writeInt(0); out.writeInt(0); return out; } public static Packet userB2Body(short type, int bodyIdCounter) { OutPacket out = new OutPacket(SendOpcode.USER_B2_BODY); out.writeInt(type); out.writeInt(bodyIdCounter); return out; } public static OutPacket lifeCount(int count) { OutPacket out = new OutPacket(SendOpcode.LIFE_COUNT); out.writeInt(count); return out; } public static OutPacket goldHammerItemUpgradeResult(byte returnResult, int msg) { OutPacket out = new OutPacket(SendOpcode.GOLD_HAMMER_RESULT); out.write(0); out.write(returnResult); out.writeInt(msg); out.writeInt(0); out.writeInt(0); return out; } public static OutPacket modComboResponse(int combo) { OutPacket out = new OutPacket(SendOpcode.MOD_COMBO_RESPONSE); out.writeInt(combo); return out; } public static OutPacket incJudgementStack(byte amount) { OutPacket out = new OutPacket(SendOpcode.INC_JUDGEMENT_STACK_RESPONSE); out.write(0); out.write(amount); return out; } public static OutPacket updateVMatrix(MapleCharacter chr, boolean update, MatrixUpdateType updateType, int pos) { OutPacket out = new OutPacket(SendOpcode.UPDATE_MATRIX); chr.getMatrixInventory().encode(out); out.writeInt(update); if (update) { out.writeInt(updateType.getVal()); out.writeInt(pos); } return out; } public static OutPacket nodeCraftResult(int coreID, int quantity, int skillID1, int skillID2, int skillID3) { OutPacket out = new OutPacket(SendOpcode.NODE_CRAFT_RESULT); out.writeInt(coreID); out.writeInt(1); out.writeInt(skillID1); out.writeInt(skillID2); out.writeInt(skillID3); out.writeInt(quantity); //size return out; } public static OutPacket nodeEnhanceResult(int recordID, int exp, int slv1, int slv2) { OutPacket out = new OutPacket(SendOpcode.NODE_ENHANCE_RESULT); out.writeInt(recordID); out.writeInt(exp); out.writeInt(slv1); out.writeInt(slv2); return out; } public static OutPacket nodeShardResult(int shard) { OutPacket out = new OutPacket(SendOpcode.NODE_SHARD_RESULT); out.writeInt(shard); return out; } public static OutPacket erdaSpectrumCounter(int erda, int arg1, int arg2) { OutPacket out = new OutPacket(SendOpcode.ERDA_SPECTRUM); out.writeInt(erda); out.writeInt(arg1); out.writeInt(arg2); return out; } public static OutPacket inGameDirectionEvent(InGameDirectionEvent igdr) { OutPacket out = new OutPacket(SendOpcode.IN_GAME_DIRECTION_EVENT); igdr.encode(out); return out; } }
Congress has fielded its national spokesperson Randeep Singh Surjewala for Jind Assembly Constituency bye-election in Haryana. "Congress President, Rahul Gandhi has approved the candidature of Randeep Singh Surjewala as Congress candidate for the ensuing by-election to the Legislative Assembly of Haryana from the 36-Jind constituency," read a press release shared by All India Congress Committee (AICC) to announce the candidature of Randeep Surjewala. Surjewala is in-charge of Communications at Indian National Congress (INC). Jind assembly constituency was represented by Hari Chand Middha, a candidate from Indian National Lok Dal (INLD) party. The seat went vacant after Middha passed away due to illness on August 26. Bye-elections for the constituency are scheduled for January 28th. The counting of votes is scheduled for January 31.
/** * @author Javier Paniza */ public class NotNullStringConverter implements IConverter { public Object toJava(Object o) throws ConversionException { return notNull(o); } public Object toDB(Object o) throws ConversionException { return notNull(o); } private String notNull(Object o) throws ConversionException { if (o == null) return ""; return o.toString(); } }
China is proposing a further tightening of controls over the internet. Pic: Karen roach/Shutterstock A CONTESTED cybersecurity law has been given the seal of approval in China after its third and final reading in parliament last week, despite strong opposition from foreign businesses and human rights groups who call the law “abusive”. Authorities in China have cited prevention of crime and terrorism as the reason for passing the law, which bans activity aimed at “overthrowing the socialist system”, reports Associated Press. China resents attempts to challenge or criticize its ruling Communist Party’s authority, and regularly punishes dissidents. The Cyber Security Law will require Internet providers to cooperate with crime and national security investigations, enforce censorship, and also imposes mandatory standards for security technology, according to AP. SEE ALSO: Disputed Chinese cybersecurity law enters third and final stage for approval Human rights groups have protested the law, saying that it will further extend controls on an already heavily-monitored and censored media, and makes the Internet even less of a safe space for the public to express themselves. Bloomberg adds that companies are also obligated under the new law to allow government investigators full access to their data if any crime is suspected. Amnesty Internationals China researcher, Patrick Poon, said in a statement: “The new cyber-security law tightens the authorities’ repressive grip on the Internet. It goes further than ever before in codifying abusive practices, with a near total disregard for the rights to freedom of expression and privacy.” Foreign companies have expressed their concern that the Cyber Security Law will cause Chinese citizens to become distrustful of the technology, and choose local rivals instead. This is most likely China’s plan anyway, as Chinese industry group officials have been quoted by state media as saying that previous restrictions on the use of foreign security technology is intended to bolster and protect China’s own providers from the competition, reports AP. U.S. Deputy Secretary of Commerce Bruce Andrews told reporters during a visit to Beijing last month that the law would put up barriers that will hinder “cross-border data flow”, which is important for trading and operations. On Monday, Zhao Zeliang, director-general of the cybersecurity bureau of the Cyberspace Administration of China, said in a news conference that foreign companies are not being singled out, and are welcome “as long as they obey Chinese laws, serve the interests [of] Chinese consumers”. But foreign companies remain unconvinced at the reassurances, and have been on edge since the draft law was introduced earlier this year. In June, more than two dozen firms from around the world signed a letter to the chairman of the China Insurance Regulatory Commission protesting the law. Signatories included the American Chamber of Commerce in China, the Canada-China Business Council, the Japanese Chamber of Commerce and Industry in China, and TheCityUK. The letter said: “China… has the right to implement measures necessary for the maintenance of cybersecurity, but we believe that the Provisions go far beyond what is necessary. “If adopted as currently drafted, however, the Provisions would create unnecessary obstacles to international trade and likely to constitute a means of arbitrary or unjustifiable discrimination against producers and service providers in countries where the same conditions prevail.” SEE ALSO: How does China’s new and terrifying credit score system work? The new law comes as China’s new credit score system for citizens has begun receiving international attention due to its similarities to satirical TV series Black Mirror, in which every person has a credit score that determines their ability to do certain things, and is based on their behavior and Internet presence. Granting the Chinese government access to foreign companies’ data may smooth this credit score system and help authorities single out dissidents. But there are major privacy and security concerns involved.
<reponame>aniketadnaik/carbondataStreamIngest<filename>core/src/main/java/org/apache/carbondata/core/cache/update/BlockletLevelDeleteDeltaDataCache.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.carbondata.core.cache.update; import java.util.HashMap; import java.util.Map; import org.apache.carbondata.core.constants.CarbonCommonConstants; import org.roaringbitmap.RoaringBitmap; /** * This class maintains delete delta data cache of each blocklet along with the block timestamp */ public class BlockletLevelDeleteDeltaDataCache { private Map<Integer, RoaringBitmap> deleteDelataDataCache = new HashMap<>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE); private String timeStamp; public BlockletLevelDeleteDeltaDataCache(Map<Integer, Integer[]> deleteDeltaFileData, String timeStamp) { for (Map.Entry<Integer, Integer[]> entry : deleteDeltaFileData.entrySet()) { int[] dest = new int[entry.getValue().length]; int i = 0; for (Integer val : entry.getValue()) { dest[i++] = val.intValue(); } deleteDelataDataCache.put(entry.getKey(), RoaringBitmap.bitmapOf(dest)); } this.timeStamp = timeStamp; } public boolean contains(int key, Integer pageId) { return deleteDelataDataCache.get(pageId).contains(key); } public String getCacheTimeStamp() { return timeStamp; } }
Getting the flu jab could be a matter of life and death. That’s not rhetoric. It’s based on hard facts. And the risk is not just personal. If you get the flu, you could very well pass it on to your children, elderly relatives, friends and work colleagues. If you work in health and social care, you could put patients and other vulnerable people in harm’s way. In 2017, almost 330,000 of the nearly 890,000 people eligible for the flu vaccine did not go and get their flu vaccine. This is what the flu virus wants – it wants to spread, grow and multiply and we give it the perfect environment if we don’t vaccinate those considered to be most at risk. Last year in Northern Ireland, we saw one of the worst flu seasons in the last 10 years. According to the official figures, of those who ended up in hospital with the flu, 119 people were critically ill and needed intensive care, and 22 of those people died. However the true death rate from the flu is likely to be in the hundreds across the province. These figures are far too high. We must fight back. Here’s what we are doing. We offer an extensive free vaccination programme which gives a vaccine to those most at risk – almost 890,000 people are eligible. We offer all children aged between two and 11 years of age a vaccine aimed at protecting them and which helps prevent the spread of the virus. We’re making it as easy as possible for everyone eligible to get their free vaccine, from flu clinics in GPs, to in-school programmes. Because flu viruses change continuously, we have also invested heavily in this year’s flu programme, introducing two new vaccines to offer even greater protection to those most at risk. The Fluad® vaccine will be offered to everyone aged 65 years and over in Northern Ireland. It is expected to significantly boost effectiveness by improving the body’s immune response to the vaccine. Due to manufacturing constraints, Fluad® is being distributed on a staggered basis across the UK. Everyone eligible here will be able to get it by the end of November, well in advance of the traditional flu season. While this might be a bit longer than previous years, there are very strong grounds for believing it is worth it. The second new flu vaccine (known as a quadrivalent vaccine) is being offered to those in high risk groups, and healthcare workers. It offers protection against four strains of flu rather than three, therefore offering additional protection. Here’s what we need you to do. We need your help. We need you to get your flu vaccine so that fewer people fall victim to the flu virus, fewer people become severely ill and fewer people die. If we can achieve this, we will also relieve some of the pressures across our hospitals over the winter months. If you or your child are eligible for the flu vaccine, I would strongly encourage you to take up the offer. I will certainly be getting mine. Keep us all healthy this winter – get the flu vaccine.
Descriptive cataloging of serials: the National Library of Medicine versus the Library of Congress. Descriptive cataloging practices for serial differ significantly in some respects between the Library of Congress and the National Library of Medicine. This paper compares some of these differences and indicates the impact they can have on the development of on-line cooperative data bases such as OCLC. Attention is also given to the possible impact of the second edition of the Anglo-American Cataloguing Rules on serials cataloging. The need for standardization is stressed.
Chicago Mayor Rahm Emanuel (D) defended Chicago public schools after President Trump said the “numbers” in the city’s schools are “very rough.” Speaking Wednesday at an event on his proposal to require high school students to show they have a post-graduation plan before receiving their diplomas, Emanuel blasted Trump’s comments from the previous day, according to multiple local reports. In a meeting with business executives at the White House on Tuesday, Trump criticized schools in New York City, Los Angeles and Chicago in response to a question about the high school graduation rate in New York and training for the next generation of workers, according to the Chicago Sun-Times. ADVERTISEMENT “If you look at so many elements of education, and it’s so sad to see what’s coming — what’s happening in the country," Trump said. “Even the numbers, as good — you say we’re doing better, but the numbers in New York, the numbers in Chicago are very rough. The numbers in Los Angeles — the cities — it’s a very rough situation.” Emanuel, whose office issued a statement condemning Trump’s remarks, publicly criticized them again on Wednesday. He touted the accomplishments of Chicago students and said, "It’s hard, but I would not call it 'rough.' " “Now the president of the United States is allowed to have fake news,” Emanuel said. "But, the facts are the facts about the city of Chicago,” he added, slamming his lectern. "It would be helpful if we didn’t run down our kids, we didn’t run down our schools, we didn’t run down our teachers and our principals, but held them up, because they are leading the country in ACT gains, graduation gains, math gains and reading gains,” he continued. "I am immensely proud that, against great odds, these kids are accomplishing great things.” The mayor said he had pulled studies from the University of Chicago about the city’s high school graduation rate and college attendance levels that he would be sending to the president and Education Secretary Betsy DeVos.
I also recorded this and turned it into a time lapse video which you can watch here - Please subscribe and like my Facebook page for more content If you like my work please do give me a like on Facebook to support me I am always trying to paint armour and weapons, something I find incredibly difficult as I find reflective materials like this very complicated to understand and tricky to paint. Anyway I decided to study and paint a sword using a photo I found online, I also recorded it. Some bits of the sword didn't turn out great, but for me this was quite a complicated piece and I am happy with the final result.I also recorded this and turned it into a time lapse video which you can watch here - youtu.be/TnMpH2svoIY Please subscribe and like my Facebook page for more contentIf you like my work please do give me a like on Facebook to support me - Also be sure to subscribe to my Youtube channel for tips and time lapse paintings - Thanks for the support guys
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="aioairctrl", version="0.2.3", description="Library for controlling Philips air purifiers (using encrypted CoAP)", long_description=long_description, author="betaboon", url="https://github.com/kongo09/aioairctrl", project_urls={ "Bug Tracker": "https://github.com/kongo09/aioairctrl/issues", }, license="MIT", package_dir={"": "."}, packages=setuptools.find_packages(), install_requires=[ "pycryptodomex", "aiocoap==0.4.3", ], python_requires=">=3.6", entry_points={ "console_scripts": [ "aioairctrl=aioairctrl.__main__:main", ], }, )
package replay import ( "errors" "github.com/watermint/toolbox/essentials/file/es_filepath" "github.com/watermint/toolbox/essentials/log/esl" "github.com/watermint/toolbox/essentials/model/mo_string" "github.com/watermint/toolbox/essentials/network/nw_replay" "github.com/watermint/toolbox/infra/control/app_control" "github.com/watermint/toolbox/infra/control/app_job_impl" "github.com/watermint/toolbox/infra/control/app_workspace" "github.com/watermint/toolbox/infra/recipe/rc_recipe" "github.com/watermint/toolbox/infra/recipe/rc_replay" "github.com/watermint/toolbox/quality/infra/qt_errors" "os" "path/filepath" "strings" ) type Approve struct { rc_recipe.RemarkSecret Id string WorkspacePath mo_string.OptionalString ReplayPath mo_string.OptionalString Name mo_string.OptionalString } func (z *Approve) Preset() { } func (z *Approve) Exec(c app_control.Control) error { home := "" if z.WorkspacePath.IsExists() { home = z.WorkspacePath.Value() } l := c.Log().With(esl.String("JobId", z.Id)) // default non transient workspace ws, err := app_workspace.NewWorkspace(home, false) if err != nil { return err } replayPath, err := rc_replay.ReplayPath(z.ReplayPath) if err != nil { return err } replayFolderInfo, err := os.Lstat(replayPath) switch { case os.IsNotExist(err): l.Debug("Not found, try create the folder") if err := os.MkdirAll(replayPath, 0755); err != nil { l.Debug("Unable to create the folder", esl.Error(err)) return err } case !replayFolderInfo.IsDir(): l.Debug("The path is not a folder") return errors.New("replay path is not a folder") } replay := rc_replay.New(c.Log()) historian := app_job_impl.NewHistorian(ws) histories, err := historian.Histories() for _, history := range histories { if history.JobId() != z.Id { continue } archiveName := strings.ReplaceAll(es_filepath.Escape(history.RecipeName()), " ", "-") if z.Name.IsExists() { archiveName += "_" + z.Name.Value() } archiveName = archiveName + ".zip" l.Debug("Replay the recipe", esl.String("jobId", history.JobId()), esl.String("recipe", history.RecipeName()), esl.String("archiveName", archiveName)) forkName := strings.ReplaceAll(es_filepath.Escape(history.RecipeName()), " ", "-") l.Debug("Replay the recipe", esl.String("jobId", history.JobId()), esl.String("recipe", history.RecipeName()), esl.String("forkName", forkName)) forkBundle, err := app_workspace.ForkBundle(c.WorkBundle(), forkName) if err != nil { l.Debug("Unable to fork the bundle", esl.Error(err)) return err } forkCtl := c.WithBundle(forkBundle) if err := replay.Replay(history.Job(), forkCtl); err == nw_replay.ErrorNoReplayFound { l.Warn("No replay data found. Could not approve it.") return err } l.Info("Approve", esl.String("recipe", history.RecipeName()), esl.String("jobId", history.JobId())) return replay.Preserve(history.Job(), filepath.Join(replayPath, archiveName)) } return ErrorJobNotFound } func (z *Approve) Test(c app_control.Control) error { return qt_errors.ErrorHumanInteractionRequired }
1. Field of the Invention This invention pertains generally to the synthesis of copolymers of 3-alkoxythiophene, and more particularly to the use of regioregular copolymers of 3-alkoxythiophene in photovoltaic applications. 2. Description of Related Art Conjugated polymers have been developed into useful materials for a variety of applications, including light-emitting diodes, photovoltaic cells (PVs),3-5 and thin-film transistors (TFTs). In the past few years, photovoltaic devices based on conjugated polymers have been extensively studied. The most widely used configuration of polymer solar cells is the so-called “bulk heterojunction” devices in which the active layer consists of a blend of an electron-donating materials, e.g., a p-type conjugated polymer, and an electron-accepting (n-type) material such as (6,6)-phenyl C61-butyric acid methyl ester (PCBM). Photo-induced charge transfer from a conjugated polymer to PCBM with quantum yields up to 100% has been obtained. Regioregular poly(3-alkylthiophene)s (P3ATs) have been found to be one of the most promising conjugated polymers. They can be used as photosensitizers and hole transporters in bulk heterojunction polymer solar cells. Power conversion efficiencies (PCE) exceeding 3% under AM1.5 G illumination and between 4 and 5% under white light illumination from a solar simulator have recently been reported. Further improvement on the PCE entails new conjugated polymers with higher carrier mobility and broader absorption of the solar spectrum, especially in the red and infrared range. Moreover, the relatively low PCE of the polymer cells is largely due to low open-circuit voltage (Voc). The maximum open-circuit voltage is limited by the difference between the electronegativity, i.e., the lowest unoccupied molecular orbital (LUMO) of PCBM and the polymer's ionization potential, i.e., the highest occupied molecular orbital (HOMO). Therefore, HOMO level is also an important parameter to consider when designing new, electron-donating polymers of low bandgap. Polythiophenes with substituents other than alkyl groups have also been investigated, among which those with electron-donating alkoxy groups have displayed promising electronic and optical properties. Compared to P3ATs, the incorporation of an alkoxy group to the 3-position of the thiophene ring yields poly(3-alkoxythiophenes) (P3AOTs) with optical absorption maxima at longer wavelength. This may be attributed to both the electron-donating effect of alkoxy group and the more coplanar conformation of the P3AOTs. Therefore, polymers and copolymers based on 3-alkoxythiophene may also have smaller bandgaps than those based on P3ATs, and they can more efficiently absorb the red and near infrared portion of the solar emission spectrum. Efforts to synthesize new conjugated polymers for photovoltaic application have been undertaken, beginning with regioregular poly(3-decyloxythiophene-2,5-diyl) (P3DOT), but it was found that thin films of P3DOT did not have sufficiently high uniformity and environmental stability.
Dynamic task allocation algorithm based on D-NSGA3 Task allocation is a key part of unmanned aerial vehicle (UAV) swarm. Although a large number of solving algorithms have been developed, there are few technologies that support task allocation algorithms in dynamic environments. Obviously, this is not in accord with the actual situation. The battlefield is changing rapidly, which may lead to the failure of the allocated tasks and the inability to allocate new tasks. In order to deal with this problem, this paper improves the original D-NSGA3 algorithm to adapt to the dynamic environment. The experimental results show that, compared with the original static algorithm, the proposed algorithm has better effect in solving the task allocation problem of high-dimensional multi-objective agent based on maximizing the number of successfully allocated tasks, maximizing the benefits of executing tasks, minimizing the consumption cost, and minimizing the time cost.
def testCommentIssue(self): c = ChannelRepository.get('fablabs-approval') ticket = GitlabProvider.createTicket( c.path, self.bot.id, self.friend.id, "[NEW LAB] This a test issue as the lab was submitted", "More than you want to know ever about this lab") discussion = GitlabProvider.createTicketDiscussion( c.path, ticket.iid, self.bot.id, "Some comment to this awesome issue") self.assertIsNotNone(discussion) self.assertIsNotNone(discussion.attributes["notes"][0]) note = discussion.attributes["notes"][0] self.assertEquals(note["body"], "Some comment to this awesome issue") self.assertEquals(note["author"]["id"], self.bot.id) discussions = [ discussion for discussion in ticket.discussions.list(all=True)] self.assertEquals(len(discussions), 1) GitlabProvider.removeTicket( c.path, ticket.iid )
/** * Send a request message to the service provider and get the response. * * @return the response * @throws IOException * failed to communicate with the service provider * @throws OAuthProblemException * the HTTP response status code was not 200 (OK) */ public OAuthMessage invoke(OAuthMessage request, ParameterStyle style) throws IOException, OAuthException { final boolean isPost = POST.equalsIgnoreCase(request.method); InputStream body = request.getBodyAsStream(); if (style == ParameterStyle.BODY && !(isPost && body == null)) { style = ParameterStyle.QUERY_STRING; } String url = request.URL; final List<Map.Entry<String, String>> headers = new ArrayList<Map.Entry<String, String>>(request.getHeaders()); switch (style) { case QUERY_STRING: url = OAuth.addParameters(url, request.getParameters()); break; case BODY: { byte[] form = OAuth.formEncode(request.getParameters()).getBytes( request.getBodyEncoding()); headers.add(new OAuth.Parameter(HttpMessage.CONTENT_TYPE, OAuth.FORM_ENCODED)); headers.add(new OAuth.Parameter(CONTENT_LENGTH, form.length + "")); body = new ByteArrayInputStream(form); break; } case AUTHORIZATION_HEADER: headers.add(new OAuth.Parameter("Authorization", request.getAuthorizationHeader(null))); List<Map.Entry<String, String>> others = request.getParameters(); if (others != null && !others.isEmpty()) { others = new ArrayList<Map.Entry<String, String>>(others); for (Iterator<Map.Entry<String, String>> p = others.iterator(); p .hasNext();) { if (p.next().getKey().startsWith("oauth_")) { p.remove(); } } if (isPost && body == null) { byte[] form = OAuth.formEncode(others).getBytes( request.getBodyEncoding()); headers.add(new OAuth.Parameter(HttpMessage.CONTENT_TYPE, OAuth.FORM_ENCODED)); headers.add(new OAuth.Parameter(CONTENT_LENGTH, form.length + "")); body = new ByteArrayInputStream(form); } else { url = OAuth.addParameters(url, others); } } break; } final HttpMessage httpRequest = new HttpMessage(request.method, new URL(url), body); httpRequest.headers.addAll(headers); HttpResponseMessage httpResponse = http.execute(httpRequest); httpResponse = HttpMessageDecoder.decode(httpResponse); OAuthMessage response = new OAuthResponseMessage(httpResponse); if (httpResponse.getStatusCode() != HttpResponseMessage.STATUS_OK) { OAuthProblemException problem = new OAuthProblemException(); try { response.getParameters(); } catch (IOException ignored) { } problem.getParameters().putAll(response.getDump()); try { InputStream b = response.getBodyAsStream(); if (b != null) { b.close(); } } catch (IOException ignored) { } throw problem; } return response; }
<reponame>tspence/lockstep-sdk-java<gh_stars>0 /** * Lockstep Platform SDK for Java * * (c) 2021-2022 Lockstep, Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author <NAME> <<EMAIL>> * @copyright 2021-2022 Lockstep, Inc. * @link https://github.com/Lockstep-Network/lockstep-sdk-java */ package io.lockstep.api.clients; import io.lockstep.api.LockstepApi; import io.lockstep.api.RestRequest; import io.lockstep.api.models.LockstepResponse; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import io.lockstep.api.models.LeadModel; /** * Contains all methods related to Leads */ public class LeadsClient { private LockstepApi client; /** * Constructor for the Leads API collection * * @param client A {@link io.lockstep.api.LockstepApi} platform client */ public LeadsClient(@NotNull LockstepApi client) { super(); this.client = client; } /** * Creates one or more Leads within the Lockstep platform and returns the records as created. * * A Lead is a person who is interested in the Lockstep platform but needs certain new features in order to use it. If you are interested in the Lockstep platform, you can create a lead with your information and our team will prioritize the feature you need. * * @param body The Leads to create * @return A {@link io.lockstep.api.models.LockstepResponse} containing the results */ public @NotNull LockstepResponse<LeadModel[]> createLeads(@NotNull LeadModel[] body) { RestRequest<LeadModel[]> r = new RestRequest<LeadModel[]>(this.client, "POST", "/api/v1/Leads"); r.AddBody(body); return r.Call(LeadModel[].class); } }
package com.darian.chain.frame; /*** * * * @author <a href="mailto:<EMAIL>">Darian</a> * @date 2020/12/24 23:18 */ public interface TaskTypeInterface { /** * 获取任务名称 * * @return */ default String getTaskName() { return this.getClass().getSimpleName(); } }
Potential salmon sperm origin of the E3 region insert of the adenovirus 5 dl309 mutant. The plasmid pJM17 is a commonly used adenoviral backbone derived from the dl309 mutant virus. It contains unknown sequences inserted in the E3 region during construction of the dl309 mutant. Complete description of the backbone sequence is required for interpretation of potential vector effects and for regulatory approval of a vector to be used in clinical trials. The anonymous E3 insert was sequenced and analyzed. The insert fragment is 646 base pairs (bp) long and is 100 bp shorter than the vector sequences it replaces. It interrupts the expression of the E3B 10.4K, 14.6K, and 14.7K genes, but not the E3A glycoprotein (gp) 19K gene. Sequence analysis and Southern blotting suggest that the insert might originate from salmon sperm DNA used as carrier during the construction of dl309. Transcription from the insert was not detected by Northern blot analysis of vector-transduced cells but was detected by reverse transcriptase polymerase chain reaction.
<reponame>maxgestic/BeautyQuests package fr.skytasul.quests.utils.compatibility; import org.bukkit.Location; import org.bukkit.entity.Player; import com.live.bemmamin.gps.api.GPSAPI; import fr.skytasul.quests.BeautyQuests; public class GPS { private static GPSAPI api; static void init(){ api = new GPSAPI(BeautyQuests.getInstance()); } public static boolean launchCompass(Player p, Location location) { if (api.gpsIsActive(p)) return false; api.startCompass(p, location); return true; } public static void stopCompass(Player p){ api.stopGPS(p); } }
Game developer Scott Cawthon never could have imagined the immense levels of success for his Five Nights at Freddy's video game series. Ever since the original computer game was released in 2014, the title has become very popular for gamers of all ages. Several video game sequels would be released in the following years, and there have been multiple attempts made to develop the story into a feature film. Last year, it was announced that Blumhouse Productions would be producing the project, and the film finally seemed to be making some traction. Unfortunately, however, Scott Cawthon has revealed that the film has been put on hold once again, due to issues with the script. A big name director had already been attached to the film in Chris Columbus, whose body of work includes helming Mrs. Doubtfire, Pixels, and two Harry Potter films. It was initially reported Columbus would also be writing, but according to Cawthon, he penned the screenplay himself, ensuring maximum faithfulness to the games the film is based on. But although Jason Blum of Blumhouse and Columbus were both happy with the script written, Cawthon personally had a change of heart about its story, opting to take it in a completely separate direction. As a result, Cawthon trashed the screenplay he had written, planning to start from scratch with an entirely new vision. "I hate delaying a project that's already seen so many delays, but I have to go with my instincts on what I think will be exciting and interesting, and what I think the fanbase will really want to see. If that means that I have to start over ten more times, then that's what I'm going to do. The good thing is that each attempt gets better and better, in my opinion. So, despite the delays, it's going in the right direction." When news of a Five Nights at Freddy's movie first hit the internet a couple years ago, Gil Kenan was attached to direct. For whatever reason, the project would stall until Blumhouse acquired the rights to produce the film in 2017, later hiring Columbus to direct. Although we are currently without a script once again, Cawthon has made it clear that the film will only be adapting the events of the first three entries in the video game series. The games to come out afterward, such as Sister Location, will not exist in the continuity of the feature film. For the sake of keeping things simple, this is probably for the best. Still, there's better news for the franchise's future when it comes to the video game series. Cawthon revealed he is hard at work on bringing several new entries in the series to life. A VR-version of the original game is nearly halfway completed, and it sounds horrifying just to think about. Among other titles, Cawthon says that a new "AAA" Five Nights at Freddy's game is coming as well. Additionally, console ports of the classic games are also in development, which will finally bring the game from computer screens onto television sets. A new line of books from Scholastic are coming as well, so there's still plenty to look forward to. We couldn't even begin to estimate when we'll finally see the Five Nights at Freddy's movie. The story will hopefully be in good hands under the creative guidance of Cawthon, so as long as he can make up his mind on its direction. Something that we're all hoping it has is practical FX and actual animatronics, as seeing the murderous robots in CGI would make them lose their effect. Hopefully the ball gets rolling on the project sooner rather than later. Cawthon's statement on the status of the film was originally printed at Steam. Five Nights at Freddy's Movie Coming Soon from Blumhouse? Five Nights at Freddy's Movie Happening at Warner Bros.