id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23529200
If I do not have the Activesheet.Hyperlinks.add line the cell values get set correctly, just missing the hyperlink... which would make me think I've lost the xCell reference but I've placed debug statements just before the hyperlink.add and it seems to be accessible. Example URL: http://www.walmart.com/ip/Transformers-Robots-in-Disguise-3-Step-Changers-Optimus-Prime-Figure/185220368 For Each xCell In Selection Url = xCell.Value If Url = "" Then 'Do Nothing ElseIf IsEmpty(xCell) = True Then 'Do Nothing ElseIf IsEmpty(Url) = False Then splitArr = Split(Url, "/") sku = splitArr(UBound(splitArr)) xCell.Value = "https://www.brickseek.com/walmart-inventory-checker?sku=" & sku 'Error happens on next command ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:=xCell.Formula End If Next xCell A: Don't both with .ValueDon't use .Formula: Sub demo() Dim s As String, xCell As Range s = "http://www.walmart.com" Set xCell = Range("B9") ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:=s, TextToDisplay:=s End Sub is a typical working example. A: There is always another possibilty, that your sheet may be locked and you have to grant permission to do so when locking the sheet. I know this is not the solution for the problem described here, but the non-deterministic error messages provided by Microsoft VBA is the same. I came here looking for the solution of my problem, an others might bump in this and find my comment relevant.
doc_23529201
public class PicksheetActivity extends AppCompatActivity { RecyclerView recyclerView; GameAdapter adapter; List<Games> gameList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.picksheet_layout); RecyclerView recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); gameReference = mFirebaseDatabase.getReference("Games"); gameQuery = gameReference.equalTo(1); // Add handle for listener mListener = gameQuery.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { for (DataSnapshot gameSnapshot : dataSnapshot.getChildren()) { Games game = new Games(gameSnapshot); // gameList.add(game); adapter = new GameAdapter(this, gameList); <--- Error here recyclerView.setAdapter(adapter); } } } @Override public void onCancelled(DatabaseError databaseError) { Log.w("SurvivorPickSheetActivity", "onCancelled", databaseError.toException()); } } }); } The GameAdapter class is as follows: public class GameAdapter extends RecyclerView.Adapter<GameAdapter.GameViewHolder> { public GameAdapter(Context mCtx, List<Games> gameList) { this.mCtx = mCtx; this.gameList = gameList; Log.d("CREATION", "*** CALLING THE GameAdapter class ***"); } @Override public GameViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mCtx).inflate(R.layout.list_layout, parent,false); GameViewHolder gameViewHolder = new GameViewHolder(view); return gameViewHolder; } } The compiler is telling me to change the GameAdapter's class constructor from Context to ValueEventListener since I guess I'm making the call to Firebase If I do that then the GameAdapter onCreateViewHolder wont work since the LayoutInflater.from() function requires Context and not a ValueEventListener to inflate the view?! Can anyone help? A: adapter = new GameAdapter(this, gameList); <--- Error here Here this refers to the surrounding class which is the anonymous inner class created by new ValueEventListener() { instance and it is not a context. In order to refer to the outer class to get the context, you can replace this with PicksheetActivity.this
doc_23529202
The problem is that every time I launch the app, it crashes right away. It started to happen when I added firebase and when I comment my Firebase code, it's working again, so now I'm pretty sure it's a problem with firebase. The problem seems to be happening when the onForeground() is called. I tried to put it on a new Thread or call it in a Handler but it keeps crashing... Here is the stack: 10-28 16:46:26.106 27724-27732/com.package.custom E/System: Uncaught exception thrown by finalizer 10-28 16:46:26.107 27724-27732/com.package.custom E/System: java.lang.IllegalStateException: The database '/data/user/0/com.package.custom/databases/google_app_measurement_local.db' is not open. at android.database.sqlite.SQLiteDatabase.throwIfNotOpenLocked(SQLiteDatabase.java:2169) at android.database.sqlite.SQLiteDatabase.createSession(SQLiteDatabase.java:365) at android.database.sqlite.SQLiteDatabase$1.initialValue(SQLiteDatabase.java:84) at android.database.sqlite.SQLiteDatabase$1.initialValue(SQLiteDatabase.java:83) at java.lang.ThreadLocal$Values.getAfterMiss(ThreadLocal.java:430) at java.lang.ThreadLocal.get(ThreadLocal.java:65) at android.database.sqlite.SQLiteDatabase.getThreadSession(SQLiteDatabase.java:359) at android.database.sqlite.SQLiteProgram.getSession(SQLiteProgram.java:101) at android.database.sqlite.SQLiteQuery.setLastStmt(SQLiteQuery.java:96) at android.database.sqlite.SQLiteQuery.close(SQLiteQuery.java:111) at android.database.sqlite.SQLiteCursor.close(SQLiteCursor.java:300) at android.database.sqlite.SQLiteCursor.finalize(SQLiteCursor.java:366) at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:202) at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:185) at java.lang.Thread.run(Thread.java:818) Here is a part of my AnalyticsHelper class: public class AnalyticsHelper { //... /** * Hook called when the app switch to foreground mode */ public static void onForeground() { Log.d(TAG, "FOREGROUND"); Bundle bundle = new Bundle(); bundle.putString(KEY_TYPE, AnalyticsCategories.CATEGORY_LIFECYCLE_ACTION_FOREGROUND); CustomApplication.getAnalytics().logEvent(AnalyticsCategories.CATEGORY_LIFECYCLE, bundle); } //... } Here is the call of the AnalyticsHelper in the activity: public class MainActivity extends AppCompatActivity { @Override protected void onResume() { super.onResume(); //... AnalyticsHelper.onForeground(); } } And here is the part of the custom Application class: public class CustomApplication extends Application { private static final String TAG = "CustomApplication"; private static CustomApplication sApplication; public static CustomApplication get() { return sApplication; } public static FirebaseAnalytics getAnalytics() { return get().getFirebaseAnalytics(); } @Override public void onCreate() { super.onCreate(); mFirebaseAnalytics = FirebaseAnalytics.getInstance(this); sApplication = this; } /** * Gets the default {@link Tracker} for this {@link Application}. * * @return tracker */ public FirebaseAnalytics getFirebaseAnalytics() { if (mFirebaseAnalytics == null) { mFirebaseAnalytics = FirebaseAnalytics.getInstance(this); } return mFirebaseAnalytics; } } I searched all the afternoon and nothing came out, please help.. Edit #1 (build.gradle): apply plugin: 'com.android.application' android { signingConfigs { release { keyAlias '##########' keyPassword '##########' storeFile file('##########') storePassword '##########' } } compileSdkVersion 25 buildToolsVersion '24.0.2' defaultConfig { applicationId "com.custom.app" minSdkVersion 18 targetSdkVersion 25 android.applicationVariants.all { variant -> def versionPropsFile = file('src/main/res/raw/version.properties') if (versionPropsFile.canRead()) { def Properties versionProps = new Properties() versionProps.load(new FileInputStream(versionPropsFile)) def code = versionProps['code'].toInteger() + 1 versionProps['code'] = code.toString() def version = versionProps['version'] versionProps.store(versionPropsFile.newWriter(), null) versionCode code versionName version } else { throw new GradleScriptException('Cant access version.properties'); } } signingConfig signingConfigs.release vectorDrawables.useSupportLibrary = true multiDexEnabled true } buildTypes { release { minifyEnabled false debuggable true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' buildConfigField "boolean", "EXPORT_EXTERNAL_STORAGE", "true" } debug { debuggable true buildConfigField "boolean", "EXPORT_EXTERNAL_STORAGE", "true" } } productFlavors { } testOptions { unitTests.returnDefaultValues = true } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile files('libs/commons-net-3.3.jar') //Debug compile files('libs/commons-lang3-3.5.jar') compile files('libs/joda-time-2.9.5.jar') compile project(':android-ble-module') debugCompile project(path: ':android-log-module', configuration: 'debug') releaseCompile project(path: ':android-log-module', configuration: 'release') compile project(':android-location-module') testCompile 'junit:junit:4.12' testCompile 'org.mockito:mockito-core:1.9.5' compile 'com.android.support:design:25.0.0' compile 'com.android.support:multidex:1.0.1' compile 'com.android.support:appcompat-v7:25.0.0' compile 'com.android.support:preference-v14:25.0.0' compile 'com.google.android.gms:play-services-gcm:9.8.0' compile 'com.google.android.gms:play-services-maps:9.8.0' compile 'com.google.android.gms:play-services-identity:9.8.0' compile 'com.google.firebase:firebase-analytics:9.8.0' } apply plugin: 'com.google.gms.google-services' A: Please move to latest version of firebase SDK. Firebase solved this memory leak issue in their updated sdk. In this case replace this line compile 'com.google.firebase:firebase-analytics:9.8.0' with below line. compile 'com.google.firebase:firebase-analytics:11.0.1'
doc_23529203
public class Statistics extends JPanel { public Object[][] data; public DefaultTableModel model; public Statistics() { super(new GridLayout(1,0)); String[] columnNames = {"Name", "Games Played", "Games Won"}; Object[][] data = { {"Kathy", new Integer(5), new Integer(2)}, {"Steve", new Integer(2), new Integer(0)}, }; model = new DefaultTableModel(data, columnNames); JTable table = new JTable(model); table.setFillsViewportHeight(true); table.setVisible(true); table.setEnabled(false); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane); } public void addRow(Object[] objects) { model.addRow(objects); } public void updateGamesPlayed(String userFolderName, int gamesPlayed) { int rowCount = model.getRowCount(); int columnCount = model.getColumnCount(); for (int i = 0; i < rowCount; i++){ for(int j = 0; j < columnCount; j++){ if (data[i][j] == userFolderName){ model.setValueAt(gamesPlayed, i, j+1); } } } } } A: You have two different data objects - a global one and a local one in your constructor. If you change Object[][] data = {...}; to data = new Object[][]{...}; in your constructor it should work as you're only setting the local one, not the global value. A: btw model.setValueAt(gamesPlayed, i, j+1); this j+1 will cause OutOfBoundsException
doc_23529204
jmeter.reportgenerator.statistic_window = 2000 jmeter.reportgenerator.apdex_satisfied_threshold=1500 jmeter.reportgenerator.apdex_tolerated_threshold=3000 jmeter.reportgenerator.exporter.html.series_filter=^(Search|Order)(-success|-failure)?$ jmeter.reportgenerator.exporter.html.filters_only_sample_series=true I notice that the jmeter article https://jmeter.apache.org/usermanual/generating-dashboard.html has metrics per each Transaction in APDEX and Statistics tables as below where as my report doesnt have metrics per each Transaction in APDEX and Statistics tables can someone please help me to configure report to have metrics per each Transaction in APDEX and Statistics tables A: You are copying example for specific sampler names below example we filter on Search and Order samples You should change regex according to your sampler names, for example for Samplers MyT1 MyT2,... use jmeter.reportgenerator.exporter.html.series_filter=^(MyT)(-success|-failure)?$ If the label is not at the start of the sampler name use: get regex using label, as `jmeter.reportgenerator.exporter.html.series_filter=(.*)MyT(.*)(-success|-failure)‌​?$`
doc_23529205
Foo | Bar | Amount 1 | A | 0 43 | A | 120 1 | B | 0 43 | B | 120 1 | C | 0 43 | C | 105 EXPECTED RESULT Foo | Bar | Amount 1 | A | 0 43 | A | 120 OR Foo | Bar | Amount 1 | B | 0 43 | B | 120 Any of the two above will do just fine since I only need the highest Amount. I have this query but doesn't seem correct. select Foo ,max(Bar) as Bar ,max(Amount) as Amount from Table1 group by Foo I am getting Foo | Bar | Amount 1 | C | 0 43 | C | 120 The result should kept the values in a row. Any help would much appreciated. Thanks A: You are applying MAx to a string so it will get the last one. You should use MIN if you want to get A. Edit: Based on your comment, the following will work; WITH CTE as( Select t1.Bar from #TBL1 t1 where t1.Amount = (Select MAX(Amount) From #TBL1) group by t1.Bar) Select t1.* From CTE ct join #TBL1 t1 on t1.Bar = ct.Bar Just replace #TBL with your table name. A: use the following SELECT TOP 1 Foo , Bar, Amount FROM Table1 order by Amount desc ,Bar asc A: If any one of the 'Bar' rows which have maximum 'Amount' is fine, hope the below query helps.. select * from table1 where bar in ( select bar from( select bar,max(amount) maxim from table1 group by bar order by maxim desc ) where rownum =1 ); Edit : select * from table1 where bar in ( select bar from( Select top(1) bar,maxim from ( select bar,max(amount) maxim from table1 group by bar order by maxim desc )) ); A: First, calculate the maximum Amount per Bar: SELECT Foo, Bar, Amount, MaxAmount = MAX(Amount) OVER (PARTITION BY Bar) FROM dbo.Table1 ; For your example the above query would return this result set: Foo Bar Amount MaxAmount --- --- ------ --------- 1 A 0 120 43 A 120 120 1 B 0 120 43 B 120 120 1 C 0 105 43 C 105 105 Now use ORDER BY MaxAmount DESC, Bar ASC (or ... Bar DESC) and apply TOP (1) WITH TIES to the result to return a subset representing just one Bar: SELECT TOP (1) WITH TIES Foo, Bar, Amount, MaxAmount = MAX(Amount) OVER (PARTITION BY Bar) FROM dbo.Table1 ORDER BY MaxAmount DESC, Bar ASC ; The first sorting criterion causes the query to return the Bar or Bars that have the biggest Amount value. The second one is needed to make sure only one Bar is returned if more than one has the same maximum. The returned rows will not have a guaranteed order. If you need one, use the second query as a derived table and sort the results again as necessary: SELECT ... FROM ( SELECT TOP (1) WITH TIES Foo, Bar, Amount, MaxAmount = MAX(Amount) OVER (PARTITION BY Bar) FROM dbo.Table1 ORDER BY MaxAmount DESC, Bar ASC ) AS s ORDER BY ... ;
doc_23529206
Phalcon DLL for PHP 5.4 provided here: http://phalconphp.com/en/download/windows does not work with my XAMP 5.5.3 PHP. A: You can compile it your own: http://szdredd.blogspot.cz/2013/11/how-to-setup-phalcon-framework-under.html?showComment=1385412595836#c3025679067378957109 or download precompiled DLL for PHP 5.5.5 (which works for 5.5.3) here: https://github.com/andont/phalcon-win
doc_23529207
ToolTip^ toolTip_patterns = gcnew ToolTip; String^ caption; caption = "Help the user blah blah..."; toolTip_patterns->Show(caption, this->textBox_patternsTer); I want the tool tip to disappear when the user leaves the text box. It should not be displayed unless the user presses F1 again. I tried to hide the tool tip with the code below in the Leave event. ToolTip^ toolTip_patterns = gcnew ToolTip; toolTip_patterns->RemoveAll(); The above doesn't work, so I tried the following. This doesn't work either. toolTip_patterns->Hide(this->textBox_patternsTer); When I use either Method (RemoveAll or Hide), the tool tip disappears when the user leaves the text box, but it comes back when they hover the mouse over the text box. I do not have any code in the MouseHover event. Why does it do this? Thanks! Update...Sorry if this isn't the right place to type an update. Thanks for the suggestion but it doesn't work. I added a ToolTip control to my form from the Form Designer, and each of my controls now has a Property named ToolTip on toolTip_patterns. I deleted the declaration below from the HelpRequest event. ToolTip^ toolTip_patterns = gcnew ToolTip I set the text to be displayed with the code below. private: System::Void textBox_patterns_HelpRequested(System::Object^ sender, System::Windows::Forms::HelpEventArgs^ hlpevent) { String^ caption; String^ module; if (sender == textBox_patternsTer) module = "Terminator"; else if (sender == textBox_patternsSec) module = "Secondary"; else if (sender == textBox_patternsPri) module = "Primary"; else return; // No help for selected control. caption = "Enter 32 bit Hex patterns for the " + module + " one pattern per line.\n"; toolTip_patterns->InitialDelay = 0; //< immediately show help toolTip_patterns->Show(caption, (TextBox^)sender); I also tried the non-modal form below. toolTip_patterns->SetToolTip((TextBox^)sender, caption); The tool tip displays fine, and when I move the focus to another control and press F1, the tool tip for the second control is displayed. The problem is that the tooltip for the first control is displayed when I hover the mouse over it. I don't want the tool tips to be displayed after the user exits the control. The Hide() method doesn't work, the RemoveAll() method doesn't work, and setting the caption to "" doesn't work. Any idea what I'm doing wrong? Thanks. A: I would be inclined to just set the text when the user requests help, and then clear it when the mouse leaves. Note that you'll need to keep a pointer to the tooltip between the help requests call and the mouse leaving, rather than allocating a new one each call to request help. If you don't do this you'll not have a handle on the object and be able to operate on it. ToolTip^ toolTip_patterns = gcnew ToolTip; void doHelpRequest() { String^ caption; caption = "Help the user blah blah..."; toolTip_patterns->Show(caption, this->textBox_patternsTer) toolTip_patterns->InitialDelay = 0; //< immediately show help } then void doMouseLeave() { toolTip_patterns->Show("", this->textBox_patternsTer) }
doc_23529208
* *OS: MacOs Monterey *Node.js version: 16 *npm version: 8.5.1 *@google-cloud/storage version: 5.18.3 Hi everyone, I'm having a problem uploading a 920Mb file. When I try to upload the file via google storage's "upload" function, I get this error message: "User-Agent":"google-api-nodejs-client/7.14.0","x-goog-api-client":"gl-node/16.13.0 auth/7.14.0","Accept":"application/json"},"responseType":"json"},"code":400,"errors":[{"message":"Cannot insert legacy ACL for an object when uniform bucket-level access is enabled. Read more at https://cloud.google.com/storage/docs/uniform-bucket-level-access","domain":"global","reason":"invalid"}],"errorMessage":"Cannot insert legacy ACL for an object when uniform bucket-level access is enabled. Read more at https://cloud.google.com/storage/docs/uniform-bucket-level-access","errorStack":"Error: Cannot insert legacy ACL for an object when uniform bucket-level access is enabled. Read more at https://cloud.google.com/storage/docs/uniform-bucket-level-access\n at Gaxios._request (/Users/lucascognamiglio/Desktop/CherryProjects/epona-ape/node_modules/gaxios/build/src/gaxios.js:129:23)\n at runMicrotasks (<anonymous>)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at async JWT.requestAsync (/Users/lucascognamiglio/Desktop/CherryProjects/epona-ape/node_modules/google-auth-library/build/src/auth/oauth2client.js:368:18)\n at async Upload.makeRequest (/Users/lucascognamiglio/Desktop/CherryProjects/epona-ape/node_modules/@google-cloud/storage/build/src/gcs-resumable-upload/index.js:605:21)\n at async Upload.getAndSetOffset (/Users/lucascognamiglio/Desktop/CherryProjects/epona-ape/node_modules/@google-cloud/storage/build/src/gcs-resumable-upload/index.js:552:26)\n at async Upload.continueUploading (/Users/lucascognamiglio/Desktop/CherryProjects/epona-ape/node_modules/@google-cloud/storage/build/src/gcs-resumable-upload/index.js:350:9)"} This only happens to me when I try to upload a file of this size, while if I try to upload an image, I don't have any kind of problem. For greater clarity I am attaching the part of the code: const tempFolder = await tmp.dir({ unsafeCleanup: true }); const destinationPathFile = `${tempFolder.path}/${fileName}`; const downloaded = await this.download(fileURL, destinationPathFile); if (downloaded) { const uploadResponse = await getStorage().bucket('bucket-name').upload(destinationPathFile, { destination: newFileName, gzip: true, metadata: { cacheControl: 'public, max-age=31536000', }, public: isPublic, }); log.info(`FileService => upload => Upload finished for file ${fileURL} with name ${newFileName}`); if (uploadResponse) { const metadata = uploadResponse[1]; return metadata.mediaLink; } } await tempFolder.cleanup(); } catch (error) { log.info(`FileService => upload => Error for file ${fileURL} with name ${newFileName}`, error); } A: It does not matter what size object, you should have received the same error. You cannot special object ACLs when uniform bucket-level access is enabled. Change your code to not specify an ACL (delete public: isPublic): const uploadResponse = await getStorage().bucket('bucket-name').upload(destinationPathFile, { destination: newFileName, gzip: true, metadata: { cacheControl: 'public, max-age=31536000' } });
doc_23529209
For grouping or clustering algorithms I've looked at like k-means, ArcGIS Grouping Analysis, etc. These do not seem to do what's needed, since they group based on the similarity of a variable don't partition into equal size based on a variable. My quick look at ESRI's districting tool suggests that this might be a possibility. Any other suggestions? A: You should consider the Shortest splitline algorithm, recommended for creating optimally compact voting districts. Here is a description of its results in solving gerrymandering. A: You can try centroidal weighted voronoi diagrams. i.e. Loyds algorithm. Pick the voronoi diagram and the center of gravity of each voronoi cell and rinse and repeat:http://www-cs-students.stanford.edu/~amitp/game-programming/polygon-map-generation/
doc_23529210
Invalid operands to binary expression ('QDataStream' and 'QJsonObject') even though the QJsonObject has an overloaded operator>> for QDataStream: The relevant code snippet: #include <QDataStream> #include <QDir> #include <QFile> #include <QJsonObject> #include <QTime> std::vector<JsonDataTypes::JsonRecords> FileCacheHandler::readLogs() { std::vector<JsonDataTypes::JsonRecords> returnRecords; QFile cacheFile(SubFolderName + QStringLiteral("/%1").arg(cacheFileName)); if (!cacheFile.open(QIODevice::ReadOnly)) { qWarning(FileCacheManagerLog) << "Couldn't open cache file with name:" << cacheFileName; return{}; } QDataStream in(&cacheFile); while (!in.atEnd()) { QJsonObject record; in >> record; #<<<<<<--- Issue occurs here, error: Invalid operands to binary expression ('QDataStream' and 'QJsonObject') returnRecords.emplace_back(record); } cacheFile.close(); return returnRecords; } In the cmake file I am including all necessary packages: find_package(Qt5 COMPONENTS Core Network REQUIRED)
doc_23529211
here's my code without back slash <?php echo ("<a href=\."http://www.example.com">Home</a> &raquo; "); for ($i = 1; $i < count($parts); $i++) { if (!strstr($parts[$i],".")) { echo("<a href=""); for ($j = 0; $j <= $i; $j++) {echo $parts[$j]."/";}; echo("">". str_replace('-', ' ', $Pages[$parts[$i]])."</a> &raquo; "); } else ?> i need it to be like this after escape <?php echo ("<a href=\"http://www.example.com\">Home</a> &raquo; "); for ($i = 1; $i < count($parts); $i++) { if (!strstr($parts[$i],".")) { echo("<a href=\""); for ($j = 0; $j <= $i; $j++) {echo $parts[$j]."/";}; echo("\">". str_replace('-', ' ', $Pages[$parts[$i]])."</a> &raquo; "); } else ?> this the parts that i want to escape <a href=\" and echo("<a href=\""); and echo("\">". i need back slash to be exist there after escape A: If you need echo <a href=\" just add "\\" for single "\" in result output. echo("<a href=\\\"");
doc_23529212
thats what the page looks like after clicking previous button
doc_23529213
The query: INSERT INTO INTERNET.WEBSECURITY@crmtest SELECT * FROM INTERNET.WEBSECURITY; The Error: ORA-06502: PL/SQL: numeric or value error: character string buffer too small Any ideas on what this might be? A: You are trying to assign a value to a plsql variable which is not big enough or it has greater size than the column data type. A: In addition: Assign/insert a non-numeric value to a numeric variable/column. Probably your table columns are a bit different in datatypes and sizes. I do not see any variables in your example.
doc_23529214
$(document).ready(function() { $('#lineitems').on('change', '.prototypeSelect', function() { var that = $(this); $.get('getItem.php?q=' + $(this).val(), function(data) { console.log(data); var objItem = jQuery.parseJSON(data); that.closest('#prototypePrice').val(objItem.item_price); //this is wrong }); }); }); Here is the Prototype Row: <div style="display:none;" id="rowPrototype" > <div> <select id="prototypeSelect" class="prototypeSelect"> //Select Options </select> </div> <div> <input type="text" id="prototypePrice" class="prototypePrice"> </input> </div> </div Here is the JQUERY to insert the prototype row: var objLineitem; $(document).ready(function() { $('.invoiceClass').click(function() { $.get('getlineItems.php?q=' + $(this).attr("name") , function(data) { console.log(data); var objLineitem = $.parseJSON(data); for (i=0; i < objLineitem.length; i++) { var newRow = $('#rowPrototype').clone(); newRow.show(); $('#lineitems').append(newRow); newRow.attr('id', 'insertedRow'); newRow.attr('class', 'row insertedPrototypeRow'); A: closest traverse up the DOM tree and get the first matched ancestor. In your case, the input that you want to set the value is the child of a div which is the next immediate sibling of parent div of that So you can use: that.closest('div').next().find('.prototypePrice').val(objItem.item_price); instead of: that.closest('#prototypePrice').val(objItem.item_price); Check: closest() , next() , find() A: It is the child of the next sibling of the changed select, so $(document).ready(function () { $('#lineitems').on('change', '.prototypeSelect', function () { var that = $(this); $.get('getItem.php?q=' + $(this).val(), function (data) { console.log(data); var objItem = jQuery.parseJSON(data); that.parent().next().find('.prototypePrice').val(objItem.item_price); //this is wrong }); }); }); Demo: Fiddle Also note that, if the given structure is repeated then you should not use id for those elements since it will create duplicate ids Also, input is a self closing element so there is no </input> A: You can use unique id for each row. Then it will be easier to search using that id $('#'+rowID + " .prototypePrice").val(newValue) or you can use row context $(".prototypePrice",that.parents('#rowPrototype')).val(newVal) Agree with arun if 'prototypePrice' is repeating then dont use it as id.Also rowPrototype. it shud be used as class $(".prototypePrice",that.parents('.rowPrototype')).val(newVal)
doc_23529215
{{#parent-component}} {{child-component-1}} {{child-component-2}} {{/parent-component}} A: One way to do this is to have the children register themselves with the parent, something like this: import ParentComponent from 'some/where/parent-component'; registerWithParent: Ember.on('didInsertElement', function() { let parent= this.nearestOfType(ParentComponent); if (parent) { parent.registerChild(this); } } Then, in the ParentComponent: registerChild: function() { // do something to keep track of children }
doc_23529216
and this is the code I have: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:card_view="http://schemas.android.com/apk/res-auto"> <androidx.cardview.widget.CardView android:id="@+id/card_view" android:layout_width="match_parent" android:layout_height="200dp" android:layout_margin="3dp" card_view:cardBackgroundColor="@color/colorwhite" card_view:cardCornerRadius="8dp" card_view:cardUseCompatPadding="false" card_view:elevation="15dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="130dp" android:layout_gravity="center_horizontal" android:orientation="horizontal"> <ImageView android:id="@+id/flag" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:scaleType="fitXY" android:src="@drawable/mac_img" /> <TextView android:id="@+id/titleTxt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginTop="85dp" android:textStyle="bold" android:textColor="@color/colorwhite" android:layout_centerHorizontal="true" /> </RelativeLayout> </androidx.cardview.widget.CardView> </LinearLayout> as I am trying also add the a text view like is shown in the image like the Closed, So all I need I want the way to do this as to put widgets like this way as in the figure.. A: Ok good I solved it by adding some margins I hope someone give me a recommendation about this, and this is the full code: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:card_view="http://schemas.android.com/apk/res-auto"> <androidx.cardview.widget.CardView android:id="@+id/card_view" android:layout_width="match_parent" android:layout_height="200dp" android:layout_margin="3dp" card_view:cardBackgroundColor="@color/colorwhite" card_view:cardCornerRadius="8dp" card_view:cardUseCompatPadding="false" card_view:elevation="15dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="130dp" android:layout_gravity="center_horizontal" android:orientation="horizontal"> <ImageView android:id="@+id/flag" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:scaleType="fitXY" android:src="@drawable/mac_img" /> <TextView android:id="@+id/titleTxt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginTop="85dp" android:textStyle="bold" android:textColor="@color/colorwhite" android:layout_centerHorizontal="true" /> </RelativeLayout> <com.cuboid.cuboidcirclebutton.CuboidButton android:layout_width="70dp" android:layout_height="70dp" app:cub_border_color="@color/color_64b5f6" app:cub_border_radius="4dp" android:layout_marginTop="85dp" android:layout_marginLeft="30dp" app:cub_color="@color/colorwhite" app:cub_hover_color="@color/color_0288D1" app:cub_icon="@drawable/eat" app:cub_riple_effect="true" /> </androidx.cardview.widget.CardView> </LinearLayout>
doc_23529217
and this is the code inside the AppDelegate : player = [[player1Data alloc] init]; player.name = @"Dave Brubeck"; player.game = @"Texas Hold’em Poker"; player.rating = 2; [playersArray addObject:player]; // to get the player1ViewController UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController; UITabBarController *tabBarController = [[navigationController viewControllers] objectAtIndex:0]; player1ViewController *playersViewController = [[tabBarController viewControllers] objectAtIndex:0]; playersViewController.playersArray = playersArray; return YES; the error was appearing at : player1ViewController *playersViewController = [[tabBarController viewControllers] objectAtIndex:0]; then the xcode shows that : Thread 1: signal SIGABRT the console shows : Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController viewControllers]: unrecognized selector sent to instance 0x687a880' here is my storyboard layout, i'm not sure if is it the right arrangement. Navigation Controller→View Controller(with a button)→Tab Bar Controller→Table View(where i want to show the players info.) So sorry my English is not very well, hoping u guys could understand what i'm talkin about. THX!! A: The initialization part of UITabBarController is the problem.Assigning a viewconroller from navigationcontroller stack to UITabBarController?? Prepare an array of VC that you need to show in UITabBarController and load it to the viewcontrollers property of UITabBarController
doc_23529218
I know that a json object consists of pairs of <key>:<value>. I have an object "channels" which contains multiple channel objects which consist of an id and some other attributes like "x", "y" and "z". In our team we found two ways to represent the object "channels", the usual way that I see people implement is like this: { "channels": [ { "id":0, "x":0, "y":0, "z":0 }, ... ] } There is also this version, which uses the id as key: { "channels": { "0": { "x":0, "y":0, "z":0 }, ... } } Please note that the first implementation explicitily uses an array while the second relies on the <key> to access the specific channel directly. What is the best way to represent this object? Is it ok to represent a key as value (like the id of the previous case)? Right now there are only two channels (always with id 0 and 1), but in the future we may add more. A: You should prefer the first approach, because it is much easier and more intuitive to consume the JSON that way. If someone wanted to use your API, they would likely create model classes to deserialize into. With the first approach this is easy: public class RootObject { public List<Channel> channels { get; set; } } public class Channel { public int id { get; set; } public int x { get; set; } public int y { get; set; } public int z { get; set; } } In fact, you can just take the JSON and dump it into a generator tool like http://json2csharp.com/ to get these classes (that is what I did here). In contrast, with the second approach, the keys in the JSON representing the IDs are dynamic, which a generator won't recognize as such. So you'll get something like this, which needs to be manually corrected: public class RootObject { public Channels channels { get; set; } } public class Channels { public __invalid_type__0 __invalid_name__0 { get; set; } } public class __invalid_type__0 { public int x { get; set; } public int y { get; set; } public int z { get; set; } } I've seen some people try to fix it like this, which will work for your one-channel example, but obviously won't scale: public class RootObject { public Channels channels { get; set; } } public class Channels { [JsonProperty("0")] public Data Item0 { get; set; } } public class Data { public int x { get; set; } public int y { get; set; } public int z { get; set; } } To consume the JSON properly with the dynamic keys, the classes actually need to look like this: public class RootObject { public Dictionary<string, Channel> channels { get; set; } } public class Channel { public int x { get; set; } public int y { get; set; } public int z { get; set; } } However, the fact that you need to use a Dictionary here is not always intuitive to the casual user. In fact, I have lost count of the number of times some flavor of the question, "How can I handle dynamic keys in JSON?" is asked on StackOverflow. Do your users a favor and don't make them have to think about it. Over and above just deserializing the JSON, the first model is also superior because the Channel object contains all the data about the channel: the id is inside the object itself. It is easy to pass around and use that way. Also it is trivial to convert a List<Channel> into a Dictionary<int, Channel> later if you need to do a key lookup: var dict = rootObject.channels.ToDictionary(ch => ch.id); With the second approach, the id is separate from rest of the channel data, so if you wanted to pass the channel to a method which needed both, you would either have to pass two parameters or create a new model class to wrap everything together. In other words, it is more awkward to use. Bottom line, I see no real upside to using the second approach at all. Go with the first. A: If a channel is an object, not an array then you should use the first option, as you define channel specific contract. If a channel can have subsets of channels, then I suggest using the second approach as you can gain an access to specific subset via the use of a key ( which has to be unique in order to work properly ).
doc_23529219
Also I want to be able to customize the format of the returned data. Now it can give me "1km SW Bart, Redmond, United States" and thats not good. Do you know how to customize it and get it to work with non English characters? GeoCoordinateWatcher myGPS; myGPS = new GeoCoordinateWatcher(); myGPS.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(myGPS_PositionChanged); myGPS.Start(); void myGPS_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e) { double myLatitude = e.Position.Location.Latitude; //do what you want with myLatitude and myLongtitude double myLongtitude = e.Position.Location.Longitude; GPSServiceReference.TerraServiceSoapClient client = new GPSServiceReference.TerraServiceSoapClient(); client.ConvertLonLatPtToNearestPlaceCompleted += new EventHandler<GPSServiceReference.ConvertLonLatPtToNearestPlaceCompletedEventArgs>(client_ConvertLonLatPtToNearestPlaceCompleted); client.ConvertLonLatPtToNearestPlaceAsync(new GPSServiceReference.LonLatPt { Lat = myLatitude, Lon = myLongtitude }); }
doc_23529220
while when I use Array, time is almost 0 milliseconds. Why so much performance difference? int _tmain(int argc, _TCHAR* argv[]) { const int size = 10000; clock_t start, end; start = clock(); vector<int> v(size*size); for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { v[i*size+j] = 1; } } end = clock(); cout<< (end - start) <<" milliseconds."<<endl; // 718 milliseconds int f = 0; start = clock(); int arr[size*size]; for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { arr[i*size+j] = 1; } } end = clock(); cout<< ( end - start) <<" milliseconds."<<endl; // 0 milliseconds return 0; } A: If you are compiling this with a Microsoft compiler, to make it a fair comparison you need to switch off iterator security checks and iterator debugging, by defining _SECURE_SCL=0 and _HAS_ITERATOR_DEBUGGING=0. Secondly, the constructor you are using initialises each vector value with zero, and you are not memsetting the array to zero before filling it. So you are traversing the vector twice. Try: vector<int> v; v.reserve(size*size); A: Change assignment to eg. arr[i*size+j] = i*j, or some other non-constant expression. I think compiler optimizes away whole loop, as assigned values are never used, or replaces array with some precalculated values, so that loop isn't even executed and you get 0 milliseconds. Having changed 1 to i*j, i get the same timings for both vector and array, unless pass -O1 flag to gcc, then in both cases I get 0 milliseconds. So, first of all, double-check whether your loops are actually executed. A: To get a fair comparison I think something like the following should be suitable: #include <sys/time.h> #include <vector> #include <iostream> #include <algorithm> #include <numeric> int main() { static size_t const size = 7e6; timeval start, end; int sum; gettimeofday(&start, 0); { std::vector<int> v(size, 1); sum = std::accumulate(v.begin(), v.end(), 0); } gettimeofday(&end, 0); std::cout << "= vector =" << std::endl << "(" << end.tv_sec - start.tv_sec << " s, " << end.tv_usec - start.tv_usec << " us)" << std::endl << "sum = " << sum << std::endl << std::endl; gettimeofday(&start, 0); int * const arr = new int[size]; std::fill(arr, arr + size, 1); sum = std::accumulate(arr, arr + size, 0); delete [] arr; gettimeofday(&end, 0); std::cout << "= Simple array =" << std::endl << "(" << end.tv_sec - start.tv_sec << " s, " << end.tv_usec - start.tv_usec << " us)" << std::endl << "sum = " << sum << std::endl << std::endl; } In both cases, dynamic allocation and deallocation is performed, as well as accesses to elements. On my Linux box: $ g++ -O2 foo.cpp $ ./a.out = vector = (0 s, 21085 us) sum = 7000000 = Simple array = (0 s, 21148 us) sum = 7000000 Both the std::vector<> and array cases have comparable performance. The point is that std::vector<> can be just as fast as a simple array if your code is structured appropriately. On a related note switching off optimization makes a huge difference in this case: $ g++ foo.cpp $ ./a.out = vector = (0 s, 120357 us) sum = 7000000 = Simple array = (0 s, 60569 us) sum = 7000000 Many of the optimization assertions made by folks like Neil and jalf are entirely correct. HTH! EDIT: Corrected code to force vector destruction to be included in time measurement. A: Your array arr is allocated on the stack, i.e., the compiler has calculated the necessary space at compile time. At the beginning of the method, the compiler will insert an assembler statement like sub esp, 10000*10000*sizeof(int) which means the stack pointer (esp) is decreased by 10000 * 10000 * sizeof(int) bytes to make room for an array of 100002 integers. This operation is almost instant. The vector is heap allocated and heap allocation is much more expensive. When the vector allocates the required memory, it has to ask the operating system for a contiguous chunk of memory and the operating system will have to perform significant work to find this chunk of memory. As Andreas says in the comments, all your time is spent in this line: vector<int> v(size*size); Accessing the vector inside the loop is just as fast as for the array. For an additional overview see e.g. * *[What and where are the stack and heap? *[http://computer.howstuffworks.com/c28.htm][2] *[http://www.cprogramming.com/tutorial/virtual_memory_and_heaps.html][3] Edit: After all the comments about performance optimizations and compiler settings, I did some measurements this morning. I had to set size=3000 so I did my measurements with roughly a tenth of the original entries. All measurements performed on a 2.66 GHz Xeon: * *With debug settings in Visual Studio 2008 (no optimization, runtime checks, and debug runtime) the vector test took 920 ms compared to 0 ms for the array test. 98,48 % of the total time was spent in vector::operator[], i.e., the time was indeed spent on the runtime checks. *With full optimization, the vector test needed 56 ms (with a tenth of the original number of entries) compared to 0 ms for the array. The vector ctor required 61,72 % of the total application running time. So I guess everybody is right depending on the compiler settings used. The OP's timing suggests an optimized build or an STL without runtime checks. As always, the morale is: profile first, optimize second. A: You are probably using VC++, in which case by default standard library components perform many checks at run-time (e.g whether index is in range). These checks can be turned off by defining some macros as 0 (I think _SECURE_SCL). Another thing is that I can't even run your code as is: the automatic array is way too large for the stack. When I make it global, then with MingW 3.5 the times I get are 627 ms for the vector and 26875 ms (!!) for the array, which indicates there are really big problems with an array of this size. As to this particular operation (filling with value 1), you could use the vector's constructor: std::vector<int> v(size * size, 1); and the fill algorithm for the array: std::fill(arr, arr + size * size, 1); A: Two things. One, operator[] is much slower for vector. Two, vector in most implementations will behave weird at times when you add in one element at a time. I don't mean just that it allocates more memory but it does some genuinely bizarre things at times. The first one is the main issue. For a mere million bytes, even reallocating the memory a dozen times should not take long (it won't do it on every added element). In my experiments, preallocating doesn't change its slowness much. When the contents are actual objects it basically grinds to a halt if you try to do something simple like sort it. Conclusion, don't use stl or mfc vectors for anything large or computation heavy. They are implemented poorly/slowly and cause lots of memory fragmentation. A: When you declare the array, it lives in the stack (or in static memory zone), which it's very fast, but can't increase its size. When you declare the vector, it assign dynamic memory, which it's not so fast, but is more flexible in the memory allocation, so you can change the size and not dimension it to the maximum size. A: When profiling code, make sure you are comparing similar things. vector<int> v(size*size); initializes each element in the vector, int arr[size*size]; doesn't. Try int arr[size * size]; memset( arr, 0, size * size ); and measure again...
doc_23529221
If this fails im going to bytecode. Thanks! EDIT: As a follow up question / or a hack around replacing the WHOLE method. I'm really just trying to change a variable that the method generates locally. If there are any better ways to do that. A: Depending on what you really want to do, I do not recommand to decompile / modify / recompile the code (be it for legal, maintainance, understandability, testability reasons.) Bytecode manipulation may not be the best solution either, but if you want to follow this way have a look at the ASM project, it's a widespread bytecode manipulation framework used by many known projects. If I were you I would first give a try to aspects (AspectJ.) The power of aspects is that you don't touch existing code, but tell the VM what to do when / before / after / in place of calling a specific method. It allows you to point out the exact context and change, enhance the behavior of the code, by writing your own code in a decoupled fashion. Hope it helps. A: Sorry, this is not an answer, but it is too long for a comment... I am reflecting this code, not using it as a library. So I dont really need to "use" this code (aka I'm just reflecting and calling functions at runtime). I'd call the "reflecting and calling functions at runtime" as using the code. There might be the reasons why to do that, but I'd prefer to simply call the function as a library function if possible (which should be possible if you can do the same using reflection). ...and manually overload it. There is nothing simpler that extending the class and override a "wrong" method. As of my understanding even if you want to "inject" the method, you have to have the code somewhere. How you will test such code? It'd be a lot easier to just extend the class... Can you specify in bigger detail what you want to achieve with a reasoning why you cannot use what I wrote above? A: If you want to change just one method you can actually extend the class and then @Override the method! Don't know if this is the perfect way to do it,but it works!
doc_23529222
For the columns common to all rows (id, common1, common2), it's clearly very simple (as shown in the code below). create table Music ( id serial, common1 int not null, common2 boolean not null, --<what to put here???> ); However I'm not sure of the best way of considering the subclass issue. Does anyone know where to go from here? A: Postgres table inheritance would work like so: create table music ( id serial primary key, common1 int not null, common2 boolean not null ); create table symphony ( layers int not null, at1 text not null ) inherits(music); create table concerto ( lead text not null, strings integer not null ) inherits(music); Consider if we have a row in each table. insert into concerto (common1, common2, lead, strings) values (1, true, 'a', 5); insert into symphony (common1, common2, layers, at1) values (2, false, 3, 'b'); insert into music (common1, common2) values (3, true); They are all rows of music. -- Fetches id, common1, and common2 from all rows. select * from music If you only want to query rows in music specify only music. -- Fetches id, common1, and common2 from only the one row in music. select * from only music If you want to use symphony columns, you have to query symphony. -- Fetches id, common1, common2, layers, at1 only from symphony select * from symphony Try it A more traditional structure would use join tables like so: create table music ( id serial primary key, common1 int not null, common2 boolean not null ); create table music_symphony ( music_id integer references music(id), layers int not null, at1 text not null ); create table music_concerto ( music_id integer references music(id), lead text not null, strings integer not null ); insert into music (id, common1, common2) values (1, 1, true); insert into music_concerto(lead, strings) values ('a', 5); insert into music (id, common1, common2) values (2, 2, false); insert into music_symphony (music_id, layers, at1) values (2, 3, 'b'); insert into music (id, common1, common2) values (3, 3, true); -- Fetch all symphonies select * from music m join music_symphony ms on ms.music_id = m.id Try it
doc_23529223
Example of a code row generating the error: if (Membership.GetUser() != null) Error description: Unable to cast object of type 'System.Int32' to type 'System.String'. Stack Trace: [InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.] System.Data.SqlClient.SqlBuffer.get_String() +141 System.Data.SqlClient.SqlDataReader.GetString(Int32 i) +96 System.Web.Security.SqlMembershipProvider.GetNullableString(SqlDataReader reader, Int32 col) +35 System.Web.Security.SqlMembershipProvider.GetUser(String username, Boolean userIsOnline) +1110 System.Web.Security.Membership.GetUser(String username, Boolean userIsOnline) +82 System.Web.Security.Membership.GetUser() +19 Does anyone have an idea of what's wrong? Update: We could not find a solution for this error. But eventually it disapeared. Now when we migrated to another server this error totally cripples our application. I'm totally out of ideas :( A: Put a try/catch block around the Membership.GetUser() call and log the username. You can get the username by calling Membership.GetCurrentUserName(). Once you have a username this is causing problems for, look at the membership table in SQL and check out the Comments field. My guess is that something funny is going on in the Comments field - maybe there are some weird unicode characters it's having trouble with, or maybe there's too much data in that field, etc. Also, try calling dbo.aspnet_Membership_GetUserByName on the membership database for the user that it had trouble with and see what result you get.
doc_23529224
After trawling through hundreds of sites/blogs (well maybe) 'explaining' how to code using OpenGL, I have hit a brick wall. The problem is my apps are fully functional and on the Market at the moment, but my latest app was developed on an HTC Desire HD, and I am getting many reports of bad performance on less powerful devices. The obvious route is a move to OpenGL. All the tutorial sites are geared towards developing from scratch. This is great for anyone starting a new project, but I need a 'retro-fit' to my apps. I don't fancy rewriting from scratch! Has anyone had experience of this? Any thoughts would be hugely appreciated. A: I recently did something similar with my app and did receive a large performance benefit. A lot of what you 'should change' depends on how your application is structured. For me the hardest thing was translating my UI elements because I had to re-generate the entire 'which control got touched' logic and setup text rendering. Neither of these problems are tough enough to be deal beakers but I'd avoid them if you can. Fortunately there are some good sides. Since your app is already only 2d you can avoid the most complex parts of learning OpenGL, dealing with the 3d dimension! I'd start by setting up a gl.SurfaceView. Use glOrtho to setup the extents of your GL world, if your game was already resolution independent that should should have idea of how wide the screen is in some 'independent' manner. Just setup glOrtho to use those same extents. I created a simple sprite class which I used for all my rendering. The Sprite had simple vertex buffer as a members, I just had it make a 1 by 1 rect, then used used scale to setup the size. (So if it was really 30x30, I would set the scale to ScaleX=30 ScaleY=30). It looked something like this ByteBuffer vbb = ByteBuffer.allocateDirect( mNumVerts * 2 * 4 ); vbb.order( ByteOrder.nativeOrder() ); mVtxBuf = vbb.asIntBuffer(); vbb = ByteBuffer.allocateDirect( mNumVerts * 2 * 4 ); vbb.order( ByteOrder.nativeOrder() ); mTexBuf = vbb.asIntBuffer(); mVtxBuf.put( -Fixed32.HALF ); mVtxBuf.put( -Fixed32.HALF ); mTexBuf.put( 0 ); mTexBuf.put( Fixed32.ONE ); mVtxBuf.put( Fixed32.HALF ); mVtxBuf.put( -Fixed32.HALF ); mTexBuf.put( Fixed32.ONE ); mTexBuf.put( Fixed32.ONE ); mVtxBuf.put( Fixed32.HALF ); mVtxBuf.put( Fixed32.HALF ); mTexBuf.put( Fixed32.ONE ); mTexBuf.put( 0 ); mVtxBuf.put( -Fixed32.HALF ); mVtxBuf.put( -Fixed32.HALF ); mTexBuf.put( 0 ); mTexBuf.put( Fixed32.ONE ); mVtxBuf.put( Fixed32.HALF ); mVtxBuf.put( Fixed32.HALF ); mTexBuf.put( Fixed32.ONE ); mTexBuf.put( 0 ); mVtxBuf.put( -Fixed32.HALF ); mVtxBuf.put( Fixed32.HALF ); mTexBuf.put( 0 ); mTexBuf.put( 0 ); mVtxBuf.position( 0 ); mTexBuf.position( 0 ); (Fixed32.HALF is just 0.5 in fixed point, you can just use 0.5 and change the Draw calls to FLOAT instead of FIXED) With the drawing code of... gl.glMatrixMode( GL10.GL_MODELVIEW ); gl.glLoadIdentity(); gl.glEnableClientState( GL10.GL_VERTEX_ARRAY ); gl.glEnableClientState( GL10.GL_TEXTURE_COORD_ARRAY ); gl.glColor4f( 1.0f * thing.getAlpha() , 1.0f * thing.getAlpha() , 1.0f * thing.getAlpha() , thing.getAlpha() ); gl.glTranslatef( thing.getX(), thing.getY(), thing.getZ() ); gl.glScalef( thing.getXScale(), thing.getYScale(), thing.getZScale() ); gl.glFrontFace( GL10.GL_CW ); gl.glVertexPointer( 2, GL10.GL_FIXED, 0, mdl.getVtxBuf() ); gl.glTexCoordPointer( 2, GL10.GL_FIXED, 0, mdl.getTexBuf() ); // gl.glColorPointer( 4, GL10.GL_FLOAT, 0, mColorBuffer ); gl.glDrawArrays( GL10.GL_TRIANGLES, 0, mdl.getVtxCount() ); A: Well, I would suggest you replace as little as you need until you're done (=fast enough). Hence, it's very import you know exactly where your performance is unacceptable. Profile, profile,profile. Of course, there are some things you will always need to implement, even if you just want to use Opengl for a tiny part of the game. Context creating, texture loading, etc...
doc_23529225
mlb = MultiLabelBinarizer() X = dataframe['body'].values y = mlb.fit_transform(dataframe['tag'].values) classifier = Pipeline([ ('vectorizer', CountVectorizer(lowercase=True, stop_words='english', max_df = 0.8, min_df = 10)), ('tfidf', TfidfTransformer()), ('clf', OneVsRestClassifier(LinearSVC()))]) predicted = cross_val_predict(classifier, X, y) When running my code I get multiple warnings: UserWarning: Label not :NUMBER: is present in all training examples. When I print out predicted and true labels, cca half of all documents has it's predictions for labels empty. Why is this happening, is it related to warnings it prints out while training is running? How can I avoid those empty predictions? EDIT01: This is also happening when using other estimators than LinearSVC(). I've tried RandomForestClassifier() and it gives empty predictions as well. Strange thing is, when I use cross_val_predict(classifier, X, y, method='predict_proba') for predicting probabilities for each label, instead of binary decisions 0/1, there is always at least one label per predicted set with probability > 0 for given document. So I dont know why is this label not chosen with binary decisioning? Or is binary decisioning evaluated in different way than probabilities? EDIT02: I have found an old post where OP was dealing with similar problem. Is this the same case? A: I too had the same error. Then I used LabelEncoder() instead of MultiLabelBinarizer() to encode the labels. from sklearn import preprocessing le = preprocessing.LabelEncoder() y = le.fit_transform(Labels) I am not getting that error anymore. A: Why is this happening, is it related to warnings it prints out while training is running? The issue is likely to be that some tags occur just in a few documents (check out this thread for details). When you split the dataset into train and test to validate your model, it may happen that some tags are missing from the training data. Let train_indices be an array with the indices of the training samples. If a particular tag (of index k) does not occur in the training sample, all the elements in the k-th column of the indicator matrix y[train_indices] are zeros. How can I avoid those empty predictions? In the scenario described above the classifier will not be able to reliably predict the k-th tag in the test documents (more on this in the next paragraph). Therefore you cannot trust the predictions made by clf.predict and you need to implement the prediction function on your own, for example by using the decision values returned by clf.decision_function as suggested in this answer. So I don't know why is this label not chosen with binary decisioning? Or is binary decisioning evaluated in different way than probabilities? In datasets containing many labels the occurrence frequency for most of them uses to be rather low. If these low values are fed to a binary classifier (i.e. a classifier that makes a 0-1 prediction) it is highly probable that the classifier would pick 0 for all tags on all documents. I have found an old post where OP was dealing with similar problem. Is this the same case? Yes, absolutely. That guy is facing exactly the same problem as you and his code is pretty similar to yours. Demo To further explain the issue I have elaborated a simple toy example using mock data. Q = {'What does the "yield" keyword do in Python?': ['python'], 'What is a metaclass in Python?': ['oop'], 'How do I check whether a file exists using Python?': ['python'], 'How to make a chain of function decorators?': ['python', 'decorator'], 'Using i and j as variables in Matlab': ['matlab', 'naming-conventions'], 'MATLAB: get variable type': ['matlab'], 'Why is MATLAB so fast in matrix multiplication?': ['performance'], 'Is MATLAB OOP slow or am I doing something wrong?': ['matlab-oop'], } dataframe = pd.DataFrame({'body': Q.keys(), 'tag': Q.values()}) mlb = MultiLabelBinarizer() X = dataframe['body'].values y = mlb.fit_transform(dataframe['tag'].values) classifier = Pipeline([ ('vectorizer', CountVectorizer(lowercase=True, stop_words='english', max_df=0.8, min_df=1)), ('tfidf', TfidfTransformer()), ('clf', OneVsRestClassifier(LinearSVC()))]) Please, notice that I have set min_df=1 since my dataset is much smaller than yours. When I run the following sentence: predicted = cross_val_predict(classifier, X, y) I get a bunch of warnings C:\...\multiclass.py:76: UserWarning: Label not 4 is present in all training examples. str(classes[c])) C:\\multiclass.py:76: UserWarning: Label not 0 is present in all training examples. str(classes[c])) C:\...\multiclass.py:76: UserWarning: Label not 3 is present in all training examples. str(classes[c])) C:\...\multiclass.py:76: UserWarning: Label not 5 is present in all training examples. str(classes[c])) C:\...\multiclass.py:76: UserWarning: Label not 2 is present in all training examples. str(classes[c])) and the following prediction: In [5]: np.set_printoptions(precision=2, threshold=1000) In [6]: predicted Out[6]: array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) Those rows whose entries are all 0 indicate that no tag is predicted for the corresponding document. Workaround For the sake of the analysis, let us validate the model manually rather than through cross_val_predict. import warnings from sklearn.model_selection import ShuffleSplit rs = ShuffleSplit(n_splits=1, test_size=.5, random_state=0) train_indices, test_indices = rs.split(X).next() with warnings.catch_warnings(record=True) as received_warnings: warnings.simplefilter("always") X_train, y_train = X[train_indices], y[train_indices] X_test, y_test = X[test_indices], y[test_indices] classifier.fit(X_train, y_train) predicted_test = classifier.predict(X_test) for w in received_warnings: print w.message When the snippet above is executed two warnings are issued (I used a context manager to make sure warnings are catched): Label not 2 is present in all training examples. Label not 4 is present in all training examples. This is consistent with the fact that tags of indices 2 and 4 are missing from the training samples: In [40]: y_train Out[40]: array([[0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0], [1, 0, 0, 0, 0, 0, 1]]) For some documents, the prediction is empty (those documents corresponding to the rows with all zeros in predicted_test): In [42]: predicted_test Out[42]: array([[0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0]]) To overcome that issue, you could implement your own prediction function like this: def get_best_tags(clf, X, lb, n_tags=3): decfun = clf.decision_function(X) best_tags = np.argsort(decfun)[:, :-(n_tags+1): -1] return lb.classes_[best_tags] By doing so, each document is always assigned the n_tag tags with the highest confidence score: In [59]: mlb.inverse_transform(predicted_test) Out[59]: [('matlab',), (), (), ('matlab', 'naming-conventions')] In [60]: get_best_tags(classifier, X_test, mlb) Out[60]: array([['matlab', 'oop', 'matlab-oop'], ['oop', 'matlab-oop', 'matlab'], ['oop', 'matlab-oop', 'matlab'], ['matlab', 'naming-conventions', 'oop']], dtype=object)
doc_23529226
Now, the basic concept in many css preprocessors is to extend the rule. // Vendor .foo { font-weight: bold; } .bar { text-color: red; } // Mine .bar { .foo } In the above example, you don't have access to .foo or .bar, but with preprocessors, you can extend functionality from .foo into .bar, which works great for less/stylus/etc. The problem, is when the vendor rules are only defined in raw css. So with that said, the most obvious solution is to have Stylus/Less import the raw css as stylus/less. However, neither seem to be able to actually do this.. that i've found at least. Less doesn't seem able to (@import "foo.css" directives are ignored) and while Stylus has an option to actually include the imported raw CSS, it did not seem to actually be processing it. That is to say, it would include the css, but @extend directives failed (perhaps i am wrong?). The other option i could think of is simply renaming the .css files to the preprocessor language extension. Since we want to keep the vendor stuff out of our hands, allowing for proper versioning/etc, This involves a build process which copies the target css files and renames them into the target language extension, but this is error prone. Stylus ran into syntax errors immediately, and Less could just as easily (as not all CSS is valid Less. most is, but not all). So.. any additional thoughts on this front? Hopefully there is an option i may be missing? Perhaps SCSS handles this better? Currently, with what i have found is/isn't possible.. i feel the only stable way is to simply copy the raw css bits into my css code. If the vendor code changes, i'll have to update manually, but at least i don't run the risk of vendor stuff changing and all of a sudden the build process fails, because vendor introduced some CSS syntax not supported by less/etc. It is far from good.. but the worst that can happen is my css looks funny, and i need to update. edit: I'm going to try SCSS next.. we'll see how it goes. On the site, they claim all CSS(3 only?) syntax is valid SCSS edit2: For clarity. My question is, give the above scenario, what would you do? Importing the .css files is not possible (See note below!), and renaming .css files to .less/.stylus can in turn be error prone, since less is not a perfect superset of CSS(namely due to proprietary features). !Note!: I have since been digging around the less source to see what could be done to fix this problem, rather than work around it, and ran into a dozen support tickets on the matter. The main discussion of which seems to be taking place on #issue 1185, and more importantly, check out the changelog which *(i believe) addresses this issue! CHANGELOG 1.4.0 Beta So with that said, the @import (less) "file.css" is likely the winning scenario here, even if it may have a few bugs due to the beta status. Yay :) A: Your best bet is either what @Lee Olayvar said, or use the new ":extend()" feature in LESS. It sounds like you might have tried the extend feature, but you used the "SASS directive" syntax (which IMO is improper use of an at-rule), whereas LESS uses the CSS-like pseudo-selector syntax: .foo:extend(.bar) {} And if you are patient (in the coming days/weeks), you will see a new feature that is perfect for what you want to do, and it's unique to LESS. It will allow you to extend or mixin external "silent" styles. Meaning you will be able to "@import" and external stylesheet but the styles won't show up in your compiled code unless you extend them or use them as a mixin. I'm on the core team for Less.js btw, so let me know if you have any other questions or if I can be of further help. A: It looks like all imported .css files won't be prepocessed by less but will just be added with an @import at the top. You can import both CSS and LESS files. Only LESS files import statements are processed, CSS file import statements are kept as they are. If you want to import a CSS file, and don’t want LESS to process it, just use the .css extension Source: http://lesscss.org/ The best thing you could do would be the renaming I believe. A: While still in beta, the newly added @import (less) "file.css" syntax should properly handle all CSS files. Due to the "official" support, it can also be expected/assumed that any proprietary syntax that breaks LESS would be fixed (though possibly not "supported"). So in theory this is the best option! Barring SCSS, which i have not tried yet in this scenario. Stylus still has issues though, in my tests. For more information, check out this issue or this changelog.
doc_23529227
The relevant code is: int main(){ while(cin){ int n = 0; int sum = 0; cout << "\n\nEnter a size (n) for the matrix: "; cin >> n; vector<vector<int> > matrix ( n, vector<int> ( n ) ); int k = 0; for ( int i = 0; i < n; i++ ) { for ( int j = 0; j < n; j++ ) matrix[i][j] = k++; } for ( int i = 0; i < n; i++ ) { for ( int j = 0; j < n; j++ ) cout<< setw ( 3 ) << matrix[i][j] <<' '; cout<<'\n'; } for ( int i = 0; i < n; i++ ) { for ( int j = 0; j < n; j++ ) sum += matrix[i][j]; } cout << "\nThe sum of the elements of the matrix is: " << sum << ' \n'; } } So, what's weird is...when it prints the value of 'sum', for some reason, I am getting "8202" appended to the value. If I given it n = 1, it will print out 08202, or for n of 3 it will print out 368202. Any ideas? I tried the debugger in Code::Blocks w/o success. A: You output ' \n'. Note the space before the \n. That's two characters/a string. However, you put 's around it meaning it interprets two characters as one character giving you strange results. Change it to " \n". BONUS EPIC-PHUNZIES CONTENT: How did I figure it out? Well... what else could it be? The sum outputted correctly so something must be wrong after it. And what's the only thing after you output sum? You output ' \n'... well, what's wrong with that? And BAM! Problem solved.
doc_23529228
import tweepy query = " #CMKP_IN_DIRUPPER -is:retweet" client = tweepy.Client() counts = client.get_recent_tweets_count(query=query, granularity='day') for i in counts.data: print(i["tweet_count"]) I am using the following code to find out how many tweets are there in a certain trend. But the values I am getting using Twitter API v1 and the values being shown in the Trend Tab on the twitter website are totally different. For this hashtag "#CMKP_IN_DIRUPPER" the API is giving me 14,000+ tweets, but on the twitter websites it currently has 30k+ tweets. Can anyone explain to me the reason for this difference, is there a problem with my code?
doc_23529229
%pylab plt.xkcd() plt.plot(sin(linspace(0, 10))) plt.title('Whoo Hoo!!!') I get instead of What am I doing wrong? A: Using ubuntu 16.04 and python 3, with matplotlib 2.0.0 installed the following fixes the problem for me. * *Install Comic sans: sudo apt install fonts-humor-sans *Remove matplotlib cache: rm ~/.cache/matplotlib -r A: To get it working, you need * *matplotlib 1.3.1 (it won't work with matplotlib 1.3.0 or earlier) * *sudo pip install matplotlib --upgrade *font Humor Sans * *download from here or here, install (on OS X you open it and click Install) *remove the matplotlib font cache (as suggested by DanHickstein in matplotlib/issues/2269) * *rm ~/.matplotlib/fontList.cache Now, execute the code and it should work. You do not need to change backend to TkAgg, as some people suggest. For me it works perfectly fine on 'module://IPython.kernel.zmq.pylab.backend_inline' (you can check it by plt.get_backend()). (I had the same problem and I've solved it, at least on OS X 10.8.5, with matplotlib 1.3.1 and IPython 2.0.0; removing font cache was necessary to get the font running.) A: Make sure you have fonts-humor-sans installed. In Ubuntu/Debian, you can install them with (from the command-line): $ sudo apt install python3-xkcd fonts-humor-sans Then the best option (instead of deleting the matplotlib cache) is to rebuild the font manager (from within the Python interpreter, script or Jupyter notebook): import matplotlib matplotlib.font_manager._rebuild() A: From the blog post you linked: Also, if you want to have the font match above, be sure to download and install the Humor Sans font on your system. For matplotlib to recognize it, you may have to remove the font cache... As far as which version of the font to download, I would try the most current.
doc_23529230
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="screen"> <html> <body bgcolor="white"> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="title"> <h1> <xsl:apply-templates/> </h1> </xsl:template> <xsl:template match="field"> <p><b><xsl:value-of select="@label"/>: </b><xsl:apply-templates/></p> </xsl:template> <xsl:template match="table"> <table><xsl:apply-templates/></table> </xsl:template> <xsl:template match="table/row"> <xsl:variable name="bgcolor"> <xsl:choose> <xsl:when test="(position() mod 2) = 0">linen</xsl:when> <xsl:otherwise>white</xsl:otherwise> </xsl:choose> </xsl:variable> <tr bgcolor="{$bgcolor}"><xsl:apply-templates/></tr> </xsl:template> <xsl:template match="table/row/cell"> <td><xsl:apply-templates/></td> </xsl:template> </xsl:stylesheet> Input XML: <?xml version="1.0"?> <screen> <title>Dissociation</title> <field label="Artist">Dillinger Escape Plan</field> <table> <row> <cell>Limerent Death</cell> <cell>4:06</cell> </row> <row> <cell>Symptom Of Terminal Illness</cell> <cell>4:03</cell> </row> <row> <cell>Wanting Not So Much To As To</cell> <cell>5:23</cell> </row> </table> </screen> Output HTML: <html><body bgcolor="white"> <h1>Dissociation</h1> <p><b>Artist: </b>Dillinger Escape Plan</p> <table> <tr bgcolor="linen"> <td>Limerent Death</td> <td>4:06</td> </tr> <tr bgcolor="linen"> <td>Symptom Of Terminal Illness</td> <td>4:03</td> </tr> <tr bgcolor="linen"> <td>Wanting Not So Much To As To</td> <td>5:23</td> </tr> </table> </body></html> A: Change <table><xsl:apply-templates/></table> to <table><xsl:apply-templates select="row"/></table> or use <xsl:strip-space elements="*"/> or at least <xsl:strip-space elements="table"/>. Currently you are processing all child nodes, including white space text nodes, that way your attempt using position() fails.
doc_23529231
UPDATE `table` SET `my_bool` = NOT my_bool And also I need to change only the row with the selected id My attempt below UPDATE Model m SET m.flag = NOT m.flag WHERE m.id is :id function(Integer id){ StringBuilder queryBuilder = new StringBuilder("UPDATE Model m SET m.flag = NOT m.flag WHERE m.id is :id"); this.em.createQuery(queryBuilder.toString()); } I get the following error: unexpected token: NOT I have just started learning HQL and the documentation says it is a valid operator 11.6.9. NOT predicate operator The NOT operator is used to negate the predicate that follows it. If that following predicate is true, the NOT resolves to false. If the predicate is true, NOT resolves to false. If the predicate is unknown, the NOT resolves to unknown as well. Can you please help A: It works for me: UPDATE Model m SET m.flag = !m.flag WHERE m.id = :id And C# code: var query = container.Resolve<ISession>().CreateQuery(hql); query.SetParameter("id", 1); query.ExecuteUpdate();
doc_23529232
topic student level week 1 a 1 1 1 b 2 1 1 a 3 1 2 a 1 2 2 b 2 2 2 a 3 2 2 b 4 2 The new dataframe should represent an interaction between students through the topic. It should contain four columns: "student source", "student destination", "week" and "reply count". Student Destination is a student that each student shared the topic with. Reply count is a number of times in which Student Destination "directly" replied to Student Source. The new dataframe should look like: st_source st_dest week reply_count a b 1 1 a b 2 2 b a 1 1 b a 2 1 Reply count can be explained easier with an example. If a thread is started by student A (by sending a message at level 1), B replied to A (sending a message at level 2), C replied to B (sending a message at level 3). Then B "directly" replied to A, and C "directly" replied to B, but C's reply to A is not direct (and so we don't count it). Does anyone have some idea? Thank you in advance! A: result = (df.groupby('week').apply( lambda g: g.groupby([g.student.shift(), g.student]) .week.agg({'reply_count': 'count'}) .rename_axis(("st_source", "st_dest")) ).reset_index()) ​ result[['st_source', 'st_dest', 'week', 'reply_count']].sort_values(['st_source', 'st_dest']) # st_source st_dest week reply_count #0 a b 1 1 #2 a b 2 2 #1 b a 1 1 #3 b a 2 1
doc_23529233
A: If I understand correctly, you want some kind of long-polling stuff -- you should search for the term "comet". For instance, here are a couple of posts that might interest you : * *Is there some way to PUSH data from web server to browser? *Online tutorials for implementing comets (server push) *Using comet with PHP? *Problem of choosing comet server *Comet & PHP: How to use Comet with a PHP Chat System ? Still, one might say that PHP, because of its non-threaded model, I suppose, is not the best language/technology for that kind of stuff... And maybe you'll end up looking to another technology for that part of your site... For instance, you can take a look at : * *Choosing and deploying a comet server. A: some links about reverse http: reverse http 1 making-real-time-web-real-time reverse http 2 rest-requires-asynchronous-notification A: After much research last night, I found this as the answer for the server side. Then write a php script for the client side. Then have ajax call the client which calls the server. Only problem is some of the extensions have to be manually installed. http://php-mag.net/itr/online_artikel/psecom,id,484,nodeid,114.html
doc_23529234
* *it always give a success code (because it's not blocking) *The instances is always running as cloud rundoesn't know when to turn it off(because it's not blocking). I think the problem is blocking :-) Here's a sample of my code: async def curve_builder(secret: str): os.system("python3 scripts/my_script.py") return {"succcess": True, "status": "Batch job completed"} Is there a way to let the script and then return a success/fail message once it's done? I'm not sure how to block it, it seems to just return a success as soon as the command is executed. I'm not sure if this is specific to fastapi or general python. A: Blocking operations could hang up your current worker. When you want to execute blocking code over a coroutine, send its logic to a executor. * *Get the event loop loop = asyncio.get_running_loop() *Any blocking code must go out of your coroutine. So, your current worker will be able to execute other coroutines. await loop.run_in_executor(None, func) For your case, the final result will be: async def curve_builder(secret: str): loop = asyncio.get_running_loop() result = await loop.run_in_executor(None, lambda: os.system("python3 scripts/my_script.py")) return {"status": result} You can read further information in the docs: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor A: Assign the ‘os.system()’ call to a variable. The exit code of your script is assigned, so it will wait till it finished, despite being a async method you are working from. The answer was wrong, I've tested an example setup but could not reproduce the issue. Script1: import os import asyncio async def method1(): print("Start of method1") os.system("python /path/to/other/script/script2.py") print("End of method1") print("start script1") asyncio.run(method1()) print("end script1") Script2: import asyncio async def method2(): print("Start method2") await asyncio.sleep(3) print("End method2") print("start async script2") asyncio.run(method2()) print("end async script2") Output: start script1 Start of method1 start async script2 Start method2 End method2 End async script2 End of method end script1
doc_23529235
P.S. When I set the program to list the filesystem in C:\Windows\ it worked. This is the code that I used: private void ListDirectory(TreeView treeView, string path) { treeView.Nodes.Clear(); var rootDirectoryInfo = new DirectoryInfo(path); treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo)); } private static TreeNodeCreateDirectoryNode(DirectoryInfo directoryInfo) { var directoryNode = new TreeNode(directoryInfo.Name); foreach (var directory in directoryInfo.GetDirectories()) directoryNode.Nodes.Add(CreateDirectoryNode(directory)); foreach (var file in directoryInfo.GetFiles()) directoryNode.Nodes.Add(new TreeNode(file.Name)); return directoryNode; } In the program, ti call the method I used: mainWindow(){ InitialiseComponent(); ListDirectory(treeView1, @"C:\"); } A: This code will run under the user account that is executing it. Based on the permissions of that account a System.UnauthorizedAccessException may occur for some directories such as a user account folder or the recycle bin. This will not prevent you from navigating partway through the directory structure, but would prevent that account from reading all of the directories inside of the protected folders. You could write code to pull the access control list using directoryInfo.GetAccessControl() Or you could catch the System.UnauthorizedAccessException. Then your code might look like this: try { var directoryNode = new TreeNode( directoryInfo.Name ); foreach ( var directory in directoryInfo.GetDirectories() ) directoryNode.Nodes.Add( CreateDirectoryNode( directory ) ); foreach ( var file in directoryInfo.GetFiles() ) directoryNode.Nodes.Add( new TreeNode( file.Name ) ); return directoryNode; } catch ( System.UnauthorizedAccessException ) { return new TreeNode( "Unavailable Node" ); } catch ( System.IO.PathTooLongException ) { return new TreeNode( "Unavailable Node" ); }
doc_23529236
width: max(33.33%, 200px) But it doesn't work. I found the note here: Math expressions involving percentages for widths and heights on table columns, table column groups, table rows, table row groups, and table cells in both auto and fixed layout tables may be treated as if auto had been specified How can I solve this problem? A: Using min-width works: td:first-child { width:33.3%; min-width:150px; } td { border:1px solid blue; } <div style="resize:both; overflow:auto; padding:2em; background:#fec"> <table style="border:1px solid red; width:100%"> <tr> <td>cell 1</td> <td>cell 2</td> <td>cell 3</td> </tr> </table> </div>
doc_23529237
A: Open chrome://flags/#enable-site-per-process and search for "Disable site isolation". If you're confident with Google and want to get more comprehensive guarantee, just choose Default. A: Current version (Chrome 75) crashes when switching flag Disable site isolation to disabled, relaunch browser and open developer tools (aka. inspect).
doc_23529238
File f = new File("log.txt"); if(f.exists()) { System.out.println("Exists"); } else { System.out.println(" Doesnt Exist"); } A: Relative paths such as "log.txt" are resolved against the user's "current working directory" which depends on how the application is started. The application could be looking for log.txt anywhere on the file system. If .exists returns true, the file exists. Print the absolute file path to see where the file is located: System.out.println(f.getAbsoluteFile() + " Exists");
doc_23529239
import java.util.concurrent.ThreadLocalRandom; import java.util.Date; public class TestDate { public static void main(String[] args) { Date d1 = new Date(ThreadLocalRandom.current().nextLong(d1.getTime())); System.out.println("Today's date is: " + d1.toString()); System.out.println("Milliseconds: " + d1.getTime()); } } When I'm just setting d1 as a variable it says 'Duplicate local variable d1' I don't get where my mistake is A: Don’t use Date. Use Instant. Instant now = Instant.now(); Instant someTime = Instant.ofEpochMilli( ThreadLocalRandom.current().nextLong(now.toEpochMilli())); System.out.println(someTime); Example output: 2000-09-12T12:14:59.258Z The code generates a random point in time between the epoch of January 1, 1970 00:00 UTC (inclusive) and now (exclusive). The Date class that you were trying to use is poorly designed and fortunately long outdated. Don’t use it. Use java.time, the modern Java date and time API. It is so much nicer to work with. The class to use for a moment in time is Instant. What went wrong in your code? Date d1 = new Date(ThreadLocalRandom.current().nextLong(d1.getTime())); In this line you are trying to declare a variable d1 and assign it an initial value using the value if d1. This creates a circular dependency. While defining something in terms of itself may occasionally work in human language because humans can think for themselves, it doesn’t work in Java. So you would have needed to pass something else that doesn’t depend on d1 to nextLong. Exception: You may say that a recursive method is defined in terms of itself. But that’s a different story. Your compiler said: The local variable d1 may not have been initialized We had wanted a clearer error message. In this case it could safely have said has not been initialized (the same message is used in situations where the may not is appropriate). It is worth noting that it pointed to the d1 in d1.getTime(): You were trying to use the value of d1 before it was initialized. Tutorial link Oracle tutorial: Date Time explaining how to use java.time. A: You should prefer to use LocalDate instead (or LocalDateTime if you want to use time too). Date and Calendar are quite old and not recommended. For example, if you want to get it from epoch day, you can use LocalDate.ofEpochDay . Here's a sample to get a random date from one date to another (including both) : @RequiresApi(Build.VERSION_CODES.O) private fun getRandomDate(startDate: LocalDate, endDate: LocalDate): LocalDate { val randomDay = Random.nextLong(startDate.toEpochDay(), endDate.toEpochDay() + 1) return LocalDate.ofEpochDay(randomDay) } Usage: val randomDate = getRandomDate(LocalDate.now().minusYears(100), LocalDate.now().plusYears(100)) Log.d("AppLog", "randomDate:$randomDate") I know it's in Kotlin, but the same should work for Java. A: Date d1 = new Date(ThreadLocalRandom.current().nextLong(d1.getTime())); You call d1.getTime() as d1 is being initialized. A: You need to actually initialize d1 before you can invoke any methods on it. Consider the following: public static void main(String[] args) { Date d1 = Calendar.getInstance().getTime(); d1 = new Date(ThreadLocalRandom.current().nextLong(d1.getTime())); System.out.println("Today's date is: " + d1.toString()); System.out.println("Milliseconds: " + d1.getTime()); } You see that I initialize the variable using Calendar.getInstance().getTime() before trying to invoke d1.getTime() in the constructor. If it at all helps you understand the situation, you could use two separate variables to achieve the same end, as I did below: Date d1 = Calendar.getInstance().getTime(); Date d2 = new Date(ThreadLocalRandom.current().nextLong(d1.getTime()));
doc_23529240
* *The .NET installer will not allow an older version of .NET to be installed. *I uninstalled .NET 4.7.2 completely (and even rebooted), but the .NET installer mistakenly believes that 4.7.2 is still on there, and thus won't allow me to install 4.7. *The only version of .NET currently on the server is 4.6, and it's just the framework (not dev pack). Is there a registry key I can change/delete so that the .NET installer will allow me to install .NET 4.7?
doc_23529241
class Development(models.Model): id = models.AutoField(primary_key=True) client = models.ForeignKey(InsName, on_delete=models.SET_NULL, null=True, blank=True) platform = models.ManyToManyField(Platform) user = models.ForeignKey(User, on_delete=models.CASCADE) and in views.py (with the corresponding url added to urls.py): class DevelopmentFilterView(generic.ListView): model = Development How do I tell my template to only output a list of the database entries for a certain client? A: You'll need to define a get_queryset function in your View Class which returns a QuerySet of the Development model. Something like this should work: def get_queryset(self): return Development.objects.filter(client__id=1) A: You have to use the method get_queryset from ListView class, like this: class DevelopmentFilterView(generic.ListView): model = Development queryset = Development.objects.all() def get_queryset(self): qs = super().get_queryset() qs = qs.filter(client=client) return qs
doc_23529242
It is a WPF application that was recently converted to .NET 4.0 and this code runs inside a background worker if(bgWorker1.IsBusy || bgWorker2.IsBusy) { Thread.Sleep(100); Application.Current.Dispatcher.Invoke( System.Windows.Threading.DispatcherPriority.Background, new System.Threading.ThreadStart(delegate { }) ); } 1 - What possible side-effect would be acheived by invoking a thread (main gui) with a no-op delegate. The other two threads also perform invokes on the main gui thread but only this one sets the priority to something else than Normal (they use Action rather than TreadStart though). 2 - I have cases that strangely resembles deadlock with this application and something tells me that this could be the cause. (mucking around the priority and main gui thread for no appearant reason). Thanks A: This thread will cause the calling function to block until the Dispatcher's thread can "process" the (no-op) delegate. This is likely not a good practice, and should probably be removed. I suspect the goal here was to allow this (third) BackgroundWorker's completion event to be a signal for when the first two BackgroundWorkers completed. In general, spinning for completion like this is typically a sign of a bad design. A much better design would be to use a CountdownEvent, which could be signaled by both BackgroundWorker instances on their completion. You could then just wait on the countdown event instead of looping with Thread.Sleep and the dispatcher invocation. A: * *"What possible side-effect would be acheived by [...]" Because it uses Invoke and not BeginInvoke it will be a blocking call. This means that your background thread won't continue to execute until your noop delegate runs. The effect is that the code won't continue until everything that was queued into the message loop before this noop has been executed. *"I have cases that strangely resembles deadlock with this application and something tells me that this could be the cause." Sounds plausible to me. This block of code screams both bad practice, and possible deadlock location. Since the code is referencing other background workers, it might be that others are doing something similar. Now, it seems clear that something is wrong, but without knowing more about what's going on it's rather hard to comment about how it could be fixed. My guess is there is a fundamental design flaw the the approach that is being taken though.
doc_23529243
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "mpi.h" struct fields{ int hostNumber; int *numberArray; }; struct fields *start(int); struct fields *gatherData(int); int main(int argc, char** argv) { int rank, size, count, *tmpArray, tmpNumOfArray; struct fields *myFields; setbuf(stdout, NULL); MPI_Init(&argc, &argv); MPI_Status status; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); while(1){ if (rank == 0){ //printf("I am parent-process with rank = %d, size = %d\n", rank, size); myFields = start(rank); //for (int i = 0 ; i < myFields->hostNumber ; i++) printf("%d\n",((myFields->numberArray)[i])); if ((myFields->hostNumber) < size){ printf("Error!!! Number of Processes is more than number of Elements.\n"); MPI_Abort(MPI_COMM_WORLD, 0); } if ((myFields->hostNumber) < (2 * size)){ printf("Error!!! The Host of Numbers should be at least double of the number of Processes!!!\n"); MPI_Abort(MPI_COMM_WORLD, 0); } tmpNumOfArray = myFields->hostNumber; MPI_Bcast(&tmpNumOfArray, 1, MPI_INT, 0, MPI_COMM_WORLD); } MPI_Barrier(MPI_COMM_WORLD); printf("process = %d, tmpNumOfArray = %d\n", rank, tmpNumOfArray); sleep(5); } MPI_Finalize(); return 0; } struct fields *start(int rank){ int input; struct fields *myFields; system("clear"); printf("1) Type 1 For Execution\n"); printf("2) Type 2 For Exit\n"); printf("Give your choice:"); scanf("%d",&input); switch(input){ case 1: myFields = gatherData(rank); break; case 2: default: MPI_Abort(MPI_COMM_WORLD, 0); } return myFields; } struct fields *gatherData(int rank){ int host; struct fields *myFields; myFields = (struct fields *)malloc(sizeof(struct fields)); if (myFields == NULL){ printf("Cannot allocate memory for myFields struct!\n"); MPI_Abort(MPI_COMM_WORLD, 0); } if (rank == 0){ printf("Give the host of the numbers to be statically checked: "); scanf("%d",&host); int *nmbArray = (int *)malloc(sizeof(nmbArray) * host); for (int i = 0; i < host; i++){ printf("Give the %d number:", i); scanf("%d", (&(nmbArray[i]))); } myFields->hostNumber = host; myFields->numberArray = &nmbArray[0]; } return myFields; } When I run it I get the followng: process = 2, tmpNumOfArray = 0 process = 0, tmpNumOfArray = 10 process = 1, tmpNumOfArray = 0 process = 3, tmpNumOfArray = 0 And what I what is: process = 2, tmpNumOfArray = 10 process = 0, tmpNumOfArray = 10 process = 1, tmpNumOfArray = 10 process = 3, tmpNumOfArray = 10 Any suggestion? Do not concentrate on gatherData() and start() functions since they run perfectly, the problem it at main() down to the MPI_Bcast() function. Also I tried with MPI_COMM_SPAWN but I think it can't broadcast from parent to children. Thanks in advance!!! A: MPI_Bcast Broadcasts a message from the process with rank "root" to all other processes of the communicator The MPI_Bcast broadcast routine is collective communication. Hence: Collective communication is a method of communication which involves participation of all processes in a communicator. The problem with your code is that only process with rank=0 is calling the MPI_Bcast; instead all the processes involved should also call that MPI routine. Fix you code by moving that call accordingly, namely: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "mpi.h" struct fields{ int hostNumber; int *numberArray; }; struct fields *start(int); struct fields *gatherData(int); int main(int argc, char** argv) { int rank, size, count, *tmpArray, tmpNumOfArray; struct fields *myFields; setbuf(stdout, NULL); MPI_Init(&argc, &argv); MPI_Status status; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); while(1){ if (rank == 0) { myFields = start(rank); if ((myFields->hostNumber) < size){ printf("Error!!! Number of Processes is more than number of Elements.\n"); MPI_Abort(MPI_COMM_WORLD, 0); } if ((myFields->hostNumber) < (2 * size)){ printf("Error!!! The Host of Numbers should be at least double of the number of Processes!!!\n"); MPI_Abort(MPI_COMM_WORLD, 0); } tmpNumOfArray = myFields->hostNumber; } MPI_Bcast(&tmpNumOfArray, 1, MPI_INT, 0, MPI_COMM_WORLD); // Move this part MPI_Barrier(MPI_COMM_WORLD); printf("process = %d, tmpNumOfArray = %d\n", rank, tmpNumOfArray); sleep(5); } MPI_Finalize(); return 0; } struct fields *start(int rank){ int input; struct fields *myFields; system("clear"); printf("1) Type 1 For Execution\n"); printf("2) Type 2 For Exit\n"); printf("Give your choice:"); scanf("%d",&input); switch(input){ case 1: myFields = gatherData(rank); break; case 2: default: MPI_Abort(MPI_COMM_WORLD, 0); } return myFields; } struct fields *gatherData(int rank){ int host; struct fields *myFields; myFields = (struct fields *)malloc(sizeof(struct fields)); if (myFields == NULL){ printf("Cannot allocate memory for myFields struct!\n"); MPI_Abort(MPI_COMM_WORLD, 0); } if (rank == 0){ printf("Give the host of the numbers to be statically checked: "); scanf("%d",&host); int *nmbArray = (int *)malloc(sizeof(nmbArray) * host); for (int i = 0; i < host; i++){ printf("Give the %d number:", i); scanf("%d", (&(nmbArray[i]))); } myFields->hostNumber = host; myFields->numberArray = &nmbArray[0]; } return myFields; }
doc_23529244
The default in rails is to use IDs as index, foreign key, and URL paths. These IDs increment linearly. What is the easiest way to generate pseudo-random integers as IDs for all tables, going forward? Is there a gem I can just toss in? Note: Rails sometimes has issues with non-integer values, so I would like to stick to integers. A: It's not so much to do with rails as it is that the convention with databases is to use auto increment primary keys. For new tables, to prevent rails from using this convention you need to tell it not to automatically create the id column, and instead create it yourself. # example of creating a users table create_table :users, id: false do |t| t.integer :id # other column definitions end add_index :users, [:id], unique: true, name: 'index_id_on_users' Then in your model you will need to set this explicitly before creating the record. class User < ActiveRecord::Base before_create :set_id def set_id loop do self.id = rand(1<<32) break unless User.exists?(self.id) end end end The loop is just making sure you get a unique key, otherwise the db constraints will raise an error. There is still a race condition, but if your worried about collisions that much than use something like UUID or SHA. As for having issues with non integer keys, I've never encountered any issues myself and have used both UUID and SHA keys, as well as using primary keys that were not the id column, that simply requires a little more configuration. As for your current models, you will have to remove the auto increment from all of your ids, otherwise i'm pretty sure the database will ignore anything you tell it. This apparently can be done by simply issuing a column change migration on id. change_column :users, :id, :integer The caveat here is that your db/schema.rb will not reflect the change, making db:schema:load not generate the right database, though i can say I have never used that rake task to load a database anyway. Just use db:migrate and all should be fine. And as always, make sure you backup your DB before running a command like this. I just ran it on sqlite3 in my dev environment and it seems to have worked ok. Update #1 An alternate route if all you are concerned with is the URLs is to use a slug instead of the ID. There are some gems out there that will handle this with a little bit of configuration and some new columns. Basically the idea is to have a column used as the url param. So when you use URL helpers instead of outputting /resources/1 it will output /resources/some-url-friendly-slug. This can be something cryptic like a UUID or SHA, or it can be something that is SEO friendly. It depends on if there's something in the model that can be slugged. For example if it was a product_path and the product had a title then the slug could be a url friendly version of the product title, great for SEO.
doc_23529245
http:// web site url / ... / page.aspx? {query string} # {ListId} / {ItemId} When a user request a data from the server, the request on the server doesn't contain hash # (because this is a client-side feature). And it looks like this: http:// web site url / ... / page.aspx? {query string} So, actually I need two requests: * *to get a page without hash and load javascript; *to handle hash data using javascript and async call required data from the server. Is it possible to implement this logic with only one request? Are there any best practices? A: You can append ListId/ItemId to query string before sending request and read it regularly on a server. var url = 'http://example.com?param1=10&param2=20#1000'; var beforeHash = url.split('#')[0]; var itemId= url.split('#')[1]; var processedUrl = beforeHash + '&itemId=' + itemId; If your request is not already fired from JavaScript, you will have to hook into link's click event... Or maybe you can get rid of # entirely and scroll content via JavaScript (my guess is that you use # because of local anchors to jump to different places in document)? BTW There is window.location.hash property. Update: Based on your comment the flow is like this: * *User types URL with #ItemId *Server returns the page *JavaScript reads #ItemId from window.location, puts it into QueryString and makes a request *Server returns the page based on modified QueryString In this situation the two-requests pattern seems to be the only viable option. By design server does not get #Item part (called fragment). So there is no way to guess ItemId upon initial request. If after second (ajax) request, you refresh #ItemId dependant parts of the page through JavaScirpt, user experience will not be hindered much.
doc_23529246
What I am trying to do is upload an app from a friends account to avoid paying the developer fee. He added me as admin, and I can publish as him but using my email. In Android this is simple to do, I can simply use a private certificate and sign the apk, this way no one but me can release updates. Is there a similar method for iOS apps for the Apple App Store? A: If I have understood your question and explanation, I think the answer is no. If you haven't got a signing certification you can not Upload to the AppStore, right? There are 'other' tools to sign applications in order to make them work outside the AppStore, but I can not help with that. What you are doing now is like be the owner of the development account, you have Admin privileges so you can control all the account, but the account can not be split in parts, it will work like one account only. There is no way to differentiate between your apps and your friend apps in the AppStore.
doc_23529247
Let's consider following code below: public interface IWatchService<TEntity> where TEntity : IEntity { IList<TEntity> MatchingEntries { get; set; } } public interface IWatchServiceDatabase<TEntity> : IWatchService<TEntity> where TEntity : IDatabaseEntity { } public interface IWatchServiceFiles<TEntity> : IWatchService<TEntity> where TEntity : IFileEntity { } class Database : IWatchServiceDatabase<DatabaseQuery> { public IList<DatabaseQuery> MatchingEntries { get; set; } } class Files : IWatchServiceFiles<CsvFile> { public IList<CsvFile> MatchingEntries { get; set; } } class Consumer { public IWatchService<IEntity> WatchService { get; set; } public Consumer(IWatchService<IEntity> watchService) { WatchService = watchService; var newList = WatchService.MatchingEntries; } public void AddNewEntries(IEntity entity) => WatchService.MatchingEntries.Add(entity); } class Program { static void Main(string[] args) { IWatchServiceDatabase<DatabaseQuery> db = new Database(); IWatchServiceFiles<CsvFile> filesCsv = new Files(); var dbConsumer = new Consumer(db); //cannot convert from 'IWatchServiceDatabase<DatabaseQuery>' to 'IWatchService<IEntity>' var filesCsvConsumer = new Consumer(filesCsv); //cannot convert from 'IWatchServiceFiles<CsvFile>' to 'IWatchService<IEntity>' dbConsumer.AddNewEntries(new DatabaseQuery()); dbConsumer.AddNewEntries(new CsvFile()); //illegal cause it's not FileConsumer !!! filesCsvConsumer.AddNewEntries(new CsvFile()); filesCsvConsumer.AddNewEntries(new DatabaseQuery()); //illegal cause it's not DbConsumer !!! } } public interface IEntity { } public interface IFileEntity : IEntity { int Id { get; set; } string Name { get; set; } } public interface IDatabaseEntity : IEntity { } public class CsvFile : IFileEntity { public int Id { get; set; } public string Name { get; set; } } public class XmlFile : IFileEntity { public int Id { get; set; } public string Name { get; set; } } public class DatabaseQuery : IDatabaseEntity { } We have two errors there: var dbConsumer = new Consumer(db); var filesCsvConsumer = new Consumer(filesCsv); Errors: cannot convert from 'IWatchServiceDatabase' to 'IWatchService' cannot convert from 'IWatchServiceFiles' to 'IWatchService' This seems to be understandable because otherwise "we would be able" to add CsvFile or XmlFile to dbConsumer where generic IDatabaseEntity is expected and CsvFile and XmlFile are in fact IFileEntity and from the other hand DatabaseQuery to filesConsumer which expects IFileEntity and DatabaseQuery is IDatabaseEntity //Database related dbConsumer.AddNewEntries(new DatabaseQuery()); dbConsumer.AddNewEntries(new CsvFile()); //illegal cause it's not FileConsumer !!! //Files related filesCsvConsumer.AddNewEntries(new CsvFile()); filesCsvConsumer.AddNewEntries(new DatabaseQuery()); //illegal cause it's not DbConsumer !!! From my understanding this is the clue why compiler raise those errors and which is fine. Therefore I've decided to overcome it in this way: public interface IWatchService<out TEntity> where TEntity : IEntity { IEnumerable<TEntity> MatchingEntries { get; } } As can be seen i marked generic parameter out and changed IList to IEnumerable because IEnumerable can be only foreached. Without possibility to modify the list. Now having this there is no possibility to modify MatchingEntries e.g Add() on therefore we are now not able to add e.g CsvFile (IFileEntity) where IDatabaseEntity is expected and vice versa DatabaseQuery (IDatabaseEntity) where IFileEntity is expected. Fine and understandably. At the end i have two main questions: What is the benefit to have this: IEnumerable MatchingEntries { get; } since it's {get;} it cannot be initialized or populated with values therefore i would always get empty list when calling that property. Or i am in wrong? Can somebody explain showing based on my code what can be done with it? Let's imagine i want to have possibility to Add items to this MatchingEntries list and in Consumer class i want still to be able to pass in ctor either Database or Files related classes based on interfaces. How this can be accomplished? Please also show an example based on current code. Many thanks for your support and hope someone benefit from it as i saw a lot of confusions related to that topic. A: First question: What is the benefit to have this: IEnumerable<T> MatchingEntries { get; } since it's {get;} it cannot be initialized or populated with values therefore I would always get empty list when calling that property. Or I am in wrong? Can somebody explain showing based on my code what can be done with it? I am confused by the question. The interface says that a class that implements that interface must have a getter of this name and type. It says nothing at all about the contents of that sequence: interface IFoo<out T> { IEnumerable<T> Bar { get; } } Now we can implement that interface however we want: class TigerFoo : IFoo<Tiger> { public IEnumerable<Tiger> Bar { get { return new List<Tiger>() { new Tiger("Tony"), new Tiger("Terry") }; } } } So why you think the returned sequence must be empty, I do not understand. Similarly, nothing is stopping you from making a class that implements a setter: class GiraffeFoo : IFoo<Giraffe> { public IEnumerable<Giraffe> Bar { get; set; } } … GiraffeFoo gf = new GiraffeFoo(); List<Giraffe> giraffes = new List<Giraffe>() { new Giraffe("Gerry") }; gf.Bar = giraffes; Nothing stops you from changing the contents of the list: class TurtleFoo : IFoo<Turtle> { private List<Turtle> turtles = new List<Turtle>(); public IEnumerable<Turtle> Bar => turtles; public void AddATurtle() => turtles.Add(new Turtle("Tommy")); } It is a mystery to me why you think you cannot do any of these things. You want to add a member to the collection? Write a method that adds a member to the collection. You just can't put it in the interface if you wan the interface to be covariant. But the interface tells you what services you must provide, not what services you must not provide! I do not understand why you think that an interface tells you what a class cannot do. Since T is marked as out, you can now use any of these covariantly: IFoo<Animal> ia1 = new TigerFoo(); IFoo<Animal> ia2 = new GiraffeFoo(); IFoo<Animal> ia3 = new TurtleFoo(); Of course you don't get to use the methods of the class once it is in an interface, but you never get to use the methods of a class once something is in an interface. Second question: Let's imagine I want to have possibility to Add items to this MatchingEntries list and in Consumer class i want still to be able to pass in ctor either Database or Files related classes based on interfaces. How this can be accomplished? Please also show an example based on current code. Just write code that does that. I don't understand what the question is asking. Please clarify the question.
doc_23529248
Thanks in advance A: Be sure that is php who stores session data. In your core.php: Configure::write('Session.save', 'php'); If you let 'cake' to store session data external php files will not retrieve it. Also, remember to set the right name for session: session_name("CAKEPHP"); A: start the session with session_start(); and maybe need to match cookie domain with ini_set('session.cookie_domain', 'example.net'); A: it pretty simple and easy. open app\webroot\js\ckfinder\config.php. put the following codes there session_name("CAKEPHP"); session_start(); Assuming in your config.php Configure::write('Session.cookie', 'CAKEPHP'); I have written extensive tutorial for ckfinder and ckeditor. You can see here http://blog.jambura.com/2011/01/29/implementing-ckfinder-in-cakephp-1-3-with-authentication/
doc_23529249
TextBox has the method KeyDown, and I think I should use this, but I don't understand how to understand when a user presses first CTRL, then presses one random digit (still with pressed CTRL). Thank you in advance. A: Try this in KeyDown or KeyUp or anywhere if (Control.ModifierKeys.HasFlag(Keys.Control)) { //user is holding control } A: On the KeyDown Method (or KeyUp or any other one dealing with KeyEventArgs) you can write: private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == Keys.E && e.Modifiers == Keys.Control) { //Both CTRL + E were pressed } }
doc_23529250
void fillDeck(Card *deck); void printDeck(Card deck[]); void printDeck(Card p1[]); void printDeck(Card p2[]); void shuffleDeck(Card *deck); int main (int argc, char *argv[]){ Card deck[52]; Card p1[26]; Card p2[26]; fillDeck(deck); shuffleDeck(deck); printDeck(deck); //this is where the problem is happening printDeck(p1); //and here printDeck(p2); //and here } the error I get is "undefined reference to `printDeck(Card*)'" for all three of those printDeck function calls. I feel like I am just making a stupid mistake and really cant see it, but everything looks just fine to me? I've looked up syntax for passing arrays to functions and I thought I was doing it properly but perhaps not. If needed, here is the actual function: void printDeck(Card deck[], Card p1[], Card p2[]){ for(int i = 0; i < 52; i++){ printf("%d of %s",deck[i].number,deck[i].suit); printf("\n\n"); //printf("%s", deck[i].suit); //printf("\n%d\n\n", deck[i].number); } printf("\n\nP1's cards\n"); for(int i = 0; i < 52; i++){ printf("%d of %s", p1[i].number, p1[i].suit); } printf("\n\nP2's cards\n"); for(int i = 0; i < 52; i++){ printf("%d of %s", p2[i].number, p2[i].suit); } } Any help is appreciated thanks! A: These three lines: void printDeck(Card deck[]); void printDeck(Card p1[]); void printDeck(Card p2[]); declare the same function. They are equivalent to saying: void printDeck(Card []); void printDeck(Card []); void printDeck(Card []); If you want to print all the decks in one function call, you need to change the function declaration to: void printDeck(Card [], Card [], Card []); and the change the calling lines from: printDeck(deck); printDeck(p1); printDeck(p2); to printDeck(deck, p1, p2); A: You've defined your print deck function as: void printDeck(Card deck[]); void printDeck(Card p1[]); void printDeck(Card p2[]); and yet you implemented it as: void printDeck(Card deck[], Card p1[], Card p2[]){...} You really meant to define it as: void printDeck(Card deck[], Card p1[], Card p2[]); and call it as printDeck(deck, p1, p2); Otherwise the declaration does not match the definition. Besides, three declarations of the same function will cause the compiler to attempt to generate overloads, but it will fail because all three functions have the same signature.
doc_23529251
* *Created directory phantoms *cd phantoms and installed phantom module using command npm install phantom --save *Created file createlist.js: createlist.js contents: var phantom = require('phantom'); var page = require('webpage'); page.open('http://facebook.com', function(status) { console.log("Status: " + status); if(status === "success") { page.render('example.png'); } phantom.exit(); }); When i execute command node create_list.js, I am getting the following error: page.open('interact2.responsys.net/interact/jsp/jindex.jsp&#‌​39;, function(st atus) { ^ TypeError: page.open is not a function at Object.<anonymous> (C:\Users\shilshet\New folder\phantom\create_list.js:3 :6) at Module._compile (module.js:413:34) If I try to execute command like phantomjs C:/Users/shilshet/New folder/phantom/create_list.js I am getting this error bash: phantomjs: command not found Note: I am using cygwin to execute commands What I am going wrong? I installed phantomjs module also in the same folder as my node.js. Could anyone let me know apart from using headless browser, how does one create a profile list in Oracle responsys via REST API call? A: While the first answer here should work, it's not the best way to accomplish what you need. The cleaner way to solve your issue is to add the location of your phantomjs executable to your PATH variable defined in a file such as ~/.bash_history. The file may not be defined, so you may need to create the file, and then add PATH="/path/to/phantomjs/executable" If you prefer to edit your PATH var via a GUI: Edit PATH variable via Windows GUI The reason you need to do this, is that your system natively iterates over paths defined in the 'PATH' variable in order to determine where executable files are. Since phantomjs is not included in the PATH variable (nonexistent in the environment), and you try to run 'phantomjs', your system simply does not know which executable to call (or rather it doesn't know it exists) The reason this is the better approach is: * *You don't need to explicitly write out the path of where phantomjs is located every time you want to run it (it's just cleaner looking too) *What happens if you you call phantomjs from multiple files, and the location of where phantomjs is stored changes? If you explicitly typed phantomjs' absolute path everywhere, then you need to change EVERY place you typed it! Nightmare! With this approach, you simply change it in one place; the file that defines your PATH variable *It's pretty conventional to add new file paths to your PATH env variable. You shouldn't clutter it, but it makes sense in this case to add it For this: "Could anyone let me know apart from using headless browser, how does one create a profile list in Oracle responsys via REST API call?"... I would recommend asking a separate question. I personally don't know, but if you raise the new question, you may get support from someone who does. Hope this helps! If you need any help whatsoever, let me know. A: You mixed up two ways of running PhantomJS. The more straightforward, more simple way is just launching PhantomJS from command line and giving it the path of a script as an argument. On Windows you would do it like this: "C:/Users/shilshet/New folder/phantom/phantomjs.exe" "C:/Users/shilshet/New folder/phantom/create_list.js" Note the quotes here, they're needed because there are spaces in filenames.
doc_23529252
Node node = new ExprNode(); changeNodeType(node); public void changeNodeType(Node node) { node = new AddOpNode(); } then eventually my Node type will end up with AddOpNode(). Is there any way that I could eventually implement this in Java? A: You could just return the new node type and assign it outside of the function. Node node = new ExprNode(); node = changeNodeType(); public Node changeNodeType() { return new AddOpNode(); }
doc_23529253
I have a tester project (standard Window) added to the solution to test the control. Issue: When I add the control for the first time - the look of the control looks correct. However when I do some changes on the control and rebuild it - the control disappear from the window and I have to Unload the Window project and Reload it again to make the control's look reappear again. When I run debugger the control does appear correctly - it is just in design mode that it becomes difficult to work with. Is there a solution / workaround for this occurrence that does not involve unloading and reloading the window on each rebuild? EDIT I have run a test where I copied all the info from separate resource dictionaries into the Generic.Xaml and commented out the Merge Dictionary. It seems the issue does not lie with MergeDictionary operations as the problem is still there - but perhaps with ComponentResourceKey / or static properties. One of my ResourceDictionaries for instance contain a lot of the following <SolidColorBrush x:Key="{x:Static keys:Disabled.ForeGroundKey}" Color="Gray"/> Where ForeGroundKey is linked to a static class with for example: public static class Normal { static ComponentResourceKey _background = new ComponentResourceKey(typeof(G2ListBox),"ContainerBackground"); public static ComponentResourceKey BackGroundKey { get { return _background; } } } I guess seeing that the theme work sometimes mean that there is nothing wrong with the above approach and there is something wrong with how VS handles the rebuild of the control. What I do not understand though is why doesn't VS recognize either the old values / new values, instead it ignores all values linked to ComponentResourceKey - Ps. during runtime the control works perfectly. A: Well it seems like I have 3 options here. * *Use the method I have been using all along: * *Define ComponentResourceKey in C# Class public static class Normal { static ComponentResourceKey _background = new ComponentResourceKey(typeof(G2ListBox), "Normal.Background"); public static ComponentResourceKey BackGroundKey { get { return _background; } } } *Assign Key in Resource Dictionary <SolidColorBrush x:Key="{x:Static keys:Normal.BackGroundKey}" Color="Yellow"/> *Use Key in Resource Dictionary: <Setter Property="BorderBrush" Value="{DynamicResource {x:Static keys:Normal.BorderBrushKey}}"/> The advantage is that when you have multiple themes to assign and use the resource key seems simplistic and chances of errors occurring in typing over the name is reduced as you have the help of intelisence. The disadvantage is that when you are working on a large project, and you make a small adjustment to your control - none of the ComponentResourceKeys are loaded and your project looks completely lookless at design time. To fix this issue, one either has to reboot VS or unload the project that uses your control and reload it again. Ps this is only at design time. Running the project will give the correct result. This is a silly problem to have in VS!! *return to the more verbose method of defining Component resource keys in XAML i.e. * *Define and Assign the resourceKey. <SolidColorBrush x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:G2ListBox}, ResourceId=Normal.Background}" Color="Yellow"/> *Use the resourceKey: <Setter Property="BorderBrush" Value="{DynamicResource {ComponentResourceKey TypeInTargetAssembly={x:Type local:G2ListBox}, ResourceId=Normal.Background}}"/> The Advantage is VS is now working everytime in design time. Also you do not have to create a separate C# class to hold all your resourcekeys The Disadvantage is that you have to remember the ResourceId names for each resourceId and type it out as it was defined. Also using this in a control with multiple themes becomes frustrating. *Use a mixture of the 2 above i.e. * *You still Define the ResourceKey in C# library *You Assing the ResourceKey as per method 2. But the ResourceId is the "text" field assigned in the C# class and not the x:static method i.e. public static class Normal { static ComponentResourceKey _background = new ComponentResourceKey(typeof(G2ListBox), "Normal.Background"); public static ComponentResourceKey BackGroundKey { get { return _background; } } } //To assign <SolidColorBrush x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:G2ListBox}, ResourceId=Normal.Background}" Color="Yellow"/> //Thus Normal.Background and not Keys:Normal.Background!! where keys = referenced to the C# Class *Then to use <Setter Property="Background" Value="{DynamicResource {x:Static keys:Normal.BackGroundKey}}"/> //i.e we now can reference the C# class and have intelisence The advantage is that 1 you have a static class that hold all the ResourceKeys in C# (goes slightly against lookless philosophy). you also have access to proper intelisence at least in the using side. But best of all VS works perfectly in design time. This however does not shorten the assign side at all and the disadvantages therefore are still that you need to type out verbose text to assign a color to the resourcekey. Having multiple themes each with its own set of colors means that you have only shorten the Style of the control a bit and seems silly to use this method Thus if you want the best solution and do not care about the design time look I'd prefer option1. If you prefer design time visuals then I'd go for method 2 unless you have to define the style at a number of places too, then option 3 will suffice. Alternatively create a designtime ResouceDictionary and a compile time ResourceDictionary. Where at designtime method 3 is used and compile time method 2 -> Not sure how to do this automatically. I am doing this by use of Merged Dictionaries, and uncommenting the proper dictionary when Control is ready to be compiled, and deleting the designtime ResourceDictionary. Hope this helps someone, some day as I had to spend the whole day trouble shooting this (I thought there was something wrong with my control - turns out there is something wrong with VS).
doc_23529254
$(DEPENDDIR)%.d: %.cpp @mkdir -p $(DEPENDDIR) $(CXX) -M -MG -MT $(OBJECTDIR)$*.o $(CXXFLAGS) $< > $@ Can anyone see what is the problem? I tried moving the dependencies to the part where the objects are compiled, ie: $(OBJECTDIR)%.o: %.cpp @mkdir -p $(OBJECTDIR) # $(dir $@) @echo " " $(CXX) -M -MG -MT $@ $(CXXFLAGS) $< \ -MF $(patsubst $(OBJECTDIR)%.o, $(DEPENDDIR)%.d, $@) but then the header file version.hpp wasn't created (and compilation failed) KERNEL := $(shell uname -s) PROGNAME=nextsim.exec CXX = g++ # setting the C++ standard according to the gcc compiler version (from gcc-5.2, the default is C++14) ifeq ($(shell echo `$(CXX) -dumpversion | cut -f1-2 -d.` \>= 5.2 | sed -e 's/\.//g' | bc),1) CXXFLAGS += -std=c++14 else CXXFLAGS += -std=c++11 endif # add g++ option flags CXXFLAGS += -ftemplate-depth-256 -Wno-inline \ -fPIC -fopenmp \ -DHAVE_CONFIG_H -D_MULTITHREADING_ ifdef NEXTSIM_COMPILE_VERBOSE CXXFLAGS += -v endif ifdef USE_OASIS CXXFLAGS += -DOASIS CXXFLAGS += -I $(NEXTSIMDIR)/modules/oasis/include LDFLAGS += -lgfortran LDFLAGS += -L $(NEXTSIMDIR)/lib -loasis CHAN = MPI1 #LIBPSMILE = $(OASIS_DIR)/lib/libpsmile.${CHAN}.a $(OASIS_DIR)/lib/libmct.a $(OASIS_DIR)/lib/libmpeu.a $(OASIS_DIR)/lib/libscrip.a endif ifneq (,$(strip $(filter DEBUG Debug debug PROFILE Profile profile,$(NEXTSIM_BUILD_TYPE)))) #ifeq ($(NEXTSIM_BUILD_TYPE),$(filter $(NEXTSIM_BUILD_TYPE),Debug debug)) CXXFLAGS := $(filter-out -O3 -pthread,$(CXXFLAGS)) CXXFLAGS += -g -O0 -DNDEBUG ifneq (,$(strip $(filter PROFILE Profile profile,$(NEXTSIM_BUILD_TYPE)))) CXXFLAGS += -DWITHGPERFTOOLS endif ifneq ($(KERNEL),Linux) CXXFLAGS += -Wl,-no_pie endif else CXXFLAGS += -O3 -pthread endif # add include paths CXXFLAGS += -I $(NEXTSIMDIR)/core/include CXXFLAGS += -isystem $(NEXTSIMDIR)/contrib/bamg/include # suppress annoying compilation warnings from -I CXXFLAGS += -isystem $(NEXTSIMDIR)/contrib/mapx/include # suppress annoying compilation warnings from -I # CXXFLAGS += -I $(NEXTSIMDIR)/contrib/interp/include ifdef USE_ENSEMBLE CXXFLAGS += -DENSEMBLE CXXFLAGS += -I $(NEXTSIMDIR)/modules/enkf/perturbation/include endif ifdef USE_AEROBULK CXXFLAGS += -I $(AEROBULK_DIR)/include CXXFLAGS += -DAEROBULK endif # openmpi CXXFLAGS += -I $(OPENMPI_INCLUDE_DIR)/ # petsc CXXFLAGS += -I $(PETSC_DIR)/include # boost CXXFLAGS += -I $(BOOST_INCDIR)/ -I . # netcdf CXXFLAGS += -I $(NETCDF_DIR)/include # gmsh CXXFLAGS += -I $(GMSH_DIR)/include/gmsh CXXFLAGS += -I /opt/local/include ifeq ($(KERNEL),Linux) #CXXFLAGS += -std=c++0x -std=c++11 -pedantic -ftemplate-depth-256 -Wno-inline -fPIC -g -lm -pthread -v #-MMD -MP -lm -pthread -v else ifeq ($(CXX),clang) CXXFLAGS += -stdlib=libc++ endif CXXFLAGS += -I /usr/local/include #-I /opt/local/include/openmpi-mp #LDFLAGS += -Wl,-rpath,/usr/local/lib #-Wl,-rpath,/opt/local/lib/openmpi-mp #LDFLAGS += -L /usr/local/lib #-L /opt/local/lib/openmpi-mp -lmpi_cxx -lmpi -ldl -lstdc++ -lpthread ifeq ($(CXX),clang) LDFLAGS += -stdlib=libc++ endif endif LDFLAGS += -L /usr/local/lib LDFLAGS += -Wl,-rpath,$(OPENMPI_LIB_DIR)/ ifndef MACHINE_HEXAGON LDFLAGS += -L $(OPENMPI_LIB_DIR)/ -lmpi_cxx -lmpi -ldl -lstdc++ #-lpthread else LDFLAGS += -L $(OPENMPI_LIB_DIR)/ -lmpichcxx -lmpich -ldl -lstdc++ #-lpthread #-lssl -luuid -lpthread -lrt LDFLAGS += -Wl,-rpath,$(BLAS_LAPACK_DIR)/lib LDFLAGS += -L $(BLAS_LAPACK_DIR)/lib -lsci_gnu_mp endif LDFLAGS += -Wl,-rpath,$(NETCDF_DIR)/lib -L $(NETCDF_DIR)/lib -lnetcdf_c++4 LDFLAGS += -Wl,-rpath,$(BOOST_LIBDIR) LDFLAGS += -L $(BOOST_LIBDIR) -lboost_program_options -lboost_filesystem -lboost_system -lboost_serialization -lboost_mpi -lboost_date_time LDFLAGS += -Wl,-rpath,$(PETSC_DIR)/lib LDFLAGS += -L $(PETSC_DIR)/lib -lpetsc LDFLAGS += -Wl,-rpath,$(NEXTSIMDIR)/lib LDFLAGS += -L $(NEXTSIMDIR)/lib -lbamg #LDFLAGS += -L $(NEXTSIMDIR)/lib -linterp LDFLAGS += -L $(NEXTSIMDIR)/lib -lmapx #LDFLAGS += -L $(NEXTSIMDIR)/lib -loasis ifdef USE_ENSEMBLE LDFLAGS += -L $(NEXTSIMDIR)/lib -lpseudo2D LDFLAGS += -lgfortran endif ifdef USE_AEROBULK LDFLAGS += -L $(AEROBULK_DIR)/lib -laerobulk_cxx -laerobulk LDFLAGS += -lgfortran endif ifneq (,$(strip $(filter DEBUG Debug debug PROFILE Profile profile,$(NEXTSIM_BUILD_TYPE)))) #ifeq ($(NEXTSIM_BUILD_TYPE),$(filter $(NEXTSIM_BUILD_TYPE),Debug debug)) LDFLAGS += -Wl,-rpath,/opt/local/lib ifneq (,$(strip $(filter PROFILE Profile profile,$(NEXTSIM_BUILD_TYPE)))) LDFLAGS += -L /opt/local/lib -lprofiler endif endif LDFLAGS += -L $(NEXTSIMDIR)/lib -lnextsim OBJECTDIR=$(NEXTSIMDIR)/objs/ DEPENDDIR=$(NEXTSIMDIR)/.deps/ BINARYDIR=bin/ # C++ files CXXSRCDIR=. CXXHDRDIR=. CXXSRC=$(wildcard $(CXXSRCDIR)/*.cpp) # We must exclude the version.hpp file from the list of header files because otherwise we get a circular dependency CXXHDR=$(filter-out $(CXXHDRDIR)/version.hpp, $(wildcard $(CXXHDRDIR)/*.hpp)) OBJS=$(CXXSRC:%.cpp=$(OBJECTDIR)%.o) DEPS=$(CXXSRC:%.cpp=$(DEPENDDIR)%.d) # Rules to always execute. .PHONY: exec clean mrproper all cleanall mrproperall # Default action. exec: $(PROGNAME) # Create a header file with the git version version.hpp: version.sh $(CXXSRC) $(CXXHDR) $(SHELL) -x $< # Delete the object files. clean: @echo " " $(RM) $(OBJS) $(DEPS) @echo " " mrproper: clean $(RM) $(BINARYDIR)$(PROGNAME) @echo " " # Rule for making the actual target lines="==========" Lines=$(lines)$(lines)$(lines)$(lines)$(lines)$(lines)$(lines)$(lines) $(PROGNAME): $(OBJS) #$(CCOBJS) @mkdir -p $(BINARYDIR) @echo " " @echo $(Lines)$(Lines) @echo "Creating executable: $(BINARYDIR)$(PROGNAME)" @echo $(Lines)$(Lines) @echo " " $(CXX) $(CXXFLAGS) -o $(BINARYDIR)$@ $^ $(LDFLAGS) @echo " " @echo $(Lines)$(Lines) @echo "Created executable: $(BINARYDIR)$(PROGNAME)" @echo $(Lines)$(Lines) @echo " " # Rules for object files from cpp files $(OBJECTDIR)%.o: %.cpp @mkdir -p $(OBJECTDIR) # $(dir $@) @echo " " $(CXX) -o $@ -c $< $(CXXFLAGS) # Make dependancy rules $(DEPENDDIR)%.d: %.cpp @mkdir -p $(DEPENDDIR) $(CXX) -M -MG -MT $(OBJECTDIR)$*.o $(CXXFLAGS) $< > $@ # The compilation depends on this Makefile. $(OBJS): Makefile # Make everything all: cd ..; $(MAKE) all # Clean everything cleanall: cd ..; $(MAKE) clean # Properly clean everything mrproperall: cd ..; $(MAKE) mrproper # Properly clean & recompile fresh: cd ..; $(MAKE) fresh -include $(DEPS) A: It's being built because you're using -include $(DEPS). See Including Other Makefiles If an included makefile cannot be found in any of these directories, a warning message is generated, but it is not an immediately fatal error; processing of the makefile containing the include continues. Once it has finished reading makefiles, make will try to remake any that are out of date or don’t exist. See How Makefiles Are Remade. Only after it has tried to find a way to remake a makefile and failed, will make diagnose the missing makefile as a fatal error. It then goes on to say: If you want make to simply ignore a makefile which does not exist or cannot be remade, with no error message, use the -include directive instead of include, like this: -include filenames… This acts like include in every way except that there is no error (not even a warning) if any of the filenames (or any prerequisites of any of the filenames) do not exist or cannot be remade. Admittedly, this is can likely be interpreted in different ways. I just verified that it does indeed try to remake files on a -include line that have an explicit rule to be remade: all: @echo building $@ foo.d : @echo building $@ @touch $@ -include foo.d bar.d Which gives: tmp> make all building foo.d building all So, this leave an interesting case of how to solve your issue. Having a separate rule for the dependency files does increase your compile time -- you're now parsing each source file twice -- once to generate the .d and once to compile. This is not good. I believe that combining the rule for dependency and .o is in your best interest. Then make the subset of $(OBJS) that rely on version.hpp explicitly dependent on it, and you should be good. A: You ought to make the -include $(DEPS) line conditional - exclude it from the makefile when MAKECMDGOALS contains only the "clean" targets: ifneq(,$(filter-out clean distclean clobber,$(MAKECMDGOALS))) -include $(DEPS) endif As an aside, beware of assuming that cd will succeed - use && after it - or, if invoking Make in a different directory, just use its -C option.
doc_23529255
dyld: Library not loaded: /System/Library/Frameworks/OpenCL.framework/Versions/A/Libraries/libclparser.dylib Referenced from: /usr/local/bin/convert Reason: image not found Trace/BPT trap: 5 Any idea how I could fix it ? A: I got the same error and what solved the problem for me was: * *Install the latest XCode version from the Mac Appstore *Install ImageMagick using Macports (sudo port install imagemagick) Both steps took a while, but in the end ImageMagick worked fine again. A: I installed xcode but had some issue with macports. Bummer! I copied the libclparser.dylib file over from an old backup of 10.6, changed the permissions to match the other files in that folder and it worked! Also see here: https://stackoverflow.com/questions/6674666/installing-imagemagick-leads-to-weird-error-involving-opencl Edit: I found this, which may be useful: http://cactuslab.com/imagemagick/ Also, the file is here: http://www.workdreamer.com/uploads/libclparser.dylib A: I was getting this error as well–with a homebrew install of ImageMagick. Along the same lines as Pascal, I fixed it with * *Install XCode 4.1 (from the App Store) *In Xcode, go to Xcode > Preferences... > Downloads tab > click Install next to Command Line Tools *Uninstall ImageMagick with brew uninstall imagemagick *Update homebrew with brew update *Install latest homebrew with brew install imagemagick *Run brew doctor and delete any of the *.la and *.a files listed if step 4 fails on make install A: Reinstalling it even with brew instead of macports didn't work for me. Copying it did. A: Try the following command: brew doctor to diagnose the common problems. One of it could be removing DYLD_FALLBACK_LIBRARY_PATH variable from your ~/.profile Or you have to re-install libtool by: brew reinstall libtool --universal && brew unlink libtool && brew link libtool
doc_23529256
How could i find the second lowest value? 'select Date, Horse, ParentID, min(odds2) from horsesrp where odds2 < 3.1 and odds2 > 1.9 and Date = "'.$id.'" AND Track IN ("Kempton (AW)","Wolverhampton (AW)") group by ParentID order by ParentID' please note i still need to order by ParentID as i want to get the second lowest odds2 per parentid so my database look like: Racetime Odds 13:05 2 13:05 2.4 13:05 3 13:05 5 13:30 3 13:30 5 13:30 9 13:30 13.5 14:00 1.14 14:00 1.19 14:00 2 14:00 4 i want to find the second lowest value for each time but it must be between 1 and 2.9 Racetime Odds 13:05 2.4 14:00 1.19 so the output for the above would be Thanks Emma A: This is from example of another question, Product_id reg_price sale_price 244 50 40 244 45 40 244 45 0 244 40 0 To find the second lowest sale_price, SELECT MIN(NULLIF(sale_price, 0)) FROM `table` WHERE product_id = 244; EDIT 1 so in your case, SELECT MIN(NULLIF(odds2,0)) FROM horserp order by ParentID asc; this should order by ParentID as well... EDIT 2 - Second query Select TOP 1 odds2 as '2nd lowest' from (SELECT DISTINCT TOP 2 odds2 from horserp ORDER BY odds2 ASC) a ORDER BY odds2 DESC EDIT 3 - Further nesting of second query select * from (Select TOP 1 odds2 as '2nd lowest' from (SELECT DISTINCT TOP 2 odds2 from horserp ORDER BY odds2 ASC) a ORDER BY odds2 DESC) order by ParentID desc; A: You can get the second lowest value in several ways. If you are starting with this query: select Date, Horse, ParentID, min(odds2) from horsesrp where odds2 < 3.1 and odds2 > 1.9 and Date = "'.$id.'" AND Track IN ("Kempton (AW)","Wolverhampton (AW)") group by ParentID order by ParentID; Then the easiest way is to use the substring_index()/group_concat() trick: select Date, Horse, ParentID, min(odds2), substring_index(substring_index(group_concat(odds2) order by odds2, ',', 2), ',', -1) as second_odds from horsesrp where odds2 < 3.1 and odds2 > 1.9 and Date = "'.$id.'" AND Track IN ('Kempton (AW)', 'Wolverhampton (AW)') group by ParentID order by ParentID; I am a bit befuddled, though, on what this has to do with your sample data. There is no racetime in the query. A: SELECT * FROM table_name ORDER BY id ASC LIMIT 1, 1 A: Query Select TOP 1 Salary as '2nd Lowest Salary' from (SELECT DISTINCT TOP 2 Salary from Employee ORDER BY Salary ASC) a ORDER BY Salary DESC A: Try this SELECT ParentID, Horse, Date, min(odds2) FROM ( select DISTINCT HP.ParentID, HP.Horse, HP.Date, HP.odds2, SUB.min_odd from horsesrp HP INNER JOIN ( SELECT parentID,Date,Horse,min(odds2) min_odd FROM horsesrp GROUP BY parentID,parentID,Date,Horse ) SUB ON HP.ParentID = SUB.ParentID AND HP.Date = SUB.Date AND HP.Horse = SUB.Horse WHERE HP.odds2 < 3.1 and HP.odds2 > 1.9 and HP.Date = "'.$id.'" AND HP.Track IN ("Kempton (AW)","Wolverhampton (AW)") AND HP.odds2>SUB.min_odd ) SUB_END GROUP BY ParentID, Horse, Date ORDER BY ParentID the problem here is that since you're getting the second lowest, you will not see the min values if you have only 1 row for a specific parentID. The code may have errors, please let me know.
doc_23529257
create table DIM_DOMAIN unrecoverable as select * from localhost.DIM_DOMAIN; but keeps me saying that the table does not exist. If I connect as localhost the table is there. I am not sure what I am doing wrong Can you help me guys? Thanks A: You need to grant select privilege for DIM_DOMAIN table to your new user : SQL> conn localhost SQL> grant select on DIM_DOMAIN to <my_new_user>; SQL> conn <my_new_user> SQL> create table DIM_DOMAIN nologging as select * from localhost.DIM_DOMAIN; -- the table will be created successfully. P.s. unrecoverable option is deprecated, use nologging instead.
doc_23529258
It does barcodes scanning. The method sendJson should call the webService. The code runs, but in the Apache log I see NOTHING. For some reason the webService is not called. What am I doing wrong? package com.example.podk.scan; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHeader; import org.apache.http.params.HttpConnectionParams; import org.apache.http.protocol.HTTP; import org.json.JSONObject; import java.io.InputStream; public class MainActivity extends Activity implements View.OnClickListener { private View.OnClickListener onClickListener; private Button scanBtn; private TextView formatTxt, contentTxt; public void onActivityResult(int requestCode, int resultCode, Intent intent) { //retrieve scan result IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanningResult != null) { //we have a result String scanContent = scanningResult.getContents(); String scanFormat = scanningResult.getFormatName(); formatTxt.setText("FORMAT: " + scanFormat); contentTxt.setText("CONTENT: " + scanContent); //call web service: sendJson("toto","foo"); }else{ Toast toast = Toast.makeText(getApplicationContext(), "No scan data received!", Toast.LENGTH_SHORT); toast.show(); } } public void sendJson(final String email, final String pwd) { HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit HttpResponse response; JSONObject json = new JSONObject(); try { String WS_URL = "http://192.168.88.171:8080/test/test.php"; HttpPost post = new HttpPost(WS_URL); json.put("email", email); json.put("password", pwd); StringEntity se = new StringEntity( json.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); response = client.execute(post); /*Checking response */ if(response!=null){ InputStream in = response.getEntity().getContent(); //Get the data in the entity } } catch(Exception e) { e.printStackTrace(); } } public void onClick(View v){ //respond to clicks if(v.getId()==R.id.scann_button){ //scan IntentIntegrator scanIntegrator = new IntentIntegrator(this); scanIntegrator.initiateScan(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); scanBtn = (Button)findViewById(R.id.scann_button); formatTxt = (TextView)findViewById(R.id.scan_format); contentTxt = (TextView)findViewById(R.id.scan_content); //uaktywnij aktywnosc na przyciskanie scanBtn.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } A: Run adb logcat with your device connected and you'll probably see that your request is never getting sent because of a NetworkOnMainThread exception. You have to run network code in a Thread or preferably with an AsyncTask. Here's the exception documentation http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html Here's the AsyncTask documentation http://developer.android.com/reference/android/os/AsyncTask.html
doc_23529259
I have an app I'm working on with a sidebar with tabs that link to different dashboards. Each of the SidebarLinks are a router-link with the to key being fed the route prop from the main component. Inside one of these dashboards, the Analysis dashboard, there is another router that routes you to child routes for specific Analyses with their own ids (EX: /analysis/1). The user clicks on a button for a specific analysis and they are routed to a page containing that information, on the same page. The Error When I click the Analysis SidebarLink the route in the url changes back to /analysis, but the page doesn't update/refresh. I don't get an error in the console, but I do get the failure in the devtools. I understand that Vue Router doesn't route back to a route you are already on, but I need it to. If you refresh the page when the url is just /analysis it routes back to it's inital state. Is there anyway to refresh when it rereoutes to /analysis? Or a way to handle this error to work as intended? What I've tried * *I've tried changing the router-link to an <a> tag and programatically use router.push and then catch the error, but that doesn't do anything. *I've tried checking if the route.fullPath.contains("/analysis") and then just do router.back() but that doesn't seem to work either. SidebarLink router function function goToRoute() { console.log(`route.fullPath → `, route.fullPath) if (route.fullPath.match('/analysis*') as any) { console.log('route includes /analysis') router.back() } else { console.log('route doesnt inclue /analysis') router .push({ path: props.route, }) .catch(() => {}) } } Inital /analysis Page This is what the page looks like normally /analysis/1 Page This is what the route to analysis/1 looks like (url changes) /analysis/1 Page When Issue Analysis SidebarLink Clicked This is what the route to analysis looks like when the sidebarlink is clicked (url changes, but the page stays the same) A: I suspect you are fetching your data from a backend service or data files If yes you can refetch the data everytime the route param changed by watching it. watch: { '$route.params.id': function (id) { if(id) this.$store.dispatch('fetchOneAnalys', id) else this.$store.dispatch('fetchAllAnalyses') }
doc_23529260
<there was a screenshot here, I don't have the rep to post it though!> I have been keeping an eye on what this EDM is doing under the covers with the SQL Server Profiler as I've been working. When I run a simple Linq to Entities Query as below: var model = from p in Product.Products where p.archive == false && ((Prod_ID == 0) || (p.ID == Prod_ID)) select p; Which brings back all types of products that are not archived, and may potentially have an ID search in there as well, the sql profiler shows me an 800 line piece of SQL!! Is this normal? And is this performant? Or have I sent the Entity Framework crazy? <I tried to post the SQL too, but there was too much of it for the post> So please, just a sanity check and any advice! Regards, Mark A: The Entity Framework can kick out some very large queries, but generally the SQL Server query optimiser does its thing and the query executes with the server barely noticing. Beyond being generally sensible, sensible I personally tend not to worry about performance and optimisation until a performance analysis tells me I've got a bottleneck; if you're already using SQL profiler, does the query take a relatively long time to execute? Have you had a look at the execution plan and does it look ok?
doc_23529261
I have the ANSI Standard (X9.24) for DUKPT and have successfully implemented the ability to generate the IPEK from the KSN and BDK. Furthermore, I have successfully implemented the ability to generate the Left and Right MAC Request and Response Keys by XORing the PIN Encryption Keys. Lastly, I am able to generate the EPB. From here, I don't understand how to generate the MAC Request and Response from the L/R Keys that I have generated. Lastly, once I get to that step, what comes next? When do I actually have the key that decrypts the track data sent by a DUKPT enabled device? I am aware of the Thales Simulator and jPOS. My code is currently referencing the Thales Simulator to do all of its work. But, the file decryption process just isn't returning the expected data. If anybody can offer some insight into decrypting track data, it would be much appreciated. http://thalessim.codeplex.com/ http://jpos.org/ A: I spent too much time studying the horrible X9.24 spec and finally got both the encryption and decryption working with my vendor’s examples and marketing promptly decided to switch vendors. Since it is a standard, you would think that anybody’s implementation would be the same. I wish. Anyway, there are variations on how things are implemented. You have to study the fine print to make sure you are working things the same as your other side. But that is not your question. First if you need to decrypt a data track from a credit card, you are probably interested in producing a key that will decrypt the data based upon the original super secret Base Derivation Key. That has nothing to do with the MAC generation and is only mentioned in passing in that dreadful spec. You need to generate the IPEK for that key serial number and device ID and repeatedly apply the “Non-reversible Key Generation Process” from the spec if bits are set in the counter part of the full key serial number from the HSM. That part of my code looks like this: (Sorry for the long listing in a posting.) /* * Bit "zero" set (this is a 21 bit register)(ANSI counts from the left) * This will be used to test each bit of the encryption counter * to decide when to find another key. */ testBit=0x00100000; /* * We have to "encrypt" the IPEK repeatedly to find the current key * (See Section A.3). Each time we encrypt (generate a new key), * we need to use the all prior bits to the left of the current bit. * The Spec says we will have a maximum of ten bits set at any time * so we should not have to generate more than ten keys to find the * current encryption key. */ cumBits=0; /* * For each of the 21 possible key bits, * if it is set, we need to OR that bit into the cumulative bit * variable and set that as the KSN count and "encrypt" again. * The encryption we are using the goofy ANSI Key Generation * subroutine from page 50. */ for(int ii=0; ii<21; ii++) { if( (keyNumber&testBit) != 0) { char ksr[10]; char eightByte[8]={0}; cumBits |= testBit; ksn.count=cumBits; /* all bits processed to date */ memcpy(ksr, &ksn,10); /* copy bit structure to char array*/ memcpy(crypt,&ksr[2],8); /* copy bytes 2 through 9 */ /* * Generate the new Key overwriting the old. * This will apply the "Non-reversible Key Generation Process" * to the lower 64 bits of the KSN. */ keyGen(&key, &crypt, &key); } testBit>>=1; } Where keyNumber is the current counter from the ksn ksn is an 80 bit structure that contains the 80 bit Key Serial Number from the HSM crypt is a 64 bit block of data I have it of type DES_cblock since I am using openSSL. key is a 128 bit double DES_cblock structure. The keyGen routine is almost verbatim from the “Non-reversible Key Generation Process” local subroutine on page 50 of the spec. At the end of this, the key variable will contain the key that can be used for the decryption, almost. The dudes that wrote the spec added some “variant” behavior to the key to keep us on our toes. If the key is to be used for decrypting a data stream such as a credit card track, you will need to XOR bytes 5 and 13 with 0xFF and Triple DES encrypt the key with itself (ECB mode). My code looks like: DOUBLE_KEY keyCopy; char *p; p=(char*)&key; p[ 5]^=0xff; p[13]^=0xff; keyCopy=key; des3(&keyCopy, (DES_cblock *)&key.left, &key.left); des3(&keyCopy, (DES_cblock *)&key.right, &key.right); If you are using this to decrypt a PIN block, you will need to XOR bytes 7 and 15 with 0xFF. (I am not 100% sure this should not be applied for the stream mode as well but my vendor is leaving it out.) If it is a PIN block, it will be encrypted with 3-DES in ECB mode. If it is a data stream, it will be encrypted in CBC mode with a zero initialization vector. (Did I mention I don’t much care for the spec?) It is interesting to note that the encryption side could be used in a non-hardware, tamper resistant security module if the server side (above) remembers and rejects keys that have been used previously. The technology is pretty neat. The ANSI spec leaves something to be desired but the technology is all right. Good luck. /Bob Bryan A: For data encryption, the variant is 0000000000FF0000.0000000000FF0000 so you need to XOR bytes 5 and 13 instead of 7 and 15. In addition, you need an additional 3DES self-encryption step of each key parts (left and right). Here is the relevant code in jPOS https://github.com/jpos/jPOS/blob/master/jpos/src/main/java/org/jpos/security/jceadapter/JCESecurityModule.java#L1843-1856
doc_23529262
How could this be accomplished? Thanks EDIT Here is how the flow works Java calls a javascript function in browser on my local machine -> Javascript calls python with POST Request on my Server -> I want a callback to Java to know when Python is done -> So that Java can move on Do you see know how it works? A: If you are running from the command line you could use pipes | which will call the next command in line with the standard out of the first command. As follows: firstCommand | secondCommand So if your Python script writes to standard out you could invoke it from the command line, and have the Java execute from the command line also as the second command receiving it's input from standard in.
doc_23529263
We changed our IP to a dedicated IP and all of a sudden it stopped working. my XHR is 0! I'm assuming it thinks it's a cross domain issue. For a temp fix I wrote a php proxy to load the file and I'm ajaxing that -- (which works - note: file is in the wp dir so it's not a dir wide issue) thanks! //EDIT (CODE) $.ajax({ url: '/blog/?feed=rss2', success: function() { alert('worked'); }, error: function(x){ alert(x.status); } }); $.ajax({ url: '/blog/proxy.php', success: function() { alert('worked'); }, error: function(x){ alert(x.status); } }); Note: proxy.php just fopens "/blog/?feed=rss2" I'm successful on proxy.php but getting jqXHR.status = 0 A: Try checking some of these for more details. Definitely use Firebug or Chrome's XHR debugger (F12) For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods: * *readyState *status *statusText *responseXML and/or responseText when the underlying request responded with xml and/or text, respectively *setRequestHeader(name, value) *getAllResponseHeaders() *getResponseHeader() *abort()
doc_23529264
WS-I: A problem occurred while running the WS-I WSDL conformance check: org.eclipse.wst.wsi.internal.analyzer.WSIAnalyzerException. The WS-I Test Assertion Document(TAD) was not found or could not be processed. The WSDLAnalyzer was not able to validate the given WSDL file. even if I ignore the case myecplise doesn't allow me to create the client. Ignore screen #01 src-resolve: Cannot resolve the name 'impl:Arrayof_tns1_MatchingDoc' to a(n) 'type definition' component Ignore screen #02 src-resolve: Cannot resolve the name 'soapenc:Array' to a(n) 'type definition component After ignoring the 2 screens it gives me an error undefined simple or complex type 'soapenc:Array' and exist the wizard... A: This error mentioning soapenc:Array may occur if you are trying to compile the WSDL of a RPC encoded webservice that is generated by Axis1. At least that was the case for me. This was a real pain, because there is no way to compile this WSDL with wsconsume or even with wsdl2java bundled with a Axis2 distribution or with xfire. I ended up downloading the 1.4 release ofAxis1 and using the bundled WSDL2java. You will have to call it from inside the axis.jar as org.apache.axis.wsdl.WSDL2Java. The most comfortable way for that IMHO is to run the .jar from eclipse using arguments in a run configuration.Unfortunately this is not the end of the story as the generated classes have a tendency to come out with errors (like duplicate methods and such) which you will have to fix manually. So be careful when integrating the WSDL2java task into you ant build.
doc_23529265
Is there a way to workaround this slow initialization time? My current ideas are to create a UIWebView when the app launches (but before gameplay has started), and reuse that (potentially creating a pool of them to reuse, like how UITableViewCell works) or to try and see if WKWebView has better performance. A: Here are my findings: * *WKWebView does not initialize any faster. Creating WKWebViews took a similar amount of time as creating UIWebViews (in the 1 test I did, it took 46ms to create two WKWebViews. *The very first web view created takes significantly longer to create than subsequent web views. The first one takes 31–42 ms; subsequent ones take ~11ms to create. The good news here is that creating the first web view when e.g. the app launches allows future webviews to be created more cheaply, avoiding a 40ms hit while the game is running. *Creating a pool of UIWebViews was a good solution for my use case. By creating the webviews at app launch and then reusing them, I avoid causing a frame drop while the game is running. A: There is not much difference in the responsiveness between UIWebView and WKWebView because WKWebView has been introduced for a consistency matter between iOS and OSX. The underlying engine is Webkit in either way and it requires a lot of initialization. The best solution I've found recent during years has been fading a WebView starting from a view with 0.1 alpha in which the url was loaded. Be careful to not start from 0.0 and do not have your webview detached from main view hierarchy because your url would not be loaded. When didFinishLoading is called then you can fade it to 1.0 thus providing a better user experience. Personally I don't like the UIWebView pool because I have experienced some memory troubles when maintaining it, especially on iOS 7 devices.
doc_23529266
But before submitting the username and the password, the password has to be encrypted. To do so, I use the following code (Please don't mind the get method, it's normal) : <form name="myForm" action="home" method="get"> <div class="form-group pb-3 pt-0"> <label for="password"><?= $content['MyAvatarConnexion']['password'] ?></label> <input type="password" id="password" name="password" class="form-control" placeholder="<?= $content['MyAvatarConnexion']['inputPassword'] ?>"> </div> </form> And I add a listener which call the encrypter, which works with a Promise. <script> const form = document.forms["myForm"]; form.addEventListener('submit', (e) => { e.preventDefault(); function callback(encryptstring){form.password.value = encryptstring; form.submit(); } var encrypter = new Encrypter(form.password.value, callback); }); </script> The change is working however, when I click on the submit button and before the page is changing, I can see that the typied password in switching from the clear password to the encrypted password. I have tried to put form.password.hidden = true; but it changes all the page layout before changing the page which is not quitte aesthetic. How can I change the value without changing the shown value ?
doc_23529267
Any ideas? select associate_id, position_effective_date, home_department_code, most_recent_record, (last_day(date_from_parts(year(current_date()), month(current_date())-Q_LEVEL,1),month)) AS month from( WITH Q AS (SELECT LEVEL Q_LEVEL FROM DUAL A CONNECT BY LEVEL <= 36) select Q.Q_LEVEL Q_LEVEL, v_dept_history_adj.associate_id, v_dept_history_adj.home_department_code, v_dept_history_adj.position_effective_date, max(position_effective_date) OVER(PARTITION BY v_dept_history_adj.associate_id) AS most_recent_record from src_table, Q where v_dept_history_adj.position_effective_date <= last_day(date_from_parts(year(current_date()), month(current_date())-Q.Q_LEVEL,1),month)) where position_effective_date = most_recent_record order by month desc, position_effective_date desc A: The PRIOR keyword is required exactly once per CONNECT BY. https://docs.snowflake.com/en/sql-reference/constructs/connect-by.html#usage-notes The keyword PRIOR should occur exactly once in each CONNECT BY expression. PRIOR can occur on either the left-hand side or the right-hand side of the expression, but not on both. The tell-tell "from dual" makes it appear that the SQL is from Oracle. There's another note higher up in that page: The Snowflake syntax for CONNECT BY is mostly compatible with the Oracle syntax. There are some differences, and the retirement to have PRIOR once on either the right or left of the expression is one of the differences. Most likely the PRIOR keyword should come before LEVEL: WITH Q AS (SELECT LEVEL Q_LEVEL FROM DUAL A CONNECT BY prior LEVEL <= 36) That will pass the syntax check on compile and is probably what you need here, but you can experiment with the position of the PRIOR keyword to be sure. A: WITH has to be the first in a query, like the manual described https://docs.snowflake.com/en/user-guide/queries-cte.html So your query would look like I can't test it right know, but src_table, Q looks very suspicious, besides using JOINs Further v_dept_history_adj is nowhere defined, so i am guessing that it is the source_table WITH Q AS (SELECT LEVEL Q_LEVEL FROM DUAL A CONNECT BY LEVEL <= 36), Q1 AS ( select Q.Q_LEVEL Q_LEVEL , v_dept_history_adj.associate_id, v_dept_history_adj.home_department_code, v_dept_history_adj.position_effective_date , max(position_effective_date) OVER(PARTITION BY v_dept_history_adj.associate_id) AS most_recent_record from src_table, Q where v_dept_history_adj.position_effective_date <= last_day(date_from_parts(year(current_date()), month(current_date())-Q.Q_LEVEL,1),month)) select associate_id , position_effective_date , home_department_code, most_recent_record , (last_day(date_from_parts(year(current_date()) ,month(current_date())-Q_LEVEL,1),month)) AS month FRO Q1 where position_effective_date = most_recent_record order by month desc, position_effective_date desc
doc_23529268
Is there any way to let the user upload his .glb / .gltf 3d model and see it on the canvas right away? I'm thinking maybe is possible with PHP since I'm using WordPress? Can PHP and JS even communicate together that way? Or it is better uploading only with JS? Thank You! A: Yes it is possible. Have a look at Don McCurdy GLTF viewer. https://gltf-viewer.donmccurdy.com/ https://github.com/donmccurdy/three-gltf-viewer
doc_23529269
I can check in - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath if the indexPath.row is the last one, but what I want is that if the user swipes on the last cell, nothing will appear (while in the others cells appears the text "delete"). I've tried this -(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{ if (indexPath.row != ([array count]-1)) { return @"delete"; } else { NSString *a; return a; } } but of course it doesn't works (the app crashes). I've tried with return @""; but the red button appears (with no text)! What do you suggest me? Thanks! A: Try - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath { if ([indexPath row] == [tableView numberOfRowsInSection:[indexPath section]] - 1) { return UITableViewCellEditingStyleNone; } return UITableViewCellEditingStyleDelete; } A: The app crashes since you return an uninitialized pointer. But even then, you're doing it wrong ;-) You want to implement tableView:editingStyleForRowAtIndexPath: and return UITableViewCellEditingStyleDelete for all cells, except for the last. You need to return UITableViewCellEditingStyleNone for the last cell to prevent that it can be deleted.
doc_23529270
Specified 'mysql' for database adapter, but the gem is not loaded. Add gem 'mysql' to your Gemfile. There is no mention of mysql adapter anywhere any the project (it's a new one) and the adapter in database.yml is sqlite3. I also tried -d sqlite3, no luck. Some lines of the trace are: vendor/bundle/gems/activerecord-4.0.1/lib/active_record/connection_adapters/connection_specification.rb:58:in `rescue in resolve_hash_connection' vendor/bundle/gems/activerecord-4.0.1/lib/active_record/connection_adapters/connection_specification.rb:55:in `resolve_hash_connection' vendor/bundle/gems/activerecord-4.0.1/lib/active_record/connection_adapters/connection_specification.rb:46:in `resolve_string_connection' vendor/bundle/gems/activerecord-4.0.1/lib/active_record/connection_adapters/connection_specification.rb:32:in `spec' . . . /usr/local/var/rbenv/versions/2.0.0-p247/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service' /usr/local/var/rbenv/versions/2.0.0-p247/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run' /usr/local/var/rbenv/versions/2.0.0-p247/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'
doc_23529271
RollNo Name 120 john 121 johney 122 sam I want to add those values in a list box like the below format. RollNo:[RollNo] , Name: [Name] Note : [RollNo] is ColumnName Identification Format Expected output: RollNo: 120 ,Name: John RollNo: 121 ,Name: Johney I can achieve this using a for loop but is there some other way such as using linq or any other concept. Please include examples with your suggestions. I tried using the linq code below but I didn't get the proper output. string mystring="RollNo:[RollNo] , Name: [Name]"; List<DataColumn> cols = ClsGlobal.dtRecords.Columns.Cast<DataColumn>().ToList(); dtRecords.AsEnumerable().ToList().ForEach(r => cols.ForEach(c =>listBox1.Items.Add(mystring.Replace("[" + c.ColumnName + "]", r[c.ColumnName].ToString())))); A: Something like this? var query = (from c in dt.AsEnumerable() select new { Value=c.Field<int>("RollNo"), Text=c.Field<string>("Name")}).ToList(); And then just bind query to the ListBox. UPDATE OP wants just strings; so this should do it: var query = (from c in dt.AsEnumerable() select "RollNo: "+ c.Field<int>("RollNo")+ " , Name: "+ c.Field<string>("Name")).ToList();
doc_23529272
var currentTab; chrome.tabs.getSelected(null, function(tab) { currentTab = tab.url; }); console.log(currentTab); A: All the Chrome methods are asynchronous, which means that they just queue up the code to be called later. Also note that tabs.getSelected has been deprecated, so I'm using tabs.query({active: true}... instead. The callback fires out of order, after everything else has finished: var currentTab; // 1 chrome.tabs.query({active: true}, // 2, queues up callback and continues function(tabs) { currentTab = tabs[0].url; // 4, last, after everything else }); console.log(currentTab); // 3 callback hasn't fired yet, so undefined Welcome to what's sometimes called 'callback hell'. The easiest way around this is to use an asynchronous or promise wrapper library like chrome-extension-async. This let's you use async/await syntax: async function yourCode() { try { const currentTabs = await chrome.tabs.query({active: true}); const currentTab = currentTabs[0]; console.log(currentTab); } catch(err) { // Log errors etc } } You're still making a callback and executing code after it's finished, but now you can easily use variables before and after the await. I recently blogged about that in a lot more detail than will fit here.
doc_23529273
I followed Cheesesquare example to create detail view. I have exactly the xml same structure. The only difference is that I'm using this view for a fragment instead of raw activity. This occurs most of the times but sometimes it doesn't. Occurs only once for fragment object, once it fixes itself it works well. On my second phone it doesn't occur. After removing FAB it's ok. When I change sth in calendar, it also causes margin to fix itself. Attaching gif with layout lines enabled so you can see the margins. For reference: <android.support.design.widget.CoordinatorLayout android:id="@+id/main_content2" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" android:fitsSystemWindows="true" tools:context="com.habitsteacher.android.view.fragment.show.ShowHabitFragment"> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="192dp" android:fitsSystemWindows="true" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.design.widget.CollapsingToolbarLayout android:id="@+id/collapsingToolbarLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:expandedTitleMarginBottom="72dp" app:expandedTitleMarginEnd="24dp" app:expandedTitleMarginStart="48dp" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <TextView android:id="@+id/intentionText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:layout_marginBottom="16dp" android:layout_marginEnd="24dp" android:layout_marginLeft="48dp" android:layout_marginRight="24dp" android:layout_marginStart="48dp" android:ellipsize="end" android:fitsSystemWindows="true" android:maxLines="2" android:textColor="@color/icons" android:textSize="@dimen/abc_text_size_subhead_material" app:layout_collapseMode="parallax" app:layout_collapseParallaxMultiplier="0.25"/> <android.support.v7.widget.Toolbar android:id="@+id/toolbar_show_habit" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_collapseMode="pin" app:popupTheme="@style/ThemeOverlay.AppCompat.Light"> </android.support.v7.widget.Toolbar> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="fill_vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <LinearLayout android:id="@+id/habit_view" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/background_light" android:orientation="vertical" android:paddingTop="32dp"> <android.support.v7.widget.CardView android:id="@+id/calendarWrapper" android:layout_width="match_parent" android:layout_height="343dp" android:layout_margin="@dimen/card_margin"> </android.support.v7.widget.CardView> </LinearLayout> </android.support.v4.widget.NestedScrollView> <android.support.design.widget.FloatingActionButton android:id="@+id/floating_button_edit_habit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="0dp" android:layout_marginEnd="16dp" android:layout_marginRight="16dp" android:clickable="true" android:src="@drawable/ic_mode_edit_white_24dp" app:layout_anchor="@id/appbar" app:layout_anchorGravity="bottom|right|end"/> </android.support.design.widget.CoordinatorLayout> Any thought what could be the reason, or how to investigate this deeper? A: It looks like CoordinatorLayout doesn't work properly inside a fragment which is added as non-first to the activity. This looks like a bug in SDK but I couldn't locate the root cause precisely. As it works properly only when the layout is located on the first added fragment to the activity, I moved fragment with this layout to separate activity and is works properly now. Still, it's avoiding this behaviour not fixing it so any answer is still appreciated.
doc_23529274
I can enable the following user experiences for non-Microsoft file types on "SharePoint Online" and "One Drive for Business": * *customized file icons *file preview in the browser *rich view/edit capability While these information is very great, I would like to apply these techniques to "OWA" too. What would be a good way to do it? Thanks. A: During Ignite 2015, I demoed file handlers in Outlook Web App (OWA) as something we are actively (and still) working on. Our team is currently validating that these add-ins work end to end in OWA, and will release the feature to the public after we finish this testing. We'll be sure to announce on Twitter, dev.office.com, etc. once we do - keep an eye out :)
doc_23529275
A first chance exception of type 'System.NullReferenceException' occurred in GRCWebApp.dll Additional information: Object reference not set to an instance of an object. The error is related to this line in the controller : currentMembershipType.Type = model.Type; The Post Method is [HttpPost] [ValidateAntiForgeryToken] public ActionResult EditClubMembershipType(EditMembershipTypeViewModel model) { if (ModelState.IsValid) { //Go fetch the membership type from the database var currentMembershipType = db.MembershipTypes.FirstOrDefault(p => p.MembershipTypeId == model.MembershipTypeId); // Save new Membership Type currentMembershipType.Type = model.Type; currentMembershipType.Description = model.Description; currentMembershipType.Cost = model.Cost; currentMembershipType.ReducedCost = model.ReducedCost; currentMembershipType.DayId = model.ReducedDay; currentMembershipType.MonthId = model.ReducedMonth; currentMembershipType.MinAge = model.MinAge; currentMembershipType.MaxAge = model.MaxAge; // Save Changes db.SaveChanges(); return RedirectToAction("AddClubMembershipType", new { clubId = model.ClubId, editMode = true } ); } return View("Error"); } The View is: @model GRCWebApp.ViewModels.EditMembershipTypeViewModel @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.ClubId) <div class="col-md-12"> <h3>Edit Membership Type</h3> </div> <div class="form-horizontal"> <hr /> <div class="row"> <div class="col-md-10"> <div class="well bs-component"> <div class="form-group"> </div> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> <div class="row col-offset-md-1 col-md-11"> <div class="col-md-3"> @Html.LabelFor(model => model.Type, htmlAttributes: new { @class = "control-label" }) @Html.EditorFor(model => model.Type, new { htmlAttributes = new { @class = "form-control", placeholder = "e.g. Full" } }) @Html.ValidationMessageFor(model => model.Type, "", new { @class = "text-danger" }) </div> <div class="col-md-4"> @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label" }) @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" }) </div> <div class="col-md-2"> @Html.LabelFor(model => model.Cost, htmlAttributes: new { @class = "control-label" }) <div class="input-group"> <div class="input-group-addon"> £</div>@Html.EditorFor(model => model.Cost, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Cost, "", new { @class = "text-danger" }) </div> </div> </div> </div> <h4>Do you offer reduced membership cost part way through the year? Add details here:</h4> <div class="form-group"> <div class="row col-offset-md-1 col-md-11"> <div class="col-md-2"> @Html.LabelFor(model => model.ReducedCost, htmlAttributes: new { @class = "control-label" }) <div class="input-group"> <div class="input-group-addon">£</div> @Html.EditorFor(model => model.ReducedCost, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ReducedCost, "", new { @class = "text-danger" }) </div> </div> <div class="col-md-2"> @Html.LabelFor(model => model.ReducedDay, htmlAttributes: new { @class = "control-label" }) @Html.DropDownListFor(model => model.ReducedDay, new SelectList(Model.Days, "DayId", "DayNum", 1), new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.ReducedDay, "", new { @class = "text-danger" }) </div> <div class="col-md-2"> @Html.LabelFor(model => model.ReducedMonth, htmlAttributes: new { @class = "control-label" }) @Html.DropDownListFor(model => model.ReducedMonth, new SelectList(Model.Months, "MonthId", "MonthName"), new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.ReducedMonth, "", new { @class = "text-danger" }) </div> </div> </div> <h4>Are there age restrictions for this Membership Type? Add details here:</h4> <div class="form-group"> <div class="row col-offset-md-1 col-md-11"> <div class="col-md-2"> @Html.LabelFor(model => model.MinAge, htmlAttributes: new { @class = "control-label" }) @Html.EditorFor(model => model.MinAge, new { htmlAttributes = new { @class = "form-control", @Value = "1" } }) @Html.ValidationMessageFor(model => model.MinAge, "", new { @class = "text-danger" }) </div> <div class="col-md-2"> @Html.LabelFor(model => model.MaxAge, htmlAttributes: new { @class = "control-label" }) @Html.EditorFor(model => model.MaxAge, new { htmlAttributes = new { @class = "form-control", @Value = "150" } }) @Html.ValidationMessageFor(model => model.MaxAge, "", new { @class = "text-danger" }) </div> </div> </div> <div class="form-group"> <div class=" col-md-10"> <input type="submit" name="Submit" value="Save" class="btn btn-success btn-lg" /> </div> </div> </div> </div> </div> </div> } <div> @Html.ActionLink("Back to Membership Types", "AddClubMembershipType", new { clubId = Model.ClubId, editMode = true }) </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") } A: It's likely because MembershipTypeId on your model is null. I don't see anywhere in your view where that value is being bound, and if it's not, it will not be part of the submitted form data and therefore not populated in the model passed into the HttpPost controller method. Most common fix is to add a Html.HiddenFor(m => m.MembershipTypeId) in the form. P.S. It's really unhelpful to not tell us what line number the error originated from.
doc_23529276
Now my ask is : Should I be concerned about the performance of the query on Azure SQL? If you think the difference in the execution plans is a concern, could you please advise if you have any ideas how to diagnose further or find a way to improve the Azure SQL query? If there is any more info I can provide, please let me know. Edit: SQL Server Execution plan: SQL Server XML file Azure SQL Execution plan: Azure SQL XML file A: Plan is same in both the instances.Total plan cost always rounds upto 100%.So you may see one operator having high cost compared to another,but all summing upto 100%. I am not saying keylookups are bad,but those are Random reads .From your plan i could see a single table was accessed twice (seek and lookup).So i recommend adding altering below index after testing This index [IX_InstantMessageThreadAccesses_ProfileId] should have one more key column( archived) and include this column (kastreadon).By this way you will be to avoid nearly 44% of total query cost and it will result SQL in choosing a new plan. Further i could see your statistics are not to update.I recommend doing an update stats for all the tables with fullscan(this may cause huge I/O activity if the tables are very big)... UPDATE STATISTICS <<tablename>> WITH FULLSCAN Update question if you have any questions further with steps done now and any diefferences you are seeing
doc_23529277
A: It looks like autolinked references are not supported in regular md files. This Post talks about using absolute and relative references such as: * *[<hash>](https://github.com/user/project/commit/<hash>) *[<hash>](/../../commit/<hash>)
doc_23529278
I am using react js and I could get the values from database inside `componentDidMount()' method. But I couldn't find a way to pass it to the dropdown array defined in ant. for (var i = 0; i < array.length; i++) { dropdownItems = [{ value: array[i], label: array[i] } ]; } As in the above code I tried it to fetch the result to dropdownItems array. But since dropdownItems is readonly property, it was impossible. So how can we achieve this? A: you should store dropdown values in component's state.. import { Select } from 'antd'; class MyComponent extends Component { constructor(props){ super(props); this.state = { dropdownItems: [], selectedValue: null } } componentDidMount(){ fetch(api) .then(resp => resp.json()) .then(dropdownData => { this.setState({ dropdownItems: dropdownData.map(item => ({ value: item, label: item })) }) }) } handleChange = (value) => { this.setState({ selectedValue: value }) } render(){ const { dropdownItems, selectedValue} = this.state; return( <Select defaultValue={selectedValue} onChange={this.handleChange}> {dropdownItems.map((item, index) => <Select.Option value={item.value} key={index}>{item.label}</Select.Option>)} </Select> ); } }
doc_23529279
But I got an error while using openvino. Any way to solve it?enter code here model = keras.models.load_model('/resnet50.h5') onnx_model, _ = tf2onnx.convert.from_keras(model, opset=16) onnx.save(onnx_model, '/t1_model.onnx') ie = IECore() net = ie.read_network("/t1_model.onnx") input_name = list(net.input_info.keys())[0] output_name = list(net.outputs.keys())[0] net.input_info[input_name].precision = 'FP32' net.outputs[output_name].precision = 'FP32' exec_net = ie.load_network(network=net, device_name='CPU') I faced these problems. RuntimeError: Check 'std::get<0>(valid)' failed at C:\j\workspace\private-ci\ie\build-windows-vs2019@3\b\repos\openvino\src\inference\src\ie_core.cpp:1414: InferenceEngine::Core::LoadNetwork doesn't support inputs having dynamic shapes. Use ov::Core::compile_model API instead. Dynamic inputs are :{ input:'input_1,input_1', shape={?,256,256,3}} input_shape = (None, 256,256,3) A: The IECore API doesn't support dynamic shapes so you need to make your model static before you load it into the plugin. You can use the reshape() method on the imported model. As an alternative you can switch to the 2022.1 version of OV where the dynamic shapes are supported. You have to switch from IECore to Core, read_network -> read_model, load_network -> compile_model.
doc_23529280
I am creating a website that interact with a database. I have understood how to display the data from a table but currently I am creating a new connection everytime I change the table to display. Isn't it better to create the connection at the beginning and close it at the end ? How should I share the connection informations between the different classes that are using it to query the DB ?
doc_23529281
I am writing a custom PHP strip_tags for some requirements and instead of storing every HTML/HTML5 tags in a class private property (like an array), I was wondering if some service does exist that provides this functionality? A: list isnt't that long. Create own:) http://www.w3schools.com/tags/
doc_23529282
and got result from sphinxapi (python) in list words: 'words': [{'docs': 281, 'hits': 340, 'word': 't230'}, 2011-10-11 19:42:06+0600 [-] {'docs': 4396, 'hits': 6317, 'word': 'a53'}, 2011-10-11 19:42:06+0600 [-] {'docs': 2453, 'hits': 2917, 'word': 'f60'}]}] how get "normal" words? Sphinx 0.9.9-release (r2117) A: Maybe a bit late but "t230" seems to be the soundex version of "test". In section index { ... } of your sphinx.conf file, check if the morphology contains the value soundex. If you comment the morphology line (setting it by default to none) and reindex, you'll see that the words will display what you're typing. Note that changing the morphology will impact the way Sphinx indexes your documentation and your search results will/may be different.
doc_23529283
if request.method == "POST": depName = request.POST.get("sedep") Pname = request.POST.get("name") Pmail = request.POST.get("mail") docName = request.POST.get("sedoc") Pphone = request.POST.get("phone") AppointDate = request.POST.get("date") appointment_list = Appointment_List(se_dept = depName, se_doc = docName, patient_name = Pname, patient_phone = Pphone, patient_email = Pmail, calendar = AppointDate) appointment_list.save() # SEND EMAIL subject = 'Your appointment status!' message = 'hello '+ Pname + '! \n' + 'Welcome to Doctor appointment system.\n'+ 'Congratulations your appointment is booked.\n\n Thanking you Team malloc()' from_email = settings.EMAIL_HOST_USER to_list = [Pmail] send_mail(subject,message,from_email,to_list,fail_silently = True) EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'sa3518548@gmail.com' EMAIL_HOST_PASSWORD = 'uqnoifwqucnlefgp' EMAIL_PORT = 587
doc_23529284
Today's the first time this appeared. I published my game a few weeks ago and dozens of people have played it with no issues so I'm trying to figure out why this happened now when the same code worked successfully probably at least 50 times before. It happened 10 seconds after session start: Exception java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference The two lines of code involved appear in the onTick method of a CountDownTimer that's started when the user clicks a button. They are: View currentView = gridView.getChildAt(randomPosition); ImageView image = (ImageView) currentView.findViewById(R.id.button); The GridView is implemented near the beginning of the onCreate method: adapter = new ButtonAdapter(this, clickButtons); gridView = (GridView) findViewById(R.id.gridview); gridView.setAdapter(adapter); I'm guessing that the gridView was somehow null but since the code that implements it in onCreate runs before the CountDownTimer is started, I'm not sure how that's possible. Edit: now I'm beginning to think the problem is in the adapter. public class ButtonAdapter extends ArrayAdapter<ClickButton> { public ButtonAdapter(@NonNull Context context, @NonNull ClickButton[] objects) { super(context, 0, objects); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { // Check if an existing view is being reused, otherwise inflate the view View gridItemView = convertView; if (gridItemView == null) { gridItemView = LayoutInflater.from(getContext()).inflate( R.layout.button, parent, false); } ClickButton currentButton = getItem(position); ImageView button = (ImageView) gridItemView.findViewById(R.id.button); button.setImageResource(currentButton.mSource); button.setAlpha(currentButton.mOpacity); return gridItemView; } } Android Studio wants me to replace button.setImageResource(currentButton.mSource); button.setAlpha(currentButton.mOpacity); with button.setImageResource(currentButton != null ? currentButton.mSource : 0); button.setAlpha(currentButton != null ? currentButton.mOpacity : 0); Can someone explain what these changes do? Do you think that not having these changes is what caused the crash and do you have any idea why the crash only occurred once and not every time you use the app?
doc_23529285
A: Use ListView's headers and footers if you want to put some items only at the end/beginning of the ListView. Watch this video beginning from 42:40 it's really useful. A: ListView inside ScrollView is not possible. <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scrollView1" android:layout_width="match_parent" android:layout_height="wrap_content" > <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <!-- here the picture info --> </LinearLayout> </LinearLayout> A: A list view will scroll automatically once it goes past its parents height or the ListViews maximum height A: If you put your ListView/any scrollable View inside the scrollView it will not work properly because when you touch the screen ,main focus of your touch is on parent view(scrollView ) not the child View (ListView). <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" > <ListView android:layout_height="match_parent" android:id="@+id/all_workouts_list" android:cacheColorHint="#ffffffff" android:layout_width="match_parent" android:layout_above="@+id/add_workout_all_workout_list"></ListView> <Button android:layout_width="wrap_content" android:id="@+id/add_workout_all_workout_list" android:layout_height="wrap_content" android:text="Add Workout" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true"></Button> </RelativeLayout> A: I have no any ready example with me, So written a raw code like this as you asked in comment, ListView lv = (ListView) findViewById(R.id.listView); LinearLayout ll = new LinearLayout(this); ll.setLayoutParams(new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT))); Button btn = new Button(this); ll.addView(btn); lv.addFooterView(ll, null, true);
doc_23529286
(1274649,682844,872502,1016256) INTERSECT (SELECT id FROM `users` WHERE `id` IN (1274649,682844,872502,1016256)) Adapting from the comments: These four numbers are the IDs that I have now. I want to know which of these IDs do not have an an entry in my table, and how many of them don't have an entry? A: select t.id from ( select 1274649 as id union select 682844 union select 872502 union select 1016256 ) t left join users u on u.id = t.id where u.id is null This returns those ids that haven't corresponding id in users table. Added this is the answer to OP explanation in comment: Which entries in my list do not have an entry in my table?
doc_23529287
Customer_Loc (table name) Cust_ID | Rd_dist (column names) I've tried the query below which returns syntax errors. select count(Rd_dist) / count (Cust_ID) from customer_loc where Rd_Dist <=10 *100 as percentage I realise the solution to this may be fairly easy but I'm new to SQL and it's had me stuck for ages. A: The problem with your query is that you are filtering out all the customers who are more than 10 miles away. You need conditional aggregation, and this is very easy in MySQL: select (sum(Rd_Dist <= 10) / count(*)) * 100 as percentage from customer_loc;
doc_23529288
import java.awt.*; import javax.swing.*; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionListener; import java.io.*; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; public class assignment_tauqeer_abbasi extends JApplet implements ActionListener { JTextArea textInput; // User Input. JLabel wordCountLabel; // To display number of words. public void init() { // This code from here is the customisation of the Applet, this includes background colour, text colour, text back ground colour, labels and buttons setBackground(Color.black); getContentPane().setBackground(Color.black); textInput = new JTextArea(); textInput.setBackground(Color.white); JPanel south = new JPanel(); south.setBackground(Color.darkGray); south.setLayout(new FlowLayout(-1)); /* Creating Analyze and Reset buttons */ JButton countButton = new JButton("Analyze"); countButton.addActionListener(this); south.add(countButton); JButton resetButton = new JButton("Reset"); resetButton.addActionListener(this); south.add(resetButton); JButton fileButton = new JButton("Analyze Text File"); fileButton.addActionListener(this); south.add(fileButton); /* Labels telling the user what to do or what the program is outputting */ wordCountLabel = new JLabel(" No. of words:"); wordCountLabel.setBackground(Color.black); wordCountLabel.setForeground(Color.red); wordCountLabel.setOpaque(true); south.add(wordCountLabel); /* Border for Applet. */ getContentPane().setLayout(new BorderLayout(2, 2)); /* Scroll bar for the text area where the user will input the text they wish to analyse. */ JScrollPane scroller = new JScrollPane(textInput); getContentPane().add(scroller, BorderLayout.CENTER); getContentPane().add(south, BorderLayout.SOUTH); } // end init(); public Insets getInsets() { // Border size around edges. return new Insets(2, 2, 2, 2); } // end of Applet customisation // Text analysis start // }}; // Text analysis end public void actionPerformed(java.awt.event.ActionEvent e) { String command = e.getActionCommand(); if (command.equals("Analyze")) { String[] array = textInput.getText().split(" "); int maxWordLength = 0; int wordLength = 0; for (int i = 0; i < array.length; i++) { array[i] = array[i].replaceAll("[^a-zA-Z]", ""); wordLength = array[i].length(); if (wordLength > maxWordLength) { maxWordLength = wordLength; } } int[] intArray = new int[maxWordLength + 1]; for (int i = 0; i < array.length; i++) { intArray[array[i].length()]++; } StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); out.print("<html>"); for (int i = 1; i < intArray.length; i++) { out.printf("%d word(s) of length %d<br>", intArray[i], i); } out.print("</html>"); wordCountLabel.setText(sw.toString()); } else if (command.equals("Reset")) { textInput.setText(""); wordCountLabel.setText("No of words:"); textInput.requestFocus(); } } } How will I go about working out the mean length of whatever the user inputs? Any help will be highly appreciated. A: Since this is an assignment, I'll give you some guidance and you'll learn the most by working out the code on your own. The intuition needed here is that you are creating a program to implement the algorithm defined by its mathematical notation. The Sigma is equivalent to your for loop with an "addition" operation at each pass in the loop. Since you have an array of all the words, and you know the length of each word, you need to write code that implements the algorithm: * *start with a sumValue of 0 *add each length to the sumValue *divide the result by the size of your array
doc_23529289
I'm using an old struts application (no choice). I'm refactoring old services with spring annotation using AnnotationConfigApplicationContext and a configuration class. I use JBoss AS 7.0.1. I need to implement web services in my application. So I'm trying to set DispatcherServlet using WebApplicationInitializer. I've tried by implemeting, "WebApplicationInitializer", or extending "AbstractDispatcherServletInitializer", "AbstractAnnotationConfigDispatcherServletInitializer", but class is not detected and processed once JBoss is started and war is deployed. How does Jboss to detect this type of class. Do we have to set a declaration somewhere. sample code of my last try : import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { String test = ""; test.toLowerCase(); return null; } @Override protected Class<?>[] getServletConfigClasses() { String test = ""; test.toLowerCase(); return new Class[] {ApplicationContextConfiguration.class}; } @Override protected String[] getServletMappings() { String test = ""; test.toLowerCase(); return new String[] { "*.html" ,"*.json" }; } } A: FOUND. To detect the "WebApplicationInitializer" implementation. Add the file : /META-INF/services/javax.servlet.ServletContainerInitializer Set this file in a JAR Set in the full packagge and class name : com.xxxxxxx.AbstractAnnotationConfigDispatcherServletInitializer Spring implements the ServletContainerInitializer through SpringServletContainerInitializer class. Per the Servlet specs, this implementation must be declared in a META-INF/services/javax.servlet.ServletContainerInitializer file of the libraries jar file - Spring declares this in spring-web*.jar jar file and has an entry org.springframework.web.SpringServletContainerInitializer
doc_23529290
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-ClANdr6bWuUdXWELI09IBiITbU5zbvg6V1dZp9mr55Q='), or a nonce ('nonce-...') is required to enable inline execution. For the code I have tried to add "content_security_policy": { "extension_page": "script-src 'self' 'sha256-ClANdr6bWuUdXWELI09IBiITbU5zbvg6V1dZp9mr55Q='" }, to Manifest but it didn't help How can I solve it? A: MV3 extensions cannot execute arbitrary stringified scripts, however you can "inject functions" from the background page via the chrome.scripting.executeScript API. For example: chrome.scripting.executeScript(tabId, { func: () => { alert('hi') // The rest of the JS code, not a string } })
doc_23529291
I have to use these structs and dont know how to access the Date struct right. Here is my code: #include <iostream> #include <string.h> using namespace std; struct Date { short year; short month; short day; }; struct Stuff { Date birth; }; struct ListElement { struct Stuff* person; // Pointer to struct Stuff struct ListElement* next; // Pointer to the next Element }; int main() { short birth_year; short birth_month; short birth_day; cin >> birth_year; cin >> birth_month; cin >> birth_day; ListElement* const start = new ListElement(); ListElement* actual = start; actual->person = new Stuff(); actual->person->birth.year = new short[sizeof(birth_year)]; // Conversion Error delete start; delete actual; } Error message from GCC: main.cpp: In function 'int main()': main.cpp:35:29: error: invalid conversion from 'short int*' to 'short int' [-fpermissive] actual->person->birth.year = new short[sizeof(birth_year)]; // Conversion Error A: You cannot allocate memory for actual->person->birth.year, as birth.year is not a pointer. You can just use: actual->person->birth.year = 2014; or actual->person->birth.year = birth_year; A: I think that what you want to really do is this: actual->person->birth.year = birth_year; If I am wrong, then read the following: You have in your struct: short year; but you trying to assign what new returns to year. You should do that a short* year; and handle it dynamically (never forget to de-allocate it)! A: The year is a short which is a direct member of Date. That is, if you create a Stuff object, it contains birth, which contains year. These don't need to be manually allocated, which is what you're trying to do with new short[sizeof(birth_year)]. Instead, you should just assign it a value: actual->person->birth.year = 1990; The reason for your error is that new ... expressions return a pointer to the object they allocate. That means it's giving you a short*, which you are then trying to store in a short - that's not going to work. Another problem you have is that new doesn't work like malloc. You just pass it how many objects you want, not how many bytes. If you want a single short, you just do new short. If you wanted an array of, say, two shorts, you would do new short[2]. Remember that a dynamically allocated object needs to be deleted - in the case of a dynamically allocated array, you need to use delete[] to destroy it.
doc_23529292
* *maintabholder.h: #ifndef MAINTABHOLDER_H #define MAINTABHOLDER_H #include <QMainWindow> namespace Ui { class MainTabHolder; } class MainTabHolder : public QMainWindow { Q_OBJECT public: explicit MainTabHolder(QWidget *parent = 0); ~MainTabHolder(); private: Ui::MainTabHolder *ui; }; #endif // MAINTABHOLDER_H *maintabholder.cpp: #include "maintabholder.h" #include "ui_maintabholder.h" MainTabHolder::MainTabHolder(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainTabHolder) { ui->setupUi(this); } MainTabHolder::~MainTabHolder() { delete ui; } *main.cpp: #include "maintabholder.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainTabHolder w; w.show(); return a.exec(); } *ui_maintabholder.h #ifndef UI_MAINTABHOLDER_H #define UI_MAINTABHOLDER_H #include <QtCore/QVariant> #include <QtWebKitWidgets/QWebView> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QTabWidget> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_Form { public: QHBoxLayout *horizontalLayout; QTabWidget *tabWidget; QWidget *comicViewer; QWidget *comicSearcher; QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout_2; QPushButton *pushButton; QSpacerItem *horizontalSpacer; QPushButton *pushButton_2; QWebView *webView; void setupUi(QWidget *Form) { if (Form->objectName().isEmpty()) Form->setObjectName(QStringLiteral("Form")); Form->resize(531, 308); horizontalLayout = new QHBoxLayout(Form); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); tabWidget = new QTabWidget(Form); tabWidget->setObjectName(QStringLiteral("tabWidget")); comicViewer = new QWidget(); comicViewer->setObjectName(QStringLiteral("comicViewer")); comicViewer->setCursor(QCursor(Qt::ArrowCursor)); tabWidget->addTab(comicViewer, QString()); comicSearcher = new QWidget(); comicSearcher->setObjectName(QStringLiteral("comicSearcher")); verticalLayout = new QVBoxLayout(comicSearcher); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); pushButton = new QPushButton(comicSearcher); pushButton->setObjectName(QStringLiteral("pushButton")); horizontalLayout_2->addWidget(pushButton); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_2->addItem(horizontalSpacer); pushButton_2 = new QPushButton(comicSearcher); pushButton_2->setObjectName(QStringLiteral("pushButton_2")); pushButton_2->setEnabled(false); horizontalLayout_2->addWidget(pushButton_2); verticalLayout->addLayout(horizontalLayout_2); webView = new QWebView(comicSearcher); webView->setObjectName(QStringLiteral("webView")); webView->setUrl(QUrl(QStringLiteral("about:blank"))); verticalLayout->addWidget(webView); tabWidget->addTab(comicSearcher, QString()); horizontalLayout->addWidget(tabWidget); retranslateUi(Form); tabWidget->setCurrentIndex(1); QMetaObject::connectSlotsByName(Form); } // setupUi void retranslateUi(QWidget *Form) { Form->setWindowTitle(QApplication::translate("Form", "Form", 0)); tabWidget->setTabText(tabWidget->indexOf(comicViewer), QApplication::translate("Form", "Comic Viewer", 0)); pushButton->setText(QApplication::translate("Form", "Go to SubManga", 0)); pushButton_2->setText(QApplication::translate("Form", "Download Comic", 0)); tabWidget->setTabText(tabWidget->indexOf(comicSearcher), QApplication::translate("Form", "Search For Comics", 0)); } // retranslateUi }; namespace Ui { class Form: public Ui_Form {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINTABHOLDER_H the compiler errors are: [...]\maintabholder.cpp: In constructor 'MainTabHolder::MainTabHolder(QWidget*)': [...]\maintabholder.cpp:6:16: error: invalid use of incomplete type 'class Ui::MainTabHolder' In file included from [...]\maintabholder.cpp:1:0: [...]\maintabholder.h:7:7: error: forward declaration of 'class Ui::MainTabHolder' [...]\maintabholder.cpp:8:7: error: invalid use of incomplete type 'class Ui::MainTabHolder' In file included from [...]\maintabholder.cpp:1:0: [...]\maintabholder.h:7:7: error: forward declaration of 'class Ui::MainTabHolder' [...]\maintabholder.cpp: In destructor 'virtual MainTabHolder::~MainTabHolder()': [...]\maintabholder.cpp:13:12: warning: possible problem detected in invocation of delete operator: [enabled by default] [...]\maintabholder.cpp:13:12: warning: invalid use of incomplete type 'class Ui::MainTabHolder' [enabled by default] In file included from [...]\maintabholder.cpp:1:0: [...]\maintabholder.h:7:7: warning: forward declaration of 'class Ui::MainTabHolder' [enabled by default] [...]\maintabholder.cpp:13:12: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined Can you give a help with this? I would appreciate it... A: You are using a file generated by uic from Qt; you should verify that this tool successfully generate the file, by for example checking the build output and the file itself. Also, check that it is in the *.pro file (ie, that maintabholder.h is marked to be processed by uic). I personnally advise to use the multiple inheritance method for ui : // in maintabholder.h // ... #include "ui_maintabholder.h" class MainTabHolder : public QMainWindow, public Ui::MainTabHolder { // ... }; Simpler to use, and if you have a problem with the ui_*.h file the error is more explicit. You should post ui_maintabholder.h. A: You included the ui define head in your .cpp file, and defined a private member "Ui::MainTabHolder *ui;" in your .h file, so you need to add a forward declaration in your .h file(maintabholder.h:) before your class defination: class Ui_MainTabHolder; here Ui_MainTabHolder is your Ui class name, check your own project for correct one.
doc_23529293
How do I determine if this reference is no longer used? Since I can only see a import line of code. Yet Visual Basic is not telling me the assembly is no longer needed (like it does with C#).
doc_23529294
I don't know how to find the link.
doc_23529295
Code: #include <stdio.h> #include <cs50.h> int main(void){ int x; int y; do{ x=get_int("Width of the hash floor: "); y=get_int("Length of the hash floor: "); return x; return y; } while (x>1); for (int n=0;n<x;n++){ printf("#"); for(int a=0;a<y;a++){ printf("#\n"); } } } A: You probably want this: * *remove both return statements, they don't make any sense here. *change the while loop (see comment in the code below). #include <stdio.h> #include <cs50.h> int main(void) { int x; int y; do{ x = get_int("Width of the hash floor: "); y = get_int("Length of the hash floor: "); } while (x < 1 || y < 1); // ask for width and length until both // x and y are larger than 0 for (int n = 0; n < x; n++) { printf("#"); for (int a = 0; a < y; a++) { printf("#\n"); } } } A: in the do while ... Don't use return and let the condition of while fulfill. The Return instruction is used to return to the Main Program from a Subroutine Program or Interrupt Program
doc_23529296
class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. } } And assume that the above code is saved in a file called HelloWorld.java. So my question is: since HelloWorld is now a package-private class, how does it work? The main() method should not be visible or accessible across packages, am I right? It makes perfect sense to me if the class HelloWorld is declared public. Confusion is only when it is declared with the default package-private access. A: JVM startup is described in §12.1 Virtual Machine Start-Up of the JLS. Note that this chapter says nothing about visibility checks with regards to the class. It only specifies that the main method must be public. This means that there simply is no check for visibility on the class level (which kind-of makes sense as there is no context yet against which to check the visibility: in which "package" is the "caller"?). A: Main method won't be visible to other classes which reside in different packages. But the JVM can see it all. It won't have any difficulty in finding your main method and running it for you. If you want to simulate the access restriction, write another class in a different package and try to call HelloWorld.main and see if the compiler keeps quiet. A: You have not made it very clear, but I assume that your question is why that main method can be run when you type java HelloWorld at the command line. The answer is that the Java Language Specification simply does not require the class that contains the main method to be public. Access modifiers are a language mechanism mainly intended to help maintainability via encapsulation. They're not really a security feature, and certainly not unshakable laws of physics. The JVM startup mechanism simply ignores them. In fact, you can even use a private inner class, and it will still run. A: Probably the designers of JLS decided there is no need to restrict access to main method if you know the class name, while at the first glance it looks counter-intuitive; from the other side - the access could be always got via reflection so it couldn't be treated as a security hole... Anyway e.g. by creating facade to a package-private class we access that one indirectly... So the protection is rather from incorrect usage and to allow further changes.
doc_23529297
Edited Question - Removed irelevant distractions as I now realise it has nothing to do with dynamic content. Every so often javascript files I am working on are not getting fully downloaded. The file I am currently having a problem with is only 49 lines long and is getting cut off with only 30 or characters to go. Anyone else seen this? TIA Pat A: Seems to be a caching bug with StaticFileHandler. Check out this blog post and this thread on Episerver World. Haven't tried it fully yet, but they say setting cacheControl="private" on staticFile should solve the problem "sort of". <staticFile expirationTime="1.0:0:0" cacheControl="private" /> A: This is a longshot, but try switching to the ASP.NET StaticFileHandler in web.config.
doc_23529298
Extremely surprisingly, the value returned to the child_added event is ~300ms different from what is in fact stored in the Firebase Database node. Subsequent reads at the same node, provides the 'correct' time as stored at the node. It is only the initial child_added event that is triggered right when the push is occurring, that is returning a wrong time. Has anyone observed this issue? ref = new Firebase(/some/path); ref.on('child_added', function (childData) { console.log('childData.pushTime = ' + childData.pushTime); }); ref.push({pushTime: Firebase.ServerValue.TIMESTAMP}); What the console.log prints is off by ~300ms from what is in fact stored at the path. A: The behaviour that you are seeing is the expected behaviour. It occurs because the child_added event is fired locally, using a value for ServerValue.TIMESTAMP that's determined using the local time and the offset of the local clock from the server clock. However, it's not possible to account for the time it will take for the request to arrive at the server - hence the differing timestamps. If you also listen to the child_changed event, it will fire with a snapshot that includes the correct time once the write is complete.
doc_23529299
* *I have an android app which has custom like button. *When this button is hit, I am currently calling login to facebook with "publish_stream" permission. *Upon login, the access token is passed to the backend where we use graph api to like it for the user and accumulate all the like counts. *Effective 1 May 2015 - FB has blocked the api as "publish_actions" permission is missing. *The step to resolve seems like adding "publish_actions" to the application code and asking facebook to review the same. My questions is that - If I do not change my code and want to support the applications already installed, and if we go to Facebook and submit for review. While submitting, add publish_actions on facebook developer. Will it work? OR the only way is to add permission and upgrade the app? Update: From the reply - it is clear that current app will not work as is. There are 2 options which I see: * *add publish_actions permission and go for review with facebook. *If I don't want to add this permission - I can add the facebook like button to my view using facebook sdk. Link to add like is here However, not too sure what are the customization options on this button? a. Can I override this view with my own image? b. What are the options FB provides? In the document here read about this: public void setLikeViewStyle(Style likeViewStyle) - but no pictorial depiction is shown. A: You need to update the app and ask for publish_actions. publish_streams was deprecated several years ago and finally removed end of April this year