id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_3400
For example: Code Item Date Price1 Price2 -------------------------------------------------------------- 0000 10000 2020-04-10 00:00:00.000 55.000000 55.000000 0000 10000 2020-04-04 00:00:00.000 55.000000 55.000000 0000 10000 2020-03-07 00:00:00.000 55.000000 55.000000 0000 10000 2020-03-04 00:00:00.000 55.000000 55.000000 0000 10000 2020-02-04 00:00:00.000 48.000000 48.000000 The SQL syntax written so far, returns and orders the records by DESC, via an inner join of the 2 tables, but we need to get the 2 most recent records, having as parameter the date and the record entry. SELECT t0.Code, t1.Item, t0.Date, t1.Price AS price1, t1.Price AS price2 FROM dbo.INV AS t0 INNER JOIN dbo.INV1 AS t1 ON t0.RecEntry = t1.RecEntry WHERE (t1.Price <> 0) ORDER BY t1.Date DESC Using SELECT TOP * 2 for example, after the order by doesn't work, probably due to the syntax, as we never wrote a similar query before. Any hints are appreciated! Thanks. A: Try this SELECT top 2 t0.Code, t1.Item, t0.Date, t1.Price AS price1, t1.Price AS price2 FROM dbo.INV t0 INNER JOIN dbo.INV1 t1 ON t0.RecEntry = t1.RecEntry WHERE (t1.Price <> 0) ORDER BY t1.Date DESC
doc_3401
myPowershellScript.ps1 function GetLatestText { return "Hello World" } I was trying to use the For /F function. There may be a better way. myBatch.bat for /f "delims=" %%a in (' powershell -command "\\Rossi2\Shared\myPowershellScript.ps1" ') do set "var=%%a" echo %var% Desired output, would be to have 'Hello World' output in the cmd window. I was trying to use the batch file as some old processes use them. For newer processes I do everything in PowerShell and it works fine. The current output is blank. A: * *Your syntax for trying to capture output from a PowerShell script from a batch file is correct (assuming single-line output from the script),[1] except that it it is more robust to use the -File parameter of powershell.exe, the Windows PowerShell CLI than the -Command parameter. * *See this answer for when to use -File vs. -Command. *Your problem is with the PowerShell script itself: * *You're defining function Get-LatestText, but you're not calling it, so your script produces no output. *There are three possible solutions: * *Place an explicit call to Get-LatestText after the function definition; if you want to pass any arguments received by the script through, use Get-LatestText @args *Don't define a function at all, and make the function body the script body. *If your script contains multiple functions, and you want to call one of them, selectively: in your PowerShell CLI call, dot-source the script file (. <script>), and invoke the function afterwards (this does require -Command): for /f "delims=" %%a in (' powershell -Command ". \"\\Rossi2\Shared\myPowershellScript.ps1\"; Get-LatestText" ') do set "var=%%a" echo %var% [1] for /f loops over a command's output line by line (ignoring empty lines), so with multiline output only the last line would be stored in %var% - more effort is needed to handle multiline output. A: You can combine the batch and the powershell in single file (save this as .bat ): <# : batch portion @echo off & setlocal for /f "tokens=*" %%a in ('powershell -noprofile "iex (${%~f0} | out-string)"') do set "result=%%a" echo PS RESULT: %result% endlocal goto :EOF : end batch / begin powershell #> function GetLatestText { return "Hello World" } write-host GetLatestText
doc_3402
My main concern is the concurrent connection. I would like to limit the number of connection, so whatever happens, the crawler would never use more than 15 concurrent connections. The server block the IP whenever the limit of 25 concurrent connections by IP is reached and for some reason, I can't change that on the server side, so I have to find a way to make my script never use more than X concurrent connections. Is this possible? Or maybe I should rewrite the whole thing in another language? Thank you, any help is appreciated! A: well you can use curl_set_opt(CURLOPT_MAXCONNECTS, 15); to limit the number of connections. But you might also want to make a simple connection manager if that doesnt do it for you. A: Maybe write a simple connection table: target_IP | active_connections 1.2.3.4 10 4.5.6.7 5 each curL call would increase the number of connections, each close decrease it. You could store the table in a mySQL table, or a Memcache for speed. When you encounter a IP that already has its maximum connections, you would have to implement a "try later" queue.
doc_3403
from sklearn.model_selection import GridSearchCV parameters = [{'n_estimators': [100, 200], 'max_features': ['auto', 'sqrt', None], 'max_depth': [10, 20, 30, None], 'criterion': ['gini', 'entropy'], 'min_samples_split': [5, 10,15], 'min_samples_leaf': [1,4,6], 'bootstrap': [True, False]}] grid_search = GridSearchCV(estimator = classifier, param_grid = parameters, scoring = 'accuracy', cv = 5, n_jobs = -1) #n_jobs to optimise grid search process grid_search.fit(X_train, Y_train) best_accuracy = grid_search.best_score_ best_parameters = grid_search.best_params_ print("\n") print("Results for Grid Search") print("Best Accuracy: {:.2f} %".format(best_accuracy*100)) print("Best Parameters:", best_parameters) A: GridSearchCV enables passing a list of scoring functions, provided that you specify a single scoring function to which the best parameters will be chosen to refit the model. grid_search = GridSearchCV( estimator=classifier, param_grid=parameters, scoring=['accuracy', 'f1', 'precision', 'recall'], refit="accuracy", # Or any other value from `scoring` list ) Then you can access the entire cross validation results in the cv_results_ attribute. It can be easier to first pack the cv_results_ as a pandas DataFrame and then access the row corresponding to best_index_ attribute: cv_results = pd.DataFrame(grid_search.cv_results_) best_model_results = cv.results.loc[grid_search.best_index_] The you get a Series indexed by score names, so you can access, for example, "mean_test_recall", "mean_test_f1", etc. Note that, for your question, specificity is not a built-in scoring name, but you can also supply GridSearchCV with custom metrics, so it's possible to pass a callable calculating it (say by using confusion matrix)
doc_3404
Firstly, I have created a new Rails app called "MicroTwitter": rails new MicroTwitter -T Here the -T option to the rails command tells Rails not to generate a test directory associated with the default Test::Unit framework. After that, I added a few lines on the Gemfile: group :development do gem 'rspec-rails' end group :test do gem 'rspec' gem 'webrat' end And so I did a bundle install But after minutes of waiting, It was stuck up. C:\Users\MDF\Desktop\apps\rails apps\MicroTwitter>bundle install Fetching source index for http://rubygems.org/ Using rake (0.8.7) Using abstract (1.0.0) Using activesupport (3.0.5) Using builder (2.1.2) Using i18n (0.5.0) Using activemodel (3.0.5) Using erubis (2.6.6) Using rack (1.2.2) Using rack-mount (0.6.14) Using rack-test (0.5.7) Using tzinfo (0.3.26) Using actionpack (3.0.5) Using mime-types (1.16) Using polyglot (0.3.1) Using treetop (1.4.9) Using mail (2.2.15) Using actionmailer (3.0.5) Using arel (2.0.9) Using activerecord (3.0.5) Using activeresource (3.0.5) Using bundler (1.0.11) Using diff-lcs (1.1.2) Using nokogiri (1.4.4.1) Using thor (0.14.6) Using railties (3.0.5) Using rails (3.0.5) Using rspec-core (2.5.1) Using rspec-expectations (2.5.0) Using rspec-mocks (2.5.0) Using rspec (2.5.0) Using rspec-rails (2.5.0) Using sqlite3 (1.3.3) It stuck up just to sqlite3. To those who knew how to solve this problem, Your help is highly appreciated. Thanks! A: Ok, I found out the problem. I for got to install the "webrat" gem. After I installed webrat: gem install webrat and did a bundle install again, It works like magic! I guess I have to be more careful next time. Thank you for all the answers and comments! :)
doc_3405
import geemap import ee ee.Authenticate() ee.Initialize() img=ee.ImageCollection("LANDSAT/LC08/C02/T1_TOA") collection = ee.ImageCollection("LANDSAT/LC08/C02/T1_TOA").select(['B4', 'B3', 'B2']).filterDate('2019-12-30', '2019-12-31') geemap.ee_export_image_collection_to_drive(collection, folder='GoogleEarth', scale=10) When I run it, nothing gets downloaded in my drive. Has anyone encountered this problem?
doc_3406
Pseudo code is : @TransactionAttribute(TransactionAttributeType.REQUIRED) public someMethod{ dao.update(someObject); sendToMDB(someObjectID); << sending ID of above updated object dao.doSomeThingMore(); } In the MDB i am just fetching the above updatedObject : onMessage(){ .... dao.find(someObjectID); } The problem I am facing is when i retrieve someObject in MDB its retrieving the old values of someObject and not the updated ones!!! I tried to take away all methods in MDB and put all together in method someMethod() and it works all fine. I even tried using flush() & clear() after dao.update() but still same problem. Please help. Thanks in advance. A: Most probably you need to create transactional queue session. QueueSession createQueueSession( QueueConnection qu ) throws JMSException { return qu.createQueueSession(true, -1); } Note here true parameter will make session transactional. Here -1 just dummy parameter when you want to neglect acknowledgement param , you may use predefined ack modes though. Also there may be some transactional configurations you can set in your applications server console if needed to make calls transactional.
doc_3407
What I wish to do is that when the user clicks a button, a javascript code linked to it should open up in an editor on the same webpage. This would aid the users to see how the code is working and give them scope to modify and learn. I know its not a constructive question but any help is appreciated! Thanks! A: you can just wantch here how it is done They made it with knockout MVVM but you can use angular or anything else you like. A: I used tags to store my code and displayed it using codemirror's setValue property mentioned by @georg.
doc_3408
$ch = curl_init(); $url = "www.sample.com"; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8", "Accept:application/json, text/javascript, */*; d=0.2")); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_COOKIE, 'auth_tkt=myToken; anotherArg=234'); $result = curl_exec($ch); curl_close($ch); Now, I got to translate and perform this in R. I tried with the following, however, I get status 403 back, so I guess the headers or the cookies are not set properly: library(httr) url <- "www.sample.com" res <- GET(url, add_headers(`Content-Type` = "application/json", charset="utf-8", Accept = c("application/json", "text/javascript", "*/*"), d="0.2"), set_cookies(auth_tkt="myToken", anotherArg="234") A: This: httr::GET( url = "http://httpbin.org/", httr::set_cookies( auth_tkt = "myToken", anotherArg = 234L ), httr::content_type("application/json; charset=utf-8"), httr::accept("application/json, text/javascript, */*; d=0.2"), httr::verbose() ) is almost the same thing @Alberto posted except it uses some additional httr helper functions and sets the values correctly. I made it verbose() so I could show what was sent: -> GET / HTTP/1.1 -> Host: httpbin.org -> User-Agent: libcurl/7.54.0 r-curl/3.2 httr/1.3.1 -> Accept-Encoding: gzip, deflate -> Cookie: auth_tkt=myToken;anotherArg=234 -> Content-Type: application/json; charset=utf-8 -> Accept: application/json, text/javascript, */*; d=0.2 @Alberto's code ends up sending: -> GET / HTTP/1.1 -> Host: httpbin.org -> User-Agent: libcurl/7.54.0 r-curl/3.2 httr/1.3.1 -> Accept-Encoding: gzip, deflate -> Cookie: auth_tkt=myToken;anotherArg=234 -> Accept: application/json, text/xml, application/xml, */* -> Content-Type: application/json -> charset: utf-8 -> Accept1: application/json -> Accept2: text/javascript -> Accept3: */* -> d: 0.2 which does not fully mimic the PHP example code. A: You have a typo in the url variable on the 3rd line, here's the correct code: library(httr) url <- "www.sample.com" res <- GET(url, add_headers(`Content-Type` = "application/json", charset="utf-8", Accept = c("application/json", "text/javascript", "*/*"), d="0.2"), set_cookies(auth_tkt="myToken", anotherArg="234")
doc_3409
0xb48daed9 <+3479>: lea -0xc(%ebp),%esp I am not very comfortable with Assembly instructions. Actually I am getting a SIGABRT in my application and the culprit, it seems, is this particular assembly instruction. A: On the mechanical level, the instruction lea -0xc(%ebp),%esp adds -0xc (that is: -12) to %ebp and writes the result to %esp. On the logical level, it allocates a called function's stack frame. I'd expect to see it in a context similar to this: push %ebp ; save previous base pointer mov %esp,%ebp ; set %ebp = %esp: old stack pointer is new base pointer lea -0xc(%ebp),%esp ; allocate 12 bytes for local variables %ebp and %esp are the stack pointer registers. %ebp points to the base of the stack frame and %esp to its "top" (actually the bottom because the stack grows downward), so the lea instruction moves the stack pointer 12 bytes below the base, staking a claim of 12 bytes for local variables. Doing this after saving the old base pointer and setting the new base pointer to the old stack pointer pushes a new frame of 12 bytes onto the call stack. It seems unlikely that this instruction itself causes a trap, but in the event of a stack overflow, the allocated stack frame will be invalid and explosions are expected when trying to use it. My suspicion is that you have a runaway recursive function. Another possibility, as @abligh mentions, is that the stack pointer became corrupted somewhere along the line. This can happen, among other things, if a buffer overflow happens in a stack-allocated buffer so that a previously saved base pointer is overwritten with garbage. Upon return from the function, the garbage is restored in lieu of the overwritten base pointer, and a subsequent function call will not have anything sensible with which to work. A: lea -0xc(%ebp),%esp will: * *compute the effective address [1] of %ebp - 12, and *store it in %esp It has been/is used to perform fast arithmetic with memory operands. According to the Intel manual, it may throw an exception if the source operand is not a memory location. [1] "Effective address", in Intel's parlance, is an offset which is supplied either as a static value or an address computation of the form: Offset = Base + (Index * Scale) + Displacement
doc_3410
SQL query: 3 column table, searching "John" 's max value returning City only. Data: Name | City | Value <br> John | LDN | 50 <br> Joey | MCR | 12<br> Dave | BHM | 5<br> John | NTH | 56 <br> Desired result: NTH (4th row) How can I achieve this? Thanks in advance. A: You can use row_number() select city from ( select *, row_number() over(partition by name order by value desc) as rn from tablename )A where rn=1 and name='John' Alternatively, select city from tablename t where name='John' and value = (select max(value) from tablename t1 where t.name=t1.name) A: You can use order by and some way of limiting the results: select t.* from t order by value desc fetch first 1 row only; Some databases use select top (1) or limit 1 to limit to a single row.
doc_3411
We have a use case where we are plotting 3 values on the same graph. We want to setup alerting that alerts us when there is a difference of configured percentage between any of the values. For example lets say. value A is 100, value B is 105, value C is 103. If the configured percentage is 10%, we should not get any alert. value A is 100, value B is 105, value C is 103. If the configured percentage is 4%, we should get alert that there is a bigger discrepancy than the configured between any values. Is that possible? Thanks a lot in advance.
doc_3412
I'm not good at code. Can someone explain to me how to create a function in python? ex : given a table like this text similarity polarity ABCDD 0.6 POSITIF ASDAS 0.4 NEGATIF ASGAS 1.0 POSITIF So , i want to make a function with if condition. The condition is like this : If the value in column dataframe ['similarity'] is greater than 0.5 , and the value in other column dataframe ['polarity'] is "POSITIF". Then , i want to append a new line of text to a .txt file. Can someone explain how to make that possible? I've tried myself , but i guess it's a total mess if (df['similarity'] > 0.5) & df['polarity'].str.contains('POSITIF').any(): with open("text.txt","a") as myfile: myfile.write("text appended \n") A: It depends what you want to do exactly. If you need to loop over all the rows, useiterrows (Warning, it is slow!): with open("text.txt","a") as myfile: for key, row in df.iterrows(): if (row['similarity'] > 0.5) and ('POSITIF' in row['polarity']): myfile.write("text appended \n") If you want to append the line if any row matches both conditions: if (df['similarity'].gt(0.5) & df['polarity'].str.contains('POSITIF')).any(): with open("text.txt","a") as myfile: myfile.write("text appended \n")
doc_3413
So I'm brand new to Angular. I'd like a clean way to reference the path to my assets based on NODE_ENV. I'd like to do this: // Utility class class Utilities { public static getAssetsPath(env) { return env == 'dev' ? 'src/assets' : '../assets'; } private constructor() {} } // Component class import {Utils} from 'shared/utilities/utils'; class MyComponent { const ENVIRONMENT = process.env.NODE_ENV; constructor( private route: ActivatedRoute, private router: Router ) { this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { const eventUrl = /(?<=\/).+/.exec(event.urlAfterRedirects); const currentRoute = (eventUrl || []).join(''); this.myIcon = Utils.getAssetPath(ENVIRONMENT) + '/icons/myIcon.png'; } }); } } But I'm guessing there's a more Angular way to do this so every component will have access to it without having to import the Utilities class. Like a provider, for instance. Is my solution not the Angular-way to do it? Thanks for any pro tips. A: In your component, you add where is the image like this <img src="../assets/icons/myIcon.png"/> You shouldnΒ΄t have problems when you deploy your application using the following command ng build A: One way to approach this is to create a component that represents an image and pass the image path to the component. Use the component's selector in the html like so: <my-image-component [path]="'/icons/myIcon.png'"></my-image-component> This way the utilities class only has to be injected in the image component.
doc_3414
I want the owl to change into random colors any suggestions? This is an exercises from Reas and Fry's processing book. void setup ( ) { size(700,500); background(200); smooth( ); frameRate(10); } void pick () { color (random(255),random(255),random(255)); } void draw ( ) { owl(35,100); } void owl (int x, int y, color z) { pick (); stroke(0) ; strokeWeight(70) ; line(x, -35+y, x, -65+y) ; // body noStroke() ; fill(255) ; ellipse(-17.5+x, -65+y, 35, 35) ; // left eye dome ellipse( 17.5+x, -65+y, 35, 35) ; // right eye dome arc(0+x, -65+y, 70, 70, 0, PI) ; fill(0) ; ellipse(-14+x, -65+y, 8, 8) ; // left eye ellipse( 14+x, -65+y, 8, 8) ; // right eye quad(0+x, -58+y, 4+x, -51+y, x, -44+y, -4+x, -51+y) ; } A: v.k. is actually right, although he did not tell you why the colour does not change. The problem is of course that you are calling owl with two parameters while it needs three. As far as I understand you want to pick the random colour with the pick() method, thus you don't need the third parameter in there. void owl (int x, int y, color z) { should be void owl (int x, int y) { Also you need to somehow fill (or stroke) things with the random colour you have correctly created. The problem is, as long as you don't pass it in a fill() or a stroke() method, it will not colour anything... So you need to have that colour somehow in the owl() method, you thus return it from the pick() command and use it like this: color pick () { return color (random(255),random(255),random(255)); } and you retrieve it in the owl method and store it in a variable so that you can use it: color z = pick(); then to change the colour of the eyes you change fill(0); to: fill(z); Here's the final code in case I have confused you: void setup ( ) { size(700,500); background(200); smooth( ); frameRate(10); } color pick () { return color (random(255),random(255),random(255)); } void draw ( ) { owl(35,100); } void owl (int x, int y) { color z = pick(); stroke(0) ; strokeWeight(70) ; line(x, -35+y, x, -65+y) ; // body noStroke() ; fill(255) ; ellipse(-17.5+x, -65+y, 35, 35) ; // left eye dome ellipse( 17.5+x, -65+y, 35, 35) ; // right eye dome arc(0+x, -65+y, 70, 70, 0, PI) ; fill(z) ; ellipse(-14+x, -65+y, 8, 8) ; // left eye ellipse( 14+x, -65+y, 8, 8) ; // right eye quad(0+x, -58+y, 4+x, -51+y, x, -44+y, -4+x, -51+y) ; } A: color is a Processing Datatype for colors. It is aware of colorMode(). The problem is simple, your own method is expecting 3 parameters void owl (int x, int y, color z) {... and you are calling it with 2 owl(35,100). If you say: owl(35,100, color(random(255),random(255),)random(255)); it will work.
doc_3415
we are trying to provide Edit Feature in that when we give <---Field> Components its working fine also able to see SAVE button but when it <---Input> Components no SAVE button is visible and Component does take inputs. Code when Field Components are used import React, { Component } from 'react'; import { Components } from 'admin-on-rest'; const CustomerEdit = (props) => ( <Edit {...this.props}> <TabbedForm> <FormTab label="Profile"> <TextField source="firstName" /> <TextField source="middleName" /> <TextField source="lastName" /> </FormTab> <FormTab label="Address"> <ReferenceManyField addLabel={false} reference="CustomerAddresses" target="customerProfileId"> <Datagrid> <EditButton/> <TextField source="id" /> <TextField source="line1" /> <TextField source="pinCode" /> </Datagrid> </ReferenceManyField> </FormTab> </TabbedForm> </Edit> ); export default CustomerEdit; Code when Input Components are used import React, { Component } from 'react'; import { Components } from 'admin-on-rest'; const CustomerEdit = (props) => ( <Edit {...this.props}> <TabbedForm> <FormTab label="Profile"> <TextInput source="firstName" /> <TextInput source="middleName" /> <TextInput source="lastName" /> </FormTab> <FormTab label="Address"> <ReferenceManyField addLabel={false} reference="CustomerAddresses" target="customerProfileId"> <Datagrid> <EditButton/> <TextInput source="id" /> <TextInput source="line1" /> <TextInput source="pinCode" /> </Datagrid> </ReferenceManyField> </FormTab> </TabbedForm> </Edit> ); export default CustomerEdit; This is App.js import React from 'react'; import PropTypes from 'prop-types'; // redux, react-router, redux-form, saga, and material-ui // form the 'kernel' on which admin-on-rest runs import { combineReducers, createStore, compose, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import createHistory from 'history/createHashHistory' import { Switch, Route } from 'react-router-dom' import { ConnectedRouter, routerReducer, routerMiddleware } from 'react-router-redux'; import { reducer as formReducer } from 'redux-form'; import createSagaMiddleware from 'redux-saga'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; // prebuilt admin-on-rest features import { adminReducer, localeReducer, crudSaga, TranslationProvider, } from 'admin-on-rest'; import restClient from './restClient'; import GenericList from './ui/List'; import CustomerEdit from './ui/views/customer/customerEdit'; const reducer = combineReducers({ admin: adminReducer([{ name: 'CustomerProfiles' }, { name: 'CustomerAddresses' }]), locale: localeReducer(), form: formReducer, routing: routerReducer, }); const sagaMiddleware = createSagaMiddleware(); const history = createHistory(); const store = createStore(reducer, undefined, compose( applyMiddleware(sagaMiddleware, routerMiddleware(history)), window.devToolsExtension ? window.devToolsExtension() : f => f, )); sagaMiddleware.run(crudSaga(restClient)); const App = () => ( <Provider store={store}> <TranslationProvider messages={messages}> <ConnectedRouter history={history}> <MuiThemeProvider> <Switch> <Route exact path="/profile" hasCreate render={ (routeProps) => <GenericList resource="CustomerProfiles" {...routeProps} /> } /> <Route exact path="/profile/:id" hasEdit render={ (routeProps) => <CustomerEdit resource="CustomerProfiles" {...routeProps} /> } /> </Switch> </MuiThemeProvider> </ConnectedRouter> </TranslationProvider> </Provider> ); export default App This in case of Input Components No Data from Backend for CustomerAddress and also no Save Button This in Case of Field Component when we use <---FIELD/> Component A: Don't you have an error in the console about ReferenceManyInput ? This component does not exist. I checked the documentation and we indeed included it in the Resources chapter. It will be fixed soon. For referencing many other resources, you should use the ReferenceArrayInput. However, it does not support Datagrids. There are not components allowing you to edit related resources yet.
doc_3416
Is there a way using react native to when media is played, have is NOT played on the screen and only through outputs such as the USB-C?
doc_3417
* *AuthorID -> primary key *FirstName *LastName Table name: Titles * *ISBN -> primary key *BookTitle *EditionNumber *CopyRight Table name: AuthorISBN * *ISBN -> foreign key *AuthorID -> foreign key I can do: var AuthorsAndISBNs = from author in database.Author join books in database.AuthorISBN on author.AuthorID equals books.AuthorID orderby author.LastName, author.FirstName select new { author.FirstName, author.LastName, books.ISBN }; However, I cannot do: var authorsAndTitles = from title in database.Titles from book in title.AuthorISBN let author = book.Author orderby author.LastName, author.FirstName, title.BookTitle select new { author.FirstName, author.LastName, title.BookTitle }; I thought LINQ automatically creates properties based on foreign-key relationships, which enables you to easitly access related rows in other tables:( Author has one-to-many relationship with AuthorISBN which has 'many-to-one' relationship with Titles Please help! been stuck on this for days:'( THANK YOU! A: In Order for LINQ let you access related rows in other tables, every table MUST have a PrimaryID. The issue was that 'AuthorISBN' Table did not have a primaryID, therefore no properties were being created:)
doc_3418
http://www.eclipse.org/downloads/ Eclipse IDE for C/C++ Developers (includes Incubating components) I can not find the bin directory containing gdb. A: Follow below steps: * *Install Eclipse *Install PDE *Install CDT -done-
doc_3419
public class MyClass { private Boolean started = false; private Handler handler1 = new Handler(); private Handler handler2 = new Handler(); private Runnable runnable1 = new Runnable() { @Override public void run() { sendMessage("blah"); } }; private Runnable runnable2 = new Runnable() { @Override public void run() { sendMessage("blah blah"); if (started) { triggerMessageSending(); } } }; } public void startMessageSending(){ triggerMessageSending(); } private void triggerMessageSending(){ started = true; handler1.postDelayed(runnable1, 500); handler2.postDelayed(runnable2, 1000); } public void stopMessageSending(){ started = false; handler1.removeCallbacks(runnable1); handler2.removeCallbacks(runnable2); } } Here is my activity: public class MyActivity extends Activity { private MyClass myClass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); myClass = new MyClass(); myClass.startMessageSending(); } @Override protected void onStop() { super.onStop(); myClass.stopMessageSending(); } } Everything works fine for the first time. If I press back button and go to the previous activity and come back again(without exiting the app), the sendMessage method is called twice. This becomes three if I do it again. It calls the method as many times as I start this activity without exiting the app. If I exit the app and do this again, it works fine for the first time. What is the reason for this? Where am I wrong? A: Not sure about your business logic , but these are the problems that I can see in your code. * *If both the Runnable are doing the same job ( sendMessage ) what is the point in having two runnables? *In second Runnable runnable2, again the same is done. Only difference is check of boolean started which triggers triggerMessageSending() going for a loop Now MyClass object initiation is done in onCreate with triggerMessageSending() method, which initiates two handlers and then runnables NOTE: onStop() may or may not get called during activity life cycle . Check this link . I mean its not guaranteed. Do the myClass.stopMessageSending(); in onPause() and check So your message is called twice.
doc_3420
int b = 3; int* ptr = &b; //says something about cannot convert int* to type const int*& const int*& ptr_ref = ptr; Thanks in advance, 15 yr old C++ noob A: The issue is that the types do not match, and thus you cannot create a reference. int b = 3; int* ptr = &b; int*& ptr_ref = ptr; Is legal. int b = 3; const int* ptr = &b; const int*& ptr_ref = ptr; Is legal. int b = 3; int* ptr = &b; const int*& ptr_ref = ptr; Is a mismatch. G++'s error message might be helpful to you: error: invalid initialization of non-const reference of type 'const int*&' from an rvalue of type 'const int*' const int*& ptr_ref = ptr; ^ Essentially meaning, it had to create a const int* for this expression, which is an rvalue (essentially a temporary object), and thus you cannot hold a reference to it. A simpler way to put that is, you cannot do what you wrote for the same reason this is illegal: int& added = 3 + 2; Depending on your situation, you might solve this simply by removing the reference designation. Most compilers will output identical assembly with or without it, at least when optimized, due to their ability to figure out the fact your variable name is just an alias. There are even some cases references can perform worse, which depending on your intent, might be worth knowing - I was surprised to know it when I found out. A: ptr_ref is declared not as a const reference to pointer to int, but rather a reference to pointer to const int, so you have a type mismatch. You would have to do int* const& ptr_ref = ptr; A: A reference is inherently const, so there is no really point in defining it as int *& const ptr_ref = ptr When you talk about a const reference, it normally means a reference to a const, which is the definition you've used in your question. [edit] Edited my answer as I had put the const by mistake on the wrong side of the ampersand -- C++ doesn't forgive you [/edit]
doc_3421
select * from table where Date between '2010-01-01' and '2010-12-31' $result1 = mysql_query($query1) or die('Query failed: ' . mysql_error()); while ($line = mysql_fetch_assoc($result1)) { echo "\t\t<tr>\n"; $Data['Date'] = $line['Date']; $Data['Time'] = $line['Time']; $Data['Serial_No'] = $line['Serial_No']; $Data['Department'] = $line['Department']; $Data['Team'] = $line['Team']; foreach ($Data as $col_value) { echo "\t\t\t<td>$col_value</td>\n"; }; echo "\t\t</tr>\n"; } A: Try adding an index to your date column. Also, it's a good idea to learn about the EXPLAIN command. As mentioned in the comments above, 1 second is still pretty long for your results. You might consider putting all your output into a single variable and then echoing the variable once the loop is complete. Also, browsers wait for tables to be completely formed before showing them, so that will slow your results (at least slow the process of building the results in the browser). A list may work better - or better yet a paged view if possible (as recommended in other answers). A: It's not PHP that's causing it to be slow, but the browser itself rendering a huge page. Why do you have to display all that data anyway? You should paginate the results instead. Try constructing a static HTML page with 20,000 table elements. You'll see how slow it is. You can also improve that code: while ($line = mysql_fetch_assoc($result1)) { echo "\t\t<tr>\n"; foreach ($line as $col_value) { echo "\t\t\t<td>$col_value</td>\n"; flush(); // optional, but gives your program a sense of responsiveness } echo "\t\t</tr>\n"; } In addition, you should increase your acceptance rate. A: You could time any steps of the script, by echoing the time before and after connecting to the database, running the query and outputting the code. This will tell you how long the different steps will take. You may find out that it is indeed the traffic causing the delay and not the query. On the other hand, when you got a table with millions of records, retreiving 20000 of them can take a long time, even when it is indexed. 20 minutes is extreme, though...
doc_3422
SELECT SUM(CASE WHEN orders.status = "send" THEN 1 ELSE 0 END) countSend, SUM(CASE WHEN orders.status = "pending" THEN 1 ELSE 0 END) countPending FROM orders LEFT OUTER JOIN order_posts AS op ON op.order_id = orders.id LEFT OUTER JOIN posts AS p ON p.id = op.post_id WHERE (orders.id LIKE "%Shop 3%") OR (p.title LIKE "%Shop 3%") GROUP BY orders.id LIMIT 1 A: I'm not quite sure what you are trying to accomplish, but the GROUP BY may not be necessary. The following will always return one row: SELECT SUM(o.status = 'send') as countSend, SUM(o.status = 'pending') as countPending FROM orders o LEFT OUTER JOIN order_posts op ON op.order_id = o.id LEFT OUTER JOIN posts p ON p.id = op.post_id WHERE (o.id LIKE '%Shop 3%') OR (p.title LIKE '%Shop 3%'); If the WHERE clause filters everything out, you will still get one row, with NULL values. Use COALESCE() to return 0 instead: SELECT COALESCE(SUM(o.status = 'send'), 0) as countSend, COALESCE(SUM(o.status = 'pending'), 0) as countPending A: You can use coalesce() which will return the value the first expression evaluates to, when that value isn't NULL or the value of the second expression. (This also goes on for more than two expressions but in your case it's only two). SELECT coalesce(sum(CASE WHEN orders.status = "send" THEN 1 ELSE 0 END), 0) countSend, coalesce(sum(CASE WHEN orders.status = "pending" THEN 1 ELSE 0 END), 0) countPending ...
doc_3423
Error in .local(conn, statement, ...) : could not run statement: The used command is not allowed with this MySQL version library(readxl) library(RMySQL) library(DBI) mydb = dbConnect(RMySQL::MySQL(), host='<ip>', user='username', password='password', dbname="db",port=3306) setwd("<directory path>") file.list <- list.files(pattern='*.xlsx') print(file.list) dat = lapply(file.list, function(i){ print(i); x = read_xlsx(i,sheet=NULL, range=cell_cols("A:D"), col_names=TRUE, skip=1, trim_ws=TRUE, guess_max=1000) x$file=i x }) df = do.call("rbind.data.frame", dat) dbWriteTable(mydb, name="table_name", value=df, append=TRUE ) dbDisconnect(mydb) I checked the definition of the dbWriteTable function and looks like it is using load data local inpath to store the data in the database. As per some other answered questions on Stackoverflow, I understand that the word local could be the cause for concern but since it is already in the function definition, I don't know what I can do. Also, this statement is using "," as separator. But my data has "," in some of the values and that is why I was interested in using the dataframes hoping that it would preserve the source structure. But now I am not so sure. Is there any other way/function do write the dataframe to the MySQL tables? A: I solved this on my system by adding the following line to the my.cnf file on the server (you may need to use root and vi to edit!). In my this is just below the '[mysqld]' line local-infile=1 Then restart the sever. Good luck! A: You may need to change dbWriteTable(mydb, name="table_name", value=df, append=TRUE ) to dbWriteTable(mydb, name="table_name", value=df,field.types = c(artist="varchar(50)", song.title="varchar(50)"), row.names=FALSE, append=TRUE) That way, you specify the field types in R and append data to your MySQL table. Source:Unknown column in field list error Rmysql
doc_3424
But I found an issue, sometimes it does not work as expected. For example, here I have a model with two fields: public int A { get; set; } public bool B { get; set; } Then my request payload looks like following: { "A": 123.4, "B": true } Obviously the A is in a invalid format, it should be int but I gave it a float. So I got an error in ModelState: Input string '123.4' is not a valid integer. Path 'A', line x, position x.. This totally make sense. But another error occurs in the ModelState at the same time: Unexpected token when deserializing object: Boolean. Path 'B', line x, position x.. It seems that when A is not an int, C# will have errors in deserializing the rest part of the json. How could I avoid this? I hope there's only the first error in the ModelState. Thank you all! ------------------------------EDIT-------------------------------- Many thanks for the help. I'd like to add some comments here. For sure I used ModelState.IsValid to check if the payload is valid. And the result is false. Which is correct. But the mistake here is, only the first field A is invalid, but B is valid. So I wish to have only A's error in the ModelState. A: You may try this way if ModelState.IsValid is not working properly: private int _a; public int A { get { return _a; } set { bool success = Int32.TryParse(value.ToString(), out int number); if (success) { _a = number; } } } if not using .net core 3 then just declare int number; above the try parse and remove the int from there int number bool success = Int32.TryParse(value.ToString(), out number); if (success) { _a = number; } A: In order to check the validity (whether thats one property or all properties), i have always used the following if statement. This normally covers the request with 1 or more errors and returns a BadRequest status. if (!ModelState.IsValid) { return BadRequest(ModelState); } If you are interested in running tests and making sure all properties are correct, I can suggest using TestController type of class that would validate the data. Read Here for details on how to set that up. Lots of examples here.
doc_3425
I am aspiring to separate interface from implementation. This is primarily to protect code using a library from changes in the implementation of said library, though reduced compilation times are certainly welcome. The standard solution to this is the pointer to implementation idiom, most likely to be implemented by using a unique_ptr and carefully defining the class destructor out of line, with the implementation. Inevitably this raises concerns about heap allocation. I am familiar with "make it work, then make it fast", "profile then optimise" and such wisdom. There are also articles online, e.g. gotw, which declare the obvious workaround to be brittle and non-portable. I have a library which currently contains no heap allocations whatsoever - and I'd like to keep it that way - so let's have some code anyway. #ifndef PIMPL_HPP #define PIMPL_HPP #include <cstddef> namespace detail { // Keeping these up to date is unfortunate // More hassle when supporting various platforms // with different ideas about these values. const std::size_t capacity = 24; const std::size_t alignment = 8; } class example final { public: // Constructors example(); example(int); // Some methods void first_method(int); int second_method(); // Set of standard operations ~example(); example(const example &); example &operator=(const example &); example(example &&); example &operator=(example &&); // No public state available (it's all in the implementation) private: // No private functions (they're also in the implementation) unsigned char state alignas(detail::alignment)[detail::capacity]; }; #endif This doesn't look too bad to me. Alignment and size can be statically asserted in the implementation. I can choose between overestimating both (inefficient) or recompiling everything if they change (tedious) - but neither option is terrible. I'm not certain this sort of hackery will work in the presence of inheritance, but as I don't much like inheritance in interfaces I don't mind too much. If we boldly assume that I've written the implementation correctly (I'll append it to this post, but it's an untested proof of concept at this point so that's not a given), and both size and alignment are greater than or equal to that of the implementation, then does the code exhibit implementation defined, or undefined, behaviour? #include "pimpl.hpp" #include <cassert> #include <vector> // Usually a class that has behaviour we care about // In this example, it's arbitrary class example_impl { public: example_impl(int x = 0) { insert(x); } void insert(int x) { local_state.push_back(3 * x); } int retrieve() { return local_state.back(); } private: // Potentially exotic local state // For example, maybe we don't want std::vector in the header std::vector<int> local_state; }; static_assert(sizeof(example_impl) == detail::capacity, "example capacity has diverged"); static_assert(alignof(example_impl) == detail::alignment, "example alignment has diverged"); // Forwarding methods - free to vary the names relative to the api void example::first_method(int x) { example_impl& impl = *(reinterpret_cast<example_impl*>(&(this->state))); impl.insert(x); } int example::second_method() { example_impl& impl = *(reinterpret_cast<example_impl*>(&(this->state))); return impl.retrieve(); } // A whole lot of boilerplate forwarding the standard operations // This is (believe it or not...) written for clarity, so none call each other example::example() { new (&state) example_impl{}; } example::example(int x) { new (&state) example_impl{x}; } example::~example() { (reinterpret_cast<example_impl*>(&state))->~example_impl(); } example::example(const example& other) { const example_impl& impl = *(reinterpret_cast<const example_impl*>(&(other.state))); new (&state) example_impl(impl); } example& example::operator=(const example& other) { const example_impl& impl = *(reinterpret_cast<const example_impl*>(&(other.state))); if (&other != this) { (reinterpret_cast<example_impl*>(&(this->state)))->~example_impl(); new (&state) example_impl(impl); } return *this; } example::example(example&& other) { example_impl& impl = *(reinterpret_cast<example_impl*>(&(other.state))); new (&state) example_impl(std::move(impl)); } example& example::operator=(example&& other) { example_impl& impl = *(reinterpret_cast<example_impl*>(&(other.state))); assert(this != &other); // could be persuaded to use an if() here (reinterpret_cast<example_impl*>(&(this->state)))->~example_impl(); new (&state) example_impl(std::move(impl)); return *this; } #if 0 // Clearer assignment functions due to MikeMB example &example::operator=(const example &other) { *(reinterpret_cast<example_impl *>(&(this->state))) = *(reinterpret_cast<const example_impl *>(&(other.state))); return *this; } example &example::operator=(example &&other) { *(reinterpret_cast<example_impl *>(&(this->state))) = std::move(*(reinterpret_cast<example_impl *>(&(other.state)))); return *this; } #endif int main() { example an_example; example another_example{3}; example copied(an_example); example moved(std::move(another_example)); return 0; } I know that's pretty horrible. I don't mind using code generators though, so it's not something I'll have to type out repeatedly. To state the crux of this over-long question explicitly, are the following conditions sufficient to avoid UB|IDB? * *Size of state matches size of impl instance *Alignment of state matches alignment of impl instance *All five standard operations implemented in terms of those of the impl *Placement new used correctly *Explicit destructor calls used correctly If they are, I'll write enough tests for Valgrind to flush out the several bugs in the demo. Thank you to any who get this far! A: Yes, this is perfectly safe and portable code. However, there is no need to use placement new and explicit destruction in your assignment operators. Aside from it being exception safe and more efficient, I'd argue it's also much cleaner to just use the assignment operator of example_impl: //wrapping the casts const example_impl& castToImpl(const unsigned char* mem) { return *reinterpret_cast<const example_impl*>(mem); } example_impl& castToImpl( unsigned char* mem) { return *reinterpret_cast< example_impl*>(mem); } example& example::operator=(const example& other) { castToImpl(this->state) = castToImpl(other.state); return *this; } example& example::operator=(example&& other) { castToImpl(this->state) = std::move(castToImpl(other.state)); return *this; } Personally, I also would use std::aligned_storage instead of an manually aligned char array, but I guess thats a matter of taste.
doc_3426
const { Pool } = require('pg'); module.exports = new Pool({ user: 'postgres', password: 'xxxx', host: 'localhost', port: 5432, database:'gymmanager' }); When I was only running locally, everything was working fine, so I decided do deploy the app to Heroku. In order to do so, I've created a .env file with my environment variables for development. Here is the .env file: NODE_ENV=dev DB_USER='postgres' DB_PASS='xxxx' DB_HOST='localhost' DB_PORT=5432 DB_DATABASE='gymmanager' And I have changed my "db.js" file, that now looks like this: if(process.env.NODE_ENV !== 'dev') { const { Client } = require('pg'); const client = new Client({ connectionString: process.env.DATABASE_URL, ssl: true }); client.connect(); module.exports = client; } else { require('dotenv').config(); const { Pool } = require('pg'); module.exports = new Pool({ user: process.env.DB_USER, password: process.env.DB_PASS, host: process.env.DB_HOST, port: process.env.DB_PORT, database: process.env.DB_DATABASE, rejectUnauthorized: false }); } My app was deployed and is running smoothly on Heroku, but now, when I run 'npm start' locally, I get the following Error: (node:12989) UnhandledPromiseRejectionWarning: Error: self signed certificate at TLSSocket.onConnectSecure (_tls_wrap.js:1491:34) at TLSSocket.emit (events.js:315:20) at TLSSocket._finishInit (_tls_wrap.js:933:8) at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:691:12) I have tried several solutions... Ignore invalid self-signed ssl certificate in node.js with https.request? nodejs - error self signed certificate in certificate chain But none of them seems to work. Can anyone help me? Thanks in advance. :) A: Can you try, export NODE_TLS_REJECT_UNAUTHORIZED=0 on the command line? This sets the property globally rather than process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0; which set the property to that particular process. Hope you also executed npm config set strict-ssl false.
doc_3427
I'm doing this. I created a json file and added to mydirectory: { "hosting": { "public": "public", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ] } } Then cd mydirectory firebase init Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys ? What do you want to use as your public directory? public ? Configure as a single-page app (rewrite all urls to /index.html)? No ? Set up automatic builds and deploys with GitHub? No ? File public/404.html already exists. Overwrite? No i Skipping write of public/404.html ? File public/index.html already exists. Overwrite? No i Skipping write of public/index.html Next firebase deploy Deploy complete! Still seeing this: I'm following this tutorial: https://www.youtube.com/watch?v=Gl-qlxfTJHE but still doesn't work. Any help? A: This tutorial is old try command firebase deploy --only hosting Look this: https://firebase.google.com/docs/hosting/quickstart
doc_3428
I have tried some fixes but still the problem exists. Fix failed - Workload Install failed: `dotnet workload install --sdk-version 6.0.100-preview.7.21379.14 --no-cache --disable-parallel android-aot ios maccatalyst tvos macos maui wasm-tools --skip-manifest-update --source "https://api.nuget.org/v3/index.json" --source "https://pkgs.dev.azure.com/dnceng/public/_packaging/6.0.100-preview.7.21379.14-shipping-1/nuget/v3/index.json"` ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── ! There were one or more problems detected. Please review the errors and correct them and run maui-check again.
doc_3429
(1/7390) to (7390/7390) -> (data which is inserted/total data to be inserted) I am using Alamofire as HTTPClient at my app.So,how to insert data with progress into my realm object model after it has downloaded from server?Any help cause I am a beginner. I wont show the data model exactly,so,any example is appreciated.Let say my json string is. { { name : Smith, age : 23, address : New York }, { name : Adam, age : 22, address : Maimi }, { name : Johnny, age : 33, address : Las Vegas }, ... about 7392 records } A: Supposing you have a label for do this. Ok. Supposing you using MVVM pattern too. Ok. ViewController has label and "observe"(*) the ViewModel property 'progress' ViewModel has property 'progress' class ViewModel: NSObject { dynamic var progress: Int = 0 func save(object object: Object) { do { let realm = try Realm() try realm.write({ () -> Void in // Here your operations on DB self.progress += 1 }) } catch let error as NSError { ERLog(what: error) } } } In this way viewController is notified when "progress" change and you can update UI. Your VC should have a method like this, called by viewDidLoad for instance: private func setupObservers() { RACObserve(self.viewModel, keyPath: "progress").subscribeNext { (next: AnyObject!) -> Void in if let newProgress = next as? Int { // Here update label } } } Where RACObserve is a global function: import Foundation import ReactiveCocoa func RACObserve(target: NSObject!, keyPath: String) -> RACSignal { return target.rac_valuesForKeyPath(keyPath, observer: target) } (*) You can use ReactiveCocoa for instance. A: Katsumi from Realm here. First, Realm has no way to know the total amount of data. So calculating progress and notifying it should be done in your code. A total is a count of results array. Store count as a local variable. Then define progress variable to store the number of persisted. progress should be incremented every save an object to the Realm. Then notify the progress. let count = results.count // Store count of results if count > 0{ if let users = results.array { let progress = 0 // Number of persisted let realm = try! Realm() try realm.write { for user in users{ let userList=UserList() [...] realm.add(userList,update: true) progress += 1 // After save, increment progress notify(progress, total: count) } } } } So there are several ways to notify the progress. Here we use NSNotificationCenter for example: func notify(progress: Int, total: Int) { NSNotificationCenter .defaultCenter() .postNotificationName("ProgressNotification", object: self, userInfo: ["progress": progress, "total": total]) }
doc_3430
The Surfaceview has a method for that: surfaceView.getHolder().getSurface() Or is there no surface in TextureView? A: First step is to get the SurfaceTexture from the TextureView using the getSurfaceTexture() member function. SurfaceTexture surfaceTexture = textureView.getSurfaceTexture(); Then create the Surface object from the constructor Surface(SurfaceTexture surfaceTexture) that will accept the SurfaceTexture from your TextureView object. Surface surface = new Surface(surfaceTexture); For more information take a look at this issue report. It confirms that by constructing the Surface object in the manner I described it is possible to use the Surface from a TextureView with ExoPlayer. A: You can also now in the new versions add an "AnalyticsListener" to the "SimpleExoPlayer" instance, and implement the method "onRenderedFirstFrame" which has the surface as one of its parameters.
doc_3431
I've tried LineSeries.Mapping, but i don't know how to change ChartPoint color? ` lineSeries.Mapping = (value, point) => { if (value > 37) { //lineSeries.DataLabelsPaint = new SolidColorPaint(SKColors.Red); } else { } point.PrimaryValue = value; point.SecondaryValue = point.Context.Entity.EntityIndex; }; ` A: LiveCharts2 is based on LiveCharts but the API is a little bit different, this feature is now called ConditionalDraw and while it is not properly documented yet, you can get info about it here. // full code at // https://github.com/beto-rodriguez/LiveCharts2/blob/master/samples/ViewModelsSamples/General/ConditionalDraw/ViewModel.cs var series1 = new ColumnSeries<ObservableValue> { Name = "Mary", Values = new ObservableValue[] { ... } } .WithConditionalPaint(new SolidColorPaint(SKColors.Black.WithAlpha(50))) .When(point => point.Model?.Value > 5); I think changing the color of the labels is not supported by now, I will take deeper look into that and update the docs.
doc_3432
class ClassWithConstants { private const string ConstantA = "Something"; private const string ConstantB = ConstantA + "Else"; ... } Is there a risk of ending up with ConstantB == "Else"? Or do the assigments happen linearly? A: You will always get "SomethingElse". This is because ConstantB depends upon ConstantA. You can even switch lines and you'll get the same result. The compiler knows that ConstantB depends upon ConstantA and will handle it accordingly, even if you write it in partial classes. To be completely sure you can run VS Command Prompt and call ILDASM. There you can see the actual compiled code. Additionally, if you try to do the following you'll get a compile error: private const string ConstantB = ConstantA + "Else"; private const string ConstantA = "Something" + ConstantB; Error: The evaluation of the constant value for 'ConsoleApplication2.Program.ConstantB' involves a circular definition This sort of proves the compiler knows its dependencies. Added: Spec reference pointed out by Jon Skeet: This is explicitly mentioned in section 10.4 of the C# 3 spec: Constants are permitted to depend on other constants within the same program as long as the dependencies are not of a circular nature. The compiler automatically arranges to evaluate the constant declarations in the appropriate order. A: this string concatenation happens at compile-time because there are only string literals (search for constant folding in compiler construction literature). Don't worry about it. A: It should always evaluate to "SomethingElse"
doc_3433
The issue seem to originate from the fact that sr-latch is not describable using combinational logic. We are not sure if the task at hand is possible and were hoping to get some advice whether its possible and, if so, on the techniques used in such cases. Our description so far is like so: Require Import BenB. (* time elapsed from some point in past in microseconds as real numbers *) Definition T := R. (* durations in microseconds as real numbers *) Definition D := R. (* some arbitrary constant duration time-delta representing the oscialltion period / 2 *) Variable td: D. (* a type representing the io pins of the 555 IC *) Inductive Pin: Type := | output : Pin | voltage : Pin | trigger : Pin | threshold : Pin | reset : Pin | ground : Pin | control : Pin | discharge : Pin . (* predicate representing the logical state of the pin at certain time *) Variable isHigh : T -> Pin -> Prop. (* represents the if the current can flow through the 555 IC *) Definition ICPowered (t:T) := (isHigh t voltage) /\ ~(isHigh t ground) . Definition srLatch (t: T) := (isHigh t reset) /\ . Definition initialConditions := ICPowered . (* Definition describing the expected oscillating behaviour of the output signal *) Definition oscillationObligation := forall t: T, ((isHigh t output) -> ~(isHigh (t+d) output)) /\ (~(isHigh t output) -> (isHigh (t+d) output)) . Definition correctnessTheorem := initialConditions -> oscillationObligation . P.S. We assume that we are allowed to use forums as learning resource, and without a doubt will mention all the sources used in the work including any answer we may recive.
doc_3434
Typically I have a docker image with Cloud9 + appropriate stack and I run container per project. The way Cloud9 SDK is being installed is something along these lines: git clone git://github.com/c9/core.git c9sdk --depth 1 cd c9sdk ./scripts/install-sdk.sh ./server.js -p 5000 --listen 0.0.0.0 -a : -w ~/src/${project-name} A mild inconvenience is that I have Cloud9 instances sitting all over the place. Question: I wonder if there is a way to run the server.js to use ssh workspace from another machine / docker container? I know this can be done in online version. Some hints: I grepped through the sources a bit and it looks like the right way to do it is to create a custom client-workspace file with proper configs for c9.vfs.XXXX and then to run Cloud9 with --workspacetype option. But I just can't figure out how to set up the plugins to make Cloud9 run things over SSH as opposed to locally. I think I don't even need SSHFS for now because I can mount volumes with source code through docker.
doc_3435
I would simply sync this stream and check the flag from the host, but I need to do so from inside a CUDA graph. AFAIK I need to somehow encode this host-side error checking inside a cudaLaunchHostFunc callback. I am trying to understand how the cudaLaunchHostFunc function deals with exceptions. The documentation does not mention anything about it. Is there any way to catch of an exception thrown from inside the function provided to cudaLaunchHostFunc? Consider the following MWE: #include<iostream> #include <stdexcept> __global__ void kern(){ int id = blockIdx.x*blockDim.x + threadIdx.x; printf("Kernel\n"); return; } void foo(void* data){ std::cerr<<"Callback"<<std::endl; throw std::runtime_error("Error in callback"); } void launch(){ cudaStream_t st = 0; kern<<<1,1,0,st>>>(); cudaHostFn_t fn = foo; cudaLaunchHostFunc(st, fn, nullptr); cudaDeviceSynchronize(); } int main(){ try{ launch(); } catch(...){ std::cerr<<"Catched exception"<<std::endl; } return 0; } The output of this code is: Kernel Callback terminate called after throwing an instance of 'std::runtime_error' what(): Error in callback Aborted (core dumped) The exception is thrown but it appears that it is not propagated to the launch function. I would have expected the above launch() function to be equivalent (exception-wise) to the following: void launch(){ cudaStream_t st = 0; kern<<<1,1,0,st>>>(); cudaStreamSynchronize(st); foo(nullptr); // cudaHostFn_t fn = foo; // cudaLaunchHostFunc(st, fn, nullptr); cudaDeviceSynchronize(); } which does outputs the expected: Kernel Callback Catched exception Additionally, in the first case, all cuda calls return cudaSuccess. A: Thanks to the comments I understand now that my question is essentially the same as, for instance, this one: How can I propagate exceptions between threads? The techniques used to take exceptions from a worker thread to the main thread also apply here. For completion, the foo and launch functions in my dummy example could be rewritten as follows void foo(void* data){ auto e = static_cast<std::exception_ptr*>(data); std::cerr<<"Callback"<<std::endl; try{ throw std::runtime_error("Error in callback"); } catch(...){ *e = std::current_exception(); } } void launch(){ cudaStream_t st = 0; dataD = 0; kern<<<1,1,0,st>>>(); cudaStreamSynchronize(st); cudaHostFn_t fn = foo; std::exception_ptr e; cudaLaunchHostFunc(st, fn, (void*)&e); cudaDeviceSynchronize(); if(e) std::rethrow_exception(e); } Which prints the expected: Kernel Callback Catched exception
doc_3436
timestamp sell2 close 1597133400 [11959, 11971] 11760.0 1597133700 [11959, 11971] 11773.5 1597134000 [12339.6, 12457.12] 11752.0 1597134300 [12331.725, 12449.17] 11744.5 1597134600 [12320.7, 12438.04] 11734.0 1597134900 [12315.975, 12433.27] 11729.5 1597135200 [11923, 11935] 11732.0 1597135500 [11923, 11935] 11745.5 1597135800 [12336.45, 12453.94] 11749.0 1597136100 [11923, 11935] 11724.0 1597136400 [12354.825, 12472.49] 11766.5 1597136700 [12354.300000000001, 12471.960000000001] 11766.0 1597137000 [12351.15, 12468.78] 11763.0 1597137300 [12362.7, 12480.44] 11774.0 1597137600 [12361.65, 12479.380000000001] 11773.0 1597137900 [12351.15, 12468.78] 11763.0 1597138200 [12343.800000000001, 12461.36] 11756.0 1597138500 [12349.575, 12467.19] 11761.5 1597138800 [12329.625, 12447.050000000001] 11742.5 1597139100 [12317.025, 12434.33] 11730.5 1597139400 [12313.875, 12431.150000000001] 11727.5 1597139700 [12299.7, 12416.84] 11714.0 1597140000 [12277.125, 12394.050000000001] 11692.5 1597140300 [12291.825, 12408.890000000001] 11706.5 This is the code that I'm using, first it looks over all the pandas and then over a list on the column sell2 price_pool_short =[] index = data4.index for i in range(0,len(index)): y = [x for x in data4.sell2[data4.index==index[i]]][0] close = data4.close[index[i]] best_price = 0.007 for j in range(len(y)): if (y[j]>close) and (1-(close/y[j])>best_price): pps = y[j] break else: pps = close*1.05 price_pool_short.append(pps) and here is the desired output: [11959, 11959, 12339.6, 12331.725, 12320.7,12315.975,11923, 11923,12336.45,11923,12354.825,12354.300000000001,12351.15,12362.7, 12361.65,12351.15,12343.800000000001,12349.575,12329.625,12317.025, 12313.875,12299.7,12277.125,12291.825,12294.45,12297.6] I am trying to make it in a vectorized way but I am having a hard time on this, I tried something like: y = [x for x in data4.sell2][0] close = data4.close.to_numpy() best_price = 0.007 price_pool_short = np.where((y[j]>close) and (1-(close/y[j])>best_price),y[j],close*1.05) price_pool_short but it dosen't work. How can I make it in a way that consumes less time? im adding an example of data where we can see what should happend sell close timestamp 1597134300 [[[12331.725, 12449.17]]] 11744.5 1597134600 [[[12320.7, 12438.04]]] 11734.0 1597134900 [[[12315.975, 12433.27]]] 11729.5 1597135200 [[[11923, 11935]]] 11732.0 1597135500 [[[11923, 11935]]] 11745.5 1597135800 [[[12336.45, 12453.94]]] 11749.0 the output: [12331.725, 12320.7, 12315.975, 11923, 11923, 12336.45] here we have that the row 0,1,2 are on the else case(close1.05) then the 3 and the 4 works on the if sentence, the last one agin is close1.05 A: IIUC, explode your sell2 column: df1 = df.explode('sell2') msk = (df1['sell2'] > df1['close']) & (1-(df1['close'] / df1['sell2']) > best_price) price_pool_short = df1[msk].groupby(level=0)['sell2'].first().tolist() Output: >>> price_pool_short [11959, 11959, 12339.6, 12331.725, 12320.7, 12315.975, 11923, 11923, 12336.45, 11923, 12354.825, 12354.300000000001, 12351.15, 12362.7, 12361.65, 12351.15, 12343.800000000001, 12349.575, 12329.625, 12317.025, 12313.875, 12299.7, 12277.125, 12291.825]
doc_3437
strrep(myString, '()', '[]', ',', '.', '"', '') Is there any way to accomplish this? You could of course go with: strrep(strrep(strrep(myString, '()', '[]'), ',', '.'), '"', '') Or save the strings in a cell array and use this in a for loop, but both solutions are incredibly ugly. The most desired answer, is one that is generic for all functions that work in a similar way. A: To directly answer your question, there is really no consistent way of doing this, no. It really depends on the function. If you search the documentation you will often find a way to do this. With strings, at least, you can usually pass cell arrays in place of strings to perform operations on multiple strings, and in this case multiple operations on the same string. A Solution for This Particular Example You can easily use regexprep to do this for you. You can pass a cell array of the expressions to match with a corresponding cell array of the replacement values. regexprep('abc', {'a', 'b', 'c'}, {'1', '2', '3'}); %// '123' For your specific example, you would do something like: regexprep(myString, {'\(\)', ',', '"'}, {'[]', '.', ''}) And as an example: myString = 'This, is a () "string"'; regexprep(myString, {'\(\)', ',', '"'}, {'[]', '.', ''}) %// 'This. is a [] string' If you don't want to worry about escaping all of the expressions to be regex-compatible, you can use regexptranslate to do that for you. expressions = regexptranslate('escape', {'()', ',', '"'}); regexprep(myString, expressions, {'[]', '.', ''}); A: Say you want function foo to work like this: foo(Variable,Parameter1,Value1); foo(Variable,Parameter1_1,Value1,Parameter2,Value2,...); then using recursion: function[Variable]=FooBar(Variable,varargin) N=nargin-1; %\\ Count the input parameters if N>=2 Parameter=varargin{1}; Value=varargin{2}; % Process the first Parameter-value pair Variable=FooBar(Variable,varargin{3:N}); %\\ Cut first Parameter-Value pair off and pass the rest to foo again end This approach allows you to use chain of single parameters, pairs, triplets, quadruplets, etc. In this perticullar example the pairs are executed as LIFO stack and last unpaired Parameter is ignored. You can also add some conditions to implement foo(IN,Parameter1,Value1,Modifier,Parameter2,Value2,...) and many other properties... For your perticullar example: function[MyString]=FooBar(MyString,varargin) N=nargin-1; %\\ Count the input parameters if N>=2 Parameter=varargin{1}; Value=varargin{2}; MyString=regexprep(MyString,Parameter,Value) MyString=FooBar(MyString,varargin{3:N});%\\ Cut first Parameter-Value pair off and pass the rest to foo again end Examples: >> myString='This, is a () "string"'; FooBar(myString,'()','[]','"','',',','.') ans = This. is a [] string >> myString='This, is a ("string")'; FooBar(myString,'()','[]','"','',',','.') ans = This. is a (string) >> myString='This, is a ("string")'; FooBar(myString,'(','[',')',']','"','',',','.') ans = This. is a [string] A: As already said by @Suever your example can be solved by regexprep and @thewaywewalk has hinted that there is no "general" soluction for all function calls. Note I do not advocate this as a good way to code -> but its a quirky question and thus here is a suitable quirky solution.... There is lots of reason why you shouldn't do this - namely a nightmare to debug but you could in theory do this with an "intelligent" self calling function... % Create your own function which takes the following inputs: % fHandle - function handle to the function of choice % property - your starting variable % varargin - a cell array (or single var) of variables to % pass into the fHandle on each call % see examples below... function output = multipleCalls ( fHandle, property, varargin ) % call your primary function using feval and your inputs % with the 1st group of inputs from the 1st varargin if iscell ( varargin{1} ) output = feval ( fHandle, property, varargin{1}{:} ); else output = feval ( fHandle, property, varargin{1} ); end % remove the varargin variable which has just been used. varargin(1) = []; % are they aremore multiple call? if ~isempty ( varargin ) % if so self call to apply the subsequent calls. output = multipleCalls ( fHandle, output, varargin{:} ); end end % modifying your example to use this method: multipleCalls( @strrep, 'This, is a () "string"', { '()', '[]' }, { ',', '.' }, { '"', '' } ) % Its probably a longer command and is it any clearer -> probably not... % Here is another example: % Create a silly anonymous function sillyFunction = @(a,b) a + b % Then you can use it in the same way: % Where 0 is what you start with and then % each time you want to add 1, then 2, then 3 and finally 4 multipleCalls ( sillyFunction, 0, 1, 2, 3, 4 )
doc_3438
My clients website is located on a external multi-site system. We can only access the CMS and no scripts are allowed. Hope someone can help, or at least give me some hints on what to do. Cheers! A: No it's not possible to redirect mobile user, becouse you cant check if a user is mobile with html. You can make with CSS your layout responsive you make css here an example: @media only screen and (max-width: 1000px) { #website{ display:none; } #mobile{ display:block; } }
doc_3439
i have a windows application wrtitten with c# and on visual studio 2013 and want to install this application. i open command prompt write: c:\..\instalutil.exe c:\projectfolder\filename.exe after i run this code it give me the error : An exception occured during the Install phase. System.InvalidOperationException: Cannot open Service Control Manager on computer '.'. This operation might require other privileges. The inner exception System.ComponentModel.Win32Exception was thrown with the following error message: Access is denied. This is my computer i dont know why it needs access right? and i dont know how to give right privilege. also i changed my sercviceProcessInstaller Account property to LocalSystem and also tried with LocalService but both of them gives me the same error. what should i do to give right privilege? A: I found the answer finally: The solution: RUN COMMAND PROMPT AS ADMINISTRATOR A: I encountered this problem myself, in my case, since I couldn't run "Developer Command Prompt for Visual Studio" explicitly from .exe file as administrator and create a shortcut to run it inside the Visual Studio using "Tools => External Tools". To work around the issue, I tried running Visual Studio as Administrator and it worked as well. It seemed that it was the Visual Studio program that hadn't required access to perform the operations.
doc_3440
tput: No value for $TERM and no -T specified I am getting this error before the cypress test starts. It is causing to stop the start cypress tests. How can I fix this issue? Any help will be appreciated! Thanks
doc_3441
The JS in the webview fetches a local file to load templates using the following code: $.get("file:///android_asset/www/templates.html",function(data){ $("#templates").html(data); }); This code never works and I always get unknown chromium error: -6 This error happens on ICS 4.X and works normally in Froyo, Gingerbread, and Honeycomb I also tried this code: $.ajax({ url : "file:///android_asset/www/", type:"get", data : null, cache:false, success:function(data){ activity.doLog("Got it to work"); // This refers to Log.d in activity return false; }, error:function(xhr,msg,thrown){ activity.doLog("Didn't get it '"+msg.replace("\n"," --- ")); // Logged error here is 'error // Which is meaningless message return false; } }); Update: I found a solution/workaround for this problem (that doesn't make sense at all) The solution is simply: the locally loaded file must not contain single quotes, I don't know why but changing all the single quotes to double quotes solved the problem A: I found a solution/workaround for this problem (that doesn't make sense at all) The solution is simply: the locally loaded file must not contain single quotes, I don't know why but changing all the single quotes to double quotes solved the problem. * *Also change cache: false to cache: true or just remove it
doc_3442
As a beginning, I am using Adrian Brown's Outlook Add-In code. I won't duplicate his CalendarMonitor class entirely; here are the relevant parts: public class CalendarMonitor { private ItemsEvents_ItemAddEventHandler itemAddEventHandler; public event EventHandler<EventArgs<AppointmentItem>> AppointmentAdded = delegate { }; public CalendarMonitor(Explorer explorer) { _calendarItems = new List<Items>(); HookupDefaultCalendarEvents(session); } private void HookupDefaultCalendarEvents(_NameSpace session) { var folder = session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar); if (folder == null) return; try { HookupCalendarEvents(folder); } finally { Marshal.ReleaseComObject(folder); folder = null; } } private void HookupCalendarEvents(MAPIFolder calendarFolder) { var items = calendarFolder.Items; _calendarItems.Add(items); // Add listeners itemAddEventHandler = new ItemsEvents_ItemAddEventHandler(CalendarItems_ItemAdd); items.ItemAdd += itemAddEventHandler; } private void CalendarItems_ItemAdd(object obj) { var appointment = (obj as AppointmentItem); if (appointment == null) return; try { AppointmentAdded(this, new EventArgs<AppointmentItem>(appointment)); } finally { Marshal.ReleaseComObject(appointment); appointment = null; } } Bits not relevant to adding appointments have been redacted. I instantiate the CalendarMonitor class when I spool up the Add-in, and do the work in the AppointmentAdded event, including adding a UserProperty to the AppointmentItem: private void ThisAddIn_Startup(object sender, EventArgs e) { _calendarMonitor = new CalendarMonitor(Application.ActiveExplorer()); _calendarMonitor.AppointmentAdded += monitor_AppointmentAdded; } private async void monitor_AppointmentAdded(object sender, EventArgs<AppointmentItem> e) { var item = e.Value; Debug.Print("Outlook Appointment Added: {0}", item.GlobalAppointmentID); try { var result = await GCalUtils.AddEventAsync(item); //store a reference to the GCal Event for later. AddUserProperty(item, Resources.GCalId, result.Id); Debug.Print("GCal Appointment Added: {0}", result.Id); } catch (GoogleApiException ex) { PrintToDebug(ex); } finally { Marshal.ReleaseComObject(item); item = null; } } The error is thrown here, where I try to add a UserProperty to the AppointmentItem. I have followed the best example I could find: private void AddUserProperty(AppointmentItem item, string propertyName, object value) { UserProperties userProperties = null; UserProperty userProperty = null; try { userProperties = item.UserProperties; userProperty = userProperties.Add(propertyName, OlUserPropertyType.olText); userProperty.Value = value; item.Save(); } catch (Exception ex) { Debug.Print("Error setting User Properties:"); PrintToDebug(ex); } finally { if (userProperty != null) Marshal.ReleaseComObject(userProperty); if (userProperties != null) Marshal.ReleaseComObject(userProperties); userProperty = null; userProperties = null; } } ... but it chokes on when I try to add the UserProperty to the AppointmentItem. I get the ever-popular error: COM object that has been separated from its underlying RCW cannot be used. In all honesty, I have no idea what I'm doing; so I'm desperately seeking a Jedi Master to my Padawan. A: The main problem here is using Marshal.ReleaseComObject for RCW's that are used in more than one place by the managed runtime. In fact, this code provoked the problem. Let's see class CalendarMonitor: private void CalendarItems_ItemAdd(object obj) { var appointment = (obj as AppointmentItem); if (appointment == null) return; try { AppointmentAdded(this, new EventArgs<AppointmentItem>(appointment)); } finally { Marshal.ReleaseComObject(appointment); After the event returns, it tells the managed runtime to release the COM object (from the point of view of the whole managed runtime, but no further). appointment = null; } } Then, an async event is attached, which will actually return before using the appointment, right at the await line: private async void monitor_AppointmentAdded(object sender, EventArgs<AppointmentItem> e) { var item = e.Value; Debug.Print("Outlook Appointment Added: {0}", item.GlobalAppointmentID); try { var result = await GCalUtils.AddEventAsync(item); This method actually returns here. C#'s async code generation breaks async methods at await points, generating continuation passing style (CPS) anonymous methods for each block of code that handles an awaited result. //store a reference to the GCal Event for later. AddUserProperty(item, Resources.GCalId, result.Id); Debug.Print("GCal Appointment Added: {0}", result.Id); } catch (GoogleApiException ex) { PrintToDebug(ex); } finally { Marshal.ReleaseComObject(item); Look, it's releasing the COM object again. No problem, but not optimal at all. This is an indicator of not knowing what is going on by using ReleaseComObject, it's better to avoid it unless proven necessary. item = null; } } In essence the use of ReleaseComObject should be subject to a thorough review of the following points: * *Do I need to actually make sure the managed environment releases the object right now instead of at an indeterminate time? Occasionally, some native objects need to be released to cause relevant side effects. For instance, under a distributed transaction to make sure the object commits, but if you find the need to do that, then perhaps you're developing a serviced component and you're not enlisting objects in manual transactions properly. Other times, you're iterating a huge set of objects, no matter how small each object is, and you may need to free them in order to not bring either your application or the remote application down. Sometimes, GC'ing more often, switching to 64-bit and/or adding RAM solves the problem in one way or the other. *Am I the sole owner of/pointer to the object from the managed environment's point of view? For instance, did I create it, or was the object provided indirectly by another object I created? Are there no further references to this object or its container in the managed environment? *Am I definitely not using the object after ReleaseComObject, in the code that follows it, or at any other time (e.g. by making sure not to store it in a field, or closure, even in the form of an iterator method or async method)? This is to avoid the dreaded disconnected RCW exception.
doc_3443
// ... const params = useParams<ISomeInterfaceHere>(); // ... // I verified that `data` below actually loads but it does not last until the component unmounts. const { data, isLoading, isError } = useGetSomethingQuery(params.x, { refetchOnMountOrArgChange: true, }); // ... useEffect(() => { return () => { // current state: // // isLoading === true // isError === false // data === undefined }; }, []); // ... Does it have to do with the useParams hook which is from the react-router package? Is this a bug in RTKQ or, if not, what is the defined behavior? And, most importantly, how can I get the last defined value of data just before the component unmounts? There are no error messages. Update 1 I use: "react": "^16.14.0", "react-router": "^5.1.2", "react-router-dom": "^5.1.2", "@reduxjs/toolkit": "^1.6.0", Update 2 I am sure that the params are not getting updated, not even params.x. I also upgraded to @reduxjs/toolkit v1.6.1 and I have the same issue. Update 3 A code sandbox with the isolated issue is here. It looks to me like it is a bug in RTKQ. Update 4 I opened a GH bug report here. A: You are creating that cleanup callback on first render. From that moment on, that callback will hold on to stale variables from that first render until it is executed, even if hundreds of renders occur in-between. This has nothing to do with RTKQ - it's just how React works. If you want access to up-to-date values in that cleanup, you'll have to tunnel it through a ref: const { data, isLoading, isError } = useGetSomethingQuery(params.x, { refetchOnMountOrArgChange: true, }); const ref = useRef({data, isLoading, isError}) useEffect(() => { ref.current = {data, isLoading, isError} }, [data, isLoading, isError]) // ... useEffect(() => { return () => { console.log(ref.current) }; }, []);
doc_3444
var member = function (x, y, rank, name, img, background, textColor, proyek) { textColor = textColor || "#000"; var cell = new joint.shapes.org.Member({ position: { x: x, y: y }, attrs: { '.card': { fill: "#fff", stroke: background }, image: {}, '.rank': { text: rank, fill: textColor, 'word-spacing': '3px', 'letter-spacing': 0 }, '.name': { text: name, fill: textColor, 'font-size': 11, 'font-family': 'Calibri', 'letter-spacing': 0, 'text-align': 'left' }, mycustom: proyek } }); graph.addCell(cell); return cell; }; then the function called in this code... with the adding of parameter value i get from the loop var strname = member(positionx2, 200, 'Proyek ' + name + ' (' + dataLevel[i].Total + ') ', '', '#7c68fd', '#000000', dataLevel[i].Proyek); then i make the value shown on alert by this code... paper.on('cell:pointerdown', function (cellView, evt, x, y) { // alert('cell view ' + cellView.model.attr('mycustom') + ' was clicked'); } ); mycustom always undefined.. but if i change mycustom: proyek to mycustom: 'foo' its works.. why is this happening? can anybody help me.. thanks
doc_3445
I have created the table for my twitter data. create table twitter.full_text_ts as select id, cast(concat(substr(ts,1,10), ' ', substr(ts,12,8)) as timestamp) as ts, lat, lon, tweet from full_text; now I need to query it to find which hour of the day had the most tweets on a particular day. I am able to see all the timestamps (ts) of the tweets on any particular day by entering select ts from twitter.full_text_ts where to_date(ts) = '2010-03-06' order by ts desc; this outputs: 2010-03-06 02:10:01 2010-03-06 02:11:15 and so on. What i would like to do is group them by the hour so I can see what hour has the most entries. Thanks, Cale A: Try the following: select DATEPART(HH, ts) [Hour], COUNT(*) [Count] from twitter.full_text_ts where to_date(ts) = '2010-03-06' GROUP BY DATEPART(HH, ts) [Hour] order by 1 desc; A: You can use the hour() function: select hour(ts), count(*) as cnt from twitter.full_text_ts where to_date(ts) = '2010-03-06' group by hour(ts) order by cnt desc;
doc_3446
wm title "abc" ; if I miss this then tcl's window manager gives its own name. A: To remove the window manager decorations entirely, use wm overrideredirect before the toplevel window is first mapped (typically immediately after creating the toplevel) to request that it be mapped as an unmanaged window; this is what things like menus and tooltips do for you behind the scenes. set t [toplevel .abc] wm overrideredirect $t 1 # Fill out the contents Be aware that this can interact β€œinterestingly” with focus management, and that on X11 you should also set the -type attribute appropriately, such as in: wm attributes $t -type tooltip You might instead be better in some cases to make the window into a transient for another window, which (usually) changes the window decoration but not quite as radical as making it override-redirected. # e.g., this makes the window a transient of the main window wm transient $t . If you're making a full-screen undecorated window though, that's best done via: wm attributes $t -fullscreen 1
doc_3447
I checked the cost at https://forge.autodesk.com/pricing. It is said that 6 credits are consumed per hour. I tested credit consumption per execution once in my project. Two credits were consumed for one run. In my project, the work lasts about 30 seconds, but I don't know why 2 credits are paid. Please tell me how to calculate credit consumption. A: The tooltip on the pricing page says: Every second of processing Work Items (including file transfer time between systems) submitted through the Design Automation API is included in the number of processing hours. Since you haven't provided any details it's hard to say, but please note that downloading of input files and uploading of output files is also included in the processing time. What kind of task did you try and run in the Design Automation service? Was it perhaps inputting or outputting some large design file?
doc_3448
A: I think that the easiest way to approach this, considering data type representations and all of the Crystal complexity under the covers, is to layout your report with all 25 fields sized appropriately. Then, at runtime, you will need to reposition the report objects, which could be a little tricky due to the relatively unstructured way in which crystal provides the information. The way I would approach this is to loop through the report objects and generate one SortedList for the data fields and one SortedList for the header fields. They should be sorted on their Left position so that you can process them in appearance order. Once you have the sorted lists of objects, you can cycle through each one and, if it was not selected by the user, set the Width to 0. As you are moving through the fields, you will keep track of the current left position. The first field that you process will set your starting point, even if it is not visible. Then, for all subsequent fields, if the field is visible, you will set its left value to the current left position, then add its width plus some separator space to the current left position for the next field. Hopefully this will help you solve your problem. A: Give a look at these links * *http://www.c-sharpcorner.com/UploadFile/uditsingh/CR1111022006055359AM/CR11.aspx *http://www.crystalkeen.com/articles/crystalreports/dynamiccrosstab.htm Using this Google Search A: It sounds like this would be a good place for a cross-tab report. In this case you'd need to add a cross tab to your report header or footer and pass your data into the report with a column for each attribute descriptions and then group on the attribute description. See below for details: Data: RowID ColDesc ColValue 1 Attr1 Value1 1 Attr2 Value2 2 Attr1 Value3 Then you can add your crosstab where your row field is RowID, your column field is ColDesc and the field to summarize is ColValue. You can use a Max of summary on the summarized field since it is different. This is untested, but I believe that the output for this should be: CrossTab: Attr1 Attr2 1 Value1 Value2 2 Value3 As you can see that as you add a new attribute it will show up as a new column in the crosstab. As I said previously, this is untested so I apologize for any errors, but I hope it is enough to help you out. Thanks A: Crystal Reports will not automatically add columns & headers to a report given a list of fields. My recommendation is to use the Report Application Server .NET SDK to dynamically alter a report. The link includes the API reference, as well as samples.
doc_3449
I know that I can not put jars in side the jar but classes. But I don't like that solution. So I thought to build an ear file. When I read it everywhere it mentioned that it required to have ejb, war or web service component but in my case I only have general class files. Basically no EJB jar, war or web service. So my short question is can I build an ear with Java module and dependency jars inside the lib folder? I use Maven as the builder. A: Yes you can with Maven EAR Plugin: http://maven.apache.org/plugins/maven-ear-plugin/
doc_3450
A: If you are asking technically whether Hibernate calls have to be in a transaction, the answer is no. Each call (update, insert, or delete) will be done as an atomic action. After the function returns the request to the database will be complete. When the database actually commits the change is up to Hibernate, the driver, and the database itself. If you are asking whether or not you should put credits or debits into a transaction state, the answer depends on the requirements of the application. A: It depends on you haw you handle your debit and credit. Perhaps there is some level configuration you can provide to @Transactional. If you need to have more flexible transaction, you may opt for programmatic transaction management instead of declarative transaction management. As far as Spring is concerned, it do not restrict you in any way, its totally up to you how you want to handle your transactions.
doc_3451
Redisclient.del(tokenKeys,function(err,count){ Logger.info("count is ",count) Logger.error("err is ",err) }) where tokenKeys=["aaa","bbb","ccc"] , this code is work if I send one key like tokenKeys="aaa" A: Certainly at current version of node_redis (v2.6.5) it is possible to delete both with a comma separated list of keys or with an array of keys. See tests for both here. var redis = require("redis"); var client = redis.createClient(); client.set('foo', 'foo'); client.set('apple', 'apple'); // Then either client.del('foo', 'apple'); // Or client.del(['foo', 'apple']); A: del function is implemented directly as in Redis DB client, I.e. redis.del("aaa","bbb","ccc") will remove multiple items To make it work with array use JavaScript apply approach: redis.del.apply(redis, ["aaa","bbb","ccc"]) A: You can just pass the array as follows var redis = require("redis"), client = redis.createClient(); client.on("error", function (err) { console.log("Error " + err); }); client.set("aaa", "aaa"); client.set("bbb", "bbb"); client.set("ccc", "ccc"); var keys = ["aaa", "bbb", "ccc"]; client.keys("*", function (err, keys) { keys.forEach(function (key, pos) { console.log(key); }); }); client.del(keys, function(err, o) { }); client.keys("*", function (err, keys) { keys.forEach(function (key, pos) { console.log(key); }); }); If you run the above code you will get the following output $ node index.js string key hash key aaa ccc bbb string key hash key showing the keys printed after being set, but not printed after deletion A: node-redis doesn't work like that but if you really have a lot of del commands it will pipeline them automatically so it is probably more efficient than you think to do it in a loop. You can also try this module with multi: var redis = require("redis"), client = redis.createClient(), multi; client.multi([ ["del", "key1"], ["del", "key2"] ]).exec(function (err, replies) { console.log(replies); });
doc_3452
require_once __DIR__ . "/vendor/autoload.php"; $apikey = "<API KEY FROM HELLOSIGN>"; $client = new HelloSign\Client($apikey); $account = $client->getAccount(); But when I try with the below code to get an Account using SDK, reference link: https://developers.hellosign.com/api/reference/operation/accountGet/: require_once __DIR__ . "/vendor/autoload.php"; $config = HelloSignSDK\Configuration::getDefaultConfiguration(); // Configure HTTP basic authorization: api_key $config->setUsername("YOUR_API_KEY"); // or, configure Bearer (JWT) authorization: oauth2 // $config->setAccessToken("YOUR_ACCESS_TOKEN"); $api = new HelloSignSDK\Api\AccountApi($config); try { $result = $api->accountGet(null, '[email protected]'); print_r($result); } catch (HelloSignSDK\ApiException $e) { $error = $e->getResponseObject(); echo "Exception when calling HelloSign API: " . print_r($error->getError()); } It throws an error: Fatal error: Uncaught Error: Class "HelloSignSDK\Configuration" not found Added autoload, why is this issue if using SDK? Kindly help!
doc_3453
So, I have a list activity of images, say it's defaultView. On each list item click, there should open a new view of only imageview of that particular image with animation. And when I long press on tempView it should goes back to defaultView with reverse animation. so what should be my approach to solve the problem? Note : link for animation reference A: <FrameLaytou> <ListView> <defaultView/> </ListView> <tempView visible = gone> </FrameLaytou> defaultView click -> view.getLocationInWindow(location) to getXY of defaultView -> tempView setLayoutParams to defaultView's location and defaultView'size -> tempView visible -> Property Animation to set tempView target positoin and target size -> longclick -> Property Animation to set tempView defaultView's location and defaultView'size -> tempView gone
doc_3454
const App = styled.div` p { margin: 0; } ` However, I do want to be able to add margin to some <p>s, e.g.: const SpacedP = styled.p` margin-bottom: 10px; ` But when I try to use a <SpacedP> within <App>, the resulting App CSS is more specific than the SpacedP CSS, so my <SpacedP>s still have no margin! (App CSS compiles to ${App} p { ... }, while SpacedP only has one prefix, ${SpacedP} { ... }). Is there a common pattern for situations like these? I don't really like the &&& specificity workaround suggested here, seems ugly and hacky; hoping there's a more common setup that I'm missing. Thanks!
doc_3455
https://codesandbox.io/s/hungry-cohen-mjvvg?file=/src/components/Input.tsx:440-555 A: The problem is in your Predication component. Never call setState() directly inside functional component. If you want to do some work when some props change, you should use useEffect hooks and pass the props as dependencies for it. Never call setState directly inside the function component, you can think never call this.setState() in render() method of a class component. // Call API when the `input.text` and `input.model` changed useEffect(() => { if (input.text && input.model) { console.log("predict"); predict(input.text, input.model) .then((res) => setPrediction(res)) .catch((e) => <p>Noe gikk galt. PrΓΈv igjen senere</p>); } }, [input.text, input.model]); // Never do this, `setPrediction` will make the component re-render and cause the infinite loop. // Predict if text // if (input.text && input.model) { // console.log("predict"); // predict(input.text, input.model) // .then((res) => setPrediction(res)) // .catch((e) => <p>Noe gikk galt. PrΓΈv igjen senere</p>); // } Besides, you should declare the state before using it in your InputContextProvider component. export const InputContextProvider = (props: any) => { const [state, setState] = useState({ text: "", model: "bayes" }); // TODO: Replace any type const setInput = (input: any) => { setState({ ...state, text: input.text, model: input.model }); }; return ( <InputContext.Provider value={{ ...state, setInput }}> {props.children} </InputContext.Provider> ); }; Codesandbox A: this is not the recommended way to update context: useEffect(() => { inputContext.setInput({ text: debouncedText, model: debouncedText }); }, [debouncedText, model]); because once you setInput, you caused inputContext changed, and once you cause the inputContext changed, it will trigger inputContext.setInput again.. this will cause an infinite update util stack overflow. In your case, I think you could update context by setting an additional state to mark whether debouncedText, debouncedText have changed or not. const [changed, setChanged] = useState(false) useEffect(() => { if (!changed) { inputContext.setInput({ text: debouncedText, model: debouncedText }); setChanged(true) } }, [debouncedText, model, change, setChanged]);
doc_3456
private TextView up = (TextView) findViewById(R.id.tv_up); private TextView mid = (TextView) findViewById(R.id.tv_mid); private TextView down = (TextView) findViewById(R.id.tv_down); instead of define it evertime new: public void onButtonClickUp(View v) { TextView up = (TextView) findViewById(R.id.tv_up); TextView mid = (TextView) findViewById(R.id.tv_mid); TextView down = (TextView) findViewById(R.id.tv_down); <..> } public void onButtonClickDown(View v) { TextView up = (TextView) findViewById(R.id.tv_up); TextView mid = (TextView) findViewById(R.id.tv_mid); TextView down = (TextView) findViewById(R.id.tv_down); <..> } The upper methode is producing a force close error on my android device. How to solve this or is that generally possible? Thanks! A: public class TestActivity extends Activity { private TextView up; private TextView mid; private TextView down; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); up = (TextView) findViewById(R.id.tv_up); mid = (TextView) findViewById(R.id.tv_mid); down = (TextView) findViewById(R.id.tv_down); } I'm not sure why your app is crashing, but you will save yourself a lot of headache by declaring/assigning your widgets like this... only one time for the whole activity.
doc_3457
In a C# WinForm I am having a ComboBox. In a local data-base I have some "groups" that after execution become folder in "D://" ( they are five ) After that in all the folders I have some files ( the number varies ) I do not know how to populate the ComboBox with the names of those files, and after that when pressing a button I need to interact with the name selected in the ComboBox. I have absolutely no idea on how to do that. I do not beg for any code ( altho it will be well received ) I just want the guideline ( do "this" first they you can do "that" and at the end you do "that" ) and I will do all the rest. It is just I can not figure that out. Thank you all ! A: First get the names of the files that is something like this: string[] files=Directory.GetFiles("//path"); Now you have an array of all file names in the specific folder given above. Now take this string and populate it to the combo box that is something like this. foreach(string file in files){ comboBox1.Items.add(file); } After that you have to create the event behind the combo box. If you drag-drooped combo box, then you can make its event by going to properties. Then code something like this behind the item select event behind combo box. protected void combobox(bla bla) { if(comboBox1.SelectedItem == "An item") //Do whatever //it maybe selectedItem or selectedText or something like this } I code roughly so it may contain some errors. A: Based on the help given I have done: public string seltest = null; string group1 = GroupsDBForm.gone; string[] tests1 = Directory.GetFiles("D:\\Riddler\\groups\\" + group1).Select(path => Path.GetFileName(path)).ToArray(); foreach (string t1 in tests1) { test_list.Items.Add(group1+"\\"+t1); } private void begin_test_btn_Click(object sender, EventArgs e) { seltest = "D:\\Riddler\\groups\\" + test_list.Text; Do_Test_Form DoTest = new Do_Test_Form(); DoTest.ShowPath = seltest; DoTest.MdiParent = this.ParentForm; DoTest.Show(); } ( Those are the parts of the project connected to the issue, and because they are connected to other parts is might be lessunderstandeble what are the other names mentioned ) I know it is far from the best code but it works. I post it if this help another person with a close to this issue ! Thank you again Jamil!
doc_3458
I want to overlap one image on top of another image without any user interaction. So please help me asap. Hey, I tried this: http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html With this, my application crashes... A: you can follow the hierarchy of writing code(xml) in such manner that the back order imageview will written first and then so on, see Animate listview from back of layout A: Maybe a good idea to use an AnimationDrawable if you would like to make animation: AnimationDrawable Description
doc_3459
Is this possible to achieve with Apache's reverse proxy, to somehow pass handshake requests (to proxy Transport layer messages)? If not, what would be the solution?
doc_3460
connection = pyodbc.connect('DRIVER={SQL Server};SERVER=x;DATABASE=y; MARS_Connection=yes') cursor = connection.cursor() SQL = "select * from data" table = pd.read_sql(SQL , con=connection) print(table) result id name 1 v 2 u 3 o if I update the database manually by adding 4 j then I print it will not show in my flask app so I have to restart the app to show it. my question how can I make sure that flask app will update variable based database updated do I have to read the database again in each route, and save it in the same variable? like table = pd.read_sql(SQL , con=connection) or there is another way?
doc_3461
for (final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { final NetworkInterface intf = en.nextElement(); for (final Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { final InetAddress ip = enumIpAddr.nextElement(); if (!ip.isLoopbackAddress() && !ip.isLinkLocalAddress() && !ip.isAnyLocalAddress()) { return ip.getHostAddress().toString(); } } } For Python version one can do: os.environ['REMOTE_ADDR'] or String ip = self.request.remote_addr; But what would be a Java equivalent? A: If you are behind a proxy, for example, if you use ProxyPass and ProxyPassReverse you could find useful this: this.getThreadLocalRequest().getHeader("X-FORWARDED-FOR") A: OK - got it. In your Servlet which should extend RemoteServiceServlet do this: final String ip = getThreadLocalRequest().getRemoteAddr(); A: Actually, if you want the IP address you might want to use getRemoteAddr instead of getRemoteHost. String ip = getThreadLocalRequest().getRemoteAddr(); String host = getThreadLocalRequest().getRemoteHost(); * *getRemoteAddr gives you the internet protocol (IP) address of the client. *getRemoteHost gives you the fully qualified name of the client, the IP if the host name is empty. See the Oracle Javadoc: http://docs.oracle.com/javaee/7/api/javax/servlet/ServletRequest.html#getRemoteAddr%28%29
doc_3462
On my main function I then try to copy the char data[] char by char and concatenate to a new string using strcat function. When I print the char that I want to concatenate it appears to be the valid char, but when I print the final string, it is wrong. Code: #include <stdio.h> #include <string.h> int getDataLength(){ return 17; } static char data[] = {'{','"','x','"',':','1','2','5',',','"','y','"',':','1','3','7','}'}; char getData(int i){ return data[i]; } int main() { int dataLength = getDataLength(); char data[dataLength + 1]; for(int i=0 ; i < dataLength ; i++){ char chr = getData(i); // --- looking good --- printf("%c",chr); strcat(data,&chr); } data[dataLength] = '\0'; // --- broken string --- printf("\n%s",data); } Output: {"x":125,"y":137} (οΏ½οΏ½οΏ½{"x":1% What am I missing? A: You should look at your compiler warnings. strcat(data,&chr); strcat expects two strings as parameters. Your second parameter is no string but only a single character. The nul-termination is missing and you copy random garbage data. Additionally you don't initialize data before you start adding to it. Both errors cause undefined behaviour in your program.
doc_3463
* *Windows 7 (x64) *Python 3.6.3 64bit (virtual environment) *Django 2.0 *cx_Oracle 6.1 *Oracle 11.2 Enterprise Edition 64 bit (on remote machine) I am failing to migrate (django manage.py migrate) because Django is creating sql suitable for Oracle 12c; but I am using 11g. For example, django tries to execute this: SELECT CASE WHEN identity_column = 'YES' THEN 1 ELSE 0 END FROM user_tab_cols WHERE table_name = 'DJANGO_CONTENT_TYPE' AND column_name = 'NAME'; ('DJANGO_CONTENT_TYPE', 'NAME'); args=['DJANGO_CONTENT_TYPE', 'NAME'] But the column identity_column is not available on oracle 11g. How can I make django use 11g syntax? EDIT: Tracing back the exception I found this in ..\Lib\site-packages\django\db\backends\oracle\schema.py(method _is_identity_column, line 151): cursor.execute(""" SELECT CASE WHEN identity_column = 'YES' THEN 1 ELSE 0 END FROM user_tab_cols WHERE table_name = %s AND column_name = %s """, [self.normalize_name(table_name), self.normalize_name(column_name)]) So the syntax is hard coded. Does this mean Django 2.0 is for Oracle 12c an onwards? A: From the release notes of django 2.0 (with my emphasis): The end of upstream support for Oracle 11.2 is Dec. 2020. Django 1.11 will be supported until April 2020 which almost reaches this date. Django 2.0 officially supports Oracle 12.1+. So, for support of any other version of Oracle, you should downgrade to 1.11
doc_3464
A: Major modes have a hook variable for this sort of thing. Look for w3m-mode-hook. (defun my-w3m-hook nil (setq w3m-lnum-mode t)) (add-hook 'w3m-mode-hook #'my-w3m-hook) The indirection to hook a separate function is not absolutely necessary, but simplifies the management of the hook functionality (otherwise you'd have to restart Emacs or jump through several hoops to add something to an existing hook; now all you need to do is evaluate a new defun of the function called from the hook). A: You can set a default like so: (setq-default w3m-lnum-mode t) For fine-grained control, use a hook as RNAer suggests. As far as I can tell though, this is not a normal local variable but a minor mode variable. You actually probably want to do (w3m-lnum-mode 1).
doc_3465
I could manage to change language of anything but the launcher icon is still in system language. Is it possible anyhow to change that icon language? Metin A: Let's say that you are supporting N languages with this dubious feature. You will need N entries in your manifest for the launcher activity. Each of those N entries will need an android:label pointing to a string that represents what you want displayed when your app is configured for -such-and-so language. You would then use PackageManager and setComponentEnabledSetting() to disable the old activity and enable the new one. It is conceivable that you could use one <activity> element and N <activity-alias> elements to achieve your objective, but I am uncertain as to whether you can enable and disable activity aliases.
doc_3466
HTML: <embed src="pano_botanique.svg" width="100%" height="100%" ; type="image/svg+xml" id='svgsource' /> JS: $(document).ready(function () { var svgs = document.getElementsByTagName('svg'); function selfdraw() { for (var i = 0; i < svgs.length; i++) { svgs[i].classList.add('draw'); } } }); CSS: svg * { fill: none; stroke: none; } .draw * { stroke: #3675D8; stroke-width: 0.5px; -webkit-animation: self-draw 30s ease-in; -webkit-animation-fill-mode: backwards; } @-webkit-keyframes self-draw { 0% { stroke-dasharray: 0 100% } 40% { stroke-dasharray: 100% 0% } } EDIT: var svgs = document.getElementById('svgsource').contentDocument(); svgs.addEventListener('load', function () { var svg = svgs.contentDocument(); function selfdraw() { for (var i = 0; i < svgs.length; i++) { svgs[i].classList.add('draw'); } } }); This should work but doesn't :( A: You can put the stylesheet in a <style> element inside the svg file. Note that by using <embed> the svg nodes are in a different document. That means that for getElementsByTagName(...) to work you need to call it on the svg document, not on the main document. But simply replacing document with e.g document.getElementById('svgsource').getSVGDocument() isn't guaranteed to work unless you wait for the svg document to finish loading (read: you can't do this from $(document).ready, see this answer for more details. Also see How to access the content of the "embed" tag in HTML.
doc_3467
Class test<T>{ int method1(Obj Parameter1){ //in here I want to do something which I would explain as T.TryParse(Parameter1); //my problem is that it does not work ... I get an error. //just to explain: if I declare test<int> (with type Integer) //I want my sample code to call int.TryParse(). If it were String //it should have been String.TryParse() } } So thank you guys for your answers (By the way the question is: how would I solve this problem without getting an error). This probably quite an easy question for you! Edit: Thank you all for your answers! Though I think the try - catch phrase is the most elegant, I know from my experience with vb that it can really be a bummer. I used it once and it took about 30 minutes to run a program, which later on only took 2 minutes to compute just because I avoided try - catch. This is why I chose the switch statement as the best answer. It makes the code more complicated but on the other hand I imagine it to be relatively fast and relatively easy to read. (Though I still think there should be a more elegant way ... maybe in the next language I learn) Though if you have some other suggestion I am still waiting (and willing to participate) A: The problem is that TryParse isn't defined on an interface or base class anywhere, so you can't make an assumption that the type passed into your class will have that function. Unless you can contrain T in some way, you'll run into this a lot. Constraints on Type Parameters A: To access a member of a specific class or interface you need to use the Where keyword and specify the interface or base class that has the method. In the above instance TryParse does not come from an interface or base class, so what you are trying to do above is not possible. Best just use Convert.ChangeType and a try/catch statement. class test<T> { T Method(object P) { try { return (T)Convert.ChangeType(P, typeof(T)); } catch(Exception e) { return null; } } } A: Short answer, you can't. Long answer, you can cheat: public class Example { internal static class Support { private delegate bool GenericParser<T>(string s, out T o); private static Dictionary<Type, object> parsers = MakeStandardParsers(); private static Dictionary<Type, object> MakeStandardParsers() { Dictionary<Type, object> d = new Dictionary<Type, object>(); // You need to add an entry for every type you want to cope with. d[typeof(int)] = new GenericParser<int>(int.TryParse); d[typeof(long)] = new GenericParser<long>(long.TryParse); d[typeof(float)] = new GenericParser<float>(float.TryParse); return d; } public static bool TryParse<T>(string s, out T result) { return ((GenericParser<T>)parsers[typeof(T)])(s, out result); } } public class Test<T> { public static T method1(string s) { T value; bool success = Support.TryParse(s, out value); return value; } } public static void Main() { Console.WriteLine(Test<int>.method1("23")); Console.WriteLine(Test<float>.method1("23.4")); Console.WriteLine(Test<long>.method1("99999999999999")); Console.ReadLine(); } } I made a static dictionary holding a delegate for the TryParse method of every type I might want to use. I then wrote a generic method to look up the dictionary and pass on the call to the appropriate delegate. Since every delegate has a different type, I just store them as object references and cast them back to the appropriate generic type when I retrieve them. Note that for the sake of a simple example I have omitted error checking, such as to check whether we have an entry in the dictionary for the given type. A: One more way to do it, this time some reflection in the mix: static class Parser { public static bool TryParse<TType>( string str, out TType x ) { // Get the type on that TryParse shall be called Type objType = typeof( TType ); // Enumerate the methods of TType foreach( MethodInfo mi in objType.GetMethods() ) { if( mi.Name == "TryParse" ) { // We found a TryParse method, check for the 2-parameter-signature ParameterInfo[] pi = mi.GetParameters(); if( pi.Length == 2 ) // Find TryParse( String, TType ) { // Build a parameter list for the call object[] paramList = new object[2] { str, default( TType ) }; // Invoke the static method object ret = objType.InvokeMember( "TryParse", BindingFlags.InvokeMethod, null, null, paramList ); // Get the output value from the parameter list x = (TType)paramList[1]; return (bool)ret; } } } // Maybe we should throw an exception here, because we were unable to find the TryParse // method; this is not just a unable-to-parse error. x = default( TType ); return false; } } The next step would be trying to implement public static TRet CallStaticMethod<TRet>( object obj, string methodName, params object[] args ); With full parameter type matching etc. A: This isn't really a solution, but in certain scenarios it could be a good alternative: We can pass an additional delegate to the generic method. To clarify what I mean, let's use an example. Let's say we have some generic factory method, that should create an instance of T, and we want it to then call another method, for notification or additional initialization. Consider the following simple class: public class Example { // ... public static void PostInitCallback(Example example) { // Do something with the object... } } And the following static method: public static T CreateAndInit<T>() where T : new() { var t = new T(); // Some initialization code... return t; } So right now we would have to do: var example = CreateAndInit<Example>(); Example.PostInitCallback(example); However, we could change our method to take an additional delegate: public delegate void PostInitCallback<T>(T t); public static T CreateAndInit<T>(PostInitCallback<T> callback) where T : new() { var t = new T(); // Some initialization code... callback(t); return t; } And now we can change the call to: var example = CreateAndInit<Example>(Example.PostInitCallback); Obviously this is only useful in very specific scenarios. But this is the cleanest solution in the sense that we get compile time safety, there is no "hacking" involved, and the code is dead simple. A: Do you mean to do something like this: Class test<T> { T method1(object Parameter1){ if( Parameter1 is T ) { T value = (T) Parameter1; //do something with value return value; } else { //Parameter1 is not a T return default(T); //or throw exception } } } Unfortunately you can't check for the TryParse pattern as it is static - which unfortunately means that it isn't particularly well suited to generics. A: The only way to do exactly what you're looking for would be to use reflection to check if the method exists for T. Another option is to ensure that the object you send in is a convertible object by restraining the type to IConvertible (all primitive types implement IConvertible). This would allow you to convert your parameter to the given type very flexibly. Class test<T> { int method1(IConvertible Parameter1){ IFormatProvider provider = System.Globalization.CultureInfo.CurrentCulture.GetFormat(typeof(T)); T temp = Parameter1.ToType(typeof(T), provider); } } You could also do a variation on this by using an 'object' type instead like you had originally. Class test<T> { int method1(object Parameter1){ if(Parameter1 is IConvertible) { IFormatProvider provider = System.Globalization.CultureInfo.CurrentCulture.GetFormat(typeof(T)); T temp = Parameter1.ToType(typeof(T), provider); } else { // Do something else } } } A: Ok guys: Thanks for all the fish. Now with your answers and my research (especially the article on limiting generic types to primitives) I will present you my solution. Class a<T>{ private void checkWetherTypeIsOK() { if (T is int || T is float //|| ... any other types you want to be allowed){ return true; } else { throw new exception(); } } public static a(){ ccheckWetherTypeIsOK(); } } A: You probably cant do it. First of all if it should be possible you would need a tighter bound on T so the typechecker could be sure that all possible substitutions for T actually had a static method called TryParse. A: You may want to read my previous post on limiting generic types to primitives. This may give you some pointers in limiting the type that can be passed to the generic (since TypeParse is obviously only available to a set number of primitives ( string.TryParse obviously being the exception, which doesn't make sense). Once you have more of a handle on the type, you can then work on trying to parse it. You may need a bit of an ugly switch in there (to call the correct TryParse ) but I think you can achieve the desired functionality. If you need me to explain any of the above further, then please ask :) A: Best code: restrict T to ValueType this way: class test1<T> where T: struct A "struct" here means a value type. String is a class, not a value type. int, float, Enums are all value types. btw the compiler does not accept to call static methods or access static members on 'type parameters' like in the following example which will not compile :( class MyStatic { public static int MyValue=0; } class Test<T> where T: MyStatic { public void TheTest() { T.MyValue++; } } => Error 1 'T' is a 'type parameter', which is not valid in the given context SL. A: That is not how statics work. You have to think of statics as sort of in a Global class even if they are are spread across a whole bunch of types. My recommendation is to make it a property inside the T instance that can access the necessary static method. Also T is an actual instance of something, and just like any other instance you are not able to access the statics for that type, through the instantiated value. Here is an example of what to do: class a { static StaticMethod1 () virtual Method1 () } class b : a { override Method1 () return StaticMethod1() } class c : a { override Method1 () return "XYZ" } class generic<T> where T : a { void DoSomething () T.Method1() }
doc_3468
In Appium, those downloaded virtual devices are visible in the"Launch Device" dropdown menu. Then I set the apk path & try to start the Appium 1.3.4.1. By that time I am getting an error message like Starting Node Server usage: main.js [-h] [-v] [--shell] main.js: error: Unrecognized arguments: Nexus 5 - 4.4.4 - API 19 - 1080x1920. [--localizable-strings-dir LOCALIZABLESTRINGSDIR] [--app APP] [--ipa IPA] [-U UDID] [-a ADDRESS] [-p PORT] [-ca CALLBACKADDRESS] [-cp CALLBACKPORT] [-bp BOOTSTRAPPORT] [-k] [-r BACKENDRETRIES] [--session-override] [--full-reset] [--no-reset] [-l] [-lt LAUNCHTIMEOUT] [-g LOG] [--log-level {info,info:debug,info:info,info:warn,info:error,warn,warn:debug,warn:info,warn:warn,warn:error,error,error:debug,error:info,error:warn,error:error,debug,debug:debug,debug:info,debug:warn,debug:error}] [--log-timestamp] [--local-timezone] [--log-no-colors] [-G WEBHOOK] [--native-instruments-lib] [--app-pkg ANDROIDPACKAGE] [--app-activity ANDROIDACTIVITY] [--app-wait-package ANDROIDWAITPACKAGE] [--app-wait-activity ANDROIDWAITACTIVITY] [--android-coverage ANDROIDCOVERAGE] [--avd AVD] [--avd-args AVDARGS] [--device-ready-timeout ANDROIDDEVICEREADYTIMEOUT] [--safari] [--device-name DEVICENAME] [--platform-name PLATFORMNAME] [--platform-version PLATFORMVERSION] [--automation-name AUTOMATIONNAME] [--browser-name BROWSERNAME] [--default-device] [--force-iphone] [--force-ipad] [--language LANGUAGE] [--locale LOCALE] [--calendar-format CALENDARFORMAT] [--orientation ORIENTATION] [--tracetemplate AUTOMATIONTRACETEMPLATEPATH] [--show-sim-log] [--show-ios-log] [--nodeconfig NODECONFIG] [-ra ROBOTADDRESS] [-rp ROBOTPORT] [--selendroid-port SELENDROIDPORT] [--chromedriver-port CHROMEDRIVERPORT] [--chromedriver-executable CHROMEDRIVEREXECUTABLE] [--use-keystore] [--keystore-path KEYSTOREPATH] [--keystore-password KEYSTOREPASSWORD] [--key-alias KEYALIAS] [--key-password KEYPASSWORD] [--show-config] [--no-perms-check] [--command-timeout DEFAULTCOMMANDTIMEOUT] [--keep-keychains] [--strict-caps] [--isolate-sim-device] [--tmp TMPDIR] [--trace-dir TRACEDIR] [--intent-action INTENTACTION] [--intent-category INTENTCATEGORY] [--intent-flags INTENTFLAGS] [--intent-args OPTIONALINTENTARGUMENTS] Node Server Process Ended When I try to run with normal emulator in Android SDK it works well. But I want to run it with Genymotion emulator. How to do? I'm stuck up here. My questions are: * *Whether the additional emulator will work in appium windows or not? *What I need to give in the "Argument" field under appium? A: The following code works for the above question. static String deviceName = "Google Nexus 5 - 4.4.4 - API 19 - 1080x1920"; public static void main(String[] args) throws InterruptedException, ExecuteException, IOException { DesiredCapabilities capabilities = new DesiredCapabilities(); DefaultExecutor executor = new DefaultExecutor(); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); CommandLine launchEmul = new CommandLine("C:/Program Files/Genymobile/Genymotion/player"); launchEmul.addArgument("--vm-name"); launchEmul.addArgument("\""+deviceName+"\""); executor.setExitValue(1); executor.execute(launchEmul, resultHandler); Thread.sleep(40); capabilities.setCapability("deviceName","Google Nexus 5 - 4.4.4 API 19 - 1080x1920"); capabilities.setCapability("platformVersion", "4.3"); capabilities.setCapability("platformName", "Android"); capabilities.setCapability("app","D:/SOFTWARES/Apks/GOA.apk"); driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"),capabilities); System.out.println("SetUp is successful and Appium Driver is launched successfully"); } A: Recently i i've used genymotion and appium and worked fine 1-i've installed appium(i've tried windows and console version succesfully) 2-i've installed genymotion and created a virtual device in it 3-launched virtual device from genymotion 4-in my test, when i defined driver capabilities, i didnt identified a specific virtual device, so, appium try to identify any active device(virtual or not) try that and let me know if worked to help in anything i could
doc_3469
Always I'll recive a url like this: https://www.testweb.com/cordi?ll=41.403781,2.1896&z=17&pll=41.403781,2.1896 Where I need to extract the second set of this URL (in this case: 41.403781,2.1896) Just to say, that not always the first and second set of coords will be the same. I know, that can be done with some regex, but I'm not good enough on it. A: Here's how to do it with a regular expression: import re m = re.search(r'pll=(\d+\.\d+),(\d+\.\d+)', 'https://www.testweb.com/cordi?ll=41.403781,2.1896&z=17&pll=41.403781,2.1896') print m.groups() Result: ('41.403781', '2.1896') You might want look at the module urlparse for a more robust solution. A: urlparse has a functions "urlparse" and "parse_qs" for accessing this data reliably, as shown below $ python Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56) [GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> u="""https://www.testweb.com/cordi?ll=41.403781,2.1896&z=17&pll=41.403781,2.1896""" >>> import urlparse >>> x=urlparse.urlparse(u) >>> x ParseResult(scheme='https', netloc='www.testweb.com', path='/cordi', params='', query='ll=41.403781,2.1896&z=17&pll=41.403781,2.1896', fragment='') >>> x.query 'll=41.403781,2.1896&z=17&pll=41.403781,2.1896' >>> urlparse.parse_qs(x.query) {'ll': ['41.403781,2.1896'], 'z': ['17'], 'pll': ['41.403781,2.1896']} >>>
doc_3470
I have a tagged section at the top, being section 0. I want the names sorted aplhabetically to come after that. So all names beginning with A get put into section 1, B into section 2, and so on. I need to be able to somehow get the number of rows for each section, and then put the objects in each section. How do I do this? A: Here is a method for a category on NSArray to do grouping: @interface NSArray (Grouping) - (NSArray*) groupUsingFunction: (id (*)(id, void*)) function context: (void*) context; @end @implementation NSArray (Grouping) - (NSArray*) groupUsingFunction: (id (*)(id, void*)) function context: (void*) context { NSArray* groupedArray = nil; NSMutableDictionary* dictionary = [NSMutableDictionary new]; if (dictionary != nil) { for (id item in self) { id key = function(item, context); if (key != nil) { NSMutableArray* array = [dictionary objectForKey: key]; if (array == nil) { array = [NSMutableArray arrayWithObject: item]; if (array != nil) { [dictionary setObject: array forKey: key]; } } else { [array addObject: item]; } } } groupedArray = [NSMutableArray arrayWithArray: [dictionary allValues]]; [dictionary release]; } return groupedArray; } @end You can use it like this: id GroupNameByFirstLetter(NSString* object, void* context) { return [object substringToIndex: 1]; } NSInteger SortGroupedNamesByFirstLetter(id left, id right, void* context) { return [[left objectAtIndex: 0] characterAtIndex: 0] - [[right objectAtIndex: 0] characterAtIndex: 0]; } NSMutableArray* names = [NSArray arrayWithObjects: @"Stefan", @"John", @"Alex", @"Sue", @"Aura", @"Mikki", @"Michael", @"Joe", @"Steve", @"Mac", @"Fred", @"Faye", @"Paul", nil]; // Group the names and then sort the groups and the contents of the groups. groupedNames_ = [[names groupUsingFunction: GroupNameByFirstLetter context: nil] retain]; [groupedNames_ sortUsingFunction: SortGroupedNamesByFirstLetter context: nil]; for (NSUInteger i = 0; i < [groupedNames_ count]; i++) { [[groupedNames_ objectAtIndex: i] sortUsingSelector: @selector(compare:)]; } A: I modified St3fans answer to be a bit more modern and work with Blocks instead: @interface NSArray (Grouping) - (NSArray*) groupUsingBlock:(NSString* (^)(id object)) block; @end - (NSArray*) groupUsingBlock:(NSString* (^)(id object)) block { NSArray* groupedArray = nil; NSMutableDictionary* dictionary = [NSMutableDictionary new]; if (dictionary != nil) { for (id item in self) { id key = block(item); if (key != nil) { NSMutableArray* array = [dictionary objectForKey: key]; if (array == nil) { array = [NSMutableArray arrayWithObject: item]; if (array != nil) { [dictionary setObject: array forKey: key]; } } else { [array addObject: item]; } } } groupedArray = [NSMutableArray arrayWithArray: [dictionary allValues]]; [dictionary release]; } return groupedArray; } You can use it like this: NSArray *grouped = [arrayToGroup groupUsingBlock:^NSString *(id object) { return [object valueForKey:@"name"]; }]; A: You should probably create an array of arrays, one for each letter, and store your names that way. While you can use a single array for storage, there's no quick way to do the segmentation you're looking for. Sorting, sure, but not section-ization.
doc_3471
MD5 of an UTF16LE (without BOM and 0-Byte End) in C# However, I am trying to achieve this in a Swift 4 based iOS app. I tried all options discussed in How to convert string to MD5 hash using ios swift and also https://github.com/krzyzanowskim/CryptoSwift but I am not able to generate the correct MD5 hash. I generated a byte array of the input string and removed the 0-byte at the end of the string and used the functions mentioned in the thread above. If someone could please point me in the right direction. Basically the utf8 string "1234567z-Γ€bc" should become "9e224a41eeefa284df7bb0f26c2913e2" That's what I tried so far: let str = "1234567z" + "-" + "Γ€bc" let data = str.data(using: .utf16LittleEndian)! let bytesArray = data.map { $0 } let bytesArrayNoZero = bytesArray.filter{ $0 != 0} let str2 = String(bytes: bytesArrayNoZero, encoding: String.Encoding.utf16LittleEndian) print (fritz_01.MD5(str2!)) func MD5(string: String) -> Data { let messageData = string.data(using:.utf8)! var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH)) _ = digestData.withUnsafeMutableBytes {digestBytes in messageData.withUnsafeBytes {messageBytes in CC_MD5(messageBytes, CC_LONG(messageData.count), digestBytes) } } return digestData } A: This let str = "1234567z" + "-" + "Γ€bc" let data = str.data(using: .utf16LittleEndian)! already gives the UTF16LE data from which you want to compute the MD5 hash, there is no need to filter out 0-bytes or any other operations. Instead, modify the function from How to convert string to MD5 hash using ios swift to take a Data argument instead of a String: func MD5(messageData: Data) -> Data { var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH)) _ = digestData.withUnsafeMutableBytes {digestBytes in messageData.withUnsafeBytes {messageBytes in CC_MD5(messageBytes, CC_LONG(messageData.count), digestBytes) } } return digestData } so that you can call it with the already-converted data: let str = "1234567z" + "-" + "Γ€bc" let data = str.data(using: .utf16LittleEndian)! let md5Data = MD5(messageData: data) let md5Hex = md5Data.map { String(format: "%02hhx", $0) }.joined() print("md5Hex: \(md5Hex)") // 9e224a41eeefa284df7bb0f26c2913e2
doc_3472
Each of the sound clip is 1 to 2.5 seconds long. I don't need to pause, rewind, fast forward etc. Based on what I read so far AVAudioPlayer only play aiff, wav or caf and none of those are compressed. Any recommendation on what I can do? Thank you. A: CAF files can be compressed, using either lossy or lossless algorithms. If you're using the command line afconvert utility to convert, you could try: * *afconvert -f caff -d ima4 audiofile.wav (for IMA4 compression) *afconvert -f caff -d aac audiofile.wav (for AAC compression) There's also a -b parameter that allows you to set the output bit rate, and a bunch of other options. The man page is basically empty but the full array of possibilities are listed in QA1534.
doc_3473
Additional Info: Web Application, C#, Asp.Net A: The best way to handle Mixed Content warning messages is to deliver all content over HTTPS. Otherwise you open yourself up to all sorts of nasty vulnerabilities. If you are hosting your content (images, etc) on your own servers, just change the URL reference in your HTML to the HTTPS version of the URL. If the content is on another host, use their HTTPS URL.
doc_3474
An example would be something like the following: from typing import Callable, Optional, TypeVar from typing_extensions import ParamSpec P = ParamSpec('P') R = TypeVar('R') def preserve_nulls(f: Callable[P, R]) -> Callable[???, Optional[R]]: def inner(*args, **kwargs): if any(value is None for value in args): return None elif any(value is None for value in kwargs.values()): return None else: return f(*args, **kwargs) return inner In this case, given a function f with signature (foo: int, bar: str, baz: List[str]) -> int, then the decorated function preserve_nulls(f) should have signature (foo: Optional[int], bar: Optional[str], baz: Optional[List[str]]) -> Optional[int]. Expressing the new return type is simple, since I can just do Optional[R]. But I don't know what to replace the ??? in my above example with to essentially express "the result of applying Optional to every argument in P". Ultimately, my goal is to find a suitable annotation for preserve_nulls such that given something like the following, def f(foo: int, bar: str, baz: list[str]) -> int: return 0 wrapped_f = preserve_nulls(f) correct = wrapped_f(foo=1, bar=None, baz=None) incorrect = wrapped_f(foo='one', bar=None, baz=[None]) Then if I run it through MyPy (or another type checker), it will be happy that the correct call is valid, but complain that foo and baz have the wrong type in the incorrect call. Ideally the solution should be adaptable to other 'modifications' other than just Optional, like say replacing each argument type T with Callable[[], T] or List[T] or whatever. I am prepared for the possibility that this is simply not currently possible, but if it can be done then any help is much appreciated.
doc_3475
Can you create a Trigger that if a new row is inserted with the name 'Bob', increase the value associated to Bob by 25%? If so, how? A: Try this: CREATE OR REPLACE TRIGGER trigger_name BEFORE INSERT ON TABLE_NAME FOR EACH ROW BEGIN IF :new.NAME = 'Bob' then :new.VALUE := :new.VALUE + (:new.VALUE*0.25) ; END IF; END; / I'm not oracle expert but I tried. Hope u can have solution.
doc_3476
Everything works (I think) when the user is already logged into Google via their browser. The problem happens when they aren't. Instead of their todo list, or a blank one under their user id, they see the todo list of an undefined user until they hit refresh, then things work again. The Firebase url doesn't see their uid until they hit refresh. If you're logged in to Google, you can replicate the error by opening an incognito window. You can see the errors in my code at http://lacyjpr.github.io/todo-backbone, and my repo at https://github.com/lacyjpr/todo-backbone This is my authentication code: // Authenticate with Google var ref = new Firebase(<firebase url>); ref.onAuth(function(authData) { if (authData) { console.log("Authenticated successfully"); } else { // Try to authenticate with Google via OAuth redirection ref.authWithOAuthRedirect("google", function(error, authData) { if (error) { console.log("Login Failed!", error); } }); } }) // Create a callback which logs the current auth state function authDataCallback(authData) { if (authData) { console.log("User " + authData.uid + " is logged in with " + authData.provider); uid = authData.uid; } else { console.log("User is logged out"); } } This is the code that gets the UID to use as a firebase key: // Get the uid of the user so we can save data on a per user basis var ref = new Firebase(<firebase url>); var authData = ref.getAuth(); if (authData) { var uid = authData.uid; console.log(uid); } // The collection of todos is backed by firebase instead of localstorage var TodoList = Backbone.Firebase.Collection.extend({ // Reference to this collection's model. model: app.Todo, // Save all of the todos to firebase url: <firebase url> + uid, Thanks in advance for any advice you can offer! A: You're calling .getAuth() before a user is authenticated. Your app heavily relies on the uid to work properly. So in your case you would want to kick off the Backbone portion of the app once user has successfully authenticated. You could modify your app.js to only kick off if the user is authenticated. // js/app.js var app = app || {}; var ENTER_KEY = 13; $(function() { var ref = new Firebase(<firebase url>); var authData = ref.getAuth(); if (authData) { ref.authWithOAuthRedirect("google", function(error, authData) { if (error) { console.log("Login Failed!", error); } else { // kick off app new app.AppView(); } }); } else { new app.AppView(); } }); While this will work, it isn't the ideal solution. But there is no other option since you don't have a login screen. Ideally, you'd want to provide the user a place to login, and then you'd have access the .getAuth() value. Also, don't worry about storing the uid on the window. .getAuth() is the cached user, so there's no network call to get the data.
doc_3477
I've managed to get .htaccess to recognise this RewriteRule RewriteRule ^slugone/(.*)/(.*)$ /slugone/$1?query=$2 [L,R=301] But this doesn't do what I need it to, instead of masking /slugone/dynamicslug/00000 to be /slugone/dynamicslug?query=00000, it is instead redirecting the pretty URL to the URL with query parameters. /dynamicslug/ is a slug that is used to show a specific product on the page, and the ?query=00000 is used to select a variant of this product, so I can't explicitly use /dynamicslug/ in my rewrite rule, either. Searching SO hasn't given me any results, as all of the questions I can find are using index.php in their rewrite, which I am not. A: You should reverse your RewriteRule: RewriteCond %{QUERY_STRING} ^query=([0-9]+)$ RewriteRule ^slugone/([^/]+)$ /slugone/$1/%1? [L,R=301] EDIT: If you want it to behave as a pretty URL you should only remove the redirection in your initial RewriteRule: RewriteRule ^slugone/(.*)/(.*)$ /slugone/$1?query=$2 [L]
doc_3478
Code: <a href="#" onclick="window.onpopstate = function() { alert('pop'); }; return false; ">set up window.onpopstate </a><br> <a href="#somehash2">change hash</a> <div onclick="alert(location.href);">show location.href</div>​ Why does clicking the change hash link fire the popstate, shouldn't it only be fired if I click the change hash link then click back? A: The reason window.onpopstate fires are not because of a change to the hash. It's because the history has been changed when you click on the anchor tag. From https://developer.mozilla.org/en/DOM/window.onpopstate : A popstate event is dispatched to the window every time the active history entry changes. If the history entry being activated was created by a call to history.pushState() or was affected by a call to history.replaceState(), the popstate event's state property contains a copy of the history entry's state object.
doc_3479
I have an xml webservice contain only a string example: You enter Invalis data I wanna read this string to my app. my code was working perfect but suddnly it start to return an html code not the string whic i want :( here is my code: try { String xx; DefaultHttpClient httpClient = new DefaultHttpClient(); ; HttpGet httpPost = new HttpGet(urlString); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); inputStream = httpEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); StringBuilder stringBuilder = new StringBuilder(); String line = null; if ((line = reader.readLine()) != null) { stringBuilder.append(line + "\n"); xx = stringBuilder.toString(); } inputStream.close(); } catch (UnsupportedEncodingException e) { System.err.print("UnsupportedEncodingException: " + e); } catch (ClientProtocolException e) { System.err.print("ClientProtocolException: " + e); } catch (IOException e) { System.err.print("IOException: " + e); } so pleas if any one can help !!!
doc_3480
I have created a function to merge all the dates and it returns the list of dates as a varchar value like this. DECLARE @s VARCHAR(MAX) Select @s=COALESCE(@s + ',','')+LeaveDates from LeaveRequest where EmpId=1154 and Date >= DATEADD(month, -5, GETDATE()) IF '10-03-2017' in (@s) print 'Yes' else print 'No' print @s Result No '19-10-2016','08-03-2017', '09-03-2017', '10-03-2017', '11-03-2017' DECLARE @s VARCHAR(MAX) Select @s=COALESCE(@s + ',','')+LeaveDates from LeaveRequest where EmpId=1154 and Date >= DATEADD(month, -5, GETDATE()) IF '10-03-2017' in ('19-10-2016','08-03-2017', '09-03-2017', '10-03-2017', '11-03-2017') print 'Yes' else print 'No' print @s Result Yes '19-10-2016','08-03-2017', '09-03-2017', '10-03-2017', '11-03-2017' It doesn't give the required result with that function. Any help would be really appreciated. A: Try this :- If you want to check a date between FromDate and ToDate you can try this: WHERE DATE BETWEEN FromDate and ToDate
doc_3481
java.lang.RuntimeException: Unable to start activity ComponentInfo{<my activity>}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125) at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3553) at android.app.ActivityThread.access$700(ActivityThread.java:140) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1233) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4898) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at android.support.v4.app.DialogFragment.onActivityCreated(DialogFragment.java:368) at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1486) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1086) at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1877) at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:552) at <my FragmentActivity wrapper>.onStart(BaseActivity.java:16) at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1167) at android.app.Activity.performStart(Activity.java:5216) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2073) ... 12 more I have been unable to reproduce it, and the logs leading up to this crash don't seem to indicate that any DialogFragment was shown. This is the line in the support library that is causing the crash A: mDialog is null, meaning that your dialog wasn't properly created. I had the same situation where this would occur, but in very limited circumstances (nothing to do with screen rotation, but it was something I could reproduce 100% of the time), and it had to do with onCreateView() not properly creating the dialog, leading to the null mDialog. onCreateView() can be used to create a dialog -- the Basic Dialog section of http://developer.android.com/reference/android/app/DialogFragment.html even shows this -- but I proved that it is NOT always reliable. However, in my crash scenario, I found that using onCreateDialog() instead of onCreateView() would always work, even though I was using the same layout and data that my onCreateView() was using. So I changed my code to use onCreateDialog() when using the DialogFragment as a dialog and that solved the issue. So that is one thing you may want to check. If you want a brute force method to stop the crash (though the root cause of why mDialog is null would remain), you can use this code -- which I used successfully until I found the real issue above: @Override public void onActivityCreated(Bundle arg0) { if (getDialog() == null ) { // Returns mDialog // Tells DialogFragment to not use the fragment as a dialog, and so won't try to use mDialog setShowsDialog( false ); } super.onActivityCreated(arg0); // Will now complete and not crash } A: The answer here: DialogFragment : NullPointerException (support library) Add this code: @Override public Dialog onCreateDialog (Bundle savedInstanceState) //Create custom dialog if (dialog == null) super.setShowsDialog (false); return dialog; }
doc_3482
Here's the code: const compareStringsByKey = <T, K extends keyof T>(key: K) => (objA: T, objB: T): number => { if (typeof objA[key] === 'string' && typeof objB[key] === 'string') { const upperStrA = (objA[key] as string).toUpperCase(); const upperStrB = (objB[key] as string).toUpperCase(); return upperStrA.localeCompare(upperStrB, 'en', { numeric: true, sensitivity: 'base', caseFirst: 'lower', }); } return 0; }; I'm using this function to define a custom sorter for a column in my table. However, when I try to compile this code, I get the following error message. Here's the relevant code: // interfaces.ts import { Table } from 'antd'; type EditableTableProps = Parameters<typeof Table>[0]; export type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>; import { ColumnTypes } from './interfaces'; export const columns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string; })[] = [ { title: 'ID', dataIndex: 'id', key: 'id', width: '12rem', ellipsis: true, // "Argument of type 'string' is not assignable to parameter of type 'never'." sorter: compareStringsByKey('id'), editable: true, }, //... ]; I'm not sure what's causing this error or how to fix it. Can anyone help? I wrote this code out from the this link Editable Cells A: compoareStringsByKey<InterfaceOfTableRow, keyof InterfaceOfTableRow>('id') resolved the issue. Thank you guys!
doc_3483
ReferenceError: resolve is not defined. const request = require('request'); let geoLocationPromise = (zipCode) => { return new Promise(()=>{ request({ url:`https://maps.google.com/maps/api/geocode/json?address=${zipCode}`, JSON: true }, (error, response, body)=>{ if(error){ reject('Unable to connect to server'); }else if (response.statusCode === 200) { console.log(body); resolve(JSON.parse(body.currently, undefined, 2)); } }); }); }; geoLocationPromise(841101).then((loc)=>{ console.log(loc); }, (errorMessage)=>{ console.log(errorMessage); }); A: You need to declare the parameters β€œreject” and β€œresolve” for your Promise's callback, like this: const request = require('request'); let geoLocationPromise = (zipCode) => { return new Promise((resolve, reject)=>{ request({ url:`https://maps.google.com/maps/api/geocode/json?address=${zipCode}`, JSON: true }, (error, response, body)=>{ if(error){ reject('Unable to connect to server'); }else if (response.statusCode === 200) { console.log(body); resolve(JSON.parse(body.currently, undefined, 2)); } }); }); };
doc_3484
Using the following MYAPP.jnlp file with the attached APPLICATION_TEMPLATE.JNLP file included in the JNLP-INF directory of the MyApp.jar file. /MYAPP.jnlp <?xml version="1.0" encoding="utf-8"?> <jnlp spec="1.0+" codebase="$$codebase" href="MYAPP.jnlp"> <information> <title>Test App</title> <vendor>Test Vendor</vendor> <homepage href="docs/help.html"/> <description>A Test Application</description> <icon href="images/IMG.gif"/> <icon kind="splash" href="images/IMGSplash.jpg"/> </information> <security> <all-permissions/> </security> <resources> <java version="1.8+ 1.7+"/> <property name="swing.defaultlaf" value="com.test.test.MyLookAndFeel"/> <property name="sun.java2d.noddraw" value="true"/> <property name="jnlp.versionEnabled" value="true" /> <jar href="MyApp.jar" version="4.3.5" main="true"/> </resources> <application-desc main-class="com.test.test.MySwingFrame"> <argument>configFile=$$site/TEST.config</argument> <argument>envFile=$$site/TEST.properties</argument> <argument>logConfigFile=$$site/logback.xml</argument> </application-desc> </jnlp> JNLP-INF/APPLICATION_TEMPLATE.JNLP <?xml version="1.0" encoding="utf-8"?> <jnlp spec="1.0+" codebase="*" href="MYAPP.jnlp"> <information> <title>Test App</title> <vendor>Test Vendor</vendor> <homepage href="docs/help.html"/> <description>A Test Application</description> <icon href="images/IMG.gif"/> <icon kind="splash" href="images/IMGSplash.jpg"/> </information> <security> <all-permissions/> </security> <resources> <java version="1.8+ 1.7+"/> <property name="swing.defaultlaf" value="com.test.test.MyLookAndFeel"/> <property name="sun.java2d.noddraw" value="true"/> <property name="jnlp.versionEnabled" value="true" /> <jar href="MyApp.jar" version="4.3.5" main="true"/> </resources> <application-desc main-class="com.test.test.MySwingFrame"> <argument>*</argument> <argument>*</argument> <argument>*</argument> </application-desc> </jnlp> When putting the above APPLICATION_TEMPLATE.JNLP file into JNLP-INF Java Webstart fails silently after installing the application. I can't find any trace of an error in the trace logs and the console window does not even open up. When removing only the APPLICATION_TEMPLATE.JNLP the application launches. Has anyone had any success signing a JNLP file via APPLICATION_TEMPLATE.JNLP? A: I had a similar problem. My advice is to try the following things: * *Change the java security level of your machine to medium (Control Panel -> Java -> Security tab) *Clear all java cache ( Control Panel -> Java -> View...) *open cmd, set the path of your java home (java 8), open the jnlp file using 'javaws' command..
doc_3485
A: Dont put your data in Activity class . Generally from activy to activity Bundle params is used to pass data . BUt if you tell me your exact problem then may be taht we can find any solution. A: Well not sure if i understood correctly but, Can't you pass around a reference from the Activity to the "other" class method? Like : class YourClass { //bla bla bla public void yourMethod(Activity activity) { if(null != activity) activity.method(); else //something } } cheers
doc_3486
* *ESP32 starts a https server, with the limitation of 6 concurrent TCP socket connections *A Xamarin App running on Android using javax.net.ssl as the TLS client The observation is, that the App opens 6 sockets. Unfortunately we have memory limitations on the ESP32. About 160kb of heap is available and for each socket we need roughly 30kb for each SSL session context. Is it possible to limit the number of sockets created by the Android tls client? To clarify, the app is delivered by a supplier. For the communication the xamarin httpclient is used, which does not provide low level access to the sockets. Observing the network communication with wireshark it shows that the Client automatically used between 4-6 socket connects. This seems to be in line with the http protocol, to speed up the page loads. see for example https://www.oreilly.com/library/view/http-the-definitive/1565925092/ch04s04.html A: Leaving this here in case someone else stumbles upon a similar requirement "to limit number of connections". The HttpClientHandler has a Property MaxConnectionsPerServer, which sets a connection Limit per Endpoint. The full documentation can be found dotnet-maxconnections
doc_3487
I did read the typescript documentation and learned part of what's happening in that line but it still was not enough for me to understand that. A: The type Replace is replacing properties in T, with properties in R. To break it down: * *Omit<T, keyof R> removes properties from T those with same name as properties in R. *Then & R intersects the resulting type from (1) with R. That means it adds the properties in R to the resulting type. This may seem weird in that it re-adds the same properties to the resulting type those it removed earlier. But I suspect this was done to replace the type of the properties. Here is an example. type Replace<T, R> = Omit<T, keyof R> & R; type A = { prop1: string, prop2: string, prop3: string, prop4: string }; type B = { prop3: number, prop4: number }; type X = Replace<A, B>; const x: X = { prop1: '1', prop2: '2', prop3: 3, prop4: 4 } A: It remove the common key of T and R from T, then intersect the result with R as you can see, the common key is b, b of A is string, now it is boolean(from b of C) playground
doc_3488
Basically, it would be something like this: function rednessAsPercent(r, g, b) { // Does some math to determine redness. } alert(rednessAsPercent(255, 0, 0)); // Alerts: 100 alert(rednessAsPercent(255, 255, 0)); // Alerts: 0. This is pure yellow. alert(rednessAsPercent(255, 122, 122)); // Alerts: ~50. This is sort of pink. Any ideas? Thanks! A: You'd have to come up with a better definition of what "redness" means - on what scale (presumably red-blue-yellow) This might be useful: http://en.wikipedia.org/wiki/HSL_color_space
doc_3489
I'm starting to find this tedious, and so I've been trying to come up with a nice profile.ps1 which will get me a DirectoryEntry for the resource forest that I can work on with Powershell (v2.0) on my local workstation instead, and save me the tedium of constantly re-establishing RDP sessions. So I've got some code in my profile.ps1 which looks like this: $resforest = "LDAP://DC=ldap,DC=path,DC=details" $creds = Get-Credential -credential "RESOURCE_FOREST\my_admin_account" $username = $creds.username $password = $creds.GetNetworkCredential().password $directoryentry = New-Object System.DirectoryServices.DirectoryEntry($resforest,$username,$password) All of this proceeds fine, however, when I come to actually use the entry thus: $search = New-Object DirectoryServices.DirectorySearcher($directoryentry) $search.filter = "(&(anr=something_to_look_for))" $search.findall() I get a logon failure. Now, I know the credentials are fine, I can map drives with them from my workstation to machines in the resource forest - and that works fine - so what am I ballsing up here? PS - Please don't ask me to do anything with Quest's AD cmdlets - they're not allowed here. A: Turns out the issue was with the serverless binding I was attempting to do. If I modify the LDAP path to "LDAP://ldap.path.details/DC=ldap,DC=path,DC=details" then everything works. Thanks for everyone who at least looked at the question ;)
doc_3490
For example, this is the JSON I have in $json_create { "Key 1":"Value 1", "Key 2":"Value 2", "Key 3":"Value 3", "Key 4":"Value 4" } That comes over file_get_contents $requestBody = file_get_contents('php://input'); $json_create= json_decode($requestBody); And this is the JSON I am creating $final_json = [ $json_create, "type" => "message", "elements" => $json_merge, "actions" => $actions_json ]; echo json_encode($final_json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK); Which print something like { "type": "message", "elements": [ { "msg_text": "This is a simple response message" } ] } What I am trying to achieve is { "Key 1":"Value 1", "Key 2":"Value 2", "Key 3":"Value 3", "Key 4":"Value 4", "type": "message", "elements": [ { "msg_text": "This is a simple response message" } ] } There is quite a lot on that subject but somehow I could not succeed in implementing it. A: Use array_merge rather than putting the $json_create inside the array. $final_json = array_merge($json_create, [ "type" => "message", "elements" => $json_merge, "actions" => $actions_json ]); A: <?php $json_create = '{"Key1": "Value 1", "Key2": "Value 2", "Key3": "Value 3", "Key4": "Value 4"}'; $json_create = (array) json_decode($json_create); $your_array = [ "type" => "message", "elements" => 'foo', "actions" => 'bar' ]; $final_json = array_merge($json_create, $your_array); $result = json_encode($final_json); echo $result; output { Key1: "Value 1", Key2: "Value 2", Key3: "Value 3", Key4: "Value 4", type: "message", elements: "foo", actions: "bar" } A: This can be done using union operator also. $requestBody = '{ "Key 1":"Value 1", "Key 2":"Value 2", "Key 3":"Value 3", "Key 4":"Value 4" }'; $json_create= json_decode($requestBody, true ); $other_array = [ "type" => "message", "elements" => [], "actions" => [] ]; $final_json = $json_create + $other_array;
doc_3491
The structure of my bootstrap look so: ➜ bootstrap-3.1.1-dist tree . β”œβ”€β”€ css β”‚Β Β  β”œβ”€β”€ bootstrap-theme.css β”‚Β Β  β”œβ”€β”€ bootstrap-theme.css.map β”‚Β Β  β”œβ”€β”€ bootstrap-theme.min.css β”‚Β Β  β”œβ”€β”€ bootstrap.css β”‚Β Β  β”œβ”€β”€ bootstrap.css.map β”‚Β Β  └── bootstrap.min.css β”œβ”€β”€ fonts β”‚Β Β  β”œβ”€β”€ glyphicons-halflings-regular.eot β”‚Β Β  β”œβ”€β”€ glyphicons-halflings-regular.svg β”‚Β Β  β”œβ”€β”€ glyphicons-halflings-regular.ttf β”‚Β Β  └── glyphicons-halflings-regular.woff └── js β”œβ”€β”€ bootstrap.js └── bootstrap.min.js 3 directories, 12 files while the structure of downloaded directory looks so: ➜ glyphicons_free tree . β”œβ”€β”€ _changelog.txt β”œβ”€β”€ _readme_first.txt β”œβ”€β”€ glyphicons β”‚Β Β  └── png β”‚Β Β  β”œβ”€β”€ glyphicons_000_glass.png . . . β”‚Β Β  └── glyphicons_469_server_new.png └── glyphicons_social └── png β”œβ”€β”€ glyphicons_social_00_pinterest.png . . . └── glyphicons_social_49_ios.png 4 directories, 522 files Where should i put this png files? How should I refere to them? A: I usually use the icomoon app to convert svg files into a typeface. PNG would not give you the best result, you need to get the image source either AI or other vector sources, convert them into svg and feed it into this app and you can get your font. I don't think you can repack bootstrap fonts without having the sources, unless you create a new typeface with your added glyphs and all the existing bootstrap ones. which you can get their source here: Glyphicons althought not for free.
doc_3492
I have googled and found a site that suggested the following: $hex = file_get_contents('hex.txt'); file_put_contents('converted.pdf', pack('H*', $hex)); where hex.txt is extract of the data from the table. However, I am getting the error PHP Warning: pack(): Type H: illegal hex digit x in .... Below is an shorten version of the extracted hex string 0xEC5A09584CFBFB3F33A575A64D9B164EB750A..... So now, I would like to know if it is possible to convert these hex string into binary and write it into a file. Thank you and hope someone can help me with this issue. A: 0x just denotes the string as a hexadecimal number. Strip it and pack() the rest. A: Use a pdf generation library for php: * *In the php library: http://es1.php.net/manual/en/pdf.examples-basic.php *External libraries: http://www.tcpdf.org/ http://www.fpdf.org/ A: How about this: $hexAsString = file_get_contents( 'hex.txt' ); // Just in case... assert( '0x' == substr( $hexAsString, 0, 2 )); // Skip first two chars $hexDigits = substr( $hexAsString, 2, strlen( $hexAsString ) -2 ); file_put_contents( 'converted.pdf', pack('H*', $hexDigits)); A: I think you already posted the answer to your question in a comment: The hex string was generated by a software called Front Desk which converted uploaded files into hex string and store it as a hex string. Your best bet is to either find some kind of documentation on how Front Desk converts its files; or go the hard way and do some trial&error reverse-engineering by uploading some new simple test-files. It might well be the system adds for instance some kind of checks/meta-data to the hex-string. Or does some kind of compression first (think ZIP).
doc_3493
<ListView ItemsSource="{Binding PersonCollection}"> <StackPanel Orientation="Horizontal"> <Label Content="{Binding FirstName}"></Label> <ListView ItemsSource="{Binding MiddleNames}"> <Label Content="{Binding}"></Label> </ListView> <Label Content="{Binding LastName}"></Label> </StackPanel> </ListView> Here the Model: class Person { String FirstName, LastName; String[] MiddleNames; } And the Layout would look similar to this: John Ivy Robert Downey Junior Max more middlenames in fact even thousands are possible lastname Is the binding of an oberservable collection to a customized template possible? I tried the cellfactory but couldnt get my head wrapped around it, as everybody used only strings. A: I am not 100% sure this is the answer to your question as I am totally unfamiliar with xaml, but hopefully it is... Sample Implementation The sample works by setting the model object (the Person) into the namespace of the FXML loader, which allows you to use a binding expression in FXML to bind to properties of the object. In the sample, there are a few names initially in the model and you can modify the bound list in the model using the add and remove buttons to add or remove a few more canned names in the list. All code goes in a package named sample.names. name-display.fxml <?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.control.Label?> <?import javafx.scene.control.ListView?> <?import javafx.scene.layout.HBox?> <?import javafx.geometry.Insets?> <?import javafx.scene.layout.VBox?> <?import javafx.scene.control.Button?> <VBox xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.names.NameDisplayController"> <HBox prefHeight="150.0" prefWidth="220.0" spacing="5.0" > <children> <Label fx:id="firstNameLabel" text="${person.firstName}" /> <ListView fx:id="middleNameList" prefWidth="100.0" items = "${person.middleNames}" /> <Label fx:id="lastNameLabel" text="${person.lastName}" /> </children> <padding> <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" /> </padding> </HBox> <HBox alignment="CENTER" spacing="30.0"> <children> <Button mnemonicParsing="false" onAction="#addName" text="Add" /> <Button mnemonicParsing="false" onAction="#removeName" text="Remove" /> </children> <padding> <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" /> </padding> </HBox> </VBox> NameDisplayApp.java import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Stage; import java.io.IOException; public class NameDisplayApp extends Application { @Override public void start(Stage stage) throws IOException { Person person = new Person( "Bruce", new String[] { "Simon", "Larry" }, "Banner" ); FXMLLoader loader = new FXMLLoader( getClass().getResource( "name-display.fxml" ) ); loader.getNamespace().put( "person", person ); Pane pane = loader.load(); NameDisplayController controller = loader.getController(); controller.setPerson(person); stage.setScene(new Scene(pane)); stage.show(); } public static void main(String[] args) { launch(args); } } NameDisplayController.java import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; public class NameDisplayController { private Person person; private ObservableList<String> sampleNames = FXCollections.observableArrayList( "George", "Henry", "Wallace" ); public void setPerson(Person person) { this.person = person; } public void addName(ActionEvent actionEvent) { if (!sampleNames.isEmpty()) { person.getMiddleNames().add( sampleNames.remove(0) ); } } public void removeName(ActionEvent actionEvent) { if (!person.getMiddleNames().isEmpty()) { sampleNames.add( person.getMiddleNames().remove(0) ); } } } Person.java import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; public class Person { public StringProperty firstName; public StringProperty lastName; private ObservableList<String> middleNames; public Person(String firstName, String[] middleNames, String lastName) { this.firstName = new SimpleStringProperty(firstName); this.middleNames = FXCollections.observableArrayList(middleNames); this.lastName = new SimpleStringProperty(lastName); } public String getFirstName() { return firstName.get(); } public StringProperty firstNameProperty() { return firstName; } public void setFirstName(String firstName) { this.firstName.set(firstName); } public ObservableList<String> getMiddleNames() { return middleNames; } public String getLastName() { return lastName.get(); } public StringProperty lastNameProperty() { return lastName; } public void setLastName(String lastName) { this.lastName.set(lastName); } } Alternate Implementations There may be other (perhaps more preferred ways) of doing this - e.g. by associating bindings of items in code rather than FXML (which is what I usually do) or injecting the model using a dependency injection system. See afterburner.fx for an example of the injection approach - though I don't know if afterburner also places model objects into the FXML namespace or just injects into the controller (if it doesn't do the injection into the FXML namespace that might be a cool addition you could request for it).
doc_3494
At present, whether is this allowed by the Apple? A: Yes this is allowed by the Apple.
doc_3495
$scope.contacts.$add is not a function Here is my code: app.controller('contactsCtrl',['$scope','$firebaseObject',function($scope,$firebaseObject){ var ref = new Firebase("https://<database_details>.firebaseio.com/contacts"); $scope.contacts = $firebaseObject(ref) $scope.addContact = function(){ $scope.contacts.$add({ name: $scope.name, address: $scope.address, telephone: $scope.telephone, company: $scope.company, email: $scope.email }).then(function(ref){ var id = ref.key(); console.log('contact added with Id: ' + id); }); }; }]); A: You should use $firebaseArray instead of $firebaseObject app.controller('contactsCtrl','$scope','$firebaseArray',function($scope,$firebaseArray){ var ref = new Firebase("https://<database_details>.firebaseio.com/contacts"); $scope.contacts = $firebaseArray(ref) $scope.addContact = function(){ $scope.contacts.$add({ name: $scope.name, address: $scope.address, telephone: $scope.telephone, company: $scope.company, email: $scope.email }).then(function(ref){ var id = ref.key(); console.log('contact added with Id: ' + id); }); }; }]);
doc_3496
typedef void(*pf)(void*); struct M { ~M(){ printf("dtor\n"); } }; int main(void) { M *p = new M; auto f = [](M*p){delete p; }; pf p1 = (pf)&f; (*p1)(p); return 0; } [/code] The crash seems to happen within CRT, unable to debug by myself. Where my crash come from? Thanks a lot A: There are several problems: * *Non-capturing lambdas can be converted to function pointers, pointers to lambdas cannot. Get rid of address-of operator. *Type of function lambda represents is void(*)(M*). pf is void(*)(void*). They are not compatible! Either make lambda take void* or change fp to take M* argument. *C-casts silently do the wrong thing. You do not need one if everything else is correct, implicit conversion is enough. Following code will work: #include <cstdio> struct M { ~M(){ printf("dtor\n"); } }; typedef void(*pf)(M*); int main(void) { M *p = new M; auto f = [](M*p){delete p; }; pf p1 = f; (*p1)(p); return 0; } A: Deleting objects through void* is going to get you into trouble. * *Change the type of argument to f to be void f(M*) *Don't write code like this it will get you in the end Here's your code that works on gcc 4.8 #include <cstdio> class M; //forward dec typedef void(*pf)(M*); struct M { ~M(){ printf("dtor\n"); } }; int main(void) { M *p = new M; auto f = [](M*p){delete p; }; pf p1 = f; (*p1)(p); return 0; }
doc_3497
public class SalaryMonth { public int Id { get; set; } public int StartMonth { get; set; } public int StartDay { get; set; } public int EndMonth { get; set; } public int EndDay { get; set; } public string Name { get; set; } } How do I get the SalaryMonth based on the date supplied and but be one month this my business logic which always return null namespace Contracts.Attendances { public interface IAttendanceService { Task<SalaryMonth> GetASalaryMonthByDate(DateTime date); } public class AttendanceService : IAttendanceService { /.../ public async Task<SalaryMonth> GetASalaryMonthByDate(DateTime date) { var day = date.Day; var month = date.Month; var result = await _context.SalaryMonths. .FirstOrDefaultAsync(p => (p.StartMonth == month && p.StartDay >= day && p.StartDay <= day) || ( p.EndMonth == month && p.EndDay >= day && p.EndDay <= day)); return result; } } } Json from Database { "SalaryMonth": [ { "Id": "3", "StartMonth": "2", "StartDay": "26", "EndMonth": "3", "EndDay": "25", "Name": "March" }, { "Id": "4", "StartMonth": "3", "StartDay": "26", "EndMonth": "4", "EndDay": "25", "Name": "April" }, { "Id": "5", "StartMonth": "4", "StartDay": "26", "EndMonth": "5", "EndDay": "25", "Name": "May" }, { "Id": "6", "StartMonth": "5", "StartDay": "26", "EndMonth": "6", "EndDay": "25", "Name": "June" }, { "Id": "7", "StartMonth": "6", "StartDay": "26", "EndMonth": "7", "EndDay": "25", "Name": "July" }, { "Id": "8", "StartMonth": "7", "StartDay": "26", "EndMonth": "8", "EndDay": "25", "Name": "August" }, { "Id": "9", "StartMonth": "8", "StartDay": "26", "EndMonth": "9", "EndDay": "25", "Name": "September" }, { "Id": "10", "StartMonth": "9", "StartDay": "26", "EndMonth": "10", "EndDay": "25", "Name": "October" }, { "Id": "11", "StartMonth": "10", "StartDay": "26", "EndMonth": "11", "EndDay": "25", "Name": "November" }, { "Id": "12", "StartMonth": "11", "StartDay": "26", "EndMonth": "12", "EndDay": "25", "Name": "December" }, { "Id": "2", "StartMonth": "2", "StartDay": "26", "EndMonth": "2", "EndDay": "25", "Name": "February" }, { "Id": "1", "StartMonth": "12", "StartDay": "26", "EndMonth": "1", "EndDay": "25", "Name": "January" } ] } How to I query the record to allow for users to get Salary month from supplied date. Example user provides any date between 26/12/2019 to 26/01/2020 the result must January since that date is in Jan Month because Jan StartMonth is 12 and StartDate 26 and EndMonth is 1 and EndDate 25 A: So I think I know what you’re trying to do. And if I understand correctly then your logic is a little mixed up in your linq call. Given any day, that day cannot be less than or equal to a date and greater than or equal to that same date unless it is the same date. So you need to do: C# Code: .FirstOrDefaultAsync(p => (p.StartMonth == month && p.StartDay <= day) || ( p.EndMonth == month && p.EndDay >= day )); Hope this helps.
doc_3498
Sub NA() Range("E1").Select Do Until IsEmpty(ActiveCell) If Range("E1") = "password_update" Then If Range("G1") = Range("J1") Then Range("B1") = "N/A" ActiveCell.Offset(1, 0).Select Loop End Sub What I'm trying to do is check if the cell "E1" has the value "password_update" in it and if yes then also check if cell "G1" and cell "J1" has matching content, and if all these criteria matches then type "N/A" to cell "B1". I also wanted to have this script loop through all subsequent rows (E1 then E2 then E3 and so on you get the idea). Now I am no VBA expert, but I wrote this script and no matter how many times I look it makes sense to me logically but it still doesn't work. Any ideas? Help would be appreciated. A: Try this. Whenever possible, avoid using select statement in your code. Sub NA() lastrow = Cells(Rows.Count, "E").End(xlUp).Row For X = 1 To lastrow If Range("E" & X).Value = "password_update" And Range("G" & X) = Range("J" & X) Then Range("B" & X) = "N/A" Next X End Sub A: Similar to code above but if you want to be more explicit about what is happening and the sheets you are using (in case you run when in the wrong sheet for example consider putting something similar to below). This uses the same logic as you used Sub UpdateColBwithNA() 'Place in a standard module Dim wb As Workbook Dim ws As Worksheet Dim LastRow As Long Dim currentRow As Long Set wb = ThisWorkbook Set ws = wb.Sheets("Sheet1") 'Change to name of sheet you are running code against With ws LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row .Range("E1").Activate For currentRow = 1 To LastRow If .Cells(currentRow, "E") = "password_update" And _ (.Cells(currentRow, "G") = .Cells(currentRow, "J")) Then .Cells(currentRow, "B") = "N/A" End If Next currentRow End With End Sub The With statement means you don't have to go to the sheet.
doc_3499
$ worklight build /opt/ibm/Worklight-CLI/worklight: /opt/ibm/Worklight-CLI/IBMnode/bin/node: /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory Googling suggests that the CLI is a 32 bit application. Is this true and how to solve this? Worklight 6.2 Linux itdx-vsptl204 2.6.32-431.20.3.el6.x86_64 #1 SMP Thu Jun 19 21:14:45 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux A: It turns out the team were using the CLI on the server when they should have used the ant build scripts on the server. Thanks for your help. No more action needed on this one.