id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23525900
def post(self, request): author = User.objects.get(id=request.data.get('user_id')) new_article = Article.objects.create(author=author, title=request.data.get('title'), text=request.data.get('text'),img=File(request.data.get('image[0]'))) new_article.save() for i in range(20): img_key = 'image[{}]'.format(i) img = request.data.get(img_key) if img: article_img = ArticleImage(article=new_article,img=File(img), is_main=False ) article_img.save() else : break images = ArticleImage.objects.filter(article=new_article) return Response({ 'article': ArticleSerializer(new_article, context=self.get_serializer_context()).data }) It creates a new article which contains img files. The image files I save in AWS S3 bucket . Saving main image of article using new_article.save() method works fine , but article_img.save() returns an error: **File "C:\Users\Arcvi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\storages\backends\s3boto3.py", line 520, in _save_content content.seek(0, os.SEEK_SET)* ***ValueError: I/O operation on closed file.**** I guess I do something wrong in my for loop. If you need more information about code , I will share it . Please any help. A: Try maybe to open this file and then create django File object. img = request.data.get(img_key) if img: with open(img.file.seek(0), "rb") as opened_image: article_img = ArticleImage(article=new_article,img=File(opened_image), is_main=False ) article_img.save() A: This might sound obvious but ValueError: I/O operation on closed file. Means the file you are working with has closed. If it's a Python PIL image, you can run yourimage.verify(). Once you save (ex: new_article.save()), files become closed. Ex: new_article.img.closed equals True. This happened to me when overriding a Django ModelForm save method. I overcame it by setting commit equals False. The file will stay opened until you finally save.
doc_23525901
b = riakclient.bucket('test') item = b.get('key1') item.data = 'testdata' item.store() I am getting {error,locked} as a RiakError back. Once this starts to happen I also get a lot of errors between the cluster nodes that look like this: Handoff receiver for partition 1134123.... exited abnormally ... {error,locked} Any ideas what this might be or how to resolve? This is riak 2.0.2, thinking about updating but hoping to not have to do that yet. update: this problem manifested itself after the docker (did I mention that?) container I was using was restarted. After restart the riak process came up but was not in a functioning state despite being marked healthy in the cluster. A 'sv restart riak' got the cluster back to working. Still wondering what this means, does not seem to be documented although it does seem to mean the node is in a read-only state. A: This was a problem in the shutdown scripts, node was coming up in unclean state. A restart fixed the issue.
doc_23525902
[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1005 Can't create table 'SSA_DATA.#sql-431_1b8' (errno: 150) (SQL: alter table `reports_fields` add constraint rep orts_fields_report_id_foreign foreign key (`report_id`) references `reports_list` (`id`)) migration code is below public function up() { Schema::create('reports_fields', function(Blueprint $table) { $table->increments('id'); $table->smallInteger('report_id')->unsigned(); $table->smallInteger('field_id')->unsigned(); }); Schema::table('reports_fields', function($table) { $table->foreign('report_id')->references('id')->on('reports_list'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('reports_fields'); } What is the reason for this ?
doc_23525903
Error: socket hang up at connResetException (node:internal/errors:692:14) at Socket.socketOnEnd (node:_http_client:478:23) at /home/node/app/node_modules/dd-trace/packages/dd-trace/src/scope/base.js:54:19 at Scope._activate (/home/node/app/node_modules/dd-trace/packages/dd-trace/src/scope/async_resource.js:47:14) at Scope.activate (/home/node/app/node_modules/dd-trace/packages/dd-trace/src/scope/base.js:12:19) at Socket.bound (/home/node/app/node_modules/dd-trace/packages/dd-trace/src/scope/base.js:53:20) at Socket.emit (node:events:539:35) at endReadableNT (node:internal/streams/readable:1345:12) at processTicksAndRejections (node:internal/process/task_queues:83:21) { code: 'ECONNRESET' } socket hang up
doc_23525904
I would like it to Navigate back to the last UIViewController, though i get a black screen when pressing the leftBAckButton and not the previous UIViewcontroller. View Controller.m viewDidLoad UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"&" style:UIBarButtonItemStyleBordered target:self action:@selector(home:)]; self.navigationItem.leftBarButtonItem = newBackButton; This is the -(void)home:(UIBarButtonItem *)sender -(void)home:(UIBarButtonItem *)sender { [self.navigationController popToRootViewControllerAnimated:YES]; } Though i feel this is correct i receive this when pressing the button As you can see the navigationbar seems to disappear and it never navigates to the previous view controller. When using [self.navigationController popViewControllerAnimated:YES]; I receive! this on the UI What is causing this and how can i fix it?
doc_23525905
Essentially the problem is that in the call to drawRect:(CGRect)rect, rect has origin at (0,0) when it should have origin at (0,nav_bar_height). Therefore, the following code, which draws an image - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); UIGraphicsPushContext(context); // set up the image UIImage * img = [UIImage imageWithData:someData]; // flip the image to the correct orientation CGContextTranslateCTM(context, 0, rect.size.height + rect.origin.y ); CGContextScaleCTM(context, 1, -1); // draw the image CGContextDrawImage(context, rect, [img CGImage]); UIGraphicsPopContext(); } This will cut off the top 30 pixels or so of the image and leave empty the bottom 30. How can I account for the navigation bar height? A: Without knowing more about your view-structure, I risk being unhelpful, but let me know if the following helps at all: instead of using the rect parameter, which can be sort of unpredictable, try using the bounds of your custom view. In reality, I can't imagine why you'd be having this problem, unless your view is being overlapped with the navigation bar; I'd suggest checking to be sure this isn't so, in any case. Best of luck! Update Looks like that didn't help. Just offset your y parameter by self.navigationController.navigationBar.bounds.size.height. So your code should look like: //... CGFloat dy = self.navigationController.navigationBar.bounds.size.height; CGRect r = CGRectMake(rect.origin.x,rect.origin.y + dy, rect.size.width, rect.size.height - dy); //... CGContextDrawImage(context,r,img.CGImage); //... I hope that was more helpful.
doc_23525906
A: If you're using Selenium script by itself, this would be hard, if not impossible. Luckily, you can run selenium from Java, C# and more and have it integrate with JUnit, NUnit or your favorite unit testing framework. If you use one of these languages, you could use it to cause selenium to export the file to a specific location, then use C#/Java to actually go out on the file system and verify that the file was correctly exported to the location, and do any other validation on it. For doing this development, you can typically find all the client libraries under the bin directory of Selenium server. If you're using Selenium IDE, you can even export your test cases to C#, Java, Ruby, or whatever else, or just use it as an example to manually write your own in code. Hope that helps! A: I googled around for a while, and according to selenium core FAQ, u may need to use firefox template to do that. u may take a look of this: http://oopsnullpointer.wordpress.com/2011/01/14/selenium-handling-testing-downloads-with-a-custom-profile/ I have not yet personally tested that though.
doc_23525907
Question: Is there an easy way to use something like try_files within nginx to change a filepath when not found to a different folder with the same file path at the end? I'm currently using a client-side framework (AngularJS) and dealing with checking for the existence of files can get fairly expensive as I am literally performing an AJAX call for each file and looking for a 404 before performing the logic to swap out the path in Javascript. I've seen similar solutions for fallback images but haven't gotten a good solution yet. Here's the gist of what I'm looking to do: * *Look for file at /templates/$1/$2. *On HTTP 404 instead return /templates/default/$2. *This only really needs to happen in the /templates/ location for now. *It's possible that these files could be nested several layers deep so I need something like /templates/my_child_theme/main/sidebar/user_nav.html to redirect to /templates/default/main/sidebar/user_nav.html Backstory: I've been building a site in AngularJS that has a fairly complex templating setup. I am utilizing the awesome ui-router module from Angular UI for deeply nested views and have written a few custom functions to implement child themes similar to Magento's fallback system. Here's what currently happens: AngularJS requests a template path using a getTemplate() function I wrote which first looks for the file at /templates/child_theme_name_here/filepath by performing an XMLHttpRequest, checking for a status code of 404 (file not found), and then either returning that path or (in the case of a 404) returning /templates/default/filepath instead. This way I can overload modify specific templates without needing to copy the entire theme each time, making development easier (we have 3 major corporate clients which will each have their own branded child theme) by not making me keep up with each change across multiple themes. If there is a better way to do this within AngularJS I am open to that as well, it just seemed to me that Nginx would be the most logical place to perform such an action due to to it's low-level integration with the filesystem. A: Solved. Had to teach myself a bit on regular expressions, but finally got it working. Here's what worked: location ~* ^\/templates\/([^\/\\\]+)(.*)$ { try_files /templates/$1$2 /templates/default$2 =404; } Regex Explanation * *~* means case-insensitive matching (not really regex, just nginx syntax) *^ means start of a string *\/ means match a backslash templates means literally match the word templates *\/ means match a backslash again *( means start capturing the following match as a group for later use *[^\\\/] means match anything that's not a backslash or forward slash means the previous set of characters can be matched multiple times (i.e. keep matching anything that isn't a slash. *) means stop capturing characters for this group. We have now defined the string that represents the first folder after /templates/ *(.*) means match any other character as many times as needed (match everything that isn't a line feed in other words) *$ means match the end of the string try_files then tries each URL in order * */templates/$1$2 means try /templates/(everything in capture group 1 above, which holds the folder we captured)(then add everything from capture group which holds the backslash and anything after it until the end of the url) */templates/default$2 is very similar, except instead of using the text from capture group 1 ($1, the folder name we matched) we use the text "default" and then add everything from the second capture group to the end like before *=404 means that if neither of those worked return a 404 error I'm seeing a significant speed improvement by moving this fallback mechanism into the server versus all of the extraneous calls I was forced to do before on the client.
doc_23525908
{ int Array[4]; Array[0] = 1; Array[1] = 2; Array[2] = 3; Array[3] = 4; test_struct->arr = Array; //(Where arr is a pointer to array) Demo(test_struct); } What could go wrong if Array is passed to another function here? Is there possiblity of data corruption? A: Well, if Demo() has bugs that causes it to write outside the bounds of Array, which it can't know anything about, it can of course corrupt memory, yes. Note that you can't use sizeof inside Demo() to figure out the size, you must have a separate argument (or struct member) telling the number of elements available.
doc_23525909
{ "realm": "realm", "auth-server-url": "<IP-ADDRESS>/auth/", "ssl-required": "external", "resource": "client-id", "verify-token-audience": true, "public-client": true, "use-resource-role-mappings": true, "confidential-port": 0, "policy-enforcer": {} } and here how secure it //Secure api with Keycloak const keycloak = require('./config/keycloak-config.js').initKeycloak(); app.use(keycloak.middleware()); app.use("/api/posts",keycloak.protect(), posts); Now tested with it POSTMAN and in header passed 'Authorization: Bearer Token' and its working totally fine. Now come to the issue when trying to access same api with reactjs its failing function getAll(pageNo, limit){ return httpClient({ url: `api/posts?page=${pageNo}&limit=${limit}`, method: 'GET', headers: { 'Content-type': 'application/json', 'Authorization': 'Bearer ' +sessionStorage.getItem('authentication'), 'Access-Control-Allow-Origin': '*' }, }); } Its failed with the below error TypeError: Cannot read property 'keycloak-token' of undefined A: This issue i was getting because nodejs cors was added after keycloak intialization const keycloak = require('./config/keycloak-config.js').initKeycloak(); app.use(keycloak.middleware()); app.use(cors({ origin: true })); Which should be app.use(cors({ origin: true })); const keycloak = require('./config/keycloak-config.js').initKeycloak(); app.use(keycloak.middleware()); A: This issue I was getting because nodejs cors was added after keycloak initialization, app.use(keycloak.middleware()) after app.use(cors())
doc_23525910
here is my registration request code...I'm using WEB service I want to know how to add a image,,My debugger is not Coming in try And Json is giving response Successfully 'class loginAccess extends AsyncTask { protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Signin.this); pDialog.setMessage("Sig in..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... arg0) { List<NameValuePair> params = new ArrayList<NameValuePair>(); String FullName=fullName.getText().toString(); String UserName=userName.getText().toString(); String DateOfBirth=dob.getText().toString(); String Age=age.getText().toString(); String Sex=gender.getText().toString(); String InterestedIn=interestIn.getText().toString(); String ToMeet=toMeet.getText().toString(); String Email=email.getText().toString(); String Password=pwd.getText().toString(); params.add(new BasicNameValuePair("fullName", FullName)); params.add(new BasicNameValuePair("userName", UserName)); params.add(new BasicNameValuePair("dob", DateOfBirth)); params.add(new BasicNameValuePair("age", Age)); params.add(new BasicNameValuePair("gender", Sex)); params.add(new BasicNameValuePair("interestIn", InterestedIn)); params.add(new BasicNameValuePair("toMeet", ToMeet)); params.add(new BasicNameValuePair("image", null)); params.add(new BasicNameValuePair("email", Email)); params.add(new BasicNameValuePair("pwd", Password)); JSONObject json = jsonParser.makeHttpRequest(url,"POST", params); Log.d("Create Response", json.toString()); try { if (json.has((TAG_SUCCESS))) { String status = json.getString(TAG_SUCCESS); if (status.equals("Success")) { flag=0; Intent i = new Intent(getApplicationContext(),Welcome.class); /*i.putExtra("Email",email); i.putExtra("Password", pwd);*/ startActivity(i); finish(); } else { // failed to Sign in flag=1; } } }catch (JSONException e) { e.printStackTrace(); } return null; } protected void onPostExecute(String file_url) { pDialog.dismiss(); if(flag==1) Toast.makeText(Signin.this,"Please Enter Correct informations", Toast.LENGTH_LONG).show(); } } } ' A: i m using this code ..but i want know how add mg in mySql database ' private void selectImage() { final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" }; AlertDialog.Builder builder = new AlertDialog.Builder(Signin.this); builder.setTitle("Add Photo!"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if (options[item].equals("Take Photo")) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); startActivityForResult(intent, 1); } else if (options[item].equals("Choose from Gallery")) { Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, 2); } else if (options[item].equals("Cancel")) { dialog.dismiss(); } } }); builder.show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { ImageView viewImage = null; if (requestCode == 1) { File f = new File(Environment.getExternalStorageDirectory().toString()); for (File temp : f.listFiles()) { if (temp.getName().equals("temp.jpg")) { f = temp; break; } } try { Bitmap bitmap; BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions); viewImage.setImageBitmap(bitmap); String path = android.os.Environment .getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default"; f.delete(); OutputStream outFile = null; File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg"); try { outFile = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile); outFile.flush(); outFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } else if (requestCode == 2) { Uri selectedImage = data.getData(); String[] filePath = { MediaStore.Images.Media.DATA }; Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null); c.moveToFirst(); int columnIndex = c.getColumnIndex(filePath[0]); String picturePath = c.getString(columnIndex); c.close(); Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath)); Log.w("path of image from gallery......******************.........", picturePath+""); viewImage.setImageBitmap(thumbnail); } } '
doc_23525911
Trying to setup on my local machine . I have followed the instructions in this doc : https://docs.confluent.io/platform/current/quickstart/ce-docker-quickstart.html#cp-quickstart-step-1 I am unable to navigate to Control Center at http://localhost:9021 . I am getting localhost refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED I have disabled system and chrome firewalls , increased docker memory to 8GB and few suggestions on stackoverflow Could you please help me to resolve this
doc_23525912
When I run this query the output was : SUNDAY. But we know today is Tuesday(1-1-2013). And then changed the query as select TO_CHAR(to_date('01-JAN-2013', 'DD-MON-YYYY'), 'DAY') FROM DUAL; answer was :TUESDAY. then Changed query as select TO_CHAR(to_date(sysdate+1, 'DD-MON-YYYY'), 'DAY') FROM DUAL; answer is :MONDAY. When I using the sysdate why it is show SUNDAY as output? I am new in oracle db. Please help me. A: use this: select TO_CHAR(sysdate, 'DAY') FROM DUAL; you are using this : to_date(sysdate, 'DD-MON-YYYY') which is giving you date=1/1/0013 which is sunday A: Please refer the documentation for sysdate here. Sysdate is already a date data type. Your example query is inappropriate as to_date function takes first parameter as String not date. Try the simple query below: select TO_CHAR(sysdate, 'DAY') FROM DUAL; This should return TUESDAY as output. A: To_date is used to convert a strin to date. As sysdate is already a date, one must not add add to_date.
doc_23525913
int main() { int (*max)(int, int) = [](int a, int b) { return (a > b ? a : b); }; std::cout << max(10, 20) <<std::endl; int (*max2)(int, int) = [&max](int a, int b) { return max(a, b); }; std::cout << max2(10, 20) << std::endl; return 0; } I try to run one lambda function from another one, but cmake compiler prints error: no viable conversion from 'lambda' to 'int (*)(int, int)' What is my mistake?
doc_23525914
So let's say i have this url mysite.com/work when user access that url, i want to be redirected to: mysite.com/work/ (this i want to happen) But i want this only deep levels, not for .html pages mysite.com/testing.html/ (i don't want this to happen) I have this .htaccess rule, but this add trailing slash to my .html pages also. i don't want that. RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !(.*)/$ RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1/ [L,R=301] Any help? A: You can use this rule for adding trailing slash only for non-files: RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{THE_REQUEST} \s/+(.*?)[^/][?\s] RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE]
doc_23525915
Request with all the fields: { "firstName":"first", "middleName":"middle", "lastName":"last", "location":"USA" } Request with missing field middleName when I don't want to update middleName: { "firstName":"first", "lastName":"last", "location":"USA" } Request with field middleName set to null when I want to update middleName to null: { "firstName":"first", "middleName":null, "lastName":"last", "location":"USA" } How do I identify which field has been set to null and which has not been passed in the request at all.
doc_23525916
glutCreateWindow("Example") create another form, glutCreateSubWindow(hwnd, 0, 0, 100, 100), where hwnd is handle to my main Window Form in C#, i get an AccessViolation Exception. The Glut program is in a C++ DLL. My application is on C# WPF. I need to display glut view at my C# Form C++ code: extern "C" { __declspec(dllexport) int InitGlut(int hwnd, int top, int left, int width, int height) { glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(top,left); glutInitWindowSize(320,320); //glutCreateWindow("Example"); glutCreateSubWindow(hwnd, top, left, width, height); glutDisplayFunc(renderScene); glutMainLoop(); return 0; } } C# code: const string pathToDll = "../../../Release/MyDLL.dll"; [DllImport(pathToDll)] public static extern int InitGlut(IntPtr hwnd, int top, int left, int width, int height); private void Window_Loaded(object sender, RoutedEventArgs e) { IntPtr hwnd = new WindowInteropHelper(Application.Current.MainWindow).Handle; InitGlut(hwnd, 0, 0, 100, 100); } A: Looks like you're hosting a Win32 object in a WPF form. Yes, this requires workarounds. Have you seen the WPF and Win32 Interoperation guide on MSDN? http://msdn.microsoft.com/en-us/library/ms742522.aspx You'll need to check out the HwndHost class, too: http://msdn.microsoft.com/en-us/library/system.windows.interop.hwndhost.aspx
doc_23525917
In this code when I use the query: q = ('plane fly OR car drive -filter:retweets AND filter:replies') It returns tweets that either include the words 'plane' & 'fly' OR 'car' & 'drive'. But if I added another keyword filter on at random, for example: q = ('plane fly OR car drive OR cadburys chocolate -filter:retweets AND filter:replies') This does not return any tweets at all. I'm not sure if I'm misunderstanding the way the query works with the use of OR, but I'd imagine even if there were no tweets containing 'cadburys chocolate', it would still return the other tweets for the other keywords? Does anyone know where I am going wrong? If the query can be structured this way? Or if not, is there a way I can search for multiple keywords/phrases in one query? Thanks for you time, any help is appreciated. A: The syntax seems to be fine. Could you try use AND instead of space when using multiple comparison (more than two). q = ('plane AND fly OR car AND drive OR cadburys AND chocolate -filter:retweets AND filter:replies') You may need to use the AND operator when stringing multiple operators together. A: https://unionmetrics.com/resources/how-to-use-advanced-twitter-search-queries/ According to this link: You can also chain together multiple keywords to create a more complex query. The OR operator will attach to the word that immediately precedes it, very much like order of operations in algebra. For example, the following query will find tweets that mention social media metrics or social media analytics, because the OR links to the metrics and analytics terms q="social media metrics OR analytics" would return results containing the words social media metrics or social media analytics You're not wrong, but it was just never clear on how to search for terms longer than 1 word.
doc_23525918
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); I'm trying to find where createServer within http.js "looks for" a function and then passes it two objects (which above are named 'req' and 'res'. I've searched through http.js and the only thing I found was: exports.createServer = function(requestListener) { return new Server(requestListener); }; Does that mean the anonymous function: function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); } ...is passed as 'requestListener' and... return new Server(requestListener); ...is where the req and res objects get passed back? A: Yes. In Javascript functions themselves are "values" you can assign to "objects". Since you can pass an object to another function, then you may pass a function itself as an object. requestListener is the parameter createServer named as requestListener that is being used to call the Server constructor with it. You can also see this in ruby, where you can call a function and at the same time pass it the code to be executed in a do block, as a parameter.
doc_23525919
Imagine having route dashboard, where I want to gather some data from external API. I have created custom file (tools.js), that I have a function for fetching data from the source written in ( https.request(options, function(res)) {...} ), so basically the process looks like: * *I open my route in browser (tools.js is starting to gather JSON from external API) *Template renders, and result of tools.js call is still undefined *tools.js just ended its loading, displays correct data in console, but the template is already rendered with undefined results. I hope this makes sense. I understand, that this is an expected behaviour, but how can I "re-render" template after getting data from tools.js? A: You'll need to do something like this: tools.js: var https = require('https'); var options = ... exports.getData = function(cb) { var done = false; function errorHandler(err) { if (!done) { done = true; cb(err); } } https.request(options, function(res) { var buf = ''; res.setEncoding('utf8'); res.on('data', function(d) { buf += d; }).on('end', function() { if (!done) { done = true; var ret; try { ret = JSON.parse(buf); } catch (ex) { return errorHandler(ex); } cb(null, ret); } }).on('error', errorHandler); }).on('error', errorHandler).end(); }; route: var getData = require('./tools').getData; // ... app.get('/json', function(req, res) { getData(function(err, data) { if (err) return res.send(500); res.render('mytemplate', { jsondata: data }); }); }); A: You need to render your template after you've obtained the data. So, you wait for the callback or promise from your async fetching of data and in that callback, once you have the data, you can then render your template. If you post your code, we could help much more specifically. Node route handers are designed to be async. They aren't done until you explicitly tell them you're done with the appropriate function call on the response object so they can finish some time later after you're async fetching of data completes, you combine the data with your template and then tell the response object that you're done.
doc_23525920
$('#export').click(function() { $.ajax({ url: 'exportdata.aspx', cache: false, success: function(data) { } }); }); } I want to export datagrid item into excel file. when i use aler(data). item is displaying but excel save as and download window is not appearing. A: You can't use ajax for this purpose. Just open the url in new window. function exporttoexcel() { $('#export').click(function() { window.open('exportdata.aspx'); }); }
doc_23525921
A: Try placing the following in the style or CSS and see if it works: box-sizing:border-box;
doc_23525922
So I think Kafka 'knows' timestamp for every record it stores. I need to get the timestamp for the record with a specified partition and offset. Is it possible? An information system put the wrong data to Kafka (incorrect product id in client's order) and I need to analyze log files to find out the cause. It would be much easier to do it knowing the timestamp of that record. A: org.apache.kafka.clients.consumer.ConsumerRecord has a method called timestamp(). Is this what you are looking for?
doc_23525923
Since this is really really bad practice, I wanted to go head with some layout manager. Even though since it is not resizable, there should not be issues, but still it feels wrong. It looks like this : https://i.imgur.com/k1Ne5v9.png and the code for it is: public class MainMenu { private static JFrame mF = new JFrame("Main Menu"); public static void main(String[] args) { System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider"); Font menuFont = new Font("Courier",Font.BOLD,16); mF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mF.setSize(465,230); mF.setLocationRelativeTo(null); mF.getContentPane().setBackground(Color.WHITE); Color blueSteel = new Color(70,107,176); JPanel p = new JPanel(); p.setSize(600,50); p.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); p.setLocation((mF.getWidth() - p.getWidth()) /2, 20); p.setBackground(blueSteel); JLabel l = new JLabel("Welcome to the menu GENERATORRRR"); l.setFont(menuFont); l.setForeground(Color.WHITE); p.add(l, gbc); JButton runMenuButt = new JButton("Generate Menu"); runMenuButt.setLocation(20 , 90); JButton manageRecipButt = new JButton("Manage Recipients"); manageRecipButt.setLocation(240 , 90); menuUtilities.formatButton(runMenuButt); menuUtilities.formatButton(manageRecipButt); mF.setResizable(false); mF.setLayout(null); mF.add(runMenuButt); mF.add(manageRecipButt); mF.add(p); mF.setVisible(true); runMenuButt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Generate Menu pressed"); mF.dispose(); getMenuInJavaNow.main(); //MenuGenerator.generateTheMenu(); } }); manageRecipButt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DeliveryPackage menuRecipients = new DeliveryPackage(); if (menuRecipients.recipientList != menuRecipients.fileNotFoundMessage) { editRecipientList(menuRecipients); } else { JOptionPane.showMessageDialog(null,"File not found at " + menuRecipients.recipientFilePath ,menuRecipients.recipientFileName + " missing!" ,JOptionPane.ERROR_MESSAGE); } } }); } How could I convert this into GUI that uses some layout manager? Also I dont mind if you point out any mistakes/bad practices used in the code, because I am self-taught and I would definitely like to avoid them in the future. Thank you for your time A: I have done your layout using layout managers and i have added comments inside the code about the how and why i prefer things like this. However, layout managers need practice in order be able to handle them fast and easy. Just don't avoid to use them. Please, have in mind that all of these are personal preferences. You can keep what you like and ignore what you don't. Here it is: Main class: package test; import javax.swing.SwingUtilities; public class Main { /* * Having a static JFrame is only recommended when you know exactly what you are * doing. 99% of the times (i could say 100% :)) you will never need it. */ // private static JFrame mF = new JFrame("Main Menu"); public static void main(String[] args) { System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider"); /* * All Swing applications must run on their own thread, a.k.a Event Dispatch * Thread (EDT). I also like to use main method separated from GUI * methods/classes. */ SwingUtilities.invokeLater(() -> { MyFrame frame = new MyFrame(); // It is recommended to show the frame (make it visible) after its initiated and // not in its constructor frame.setVisible(true); }); } } MyFrame class: package test; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingConstants; public class MyFrame extends JFrame { private static final long serialVersionUID = -5908534022988507382L; // Things like colours,fonts, dimensions or thing that won't change, i recommend // them to define them as static private static final Font FONT = new Font("Courier", Font.BOLD, 16); private static final Color BLUE_STEEL = new Color(70, 107, 176); private static final Dimension INITIAL_SIZE = new Dimension(500, 250); private static final Dimension MINIMUM_SIZE = new Dimension(300, 200); public MyFrame() { // Now start the standard things for a frame. super("Main Menu"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); getContentPane().setBackground(Color.WHITE); // setSize(465, 230); // Initial size. Do not use setSize() for other // components. Only for frames. /* * Now depends how you want the GUI, you choose the layout manager. In your * uploaded picture you showed a TextField/JLabel at the top and 2 buttons in * the center. You can always go either with GridBag layout, or as i like to go, * with inherited panels. */ /* * In order to learn layout managers, read the java docs. For now i will show * you how to use 2 of them. */ /* * JFrame's content pane uses either FlowLayout, either BorderLayout initially. * For me, i don't actually care, i will define it anyways, so when i'll see the * code i will be able to see easily the layout. A personal preference aswell. */ /* * Read BorderLayout java doc in order to see how it works. */ getContentPane().setLayout(new BorderLayout(1, 15)); // 15 pixels vertical gap /* * Try to describe the variable fully. Personally, i use the "txt" for simple * texts that won't change during runtime. */ JLabel txtWelcome = new JLabel("Welcome to the menu GENERATORRRR"); txtWelcome.setFont(FONT); txtWelcome.setHorizontalAlignment(SwingConstants.CENTER);// Centrize text txtWelcome.setForeground(Color.WHITE); txtWelcome.setBackground(BLUE_STEEL); /* * I describe with few words about heights and dimensions in * createMainButtonsPanel() method. This is the one line :) */ txtWelcome.setPreferredSize( new Dimension(txtWelcome.getPreferredSize().width, txtWelcome.getPreferredSize().height + 15)); /* * Since you want white foreground and blue background, the component must have * opacity. In our case, it is a JLabel which is not opaque initially. */ txtWelcome.setOpaque(true); getContentPane().add(txtWelcome, BorderLayout.PAGE_START);// at the top /* * Now let's add the 2 buttons. For this, we are going to use an inhertied panel * inside the content pane. */ JPanel mainButtonsPanel = createMainButtonsPanel(); getContentPane().add(mainButtonsPanel, BorderLayout.CENTER); // at the center setSize(INITIAL_SIZE); // The initial frame size setMinimumSize(MINIMUM_SIZE); } /* * Use a different method for this panel creation, it will be easier to read the * code later. */ private JPanel createMainButtonsPanel() { JPanel panel = new JPanel(); /* Components at center with 20pixels gap horizontally */ panel.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 1)); /* * Panel's bg color is the initial color, if you want to have the background * color of the frame, must have no opacity. */ panel.setOpaque(false); JButton runMenuButton = new JButton("Generate Menu"); runMenuButton.setFont(FONT); // In case you want the font /* * Adding an actionlistener using an Anonymous inner class is fine. However, if * you use java8+ i would recommend you to go with lamdas since code will look * more clear. */ runMenuButton.addActionListener(e -> { System.out.println("Generate Menu pressed"); // Do more stuff here }); JButton manageReceiptsButton = new JButton("Manage Receipts"); manageReceiptsButton.setFont(FONT); manageReceiptsButton.addActionListener(e -> { JOptionPane.showMessageDialog(panel, "Manage Receipts pressed."); // Do more stuff here }); /* * Now let's handle their height. Flow layout will add them with their initially * height. Initial height changes when you use bigger font/bigger icon, but if * you don't want to use a bigger font you have to increase the height manually. * Other layout managers would increase their height in order fit the whole * panel. I will add them some height directly, but its preferred to use the * extra height as a static field. */ int extraHeight = 15; runMenuButton.setPreferredSize(new Dimension(runMenuButton.getPreferredSize().width, runMenuButton.getPreferredSize().height + extraHeight)); manageReceiptsButton.setPreferredSize(new Dimension(manageReceiptsButton.getPreferredSize().width, manageReceiptsButton.getPreferredSize().height + extraHeight)); /* * Now add them to the panel. I usually add them in the end of the method, * because it will be easier later to change their position. E.g: you might want * the manage receipts button first and then the generate menu button. So, it * will take you just 1 sec to change 2 lines. Adding them after they are * initialized is fine aswell. */ panel.add(runMenuButton); panel.add(manageReceiptsButton); return panel; } } P.s: Ignore if some numbers are not equal to yours (heights and sizes). I have just giving you an example :)
doc_23525924
at de.enough.polish.netbeans.J2mePolishProjectGenerator.generateProjectFromTemplate(J2mePolishProjectGenerator.java:141) at de.enough.polish.netbeans.J2mePolishProjectTemplateWizardIterator.instantiate(J2mePolishProjectTemplateWizardIterator.java:82) at org.openide.loaders.TemplateWizard$InstantiatingIteratorBridge.instantiate(TemplateWizard.java:1046) at org.openide.loaders.TemplateWizard.handleInstantiate(TemplateWizard.java:605) at org.openide.loaders.TemplateWizard.instantiateNewObjects(TemplateWizard.java:439) at org.openide.loaders.TemplateWizardIterImpl.instantiate(TemplateWizardIterImpl.java:248) at org.openide.loaders.TemplateWizardIteratorWrapper.instantiate(TemplateWizardIteratorWrapper.java:160) at org.openide.WizardDescriptor.callInstantiateOpen(WizardDescriptor.java:1590) at org.openide.WizardDescriptor.callInstantiate(WizardDescriptor.java:1531) at org.openide.WizardDescriptor.access$2200(WizardDescriptor.java:90) [catch] at org.openide.WizardDescriptor$Listener$2$1.run(WizardDescriptor.java:2171) at org.openide.WizardDescriptor$Listener$2.run(WizardDescriptor.java:2229) at org.openide.WizardDescriptor$11.run(WizardDescriptor.java:1454) at org.openide.WizardDescriptor.lazyValidate(WizardDescriptor.java:1499) at org.openide.WizardDescriptor.access$1900(WizardDescriptor.java:90) at org.openide.WizardDescriptor$Listener.actionPerformed(WizardDescriptor.java:2236) at sun.reflect.GeneratedMethodAccessor59.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.openide.util.WeakListenerImpl$ProxyListener.invoke(WeakListenerImpl.java:458) at com.sun.proxy.$Proxy26.actionPerformed(Unknown Source) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) at java.awt.Component.processMouseEvent(Component.java:6505) at javax.swing.JComponent.processMouseEvent(JComponent.java:3321) at java.awt.Component.processEvent(Component.java:6270) at java.awt.Container.processEvent(Container.java:2229) at java.awt.Component.dispatchEventImpl(Component.java:4861) at java.awt.Container.dispatchEventImpl(Container.java:2287) at java.awt.Component.dispatchEvent(Component.java:4687) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422) at java.awt.Container.dispatchEventImpl(Container.java:2273) at java.awt.Window.dispatchEventImpl(Window.java:2719) at java.awt.Component.dispatchEvent(Component.java:4687) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729) at java.awt.EventQueue.access$200(EventQueue.java:103) at java.awt.EventQueue$3.run(EventQueue.java:688) at java.awt.EventQueue$3.run(EventQueue.java:686) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87) at java.awt.EventQueue$4.run(EventQueue.java:702) at java.awt.EventQueue$4.run(EventQueue.java:700) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:699) at org.netbeans.core.TimableEventQueue.dispatchEvent(TimableEventQueue.java:159) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:154) at java.awt.WaitDispatchSupport$2.run(WaitDispatchSupport.java:182) at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:221) at java.security.AccessController.doPrivileged(Native Method) at java.awt.WaitDispatchSupport.enter(WaitDispatchSupport.java:219) at java.awt.Dialog.show(Dialog.java:1082) at org.netbeans.core.windows.services.NbPresenter.superShow(NbPresenter.java:1076) at org.netbeans.core.windows.services.NbPresenter.doShow(NbPresenter.java:1126) at org.netbeans.core.windows.services.NbPresenter.run(NbPresenter.java:1098) at org.netbeans.core.windows.services.NbPresenter.run(NbPresenter.java:128) at org.openide.util.Mutex.doEventAccess(Mutex.java:1363) at org.openide.util.Mutex.readAccess(Mutex.java:273) at org.netbeans.core.windows.services.NbPresenter.show(NbPresenter.java:1083) at java.awt.Component.show(Component.java:1651) at java.awt.Component.setVisible(Component.java:1603) at java.awt.Window.setVisible(Window.java:1014) at java.awt.Dialog.setVisible(Dialog.java:1005) at org.netbeans.core.windows.services.DialogDisplayerImpl$1AWTQuery.showDialog(DialogDisplayerImpl.java:260) at org.netbeans.core.windows.services.DialogDisplayerImpl$1AWTQuery.run(DialogDisplayerImpl.java:186) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727) at java.awt.EventQueue.access$200(EventQueue.java:103) at java.awt.EventQueue$3.run(EventQueue.java:688) at java.awt.EventQueue$3.run(EventQueue.java:686) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:697) at org.netbeans.core.TimableEventQueue.dispatchEvent(TimableEventQueue.java:159) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) at java.awt.EventDispatchThread.run(EventDispatchThread.java:91) What am i supposed to do now?
doc_23525925
What are the other tools/ways by which i can see the call-graph / resource access graph for a running process? I have an external library from a developer to construct my own machine vision algos, but the external library is in binary form. When I use the library in my code there are crashes because of the way we access images. I want to see the call-graph or the resource access graph. A: Do I need to have the executable in debug mode? I'm not sure exactly what you mean by this, but getting the call stack for a process will work for both debug-built and release-built binaries. Usually, the only real difference between debug and release is the amount of optimization and debug information included. What are the other tools/ways by which i can see the call-graph / resource access graph for a running process? The easiest way from Visual Studio is to run your program under the debugger (just press F5), however, you can also attach to a running process per the instructions included in your link. If you enable breaking on first-chance exceptions1, you can navigate to the Call Stack window when the crash occurs. Assuming your code is native, you will need the PDB file (.pdb, program database file) for your code and the 3rd party library in order to see function names on the call stack. You can also get the call stack of any running process using Process Explorer, but you will still need the PDB files in order to see the symbols. * *For native exceptions, see Debug -> Exceptions..., and check "C++ Exceptions" and "Win32 Exceptions".
doc_23525926
version: "3.9" services: db: image: mysql:5.7 volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: somewordpress MYSQL_DATABASE: wordpress MYSQL_USER: wordpress MYSQL_PASSWORD: wordpress wordpress: depends_on: - db image: wordpress:latest volumes: - wordpress_data:/var/www/html ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress volumes: db_data: {} wordpress_data: {} Error: Creating my_wordpress_db_1 ... done Creating my_wordpress_wordpress_1 ... Creating my_wordpress_wordpress_1 ... error ERROR: for my_wordpress_wordpress_1 Cannot start service wordpress: driver failed programming external connec tivity on endpoint my_wordpress_wordpress_1 (eaa2b38842baac2cbc2126426076f542fd8806509d5d5b19160e07a38f89f173) : Bind for 0.0.0.0:8000 failed: port is already allocated ERROR: for wordpress Cannot start service wordpress: driver failed programming external connectivity on endpo int my_wordpress_wordpress_1 (eaa2b38842baac2cbc2126426076f542fd8806509d5d5b19160e07a38f89f173): Bind for 0.0. 0.0:8000 failed: port is already allocated ERROR: Encountered errors while bringing up the project. A: The error message you have pasted contains a lot of blank spaces which makes the output hard to read. But if you dig through the reason, Docker states the following why your Wordpress image will not work. ERROR: for wordpress Cannot start service wordpress: driver failed programming external connectivity on endpoint my_wordpress_wordpress_1 (eaa2b38842baac2cbc2126426076f542fd8806509d5d5b19160e07a38f89f173): Bind for 0.0.0.0:8000 failed: port is already allocated The solution is to figure out which other resource is allocating port 8000 and close that program. It might be some other docker instance running, try docker ps -a to view all docker images. Alternatively you may specify a different port in your docker-compose.yml-file. You can try ports: - "8080:80" In your example you have 8000:80 A: You made a change to compiled information after running: npm run build:dev In my case I had manually modified /etc/hosts after compiling the build. This broke referenced paths in the build. Re-running npm run build:dev fixes the issue.
doc_23525927
Multidimensional Array 1: $line_items = [ 0 => ['price' => 41.99, 'id' => 12, 'quantity' => 1], 1 => ['price' => 155.95, 'id' => 11, 'quantity' => 1], 2 => ['price' => 21, 'id' => 13, 'quantity' => 1] ]; Regular Array 2: $price_array = [ 0 => 197.94, 1 => 21.00 ]; And I want to add the prices of each array from Array 1 until they equal to the first element of Array 2. At that point, I want to push the arrays from Array 1 that were used to sum that price into a new array, and repeat the process. So for example the new array would look like this from the above arrays: $finalArray = [ [ 0 => [ "price" => 41.99, "id" => 12, "quantity" => 1 ], 1 => [ "price" => 155.95, "id" => 11, "quantity" => 1 ] ],[ 0 => [ "price" => 21, "id" => 13, "quantity" => 1 ] ] ]; so far I have tried this: $disposableTransactions_array = []; foreach($lineitems_array as $lineitems){ //add the prices to the sum $sum += $lineitems['price']; //should the $sum reach the value of the first element in array if($sum == $disposableTransactions_array[0]){ //push the $lineitems into a new array $finalPrices_array[] = $lineitems; //reset the sum $sum = 0; /* remove first element from checked array to allow the next element in array to be checked */ array_shift($disposableTransactions_array); } } However, I am only getting this as output, rather than both arrays that were summed together being pushed into a multidimensional array: $finalArray = [ 0 => [ "price" => 155.95, "id" => 11, "quantity" => 1 ], 1 => [ "price" => 21, "id" => 13, "quantity" => 1 ] ]; I am a bit stuck on how to get my currently ouput array, into the array I desire. I need to do this because I need to associate the different id's to the two different price points. In my case the prices reflect transactions in an order, so line_items will appear in the same order as the price they are being compared against. The variable part is how many transactions are part of this order and how many line_items are present in a transaction. A: So I believe the problem is within your foreach loop, specifically with the way you're identifying the items that need to be put into the array (you're only checking for the sum on the first value of your prices array at key $disposableTransactions_array[0]). Since your arrays weren't attached to PHP variables*, I took some liberties in naming conventions but this code produces the output you're looking for: $line_items = [ 0 => ['price' => 41.99, 'id' => 12, 'quantity' => 1], 1 => ['price' => 155.95, 'id' => 11, 'quantity' => 1], 2 => ['price' => 21, 'id' => 13, 'quantity' => 1] ]; $price_array = [ 0 => 197.94, 1 => 21.00 ]; //$output_array stores our output $output_array = []; //$sum is used for our math, set a default value $sum = 0; //$sum_items are the items used to build the $output_array $sum_items = []; //loop through each $line_items foreach($line_items as $arrayKey => $item){ //add the price of the current items to the sum $sum += (float)$item['price']; //add the current $line_items array key to $sum_items $sum_items[] = $arrayKey; //check to see if our current $sum is in $price_array $key = array_search((float)$sum, $price_array); if(false !== $key){ //we found the sum, clear out the $output_array_entry so we have a clean slate $output_array_entry = []; //loop through each item we used to get our current $sum foreach($sum_items as $item_id){ //add each item in its entirety to the $output_array_entry from $line_items $output_array_entry[] = $line_items[$item_id]; } //add the $output_array_entry we just built to $output_array $output_array[] = $output_array_entry; //reset our variables $sum_items = []; $sum = 0; } } var_dump($output_array); The solution I'm proposing does three things different from the code you provided: * *We use array_search instead of checking on $disposableTransactions_array[0] so we can account for multiple "sums" in the $price_array *We keep track of the array key from $line_items of the items we're adding together during the foreach loop in the form of $sum_items. We then use $sum_items to create our $output_array_entry which is all of the data from $line_items that we used to find the sum. *We save the data to $output_array I will say though, this relies heavily on the way your $line_items array is structured. If we move any of those items to a different order, the addition may never find the correct $sum inside of $price_array and will return nothing. For Example, if our $line_items looks like this: $line_items = [ 0 => ['price' => 155.95, 'id' => 11, 'quantity' => 1], 1 => ['price' => 21, 'id' => 13, 'quantity' => 1], 2 => ['price' => 41.99, 'id' => 12, 'quantity' => 1], ]; The first time we loop through our $sum is 155.95, then on the next pass our $sum is 176.95, and then on the third pass $sum is 218.94 - none of which are in our $price_array. This makes me believe you may need another check - but without more context I'm not sure A: Because the line items ALWAYS perfectly align with the order of the summed prices, the following approach is suitable/reliable. Code: (Demo) $bucket_sum = 0; $bucket_index = 0; $result = []; foreach ($line_items as $row) { $result[$bucket_index][] = $row; $bucket_sum += $row['price']; if ($bucket_sum >= $price_array[$bucket_index]) { $bucket_sum = 0; ++$bucket_index; } } var_export($result); Keep pushing line items into the current element in the result array until its price total reach the defined sum in the price array. Then increment the index and reset the sum variable and proceed with pushing line items as described in the previous sentence. As a personal challenge, I wanted to try to script a solution using reference variables. Demo $result = []; foreach ($line_items as $row) { $lastKey = array_key_last($result); if ( !$result || array_sum(array_column($result[$lastKey], 'price')) == $price_array[$lastKey] ) { unset($ref); $result[] = &$ref; } $ref[] = $row; } var_export($result); And finally, a dense, functional-style approach: Demo var_export( array_reduce( $line_items, function($result, $row) use ($price_array) { $index = (int) array_key_last($result); $index += array_sum(array_column($result[$index] ?? [], 'price')) == $price_array[$index]; $result[$index][] = $row; return $result; }, [] ) ); As you can see, there are many, many ways to attack this task. I didn't even mention consuming the price array while iterating ...I'll stop here.
doc_23525928
I follow tutorial to do git mv database.yml database.yml.example and git mv secrets.yml secrets.yml.example , then created a new database.yml file on remote server. But now when I want to run app on my local mechine, it shows me an error No such file - ["config/database.yml"] Because there is no database.yml on my local repo. Can I create an new and empty database.yml to fix this? A: The guide just tells you that storing database credentials in a repository is bad practice and you shouldn't do it, but it doesn't mean you don't need to have this files at all.You application still needs it, so you definitely need to create it, just don't store it in main repo with code, this security critical information is better to store it elsewhere you decide to keep your authentification data like separate repository for credentials, key-pass storage or whatever place you want for such critical information. PS Of course, if you just learning since it's not a big deal, you COULD keep your "root-123" credits in repository, but it's better to develop right habit from the beginning or at least get the idea why it should be separated.
doc_23525929
- (NSDictionary *)UploadTranscriptionAudio:(NSString *)uploadfor forPN_ID:(NSString *)pn_id forTaskFlag:(NSString *)taskflag documentPath:(NSString *)documentpath forUserName:(NSString *)username file_path_msd:(NSString *)file_path_msd audioFilePath:(NSString *)audiofilepath{ NSDictionary *response = nil; NSURL * url = [NSURL URLWithString:[AppDelegate sharedInstance].str_webServiceUrl]; ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; [request setPostValue:uploadfor forKey:@"Uploadfor"]; [request setPostValue:pn_id forKey:@"PNID"]; [request setPostValue:taskflag forKey:@"task_flag"]; [request setPostValue:documentpath forKey:@"Path"]; [request setPostValue:username forKey:@"Username"]; [request setPostValue:file_path_msd forKey:@"file_path_msd"]; [request setFile:audiofilepath forKey:@"uploadedfile"]; [request startSynchronous]; NSError *error = [request error]; if (!error) { response = (NSDictionary*)[request responseString]; NSLog(@"Response = %@",response); return response; } return response; } This method is still returning me a NSstring in response. What i want is that this method should return me a NSDictionary. As I have to use the value for the keys inside that dictionary somewhere else. Can somebody help me on this. A: hello shikher maddy says right n u can parse string as follow if (responseString == NULL) { // do something u want } else { NSDictionary *jsonResponse = [responseString JSONValue]; NSLog(@" %@",jsonResponse); } A: If I were you I would use SBJSONParser like this: SBJsonParser *parser= [[SBJsonParser alloc] init]; NSDictionary *dictionnary = [parser objectWithString:responseString error:nil];
doc_23525930
When my root node has no prefix it usually works but in this case an exception is thrown. <xsl:template name="/sv:node" /> I am using JAVA with the Apache XALAN XSLT processor which raises a RuntimeException Caused by: java.lang.RuntimeException: Le préfixe doit se convertir en espace de noms : /sv at org.apache.xml.utils.QName.<init>(QName.java:450) at org.apache.xalan.processor.XSLTAttributeDef.processQNAME(XSLTAttributeDef.java:937) I apologize about the localized message of the RuntimeException, basically it is complaining about the prefix with is not mapped to a namespace. So the question is, how can I match this root node? Edit : Here is my stylesheet tag Here is my stylesheet tag : <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:zip="http://apache.org/cocoon/zip-archive/1.0" xmlns:sv="http://www.jcp.org/jcr/sv/1.0"> A: I suspect you really meant <xsl:template match="/sv:node" /> (with match rather than name). Using <xsl:template name="..."> declares a named template which can be called by <xsl:call-template>, not a matching template for <xsl:apply-templates>, and the name of a named template must be a QName. The exception is telling you that it's trying to treat the three characters "forward-slash, s, v" as the prefix part of the QName and finding that this prefix is not mapped to a URI. A: It was a silly mistake, I was using <xsl:template name="/sv:node" /> instead of <xsl:template match="/sv:node" />
doc_23525931
* *Project *Property *Category Assumptions: * *Each Project has multiple Properties. *Each Property has one Category. *Each Property might have parent Property. I would like to render Symfony form for Project entity. I'm using EntityType field for properties. However, instead of displaying them in one, long list, I would like to divide them in columns, with Categories as headers. Regular way of displaying EntityType field: What I would like to get: How do I do that? - Without using dirty hacks in entities or views. A: So the only way I found it working was: In Repository class (pulling list of all properties with child properties and categories): $this->getEntityManager() ->createQueryBuilder() ->select('t, category, children') ->join('t.category', 'category') ->leftJoin('t.children', 'children') ->where('t.parent IS NULL') ->orderBy('category.sortOrder', 'ASC') ->addOrderBy('t.sortOrder', 'ASC') ->addOrderBy('t.name', 'ASC'); $entities = $query->getResult(); $options = []; /** @var Property $entity */ foreach ($entities as $entity) { $options[$entity->getCategory()->getName()][] = $entity; } In Entity class (pulling the list of IDs of selected properties, to preselect checkboxes in the view file): public function getPropertyIds() { $properties = $this->getProperties(); $propertyIds = []; foreach ($properties as $property) { $propertyIds[] = $property->getId(); } return $propertyIds; } Edition form class, so the data can be validated: $builder ->add( 'properties', EntityType::class, [ 'label' => 'Properties', 'class' => Property::class, 'choice_label' => 'name', 'placeholder' => '', 'expanded' => true, 'multiple' => true, 'required' => false, ] ); And finally, the view file: {% for categoryName, items in properties %} <h2>{{ categoryName }}</h2> <ul> {% for property in items %} <li> <input type="checkbox" name="{{ form.properties.vars.full_name }}[]" value="{{ property.id }}" id="{{ form.properties.vars.id }}_{{ property.id }}"> <label for="{{ form.properties.vars.id }}_{{ property.id }}"> {{ property.name }} </label> </li> {% endfor %} </ul> {% endfor %} {% do form.properties.setRendered %} (I omitted the "checked" and "children" part in the view) However this solution is not ideal in my point of view. I would rather to get rid of manually generating <input...> in the view - I would rather want to use some helper functions. Anyway, this is some kind of low-level solution to my problem. Hope that helps.
doc_23525932
function jst() { var i = 0 ; i = <?php echo 35; ?> alert( i ); } what i really want in netbeans is to interpret that .js file through php interpreter without changing my extension of hello.js to hello.php or in other words i dont wan to change extension of my file from js . the reason behind this is Because netbean provide special support(i.e editing, coloring of text etc) for files with .js extension . this is how i am including file in index.php <script> <?php include 'hello.php'?>; </script> code is working fine but i want to use hello.js instead hello.php in netbeans like as shown in following snippet <script src="hello.js"></script> what should i do?? how professional websites handle this issue?? *.js http://s13.postimg.org/vl6vo4fif/image.png *.php http://s21.postimg.org/t7tuk42l3/after.png every thing has converted to plain text after changing extension A: You can only do as the most used way, via parameter hello.js function jst(alertMe) { alert( alertMe ); } index.php <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>jsFileTest</title> <script type="text/javascript" src="hello.js"></script> <script type="text/javascript"> var alertMe = <?php echo 35; ?> ; </script> </head> <body> <button onclick="jst(alertMe)">Try it</button> </body> </html> Develop your js within your php file. If everything works as expected then you can outsource everything as a separate file .js But remember : php is parsed and interpreted on server side . So everything outside php tags is completely ignored. Therefore : <script type="text/javascript" src="jsFile.js"></script> is pure html and will be ignored. On server side php knows nothing about the existence of these .js file and it will not load and parse it. But this is required if you want php also interpret this file too. If you want to include it with a php file, you can do it like Put <script type="text/javascript"> at the beginning. code completion starts again. jsFile.php index2.php <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>jsFileTest</title> <?php include_once 'jsFile.php'; ?> </head> <body> <?php echo "myID = ".$myId."<br>"; ?> <button onclick="myFunction()">Try it</button> </body> </html> Running : But now we come to the important part. Look at the html output source : <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>jsFileTest</title> <script type="text/javascript"> function myFunction() { alert("Hi from jsFile.php"); } </script> </head> <body> myID = idontknow<br> <button onclick="myFunction()">Try it</button> </body> </html> As you can see , javascript ( function myFuntion() ) is inserted directly in the html output. That is exactly what does not happen with <title>jsFileTest</title> <script type="text/javascript" src="jsFile.js"></script> You can not use src="jsFile.php" <script type="text/javascript" src="jsFile.php"></script> After the parsing is finished the content is sent to the client. From this moment it is useless to even try to parse embedded php code in javascript. (the server is no longer involved , has already done its work) IE detects an error (Status Line). when you double-click this Error window pops up the browser expects valid javascript code and this $myId = "idontknow"; is not a valid JS code. A: You just need to enable the PHP to read JS files. Do this: Open your httpd.conf (Apache configuration file) and find this line: AddHandler application/x-httpd-php .php And add the extension, modifying this line to: AddHandler application/x-httpd-php .php .js You can even add CSS files too. A: put this in customJs.php <?php ob_start(); ?> <script type="text/javascript"> <?php ob_end_clean(); ?> alert('aaaa'); <?php ob_start(); ?> </script> <?php ob_end_clean(); ?>
doc_23525933
task compileGwt(dependsOn: classes, type: JavaExec) { //ext.buildDir = "${project.buildDir}/resources/main/static" ext.buildDir = "${project.rootDir}/src/main/webapp" //ext.buildDir = "${project.buildDir}" ext.extraDir = "${project.buildDir}/extra" ext.generatedDir = "${project.buildDir}/generated" inputs.source sourceSets.main.java.srcDirs inputs.dir sourceSets.main.output.resourcesDir outputs.dir buildDir // Workaround for incremental build (GRADLE-1483) outputs.upToDateSpec = new org.gradle.api.specs.AndSpec() doFirst { file(buildDir).mkdirs() //classpath.each { println it.name} } main = 'com.google.gwt.dev.Compiler' classpath { [ sourceSets.main.java.srcDirs, // Java source sourceSets.main.output.resourcesDir, // Generated resources sourceSets.main.output.classesDir, // Generated classes sourceSets.main.compileClasspath, // Deps ] } args = [ 'com.company.application.UI', // Your GWT module '-war', buildDir, '-logLevel', 'INFO', '-style', 'DETAILED', '-localWorkers', '2', '-compileReport', '-gen', generatedDir, '-extra', extraDir, '-draftCompile' // Speeds up compile with 25% ] maxHeapSize = '1024M' } war.dependsOn compileGwt war { from compileGwt.buildDir } Below is the updated build.gradle with pathingJar, when I run compileGwt, it gives error saying:Could not find or load main class com.google.gwt.dev.Compiler apply plugin: "build-app" apply plugin: 'war' apply plugin: 'java' dependencies { compile("javax.validation:validation-api:1.1.0.Final") compile("javax.validation:validation-api:1.1.0.Final:sources") compile("net.sourceforge.javacsv:javacsv:2.0") compile("org.springframework.boot:spring-boot-starter-security") compile("org.springframework.security:spring-security-ldap") compile("org.apache.directory.server:apacheds-server-jndi:1.5.5") compile("org.springframework:spring-web") compile("com.fasterxml.jackson.core:jackson-databind") compile("javax.servlet:javax.servlet-api:3.1.0") compile("com.google.gwt:gwt-user:2.5.1") compile("com.google.gwt:gwt-servlet:2.5.1") compile("com.google.gwt:gwt-dev:2.5.1") compile("com.google.gwt.inject:gin:1.5.0") compile("com.googlecode.mvp4g:mvp4g:1.4.0") compile("com.googlecode.mvp4g:mvp4g:1.4.0:sources") compile("com.sencha.gxt:gxt:3.0.1") compile("com.sencha.gxt:gxt:3.0.1:sources") compile("org.atmosphere:atmosphere-gwt-client:1.1.0.RC5") compile("org.atmosphere:atmosphere-gwt-server:1.1.0.RC5") compile("com.fasterxml.jackson.datatype:jackson-datatype-hibernate4:2.1.2") compile("org.bouncycastle:bcpg-jdk16:1.46") compile("org.jsoup:jsoup:1.7.2") compile("org.eclipse.jetty:jetty-continuation:9.3.5.v20151012") compile("org.springframework.boot:spring-boot-starter-aop") compile("com.googlecode.lambdaj:lambdaj:2.3.3") compile("org.apache.poi:poi:3.9") compile("org.apache.poi:poi-ooxml:3.9") compile("commons-fileupload:commons-fileupload:1.3.1") compile("org.springframework.security:spring-security-core:4.0.3.RELEASE") compile("com.google.guava:guava:18.0") compile("com.google.guava:guava-gwt:18.0") compile("org.springframework.integration:spring-integration-core:4.2.4.RELEASE") compile("org.samba.jcifs:jcifs:1.3.3") compile("org.springframework.integration:spring-integration-file:4.2.4.RELEASE") compile("org.springframework.integration:spring-integration-ftp:4.2.4.RELEASE") compile("org.springframework.integration:spring-integration-sftp:4.2.4.RELEASE") compile("org.springframework.integration:spring-integration-flow:1.0.0.RELEASE") compile("org.springframework.integration:spring-integration-java-dsl:1.1.0.M1") compile("org.atmosphere:wasync:2.1.2") compile libs.quartz compile libs.spring_jms compile libs.spring_jpa compile libs.jdbc_sybase runtime files("src/dist/conf") runtime files("src/dist/env/local") configurations { all*.exclude group: '', module: 'servlet-api' } } task createDirs << { sourceSets*.java.srcDirs*.each { it.mkdirs() } sourceSets*.resources.srcDirs*.each { it.mkdirs() } webAppDir.mkdirs() } task initProject << { File oldSource = file("./src") File tmpSource = file("./tmp") tmpSource.mkdirs() oldSource.listFiles().each { File f -> f.renameTo new File(tmpSource, f.name) } sourceSets*.java.srcDirs*.each { it.mkdirs() } sourceSets*.resources.srcDirs*.each { it.mkdirs() } webAppDir.mkdirs() File newSource = file(sourceSets.main.java.srcDirs.iterator().next()) tmpSource.listFiles().each { File f -> f.renameTo new File(newSource, f.name) } tmpSource.delete() } task pathingJar(type: Jar) { dependsOn configurations.runtime appendix = 'pathing' doFirst { from "${project.buildDir}/classes" manifest { attributes "Class-Path": configurations.compile.files.join(" ") } } } task compileGwt(dependsOn: pathingJar, type: JavaExec) { //ext.buildDir = "${project.buildDir}/resources/main/static" ext.buildDir = "${project.rootDir}/src/main/webapp" //ext.buildDir = "${project.buildDir}" ext.extraDir = "${project.buildDir}/extra" ext.generatedDir = "${project.buildDir}/generated" inputs.source sourceSets.main.java.srcDirs inputs.dir sourceSets.main.output.resourcesDir outputs.dir buildDir // Workaround for incremental build (GRADLE-1483) outputs.upToDateSpec = new org.gradle.api.specs.AndSpec() doFirst { file(buildDir).mkdirs() //classpath.each { println it.name} } main = 'com.google.gwt.dev.Compiler' classpath { [ pathingJar.archivePath, sourceSets.main.java.srcDirs, // Java source sourceSets.main.output.resourcesDir, // Generated resources sourceSets.main.output.classesDir, // Generated classes //sourceSets.main.compileClasspath, // Deps ] } args = [ 'com.company.application.UI', // Your GWT module '-war', buildDir, '-logLevel', 'INFO', '-localWorkers', '2', '-compileReport', '-extra', extraDir, // '-draftCompile' // Speeds up compile with 25% ] maxHeapSize = '1024M' } war.dependsOn compileGwt war { from compileGwt.buildDir } A: I fixed a similar issue with this gradle plugin : https://github.com/viswaramamoorthy/gradle-util-plugins buildscript { dependencies { classpath "com.github.viswaramamoorthy:gradle-util-plugins:0.1.0-RELEASE" } } ... apply plugin: 'ManifestClasspath' A: See https://github.com/steffenschaefer/gwt-gradle-plugin/commit/087a94377fbd83cab938ffffe51ce8fab871be35 which applies a fix for the gwt-gradle-plugin which had the same issue. instead of setting classpath, you should be able to do something like the following if (System.getProperty("os.name").toLowerCase().contains("windows")) { javaExecSpec.environment("CLASSPATH", classpath.getAsPath()); } A: I fixed this issue based on info from fix for long classpath * *create the following task: task pathingJar(type: Jar) { dependsOn configurations.runtime appendix = 'pathing' doFirst { manifest { attributes "Class-Path": configurations.runtime.files.collect { it.toURL().toString().replaceFirst(/file:\/+/, '/') }.join(' ') } } } *use this task in bootRun task bootRunDev(type: org.springframework.boot.gradle.tasks.run.BootRun, dependsOn: 'build') { dependsOn pathingJar group = 'application' jvmArgs = [ "-agentlib:jdwp=transport=dt_socket,server=y,address=8000,suspend=n" ] doFirst() { main = bootJar.mainClassName classpath = files(sourceSets.main.output.files, pathingJar.archivePath) systemProperty 'spring.profiles.active', 'development' } } A: I was trying to run stand alon java program. Changing the below in run configuration fixed my issue A: This is a simplified version of @GLK's pathingJar solution that works in gradle4.10: task pathingJar(type: Jar) { dependsOn configurations.runtimeClasspath appendix = 'pathing' doFirst { manifest { Set<File> classPathJars = configurations.runtimeClasspath.files attributes "Class-Path": classPathJars.collect {it.toURI().toURL().toString().replaceFirst("file:/", '/')}.join(" ") } } } bootRun { dependsOn pathingJar doFirst { classpath = files(sourceSets.main.output.files, pathingJar.archivePath) } } My sourceSets.main.output.files (in a groovy build) resolves to: [<projectRoot>\build\classes\java\main, <projectRoot>\build\classes\groovy\main, <projectRoot>\build\resources\main]
doc_23525934
Hi i am erasing bitmap that is draw at canvas with touch (fingers) that is working fine the problem i am facing is after rotate bitmap at canvas paths draw in opposition direction mean bitmap erase in opposition direction of my finger touch . DrawingPane.class public class DrawingPanel extends ImageView implements OnTouchListener { private Matrix mMatrix = new Matrix(); private float mScaleFactor = 1f; private float mRotationDegrees = 0.f; private float mFocusX = 0.f; private float mFocusY = 0.f; private int mAlpha = 255; private int mImageHeight, mImageWidth; private ScaleGestureDetector mScaleDetector; private RotateGestureDetector mRotateDetector; private MoveGestureDetector mMoveDetector; private ShoveGestureDetector mShoveDetector; private boolean isMoving=false; EditPhotoActivity editActivity; Bitmap overlayDefault; Bitmap overlay; Bitmap bmp,bmp2; Paint pTouch; int whichTabSelected=0; private Path mPath; Display display ; private ArrayList<Path> paths = new ArrayList<Path>(); private ArrayList<Float> xlist = new ArrayList<Float>(); private ArrayList<Float> ylist = new ArrayList<Float>(); @SuppressLint("NewApi") public DrawingPanel(Context context, int colorPaint,Bitmap bmp) { super(context); if (Build.VERSION.SDK_INT >= 11) { setLayerType(View.LAYER_TYPE_HARDWARE, null); } display = ((Activity)context).getWindowManager().getDefaultDisplay(); mFocusX = display.getWidth()/2f; mFocusY = display.getHeight()/2f; try { overlayDefault=bmp; overlay=bmp; overlay=overlay.copy(Config.ARGB_8888, true); overlay.setHasAlpha(true); } catch (Exception e) { e.printStackTrace(); } mImageHeight = getHeight(); mImageWidth = getWidth(); // Setup Gesture Detectors mScaleDetector = new ScaleGestureDetector(context, new ScaleListener()); mRotateDetector = new RotateGestureDetector(context, new RotateListener()); mMoveDetector = new MoveGestureDetector(context, new MoveListener()); mShoveDetector = new ShoveGestureDetector(context, new ShoveListener()); pTouch = new Paint(Paint.ANTI_ALIAS_FLAG); pTouch.setXfermode(new PorterDuffXfermode(Mode.CLEAR)); pTouch.setColor(Color.TRANSPARENT); //pTouch.setMaskFilter(new BlurMaskFilter(30, Blur.SOLID)); pTouch.setStyle(Paint.Style.STROKE); pTouch.setStrokeJoin(Paint.Join.ROUND); pTouch.setStrokeCap(Paint.Cap.ROUND); pTouch.setStrokeWidth(50); pTouch.setAntiAlias(true); setFocusable(true); setFocusableInTouchMode(true); mPath = new Path(); paths.add(mPath); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mImageHeight=getHeight(); mImageWidth=getWidth(); bmp = Bitmap.createScaledBitmap(overlay, w, h, false); bmp2 = Bitmap.createScaledBitmap(overlayDefault, w, h, false); overlay = bmp.copy(Config.ARGB_8888, true); overlayDefault = bmp2.copy(Config.ARGB_8888, true); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); } @Override protected void onDraw(Canvas canvas) { // mCanvas.drawBitmap(overlayDefault,0, 0, null); //exclude this line to show all as you draw // mCanvas.drawCircle(X, Y, 80, pTouch); //draw the overlay over the background float scaledImageCenterX = (mImageWidth*mScaleFactor)/2; float scaledImageCenterY = (mImageHeight*mScaleFactor)/2; mMatrix.reset(); mMatrix.postScale(mScaleFactor, mScaleFactor); mMatrix.postRotate(mRotationDegrees, scaledImageCenterX, scaledImageCenterY); if(isMoving) { mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY - scaledImageCenterY); } else { mMatrix.postTranslate(0,0); } canvas.setMatrix(mMatrix); canvas.drawBitmap(overlay,0,0, null); for (Path p : paths) { canvas.drawPath(p, pTouch); } super.onDraw(canvas); } public Bitmap getBitmap(){ Bitmap b = Bitmap.createScaledBitmap(overlay,display.getWidth() ,display.getWidth(), false); overlay = b.copy(Config.ARGB_8888, true); return overlay; } public void setBitmap(Bitmap bmp1){ overlay = bmp1; invalidate(); } private float mX, mY; private static final float TOUCH_TOLERANCE = 0; public void touch_start(float x, float y) { if(xlist.size()>0 && ylist.size()>0){ xlist.clear(); ylist.clear(); } xlist.add(x); ylist.add(y); mPath.reset(); mPath.moveTo(x, y); mX = x; mY = y; mPath.transform(mMatrix, mPath); invalidate(); } public void touch_move(float x, float y) { float dx = Math.abs(x - mX); float dy = Math.abs(y - mY); if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) { mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2); mX = x; mY = y; mPath.transform(mMatrix, mPath); } xlist.add(x); ylist.add(y); invalidate(); } public void touch_up() { mPath.lineTo(mX, mY); mPath = new Path(); mPath.transform(mMatrix, mPath); paths.add(mPath); invalidate(); } public void OnTouchParent(MotionEvent event){ mScaleDetector.onTouchEvent(event); mRotateDetector.onTouchEvent(event); mMoveDetector.onTouchEvent(event); mShoveDetector.onTouchEvent(event); float scaledImageCenterX = (mImageWidth*mScaleFactor)/2; float scaledImageCenterY = (mImageHeight*mScaleFactor)/2; mMatrix.reset(); mMatrix.postScale(mScaleFactor, mScaleFactor); mMatrix.postRotate(mRotationDegrees, scaledImageCenterX, scaledImageCenterY); mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY - scaledImageCenterY); float x = event.getX(); float y = event.getY(); /*switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if(whichTabSelected==Constant.ERASE) { touch_start(x, y); invalidate(); } break; case MotionEvent.ACTION_MOVE: if(whichTabSelected==Constant.ERASE) { touch_move(x, y); invalidate(); } break; case MotionEvent.ACTION_UP: if(whichTabSelected==Constant.ERASE) { touch_up(); invalidate(); } break; } if(whichTabSelected==Constant.ERASE) { return true; } else { return false; }*/ invalidate(); } @Override public boolean onTouch(View arg0, MotionEvent event) { if(getTabMode()==Constant.PANZOOM) { mScaleDetector.onTouchEvent(event); mRotateDetector.onTouchEvent(event); mMoveDetector.onTouchEvent(event); mShoveDetector.onTouchEvent(event); float scaledImageCenterX = (mImageWidth*mScaleFactor)/2; float scaledImageCenterY = (mImageHeight*mScaleFactor)/2; } float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if(getTabMode()==Constant.ERASE) { touch_start(x, y); invalidate(); } break; case MotionEvent.ACTION_MOVE: if(getTabMode()==Constant.ERASE) { touch_move(x, y); invalidate(); } break; case MotionEvent.ACTION_UP: if(getTabMode()==Constant.ERASE) { touch_up(); invalidate(); } break; } invalidate(); return true; } public void setBottomTabMode(int mode) { whichTabSelected=mode; } public int getTabMode() { return whichTabSelected; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { mScaleFactor *= detector.getScaleFactor(); // scale change since previous event // Don't let the object get too small or too large. mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f)); return true; } } private class RotateListener extends RotateGestureDetector.SimpleOnRotateGestureListener { @Override public boolean onRotate(RotateGestureDetector detector) { mRotationDegrees -= detector.getRotationDegreesDelta(); return true; } } private class MoveListener extends MoveGestureDetector.SimpleOnMoveGestureListener { @Override public boolean onMove(MoveGestureDetector detector) { PointF d = detector.getFocusDelta(); mFocusX += d.x; mFocusY += d.y; isMoving=true; // mFocusX = detector.getFocusX(); // mFocusY = detector.getFocusY(); return true; } } private class ShoveListener extends ShoveGestureDetector.SimpleOnShoveGestureListener { @Override public boolean onShove(ShoveGestureDetector detector) { mAlpha += detector.getShovePixelsDelta(); if (mAlpha > 255) mAlpha = 255; else if (mAlpha < 0) mAlpha = 0; return true; } } } A: I fixed my problem. Actually when i rotate canvas the event.getX() and event.getY() were not map to current rotation of matrix so by adding this line in mMatrix.invert(tempMatrix); in OnDraw() and also map current x,y in OnTouch() by adding this in OnTouch() method . float[] coords = new float[] { event.getX(), event.getY() }; tempMatrix.mapPoints(coords); float x = coords[0];//event.getX(); float y = coords[1];//event.getY(); its working fine . A: This effect is happening because you are applying the matrix twice to paths. Once at touch_start/touch_move by doing mPath.transform(mMatrix, mPath);. And then again at onDraw(Canvas canvas) by canvas.setMatrix(mMatrix); and then canvas.drawPath(p, pTouch);. To fix, try to remove the mPath.transform(mMatrix, mPath); from touch_start/touch_move. Also, I do not know if it is a good practice to set the matrix directly to the canvas. Instead of canvas.setMatrix(mMatrix);, I would prefer to do the following: canvas.save(); canvas.concat(mMatrix); //write the code.... canvas.restore();
doc_23525935
I execute the tests from Jenkins (freestyle project). In order to to get the user name for each session in Report Portal, I need to know the Report Portal access_token of the user. After finding those, I added to Jenkins for each user a secret text with the ID as the user Jenkins BUILD_USER_ID. Next, In the Jenkins configure page, I clicked on Use secret text(s) or file(s) under Build Environment Then clicked on Add and Secret text. I called the Variable RP_UUID. And set Credentials to Parameter expression. Jenkins gave me a hint: A valid parameter expression consists of the parameter name enclosed within ${ and } I tried to set this filed to be ${ BUILD_USER_ID }, but I got the following error: Rebuilds build #17 Running as SYSTEM Building remotely on Automation in workspace /var/lib/jenkins/workspace/test [WS-CLEANUP] Deleting project workspace... [WS-CLEANUP] Deferred wipeout is used... [WS-CLEANUP] Done ERROR: Could not find credentials entry with ID '${ BUILD_USER_ID }' Finished: FAILURE I tried all sorts of things, but it seems that Jenkins in this stage doesn't recognize any variable name. Any idea how to resolve this, or any different approach? p.s. The field Set Jenkins user build variables is ticked. A: See JENKINS-36470 the only parameter type that can be expanded in the Parameter expression section is a Credentials Parameter. All other parameters are not supported. So if you want to use this mechanism you must define the input parameter as a Credentials type: A: You'd probably need to set "Run as SYSTEM" in Access Control for Builds at https://jenkins-url/configureSecurity When I used "Run as SYSTEM" just for "Project default Build Authorization" it didn't work. Once I set it also under "Per-project configurable Build Authorization" - Then the triggered job could evaluate the parameter expression for the credentials bindings.
doc_23525936
For example : 2015-01-01 10:00:00 and 2015-01-10 11:00:00. I want to calculate number of days between these two days as 10. I tried localtime function, but didn't work. I need a solution for this in perl. Please help. A: Time::Piece has been a standard module in Perl for awhile: use strict; use warnings; use feature qw(say); use Time::Piece; my $date1 = '2015-01-01 10:00:00'; my $date2 = '2015-01-10 11:00:00'; my $format = '%Y-%m-%d %H:%M:%S'; my $diff = Time::Piece->strptime($date2, $format) - Time::Piece->strptime($date1, $format); # subtraction of two Time::Piece objects produces a Time::Seconds object say $diff->days; A: Try this: ( Time::Piece->strptime('2015-01-01 10:00:00', '%Y-%m-%d %H:%M:%S') - Time::Piece->strptime('2015-01-10 11:00:00', '%Y-%m-%d %H:%M:%S') )->days Since v5.9.5 Time::Piece is part of the core Perl distribution
doc_23525937
I'm interested in what memory order guarantee is provided by the mprotect syscall (i.e. the behavior of mprotect with multiple threads or the memory model of mprotect). My questions are (assuming no compilier reordering or with sufficient compiler barrier) * *If thread 1 triggers a segfault on an address due to a mprotect on thread 2, can I be sure that everything happens on thread 2 before the syscall can be observed in thread 1 in the signal handler of the segfault? What if a full memory barrier is placed in the signal handler before performing load on thread1? *If thread 1 does an volatile load on an address that is set to PROT_NONE by thread 2 and didn't trigger a segfault, is this enough of a happens before relation between the two. Or in another word, if the two threads do (*ga starts as 0, p is a page aligned address started readonly) // thread 1 *ga = 1; *(volatile int*)p; // no segfault happens // thread 2 mprotect(p, 4096, PROT_NONE); // Or replace 4096 by the real userspace-visible page size a = *ga; is there a guarantee that a on thread 2 will be 1? (assuming no segfault observed on thread 1 and no other code modifies *ga) I'm mostly interested in Linux behavior and particularly on x86(_64), arm/aarch64 and ppc though information about other archs/OS are welcome to (for windows, replace mprotect by VirtualProtect or whatever it is called....). So far my tests on x64 and aarch64 Linux suggests no violations of these though I'm not sure if my test is conclusive or if the behavior can be relied on in the long term. Some searching suggests that mprotect may issue a TLB shootdown on all threads with the address mapped when permission is removed which might provide the guarantee stated here (or in another word, providing this guarantee seems to be the goal of such operation) though it's unclear to me if future optimization of the kernel code could break this guarentee. Ref LKML post where I asked about this a week ago with no reply yet... Edit: clearification about the question. I was aware that a tlb shootdown should provide the guarantee I'm looking for but I'd like to know if such a behavior can be relied on. In another word, what's the reason such requests are issued by the kernel since it shouldn't be needed if not for providing some kind of ordering guarantee. A: So I asked this on the mechanical-sympathy group a day after posting here and got an answer from Gil Tene. With his permission here's my summary of his answers. The full thread is available here in case there's anything I didn't include that isn't clear. For the overall behavior one can expect from the OS. (as in "would be surprising for an OS to not meet): * *A call to mprotect() is fully ordered with respect to loads and stores that happen before and after the call. This tends to be trivially achieved at the CPU and OS level because mprotect is a system call, which involves a trap, which in turn involves full ordering. [In strange no-ring-transition-implementations (e.g. in-kernel execution, etc.) the protect call would be presumably responsible for emulating this ordering assumption]. *A call to mprotect will not return before the protection request semantically takes hold everywhere within the process. If the mprotect() call sets a protection that would cause a fault, any operation on any thread that happens after this mprotect() call is required to fault. Similarly, if the mprotect() call sets a protection that would prevent a fault, any operation on any thread that happens after this mprotect() call is required to NOT fault. This essentially means that the memory operation on the affected pages on other threads are synchronized with the thread calling mprotect. More specifically, one can expect both of the two cases mentioned in the original question are guaranteed. I.e. * *If it is observed that a load on one thread in the affected page faults due to the mprotect call, this fault happens after mprotect() call and therefore after and is able to observer all memory operations that happens before mprotect. *If it is observed that a load on one thread in the affected page doesn't fault disbite the mprotect call, the load happens before mprotect call and the mprotect call and any code after it are after the load and will be able to observe any memory operations that happens before the load. It was also pointed out that transitivity may not work, i.e. a fault load on one thread may not be after a non-fault load on another thread. This can (effectively) be caused by the non-atomicity of the tlb flush causing different threads/cpus to observer the change in access permission at different times.
doc_23525938
An object reference is required for the non-static field, method, or property PlayerMovement.activeMoveSpeed The first problem was referencing the other Game Object and script, I not sure if its completely fixed now but at least that not the error that its giving me anymore, I've tried doing what this link says https://answers.unity.com/questions/1119537/help-how-do-i-referenceaccess-another-script-in-un.html but as you might see it hasn't worked out, every single time I get the compile errors fixed the script doesn't work because the object reference is not set to an instance of an object, any help would be extremely appreciated (the script I'm trying to reference will be at the end) Thanks using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShieldAttack : MonoBehaviour { public GameObject shield; private Vector3 mousePos; private Camera mainCam; public bool isDashing; private Rigidbody2D rb; GameObject Player; PlayerMovement playerMovement; Shooting shooting; // Start is called before the first frame update void Start() { GameObject.FindGameObjectWithTag("EnemyMelee"); GameObject.FindGameObjectWithTag("Enemy2"); mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>(); rb = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update() { mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition); Vector3 rotation = mousePos - transform.position; float rotZ = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.Euler(0, 0, rotZ); if (Input.GetKeyDown(KeyCode.Space) && playerMovement.dashCoolCounter <= 0 && playerMovement.dashCounter <= 0) { isDashing = true; Instantiate(shield, shooting.bulletTransform.position, Quaternion.identity); if (PlayerMovement.activeMoveSpeed == 5) { DestroyShield(); isDashing = false; } } } void DestroyShield() { Destroy(gameObject); } } using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public float moveSpeed; public Rigidbody2D rb2d; private Vector2 moveInput; public float activeMoveSpeed; public float dashSpeed; public float dashLength = 0.5f, dashCooldown = 1f; public float dashCounter; public float dashCoolCounter; [SerializeField] private TrailRenderer tr; //Start is called before the first frame update void Start() { activeMoveSpeed = moveSpeed; } //Update is called once per frame void Update() { if(dashCounter > 0) { tr.emitting = true; } if(dashCounter < 0) { tr.emitting = false; } moveInput.x = Input.GetAxisRaw("Horizontal"); moveInput.y = Input.GetAxisRaw("Vertical"); moveInput.Normalize(); rb2d.velocity = moveInput * activeMoveSpeed; if (Input.GetKeyDown(KeyCode.Space)) { if (dashCoolCounter <=0 && dashCounter <=0) { activeMoveSpeed = dashSpeed; dashCounter = dashLength; } } if (dashCounter > 0) { dashCounter -= Time.deltaTime; if (dashCounter <= 0) { activeMoveSpeed = moveSpeed; dashCoolCounter = dashCooldown; } } if (dashCoolCounter > 0) { dashCoolCounter -= Time.deltaTime; } } } A: You are using class name PlayerMovement.activeMoveSpeed instead of object name playerMovement.activeMoveSpeed in this part of code: if (PlayerMovement.activeMoveSpeed == 5) { DestroyShield(); isDashing = false; } Also I cannot see playerMovement variable initialization in the ShieldAttack script. You need to mark it with the [SerializeField] attribute or make it public to be able to assign it in the inspector. Or initialize it in your Start() method along with the other fields. A: When you create a variable, you do <type> <name>, where <type> is the kind of thing you want to create and <name> is how you want to reference the instance you created. We as programmers are generally lazy, so if we wanted to create a pineapple we would create an instance of the Pineapple class. What do we call it? Typically just pineapple, and then you wind up with code like Pineapple pineapple; The first term means you're wanting to create a Pineapple, and the second term means you're going to refer to that instance as pineapple. Note the capitalization differences there. The issue with your code is that you've created an instance of PlayerMovement: PlayerMovement playerMovement; but when you're trying to use the instance in your code, you are using the class name PlayerMovement and not the instance name playerMovement. Again, note the capitalization difference. The particular line that you've got: if (PlayerMovement.activeMoveSpeed == 5) should instead be: if (playerMovement.activeMoveSpeed == 5) to refer to the instance and not the class. It is possible to have things that are common to all instances of a class. Those are static items and you would access them by referencing the class name instead of the instance name. The error message you got: An object reference is required for the non-static field, method, or property PlayerMovement.activeMoveSpeed was telling you that you were trying to access a part of the class, but it wasn't static, so you needed to reference the object (instance).
doc_23525939
The folks from the qiime2 forum could´t help me, so perhaps you can. library(ggplot2) library(qiime2R) metadata<-read_q2metadata("Metadata.tsv") uwunifrac<-read_qza("weighted_unifrac_pcoa_results.qza") shannon<-read_qza("shannon_vector.qza")$data %>% rownames_to_column("SampleID") uwunifrac$data$Vectors %>% select(SampleID, PC1, PC2) %>% left_join(metadata) %>% left_join(shannon) %>% ggplot(aes(x=PC1, y=PC2, color=`Name`, shape=`Origen`, size=shannon)) + geom_point(alpha=0.5) +#alpha controls transparency and helps when points are overlapping theme_q2r() + scale_shape_manual(values=c(16,1), name="Name") + scale_size_continuous(name="Shannon Diversity") + scale_color_discrete(name="Name") ggsave("PCoA.pdf", height=4, width=5, device="pdf") When I try to compile I get the following error message: Error: Aesthetics must be either length 1 or the same as the data (9): size But If I only include 1 aesthetic as told, for instance: ggplot(aes(x=PC1, y=PC2, color=Name)) It does compile. I was wondering If there’s a way of including all the aesthetic like I tried in the first place. Here's a look into my data > uwunifrac$data$Vectors %>% + select(SampleID, PC1, PC2) %>% + left_join(metadata) %>% + left_join(shannon) Joining, by = "SampleID" Joining, by = "SampleID" SampleID PC1 PC2 Name Origen shannon_entropy 1 D1_16S 0.18825645 -0.047168594 Lixiviado de mina (2) Minas de Riotinto 6.791300 2 D2_16S 0.09366309 0.106100155 Corta Atalaya (3) Minas de Riotinto 4.375214 3 D3_16S 0.08844727 0.003118801 Rio Tinto (4) Minas de Riotinto 5.090431 4 D4_16S -0.10670870 0.494599196 Odiel 3,4% Rio Odiel 6.285716 5 D5_16S -0.51231492 0.021180538 Odiel 7,7% Rio Odiel 5.881951 6 D6_16S -0.30245182 -0.339569170 Odiel 15% Rio Odiel 5.440700 7 D7_16S 0.21368026 -0.041278615 Pool Balsas de fosfoyesos 7.715696 8 D8_16S 0.20073878 -0.072788430 Piezometro 1 Balsas de fosfoyesos 7.547468 9 D9_16S 0.13668959 -0.124193881 Piezometro 2 Balsas de fosfoyesos 7.671805 So now I realize, the name of the variable in aes( should have been shannon_entropy insted of shannon. Changing that I get a new error message Error: Insufficient values in manual scale. 3 needed but only 2 provided. Thanks in advance, Jose. A: For your updated question: You are providing two shape values (16 and 1) for Origen, but Origen has 3 values (Minas ..., Rio ..., and Balsas...). You must provide a shape value for each Origen value.
doc_23525940
First time making a keylogger,already watched some tutorials but i can´t figure out why it doesn´t work. this is my complete code import pynput from pynput.keyboard import Key, Listener count = 0 keys = [] def on_press(key): global keys, count keys.append(key) count += 1 print("{0} pressed", format(key)) if count >= 999999999999999999999999999999999999999999: count = 0 write_file(keys) keys = [] def write_file(): with open("log.txt", "a") as f: for key in keys: k = str(key).replace("'","") if k.find("space") > 0: f.write('\n') elif k.find("Key") == -1: f.write(k) def on_release(key): if key == Key.esc: return False with Listener(on_press=on_press, on_release =on_release) as listener: listener.join() There are no errors showing in pycharm... A: As John Gordon pointed out in the comments, your keylogger isn't saving until you've collected more than 999999999999999999999999999999999999999999 keys. At three keys a second, nonstop, that'll take about a year ten million billion years to type, and would create a file almost exactly 1GB 10 thousand trillion trillion GB in size. According to a typing speed test, however, people type on average 190-200 characters (not words) per minute - why not save every 15 seconds or so, after 50 characters? You can change this to whatever you'd like. I also noted that your program was not terminating properly - you left a stray space in your with Listener invocation at on_release =on_release, which prevented the keylogger from capturing the esc key (and thereby also prevented the keylogger from being killed, except with ctrl-z). This modified code ran well on my machine, and captured all my input. Spooky! import pynput from pynput.keyboard import Key, Listener count = 0 keys = [] def on_press(key): global keys, count keys.append(key) count += 1 print("{0} pressed", format(key)) #change this to whatever you want, knowing the average person types at #190-200 characters per minute. Following that logic, this logger will save every #15 seconds or so during normal typing. if count >= 50: count = 0 write_file() keys = [] def write_file(): with open("log.txt", "a") as f: for key in keys: k = str(key).replace("'","") if k.find("space") > 0: f.write('\n') elif k.find("Key") == -1: f.write(k) def on_release(key): if key == Key.esc: return False #note that if you leave a space, like "on_release =on_release", the listener won't #understand your on_release function and will ignore it with Listener(on_press=on_press, on_release=on_release) as listener: listener.join() Good luck!
doc_23525941
To keep it simple I will focus on 2 of the Activities/Classes (Activity1, and Activity2) and the DBHelper class AND I will use Pseudo Code. The classes are defined : public class Activity 1 extends Activity implements OnClickListener public class Activity 2 extends Activity implements OnClickListener public class DBHelper extends SQLiteOpenHelper Activity 1 Uses DBHelper to READ data from a DB on TWO separate occasions from TWO different tables without any problems. It then CLOSES the DB. A1 Reads and displays some of the data, (and does some other stuff) then passes Data that was read from DB to Activity 2. A2 performs some magic on the data, as I said.. there are NO problems. Things go south when I try to open the DB from Activity 2. I wrote a new method INSIDE the DBHelper class to: * *Open the DB *WRITE data *Close the DB We will call that DBwriter () to keep it simple, but it CRASHES (NullPointerException) when I call DBwriter () FROM A2. However, when I step thru with the debugger I can see that it NEVER gets to the method DBwriter (). On the line that calls DBwriter () it blows up and left a mess on the floor. After scratching my head for a while (and sweeping up all of the 1s and 0s off the floor), I edited A1 and made a call to DBwriter () And it DID NOT CRASH. It stepped right thru the method. So, there was NO PROBLEM with DBwriter (). I edited DBwriter () -- remember it is Located INSIDE the DBHelper class-- and removed EVERYTHING but the bare bones. Like this: public void DBwriter () { int Debug = 1; // this is so I can place a Break Point } Yet, in A2, it still crashes when CALLING DBwriter () and NEVER even gets to the first line of the code!! I am suspecting that it has something to do with extends SQLiteOpenHelper In A1, there is a variable: private DBHelper m_myDbHelper Now... when I create a second instance of a variable in a SEPARATE class in a Second Activity, A2... does that cause something to Blow Up because I am using DBHelper Two Times?? I could create a new class for writing, but I think it Should Work from ONE DBHelper Class. I am NOT doing anything WEIRD in the Constructor or onCreate Here is the Constructor: public DBHelper (Context context) { super (context, DB_NAME, null, 1); this.myContext = context; } Here is onCreate: @Override public void onCreate (SQLiteDatabase db) { }
doc_23525942
A: You most definitely shouldn't be running ANALYZE regularly or automatically. It sounds like you were dodging the bullet of queries stuck in the waiting for able flush state purely because the load on your servers was sufficiently low that you didn't notice it before. You should only ever run this on a table sparingly when you have clear, definitive evidence that the index statistics on that table are sufficiently detached from reality to cause the query optimiser to regularly come up with egregiously poor execution plan.
doc_23525943
I have an intermediate table with nested columns, and need unpack everything. Here's a small example. library(data.table) DT <- setDT(list( gp = c("A", "B"), etc = c("hi", "bye"), col1 = list( setDT(list(d1 = c(1, 2), d2 = c(2, 2), d3 = c(0.2, 0.2))), setDT(list(d1 = c(10, 20, 30), d2 = c(20, 20, 40), d3 = c(0.2, 0.2, 0.4))) ), col2 = list( setDT(list(d1 = c(-1, -2), d2 = c(-2, -2), d3 = c(-0.2, -0.2))), setDT(list(d1 = c(-10, -20, -30), d2 = c(-20, -20, -40), d3 = c(-0.2, -0.2, -0.4))) ) )) > DT gp etc col1 col2 1: A hi <data.table[2x3]> <data.table[2x3]> 2: B bye <data.table[3x3]> <data.table[3x3]> I need this result unnested_DT_manually <- setDT(list( gp = c("A", "A", "B", "B", "B"), etc = c("hi", "hi", "bye", "bye", "bye"), d1 = c(1, 2, 10, 20, 30), d2 = c(2, 2, 20, 20, 40), d3 = c(0.2, 0.2, 0.2, 0.2, 0.4), d1 = c(-1, -2, -10, -20, -30), d2 = c(-2, -2, -20, -20, -40), d3 = c(-0.2, -0.2, -0.2, -0.2, -0.4) )) > unnested_DT gp etc d1 d2 d3 d1 d2 d3 1: A hi 1 2 0.2 -1 -2 -0.2 2: A hi 2 2 0.2 -2 -2 -0.2 3: B bye 10 20 0.2 -10 -20 -0.2 4: B bye 20 20 0.2 -20 -20 -0.2 5: B bye 30 40 0.4 -30 -40 -0.4 A simpler (and guess the "way") solution is unnested_DT <- DT[, unlist(c(col1, col2), recursive = FALSE), by = c("gp", "etc") ] But my col's names are variables and need some of non-standard evaluation I tried unlist_cols <- function(dt, cols, by){ stopifnot(is.data.table(dt)) cols <- substitute(unlist(cols)) by <- substitute(by) dt[, eval(cols), eval(by)] } nestedcols <- c("col1", "col2") by <- setdiff(colnames(DT), nestedcols) unnested_DT <- unlist_cols(DT, nestedcols, by) A good TIP: all nested columns has the same row-lenght per "by" group and they've the same nested- columns-names. A: This seems too convoluted but works : library(data.table) nestedcols <- c("col1", "col2") DT[, unlist(unname(unlist(.SD, recursive = FALSE)), recursive = FALSE), by = c("gp", "etc"), .SDcols = nestedcols ] # gp etc d1 d2 d3 d1 d2 d3 #1: A hi 1 2 0.2 -1 -2 -0.2 #2: A hi 2 2 0.2 -2 -2 -0.2 #3: B bye 10 20 0.2 -10 -20 -0.2 #4: B bye 20 20 0.2 -20 -20 -0.2 #5: B bye 30 40 0.4 -30 -40 -0.4 A: Another way with cbind and unlist: DT[, do.call(cbind, unname(unlist(.SD, recursive = F))), by = c('gp', 'etc'), .SDcols = c('col1', 'col2')] # gp etc d1 d2 d3 d1 d2 d3 # 1: A hi 1 2 0.2 -1 -2 -0.2 # 2: A hi 2 2 0.2 -2 -2 -0.2 # 3: B bye 10 20 0.2 -10 -20 -0.2 # 4: B bye 20 20 0.2 -20 -20 -0.2 # 5: B bye 30 40 0.4 -30 -40 -0.4
doc_23525944
Below is my script: DriverUtils.getDriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); Actions action= new Actions(DriverUtils.getDriver()); WebElement fundAllocation = DriverUtils.getDriver().findElement(By.xpath("(*//div[@data-index = '" + dataIndex + "']/descendant::div//*[contains(@class, 'mli-donut-chart')]//*[contains(@transform,'translate')]//*[contains(@style,'fill-opacity: 1')])["+ x +"]")); action.moveToElement(fundAllocation).build().perform(); I also try this one on perform, but still didn't work. action.moveToElement(fundAllocation).click().build().perform(); A: You at least first need to define import Actions and define action: in your imports add import org.openqa.selenium.interactions.Actions; Then before you perform the action with something like Actions action = new Actions(DriverUtils.getDriver()); action.moveToElement(fundAllocation).click().build().perform(); Does that help?
doc_23525945
After I copied the class to my project, it works perfectly. But I would like to use it as a dependency on external module. This is repository class: @Repository public interface PersonRepository extends ReactiveMongoRepository<Person, String> { } And classes from project that should use the repository: @Configuration @ComponentScan("outer.package.repository") @EnableMongoRepositories(basePackages = { "outer.package.repository" //"local.package.repository" // temporary solution, should be external }) public class MyConfig { } @Service @RequiredArgsConstructor public class PersonService { private final PersonRepository personRepository; // do some stuff } As you see, I have all needed annotations on beans (@Repository, @Service, @Configuration), I registered mongo repositories (@EnableMongoRepositories) and even provided the directory to scan (@ComponentScan). Do you have any ideas what I've missed? UPD: I'm using maven and project structure is like this: src main java com example configuration MyConfig.java controller PersonController.java repository PersonRepository.java service PersonService.java MainApplication.java resources test pom.xml A: I've tried to reproduce the issue and it seems that changing the annotation @EnableMongoRepositories(basePackages = { "outer.package.repository" //"local.package.repository" // temporary solution, should be external }) public class MyConfig {} to its reactive equivalent: @EnableReactiveMongoRepositories(basePackages = { "outer.package.repository" //"local.package.repository" // temporary solution, should be external }) public class MyConfig {} solved the issue. More on that in the documentation MongoDB uses two different drivers for imperative (synchronous/blocking) and reactive (non-blocking) data access. You must create a connection by using the Reactive Streams driver to provide the required infrastructure for Spring Data’s Reactive MongoDB support. Consequently, you must provide a separate configuration for MongoDB’s Reactive Streams driver. Note that your application operates on two different connections if you use reactive and blocking Spring Data MongoDB templates and repositories.
doc_23525946
$(document).on('click', 'a[href^="#"]', function (event) { event.preventDefault(); var test1 = $(".sub_navi li a").attr('href'); if (window.location.hash.indexOf(test1) ) { console.log("your url contains the name" + test1); } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="sub_navi"> <li id ="sub_intro" class="active"><a href="#intro_tab">Intro </a></li> <li id="sub_intro2"><a href="#intro2_tab">Intro 2</a></li> <li id="sub_intro3"><a href="#intro3_tab">Intro 3</a></li> <li id="sub_intro4"><a href="#intro4_tab">Intro 4</a></li> </ul> A: You need to us $(this) to catch the href of the clicked item $(document).on('click', 'a[href^="#"]', function (event) { event.preventDefault(); var test1 = $(this).attr('href'); if (window.location.hash.indexOf(test1) ) { console.log("your url contains the name" + test1); } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="sub_navi"> <li id ="sub_intro" class="active"><a href="#intro_tab">Intro </a></li> <li id="sub_intro2"><a href="#intro2_tab">Intro 2</a></li> <li id="sub_intro3"><a href="#intro3_tab">Intro 3</a></li> <li id="sub_intro4"><a href="#intro4_tab">Intro 4</a></li> </ul> I kindly ask you to rate my answer
doc_23525947
07-26 10:17:25.991 I/dalvikvm(20751): Could not find method org.slf4j.LoggerFactory.getILoggerFactory, referenced from method com.app.androknife2.utils.L.init 07-26 10:17:25.991 W/dalvikvm(20751): VFY: unable to resolve static method 63525: Lorg/slf4j/LoggerFactory;.getILoggerFactory ()Lorg/slf4j/ILoggerFactory; 07-26 10:17:26.011 E/AndroidRuntime(20751): FATAL EXCEPTION: main 07-26 10:17:26.011 E/AndroidRuntime(20751): Process: com.app.gallery.premium, PID: 20751 07-26 10:17:26.011 E/AndroidRuntime(20751): java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory 07-26 10:17:26.011 E/AndroidRuntime(20751): at com.app.androknife2.utils.L.d(L.java:165) 07-26 10:17:26.011 E/AndroidRuntime(20751): at com.app.androknife2.baseClasses.BaseApp$1.d(BaseApp.java:51) ... The weird thing is, this app is in the play store as a beta app and is working for everyone, but one tester get's this exception, as soon as he start the app (the first log try fails with the above exception). Any idea, what could be the root cause? The slf4j library is packed into my code, so if I made something wrong proguarding it, it would fail on all devices as far as I understand that... Any ideas, hints or similar? A: It looks like you have reached the 65k method limit. try adding this line: android:name="android.support.multidex.MultiDexApplication" on AndroidManifest inside application tag Note that you can avoid this programatically also: Refer to Apps with Over 64K Methods for more details
doc_23525948
Is there a way to do this? A: Yes, put your request processing code in an if block. I am considering that the form is using POST method. This should work fine for you. <? if($_POST['vendor_from_list'] != "" || $_POST['vendor_from_txtbox'] != ""){ //Your data processing code, here. }else{ echo "vendor OR new vendor is required."; } ?>
doc_23525949
The main problem that I face is: to export or convert the boost Shared_Array to a compatible type for .NET C# applications. The Boost Shared_Array type is used as a buffer for the data transmitted via the socket server. Can anyone help? Any code snippet is welcomed.
doc_23525950
object1=NeuroPy("COM6") def attention_callback(attention_value): print ("Value of attention is",attention_value) return None object1.setCallBack("attention",attention_callback) object1.start() while True: if(object1.meditation>70): object1.stop() I run this code and get this error: $ python thread.py Traceback (most recent call last): File "thread.py", line 1, in <module> from NeuroPy import NeuroPy File "D:\pu\fyp\neuro\NeuroPy.py", line 1, in <module> from NeuroPy import NeuroPy ImportError: cannot import name 'NeuroPy' I changed my file name to NeuroPy.py but it makes no difference. I also changed from NeuroPy import NeuroPy to from NeuroPy.NeuroPy import NeuroPy and object1=NeuroPy("COM6") to object1=NeuroPy.NeuroPy("COM6") but I still face some errors from NeuroPy.NeuroPy import NeuroPy ModuleNotFoundError: No module named 'NeuroPy.NeuroPy'; 'NeuroPy' is not a package A: NeuroPy is not part of the Python standard library so you have to install it before you can import it. The command for this is pip install NeuroPy And you should absolutely not name your program NeuroPy.py even after you have installed the module, and if you have a program of that name, delete or rename it. Otherwise, your program will shadow the module you are trying to import.
doc_23525951
doc_23525952
procedure TForm1.ReadCardTimer(Sender: TObject); begin ReadCard2(StrToInt(PChar('$' + Form2.Edit1.Text)),1); ReadCard2(StrToInt(PChar('$' + Form2.Edit3.Text)),2); ReadCard2(StrToInt(PChar('$' + Form2.Edit2.Text)),3); ReadCard2(StrToInt(PChar('$' + Form2.Edit4.Text)),4); ReadCard2(StrToInt(PChar('$' + Form2.Edit5.Text)),5); ReadCard2(StrToInt(PChar('$' + Form2.Edit6.Text)),6); ReadCard2(StrToInt(PChar('$' + Form2.Edit7.Text)),7); ReadCard2(StrToInt(PChar('$' + Form2.Edit8.Text)),8); ReadCard2(StrToInt(PChar('$' + Form2.Edit9.Text)),9); ReadCard2(StrToInt(PChar('$' + Form2.Edit10.Text)),10); ReadCard2(StrToInt(PChar('$' + Form2.Edit11.Text)),11); ReadCard2(StrToInt(PChar('$' + Form2.Edit12.Text)),12); ReadCard2(StrToInt(PChar('$' + Form2.Edit13.Text)),13); ReadCard2(StrToInt(PChar('$' + Form2.Edit14.Text)),14); if NewValue = 0 then Image1.Hide; Image2.Hide; if NewValue > 0 then Image1.Show; Image2.Show; UpdateCardImage(NewValue,NewValue2,'Image1'); UpdateCardImage(NewValue3,NewValue4,'Image2'); UpdateCardImage(NewValue5,NewValue6,'Image3'); UpdateCardImage(NewValue7,NewValue8,'Image4'); UpdateCardImage(NewValue9,NewValue10,'Image5'); UpdateCardImage(NewValue11,NewValue12,'Image6'); UpdateCardImage(NewValue13,NewValue14,'Image7'); end; For some reason the second image i try and hide... wont hide... I can comment out the first one and the second one will hide whats going on here? A: You will need to use begin Image1.Show; Image2.Show; end; begin and end tell the compiler that the statements belong together. In your code, the second is always shown, while the first is only shown when the if expression returns True. A: I indented your code to reflect the meaning of the if statements. Hopefully it will now be clear to you what is going on. I recommend that you start indenting your code yourself! procedure TForm1.ReadCardTimer(Sender: TObject); begin ReadCard2(StrToInt(PChar('$' + Form2.Edit1.Text)),1); //etc. if NewValue = 0 then Image1.Hide; Image2.Hide; if NewValue > 0 then Image1.Show; Image2.Show; UpdateCardImage(NewValue,NewValue2,'Image1'); //etc. end; Presumably what you mean is: if NewValue = 0 then begin Image1.Hide; Image2.Hide; end; if NewValue > 0 then begin Image1.Show; Image2.Show; end; But, assuming that NewValue is never negative, then I would use the Visible property which is a short-hand for Show/Hide: Image1.Visible := NewValue>0; Image2.Visible := Image1.Visible; This declarative approach typically results in clearer, more expressive code. Additionally it allows you to express concisely the fact that the visibility of these controls is tied together. A: Why are you using PChar()? It is not necessary there. A: This why you should use a code formatter. It would have made it easy to spot the problem.
doc_23525953
All the objects (rectangles, shapes, texts, etc..) are written in BufferedImage. My questions is, after I write a graphics.drawline(..) on top of them, how to undo, or reset or clear the line(s) I created. Even if I re-execute the initialization of my graph, the lines that I drew are still there. I can still capture the coordinates of the lines. If it is a plain background I can just re-draw it with the same background. But, in this case, this wont work. A: There is no way to undo things that you do with Graphics. But there are other things you can do instead with which you can get your image back. * *Keep a copy of image before you do anything which you might want to undo. And redraw it when required. *Keep a clip image of the area of image before you do anything which you might want to undo. And redraw that area when required. To keep a Stack of these images of limited size will be a good idea to undo back in series. Don't make the stack size too big because it will consume your heap memory A: I found an answer using deep copy :) So, first, I deep copied the original or default image. Then, If I write something on the original I overwrite it with the back up copied (deep copied again).. static BufferedImage deepCopy(BufferedImage bi) { ColorModel cm = bi.getColorModel(); boolean isAlphaPremultiplied = cm.isAlphaPremultiplied(); WritableRaster raster = bi.copyData(null); return new BufferedImage(cm, raster, isAlphaPremultiplied, null); } Complete code can be found here..
doc_23525954
postgres - super user. What I've done: ALTER SCHEMA public owner to postgres; CREATE USER admin WITH PASSWORD 'my-password'; GRANT USAGE, CREATE ON SCHEMA public TO postgres; GRANT USAGE, CREATE ON SCHEMA public TO admin; CREATE DATABASE mydb; GRANT ALL ON DATABASE mydb TO admin; privileges: postgres=# \dn+ List of schemas Name | Owner | Access privileges | Description --------+----------+----------------------+------------------------ public | postgres | postgres=UC/postgres+| standard public schema | | =UC/postgres +| | | admin=UC/postgres | (1 row) what i got: How to create tables in public schema?... newfag A: The first comment nailed the most likely reason this is happening. Quoting the release announcement: PostgreSQL 15 also revokes the CREATE permission from all users except a database owner from the public (or default) schema. The reason your fix didn't work is that all actions you took on database postgres in regards to user admin's privileges on schema public concern only that schema within the database postgres. Schema public on database postgres is not the same schema public as the one on newly created mydb. Also, this: GRANT ALL ON DATABASE mydb TO admin; grants privileges on the database itself, not things within the database. admin can now drop the database, for example, still without being able to create tables in schema public. My guess is that you wanted to make admin also the owner of mydb, in which case you need to add ALTER DATABASE mydb OWNER TO admin; Or you need to repeat your GRANT USAGE, CREATE ON SCHEMA public TO admin; on mydb. Here's some more documentation on secure schema usage patterns the PostgreSQL 15 change was based on. A: You have created the DB after having granted the privileges on the public schema. Chances are your admin user is using the new DB, which only have the default priviledges
doc_23525955
Thanks James A: Here is a great article on hooking Windows API [1]. It is a little old, and not covering Windows 7 kernel. But I think you can still borrow the idea somehow.
doc_23525956
for instance in sql select go.id, sequence.name, sequence.id from sequence join (goterms,...) on ... this is not beautiful sql but my point is that I'm able to specify which .id I want returned in activerecord I'm doing this: results = Sequence.joins(:Foreigndb,:Goterm,:Taxa) .select(:header,:taxaclass, :genus, :interpro_desc,:description,:dbname,:read_depth, :name) .distinct I want to be able to get id from :Goterm but :Taxa and :Foreigndb also use id as a column in the database so i'm getting uninformative errors that I assume stem from this issue when I do the following. results = Sequence.joins(:Foreigndb,:Goterm,:Taxa) .select(:header,:taxaclass, :genus, :interpro_desc,:description,:dbname,:read_depth, :name,:id) .distinct What is the correct way to just specify that I want Goterm.id? edit - Here is the error: ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'Goterm.id' in 'field list' when I run: results = Sequence.joins(:Foreigndb,:Goterm,:Taxa).select(:header,:taxaclass,:genus, :interpro_desc,:description,:dbname, :read_depth, :name,'Goterm.id').limit(5).offset(0).dresults = Sequence.joins(:Foreigndb,:Goterm,:Taxa).select(:header,:taxaclass, :genus, :interpro_desc,:description,:dbname, :read_depth, :name,'Goterm.id').limit(5).offset(0).distinct A: results = Sequence.joins(:Foreigndb,:Goterm,:Taxa).select(:header,:taxaclass, :genus, :interpro_desc,:description,:dbname,:read_depth, :name, 'sequences.id') .distinct A: It turns out that ilan's answer is correct, however be sure that everything is lower case. I was using 'Goterm.id' to make the selection when it needs to be 'goterm.id' If anyone else runs into this, I also ran into difficulties grabbing the goterm.id data out of the returned query objects. Each time I called object.id on that return set it would give me something different from what I was expecting. I think the attribute I was expecting was being obscured by something else. To get the data I needed I did the following: results = Sequence.joins(:Foreigndb,:Goterm,:Taxa).select(:header,:taxaclass, :genus,:interpro_desc,:description,:dbname,:read_depth, :name).distinct firstRes = results[0] firstRes.attributes['id']
doc_23525957
function callServer() { alert('before : ' +uncompressed64Data.length); var compressed = LZString.compressToUTF16(uncompressed64Data); alert('after : ' +compressed.length); debugger; jQuery.ajax({ url : "/RegisterServlet_2/servlet/Register", type : "POST", data: "img="+compressed, cache : false, async : false, success : function() { }, error : function() { } }); } I am getting following error while try to receive it in error: Character decoding failed. Parameter [img] with value [Ả㠵堥ä?¢æ¡¥Æ´Û?ୠ⤡á?®ã? ä??à©?má¹?â?¤â° â?]has been ignored. Note that the name and value quoted here may be corrupted due to the failed decoding. Use debug level logging to see the original, non-corrupted values. Fyi, 1.I have mentioned header of html file utf8 2.server.xml mentioned URIEncoding="UTF-8" 3.server side mentioned, request.setCharacterEncoding("utf-8"); Please note I don't want any encoding and I just want to get the data which I sent. Thanks in advance. A: I think the problem caused by Content-Type, by default jquery use application/x-www-form-urlencoded; charset=UTF-8. Try to set it up to text/plain or multipart/form-data. Here is documentation.
doc_23525958
<?php class Teacher { /** *@ORM\OneToMany(targetEntity="Activities", mappedBy="teacher") */ protected $activities; } class Activities { /** * @ORM\ManyToOne(targetEntity="Teacher", inversedBy="activities") * @ORM\JoinColumn(name="teacher_id", referencedColumnName="id", nullable=true, onDelete="SET NULL") */ protected $teacher; /** * Activities are suspended when there is not teacher */ protected $isSuspended = false; } A: This part onDelete="SET NULL" works on a database level, so for changing the $isSuspended field, you can create a listener for the postRemove doctrine event. use Doctrine\ORM\Event\LifecycleEventArgs; public function postRemove(LifecycleEventArgs $event) { $entity = $event->getEntity(); if ($entity instanceof Teacher) { foreach($entity->getActivities() as $activity) { $activity->setIsSuspended(true); $event->getEntityManager()->persist($activity); } $event->getEntityManager()->flush(); } }
doc_23525959
Code used to login in Ajax: $.ajax({ url: 'https://xxxxxx.co.xx:7302/xxxx/faces/pages/login/login.jspx', data: {j_username: "xxxxx",j_password:"xxxxx"}, type: 'POST', crossDomain: true, dataType: 'text/html', success: function() { alert("Success"); }, error: function() { alert('Failed!'); }, headers: { 'Access-Control-Allow-Origin': '*' } }); The Error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxxxx.co.xx:7302/xxxx/faces/pages/login/login.jspx. (Reason: CORS header 'Access-Control-Allow-Origin' missing). If any possible way to auto login, please help me. Thanks in advance. A: You'll want to use single-sign-on to achieve this, and you'll need to configure the WebLogic server that runs the ADF part to do SSO with your APEX instance. Here is a video about the ADF part - https://www.youtube.com/watch?v=G7X7quNT-58 On the APEX side: http://www.oracle.com/technetwork/developer-tools/apex/learnmore/apex-oam-integration-1375333.pdf
doc_23525960
1)scaling 2)bezier movement 3)tinting 4)fade out I've noticed that if just 500 sprites or more are being used on the screen, the game drops off from 60fps. However, in the cocos2d particle tests, I see about 1000 or so "particles", moving fluidly at 60fps with tinting, gravitational movement, fading, and scaling. So the ultimate question is: 1) What's the difference between a "particle" and a "sprite", if they seem to be the same thing? 2) Is the particle system much faster than using lots of individual sprites? If so, why? Cheers! A: "Just 500 sprites" - you may need to adjust your expectations. 500 sprites can be quite a lot even for the iPhone 5S, depending on the sprite texture sizes. The larger the sprites are the fewer of them you can draw without dropping frames. Also consider sprite batching (CCSpriteBatchNode) if you haven't and be sure to test performance only on a device, never the Simulator. That said, particles are faster because they are controlled entirely by the particle system class. You can not access individual particles and even if you could, you couldn't apply many of the sprite features (skew, physics, etc.) to them. Meaning particles are fast because they are more efficiently rendered while sacrificing functionality that you often need to use with sprites. That's the simplistic explanation.
doc_23525961
thanks, [DllImport("coredll.dll")] public static extern bool VerQueryValue(byte[] buffer, string subblock, out IntPtr blockbuffer, out uint len); [DllImport("coredll.dll")] public static extern bool VerQueryValue(byte[] pBlock, string pSubBlock, out string pValue, out uint len); // private static void GetAssemblyVersion() { string filename = @"\Windows\MyLibrary.dll"; if (File.Exists(filename)) { try { int handle = 0; Int32 size = 0; size = GetFileVersionInfoSize(filename, out handle); if (size > 0) { bool retValue; byte[] buffer = new byte[size]; retValue = GetFileVersionInfo(filename, handle, size, buffer); if (retValue == true) { bool success = false; IntPtr blockbuffer = IntPtr.Zero; uint len = 0; //success = VerQueryValue(buffer, "\\", out blockbuffer, out len); success = VerQueryValue(buffer, @"\VarFileInfo\Translation", out blockbuffer, out len); if(success) { int p = (int)blockbuffer; //Reads a 16-bit signed integer from unmanaged memory int j = Marshal.ReadInt16((IntPtr)p); p += 2; //Reads a 16-bit signed integer from unmanaged memory int k = Marshal.ReadInt16((IntPtr)p); string sb = string.Format("{0:X4}{1:X4}", j, k); string spv = @"\StringFileInfo\" + sb + @"\ProductVersion"; string versionInfo; VerQueryValue(buffer, spv, out versionInfo, out len); } } } } catch (Exception err) { string error = err.Message; } } } A: After adding these two statements: Int32 dwVerMinor = j & 0xffff; Int32 dwVerBuild = k & 0xffff; it's able to retrieve the DLL version. A: Here's an implementation: using DWORD = System.UInt32; public static class NativeFile { public struct NativeFileInfo { public Version Version; public NameValueCollection StringTable; } public unsafe static NativeFileInfo GetFileInfo(string path) { if (!File.Exists(path)) { throw new FileNotFoundException(); } IntPtr handle; var size = GetFileVersionInfoSize(path, out handle); var buffer = Marshal.AllocHGlobal(size); try { if (!GetFileVersionInfo(path, handle, size, buffer)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } IntPtr pVersion; int versionLength; VerQueryValue(buffer, “\”, out pVersion, out versionLength); var versionInfo = (VS_FIXEDFILEINFO)Marshal.PtrToStructure(pVersion, typeof(VS_FIXEDFILEINFO)); var version = new Version((int)versionInfo.dwFileVersionMS >> 16, (int)versionInfo.dwFileVersionMS & 0xFFFF, (int)versionInfo.dwFileVersionLS >> 16, (int)versionInfo.dwFileVersionLS & 0xFFFF); // move to the string table and parse var pStringTable = ((byte*)pVersion.ToPointer()) + versionLength; var strings = ParseStringTable(pStringTable, size – versionLength); return new NativeFileInfo { Version = version, StringTable = strings }; } finally { Marshal.FreeHGlobal(buffer); } } private unsafe static NameValueCollection ParseStringTable(byte* pStringTable, int length) { NameValueCollection nvc = new NameValueCollection(); byte* p = pStringTable; short stringFileInfoLength = (short)*p; byte* end = pStringTable + length; p += (2 + 2 + 2); // length + valuelength + type // verify key var key = Marshal.PtrToStringUni(new IntPtr(p), 14); if (key != "StringFileInfo") throw new ArgumentException(); // move past the key to the first string table p += 30; short stringTableLength = (short)*p; p += (2 + 2 + 2); // length + valuelength + type // get locale info key = Marshal.PtrToStringUni(new IntPtr(p), 8); // move to the first string p += 18; while (p < end) { short stringLength = (short)*p; p += 2; short valueChars = (short)*p; p += 2; short type = (short)*p; p += 2; if (stringLength == 0) break; if ((valueChars == 0) || (type != 1)) { p += stringLength; continue; } var keyLength = stringLength – (valueChars * 2) – 6; key = Marshal.PtrToStringUni(new IntPtr(p), keyLength / 2).TrimEnd(”); p += keyLength; var value = Marshal.PtrToStringUni(new IntPtr(p), valueChars).TrimEnd(”); p += valueChars * 2; if ((int)p % 4 != 0) p += 2; nvc.Add(key, value); } return nvc; } private const string COREDLL = "coredll.dll"; [DllImport(COREDLL, SetLastError = true)] private static extern int GetFileVersionInfoSize(string lptstrFilename, out IntPtr lpdwHandle); [DllImport(COREDLL, SetLastError = true)] private static extern bool GetFileVersionInfo(string lptstrFilename, IntPtr dwHandle, int dwLen, IntPtr lpData); [DllImport(COREDLL, SetLastError = true)] private static extern bool VerQueryValue(IntPtr pBlock, string lpSubBlock, out IntPtr lplpBuffer, out int puLen); [StructLayout(LayoutKind.Sequential)] private struct VS_FIXEDFILEINFO { public DWORD dwSignature; public DWORD dwStrucVersion; public DWORD dwFileVersionMS; public DWORD dwFileVersionLS; public DWORD dwProductVersionMS; public DWORD dwProductVersionLS; public DWORD dwFileFlagsMask; public DWORD dwFileFlags; public FileOS dwFileOS; public FileType dwFileType; public DWORD dwFileSubtype; public DWORD dwFileDateMS; public DWORD dwFileDateLS; }; public enum FileOS : uint { Unknown = 0x00000000, DOS = 0x00010000, OS2_16 = 0x00020000, OS2_32 = 0x00030000, NT = 0x00040000, WindowsCE = 0x00050000, } public enum FileType : uint { Unknown = 0x00, Application = 0x01, DLL = 0x02, Driver = 0x03, Font = 0x04, VXD = 0x05, StaticLib = 0x07 } } And an example of usage: class Program { static void Main(string[] args) { string target = “\FlashFX Disk\ARMv4i\conmanclient2.exe”; var version = NativeFile.GetFileInfo(target); Console.WriteLine(string.Format(“File: { 0}”, Path.GetFileName(target))); Console.WriteLine(string.Format(“Version: { 0}”, version.Version.ToString(4))); foreach (var key in version.StringTable.AllKeys) { Console.WriteLine(string.Format(“{ 0}: { 1}”, key, version.StringTable[key])); } Console.ReadLine(); }
doc_23525962
* 7a5841d - (6 hours ago) commit messageA (master) | * 1552e99 - (6 hours ago) commit messageB (HEAD -> feature1) | * 2d4a3bd - (6 hours ago) commit messageC | * 31513f7 - (6 hours ago) commit messageD | * 3335afb - (7 hours ago) commit messageE |/ * 5be4cf7 - (27 hours ago) commit messageF (origin/master, origin/HEAD) | * 870f217 - (27 hours ago) commit messageG (origin/develop) | * 70f1973 - (27 hours ago) commit messageH |/ * 50e3bba - (27 hours ago) commit messageI $ git log --oneline master ^feature1 --no-merges 7a5841d commit messageA $ git log --all --oneline master ^feature1 --no-merges 7a5841d commit messageA 870f217 commit messageG 70f1973 commit messageH What does git log --all do here? Why does it return the extra two commits? A: I am assuming the first really is the complete set of all commits (I have no reason to believe it's not, but there could be more that we can't see, e.g., in reflogs—that doesn't affect this answer, but it's a subtle point either way). What --all means is all references (plus HEAD). But that's not the whole story here. (I'm also going to leave out --no-merges since there are no merges anyway.) References Let's start with the notion of references, as distinguished from branches, tags, and remote-tracking branches. A reference is the fully general form: all three of the specific varieties (branch, tag, remote-tracking branch) are a kind of reference. A branch name like master is mostly just a short way of saying the full reference name, refs/heads/master. A tag name like v1.3 is a short way of saying refs/tags/v1.3, and a remote-tracking branch name like origin/develop is a short way of saying refs/remotes/origin/develop. There are more possible references: for instance, stash is short for refs/stash. If you have an active stash (from git stash save), you have a refs/stash. That would have shown up here, and didn't; so you don't have one. But --all would include it, if you did. There are also optional Git "notes" under refs/notes, and there may be more. Anything that starts with refs/ is a reference, and the --all flag gets them all! (Plus, as I mentioned, HEAD, but usually that doesn't matter. Note that HEAD doesn't start with refs/ so it's nominally not a reference, even though it's the one Git mostly uses by default!) You can use --branches to mean "all branches" (everything in refs/heads/*), --tags to mean "all tags" (refs/tags/*), and --remotes to mean "all remote-tracking branches" (refs/remotes/*). Using some or all of these, you can leave out the extra --all items, if they exist. Short names like master Almost any time you use a name like master, Git goes through the six-step reference lookup process described in the gitrevisions documentation. Click on the link and find the six-step list, and note that the translation from master to refs/heads/master is actually step four. If there were a refs/tags/master, that happens at step three and that's the reference you would get. (I say almost any time here because some commands, such as git checkout, try to treat a name as a branch name first, and only later go through the six-step process to resolve the name. So git checkout master checks out the branch, not the tag, if there is both a branch master and a tag master. The git log command doesn't: if both exist, you get the tag here! The short version is "don't do that" :-) —never set yourself up with both a branch named X and a tag named X. It's too confusing.) Negated references, reachability, and the commit graph Your final command is: git log --all --oneline master ^feature1 --no-merges You don't need master here, because --all means all references, and master means "find a master reference" (probably the branch). It's already been found. The ^feature1, however, is crucial. When Git goes to enumerate all reachable commits, it takes into account all the places you told it to start—in this case, --all means "all references"—but it overrides these with all the places you told it to stop. A prefix hat ^ negates a reference: it means "put this into the stop list." Git finds the specific commit that feature1 names; we can see above that this is 1552e99. So Git puts 1552e99 into the "stop" list. But it doesn't just stop there: it finds all commits reachable from 1552e99 (messageB). That starts with its first and only parent commit, which is 2d4a3bd (messageC). Commit 2d4a3bd has a parent, though: that's commit 31513f7 (messageD); and that has a parent, 3335afb (messageE), which has parent 5be4cf7 (messageF). Note, though, that the parent of 5be4cf7 is 50e3bba (messageI), skipping past the other two commits. (Follow the lines connecting the asterisks in the git log --graph output. This may be easier without --oneline, at least at first; it's almost certainly easier in a graphical viewer like gitk or some GUI.) When we get to 50e3bba we stop: it has no parent at all. It is a root commit (which just means "a commit with no parents"). So that finishes up our list of "stop" commits. Now git log --all can go on to look at all references. There are a total of four: master, feature1, origin/master, and origin/develop. (Or maybe there are five or six: we should also consider HEAD and origin/HEAD. However, those last two are symbolic references, as in, they just name other existing references. So they get folded in and we're back down to just four.) Those four names resolve to commits 7a5841d (master), 1552e99 (HEAD -> feature1), 5be4cf7 (origin/master, origin/HEAD), and 870f217 (origin/develop). So git log puts—or tries to put—those four commits into the list of things to show you. 1552e99, however, is in the stop list. So Git doesn't show it; it ejects it from the "to be shown" list (or never puts it in there in the first place, which has the same effect). Git picks one of the three remaining commits and shows it. We can see that it picked 7a5841d.1 Git tries to add 7a5841d's parent commit(s) to the "show list", but 7a5841d's parent is 5be4cf7. That's already in the "stop" list, through ^feature1. It either gets thrown out or never makes it in. That leaves just 870f217 in the show list. Git shows it next, and then adds its parents to the show list. It has just one parent, 70f1973. So that's now in the show list; Git shows you that one. Git tries to add its parent to the show list, but that's 50e3bba, which is in the stop list. The show list is now empty, so git log is finished. 1There's another tricky point here. When Git is in this position of picking one commit from an otherwise un-sorted pile of possible commits, it takes the one with the numerically biggest commit date. If you make a commit that's dated far into the future, put it on a branch or tag so that it's reachable from --all, and run git log --all, that future commit comes out first every time.
doc_23525963
$cache = Zend_Cache::factory('Output', 'File', $frontendOptions, $backendOptions); // we pass a unique identifier to the start() method if(!$cache->start('mypage')) { // output as usual: echo 'Hello world! '; echo 'This is cached ('.time().') '; $cache->end(); // the output is saved and sent to the browser } As this doc explains, the above will not get into block statement if it has already been processed, consequently, the time won't refresh. Lets say the expire time is configured to 30 seconds. Visitor A comes and the Output is cached, so obviously, the visitor would see the same time for multiple refresh for 30 seconds. My question is that if Visitor B comes along the same time, will he see the same time as Visitor A because its already cached or the caching will be user specific? A: Yes, he will, because that the reason, why one should use caches: Don't process stuff for every single user over and over again. You could create the cache-ID with something user specific $cache->start('mypage'.$userId); but then you should ask yourself if it's really worth to get cached.
doc_23525964
@bot.event async def on_raw_reaction_add(payload): channel = await bot.fetch_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) if payload.emoji.name == "✅": await message.set_field_at(4,"Status:","Accepted") elif payload.emoji.name == "❎": await message.set_field_at(4,"Status:","Denied") elif payload.emoji.name == "❌": await message.set_field_at(4,"Status:","Canceled") else: pass Error given: AttributeError: 'Message' object has no attribute 'set_field_at' I don't know why this is happening... A: According to the documentation: https://discordpy.readthedocs.io/en/stable/api.html?highlight=fetch_emoji#discord.Guild.fetch_emoji You want to call await fetch_emoji(id) with the emoji id and not the PartialEmoji object (which your emoji variable is). Instead use fetch_emoji(emoji.id) Try the following: @bot.event async def on_raw_reaction_add(payload): channel = await bot.fetch_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) guild = await bot.fetch_guild(payload.guild_id) emoji = await guild.fetch_emoji(payload.emoji.id) if emoji.name == "U+2705": status = "Appected" elif emoji.name == "U+274E": status = "Denied" elif emoji.name == "U+274C": status = "Canceled" else: pass message.set_field_at(4,"Status:",f"{status}")
doc_23525965
https://developers.google.com/+/quickstart/javascript I have migrated all inline javascript code to separate files, added content_security_policy line in my manifest.json file: "content_security_policy": "script-src 'self' https://www.googleapis.com/ https://plus.google.com/ https://apis.google.com/ https://accounts.google.com/ https://ssl.gstatic.com https://csi.gstatic.com https://developers.google.com; object-src 'self'" The problem is following. When I click on the Google+ button I get following error message: Refused to execute JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self' https://www.googleapis.com/ https://plus.google.com/ https://apis.google.com/ https://accounts.google.com/ https://ssl.gstatic.com https://csi.gstatic.com https://developers.google.com". Which is obviously unhappy with content_security_policy. It throws this exception on line 468 in this file: https://apis.google.com/_/scs/apps-static/_/js/k=oz.gapi.en.aop9WHMC8-8.O/m=client,plusone,signin/rt=j/sv=1/d=1/ed=1/am=EQ/rs=AItRSTNUM79OpqDtwYl6kryPkOs00evROQ/cb=gapi.loaded_0. It seems it is trying to embed inline script and execute it after, which violates Content Security Policy. The same exception appears when I click to "Accept" button in the popup. As a result popup window hangs without response. Do you have any experience with that ? A: Try this in your manifest.json: "content_security_policy": "script-src 'self' 'unsafe-eval' https://apis.google.com/; object-src 'self'"
doc_23525966
item_questions_attributes_abc123_id I'm specifically trying to get the abc123 bit. That string can be any alphanumeric of any case. No special characters or spaces. I'm using jQuery, though I'm certainly fine with using straight javascript if that's the best solution. A: If it's always the 4th part of the string you can use split. var original = 'item_questions_attributes_abc123_id'; var result = original.split('_')[3]; A: Try this: var myArray = myString.split("_"); alert(myArray[3]); A: use split method of javascript and then use 2nd last index you will have your required data.
doc_23525967
git log -p -- <filename> But it only shows the diff of each version, I want it to show the full content of the file at each version, so I can next parse the output as my demand. Does git log support this? A: Quickest hack I can think of is to parse fast-export output, it's not hard, git fast-export --all -- path/to/file and if you're using commit signing or tagging objects other than commits you'll need to add some options to filter those out.
doc_23525968
I've tried the get the data with json_decode but unfortunately, I didn't succeed. My code is something like this: <?php $i = 0; $query = "SELECT * FROM portfolio "; $select_all_portfolio_thumbnails = mysqli_query( $connection, $query ); while( $row = mysqli_fetch_assoc( $select_all_portfolio_thumbnails ) ) { $portfolio_thumbnails = $row['portfolio_thumbnails']; ?> <div class="nv-portfolio-item-box nv-portfolio-items-hidden" id="nv-portfolio-item-box--<?php echo ++$i ?>" > <div class="nv-portfolio-item-thumbnails"> <img class="nv-portfolio-item" style="background-image: url( 'assets/img/portfolio/<?php echo $portfolio_thumbnails[$i] ?>' );"> </div> </div> <?php } ?> The data on my cell is something like this: 1.jpg,2.jpg,3.jpg On this example, I would like to create 3 image tag with the containing the image URLs in order. Thanks much. ~ Nathan. A: Here You have split that string to array then you have to loop that in foreach like below $portfolio_thumbnails = '1.jpg,2.jpg,3.jpg'; $imageArray = explode(',',$portfolio_thumbnails); foreach ($imageArray as $key => $value) {?> <div class="nv-portfolio-item-box nv-portfolio-items-hidden" id="nv-portfolio-item-box--<?php echo ++$i ?>" > <div class="nv-portfolio-item-thumbnails"> <img class="nv-portfolio-item" style="background-image: url( 'assets/img/portfolio/<?php echo $value ?>' );"> </div> </div> <?php }
doc_23525969
What I want to do is every time the Distance is greater than 10m (which I've used conditional formatting to highlight green), return in column E the measure values from the previous row up to the previous green cell, kind of like grouping them and displaying as a range. Then also return the min and max Value within that range of rows (probably in column F & G). Ex. E6 would return something like "148000-148040" in text format, E16 would be "148090-148180", E17 would just be "148200". Then F6 = -91.09, G6 = -43.91, F16 = 15.49, G16 = 138.06 and so on. Not sure if this would require VBA, but if it can be done with formulas that'd be great. Sorry if this is confusing or if a similar question has been asked before. Thank you! A: I think this demonstrates the power of the new (ish) Xlookup very well (in this case, using backwards search): For the range: =IF(D3=10,"",XLOOKUP(TRUE,D2:D$2>10,B2:B$2,B$2,0,-1)&"-"&B2) Min: =IF(D3=10,"",MIN(XLOOKUP(TRUE,D2:D$2>10,C2:C$2,C$2,0,-1):C2)) Max: =IF(D3=10,"",MAX(XLOOKUP(TRUE,D2:D$2>10,C2:C$2,C$2,0,-1):C2))
doc_23525970
Let L be the language over {a,b} generated by the following recursive definition basis: λ ∈ L recursive step: If w ∈ L then awbb is in L. closure: A string w ∈ L only if it can be obtained from the basis set by a finite number of applications of the recursive step. Part a. Give the sets L1; L2; and L3 generated by the recursive definition. Note that L0 = λ I get that The alphabet is {a,b}, Lo = the empty string, and if a string w is contained in L, then awbb is in L. But what does that mean for the next couple sets? I think L1 = {λ ,awbb} and then L2={λ , awbb, aawbbwbb}? Any help you could offer on this would be appreciated. A: I think that you're misinterpreting what the rule If w &in; L, then awbb &in; L means. This doesn't mean that the literal string "awbb" is in L. Instead, it means that if you have some string w &in; L, you can substitute that string w into the string awbb and that resulting string will be in L. For example, if ab &in; L, then aabbb &in; L as well. Using this, try constructing the sets L1 and L2 again. I think that you'll spot an immediate pattern once you've built up the first few sets. Hope this helps!
doc_23525971
<html> <head> <script type="text/javascript" src="protovis-r3.2.js"></script> </head> <body> <script type="text/javascript+protovis"> new pv.Panel().width(150).height(150).anchor("center") .add(pv.Label) .text("Hello, world!") .root.render(); </script> {{ object.name }} </body> </html> When I open this file directly in firefox, a Protovis 'Hello World' image is displayed toguether with the string "{{ object.name }}". But when accessing the .html file template from my Django server, I only see the {{ object.name }} (the object's name printed out). I haven't found similar issues so far, catering to Protovis use in Django. If anyone has gotten it working or know what I am doing wrong, please let me know. Thanks, A: You've asked for the javascript file using src="protovis-r3.2.js" When you look at the html file directly, your browser will look in the same directory as the .html file for a file called protovis-r3.2.js. However, when you ask Django to serve this same page, it doesn't follow the same protocol. See this article for more information. To get it to work: * *Move the protovis-r.32.js file to a new directory: /path/to/my/django_site/static (where /path/to/my/django_site is the absolute path to the django app) *Configure urls.py with the line: (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/path/to/my/django_site/static'}), * *Change the src attribute of the script tag in your html code to: src="/static/protovis-r3.2.js"
doc_23525972
Is there a way to calculated Wt * Reps * Sets for each exercise, save the result as a new column ending Load, and then add all columns ending Load for Total_load? MWE: exercise = data.frame(BicWt= c( 3,3,4), BicSets = c(2,2,2), BicReps = c(10,12,12), LatWt = c(4,4,4), LatSets = c( 2,2,2), LatReps = c(6,8,10)) BicWt BicSets BicReps LatWt LatSets LatReps 1 3 2 10 4 2 6 2 3 2 12 4 2 8 3 4 2 12 4 2 10 Desired output is: BicWt BicSets BicReps BicLoad LatWt LatSets LatReps LatLoad Total_Load 1 3 2 10 60 4 2 6 48 108 2 3 2 12 72 4 2 8 64 136 3 4 2 12 96 4 2 10 80 176 where BicLoad = BicWt * BicSets * BicReps etc. EDIT Some of the exercise columns have CAPITAL letters before Wt,Reps and Sets. exercise = data.frame(BicWt= c( 3,3,4), BicSets = c(2,2,2), BicReps = c(10,12,12), LatWt = c(4,4,4), LatSets = c( 2,2,2), LatReps = c(6,8,10), PullUpWt = c(5,5,5), PullUpSets = c(2,2,2), PullUpReps = c(6,8,10)) BicWt BicSets BicReps BicLoad LatWt LatSets LatReps LatLoad PullUpWt PullUpSets PullUpReps PullUpLoad Total_Load 1 3 2 10 60 4 2 6 48 5 2 6 60 168 2 3 2 12 72 4 2 8 64 5 2 8 80 216 3 4 2 12 96 4 2 10 80 5 2 10 100 276 A: We could remove the suffix part of the column names and split into a list of data.frames, then do elementwise multiply with Reduce on those datasets. Create the total by doing elementwise sum across the list lst1 <- lapply(split.default(exercise, sub("[A-Z][a-z]+$", "", names(exercise))), \(x) Reduce(`*`, x)) exercise[paste0(names(lst1), "Load")] <- lst1 exercise$Total_Load <- Reduce(`+`, lst1) -output > exercise BicWt BicSets BicReps LatWt LatSets LatReps BicLoad LatLoad Total_Load 1 3 2 10 4 2 6 60 48 108 2 3 2 12 4 2 8 72 64 136 3 4 2 12 4 2 10 96 80 176 Or in tidyverse, create the 'BicLoad', 'LatLoad' columns individually by looping across the 'Bic', 'Lat' columns, do the elementwise multiplication with reduce and create the 'Total_load' by adding the BicLoad and LatLoad library(dplyr) library(purrr) exercise %>% mutate(BicLoad = across(starts_with('Bic')) %>% reduce(`*`), .after = BicReps) %>% mutate(LatLoad = across(starts_with('Lat')) %>% reduce(`*`), .after = LatReps) %>% mutate(Total_Load = BicLoad + LatLoad) -output BicWt BicSets BicReps BicLoad LatWt LatSets LatReps LatLoad Total_Load 1 3 2 10 60 4 2 6 48 108 2 3 2 12 72 4 2 8 64 136 3 4 2 12 96 4 2 10 80 176
doc_23525973
A: if ('serviceWorker' in navigator && 'SyncManager' in window) { // service worker stuffs here } else { console.error('Background sync not supported'); }
doc_23525974
This is my actual view with the headScript()->appendFile(): <?php echo $this->headScript()->appendFile($this->basePath('js/dashboard.min.js')); ?> With this implementation, when my page is loaded, all the requests are made twice and this is very bad cause are async requests to an API: Test [2, 1, 0, 0, 0, 0, 0] Test [2, 1, 0, 0, 0, 0, 0] I tried also without the $this->basePath(): <?php echo $this->headScript()->appendFile('js/dashboard.min.js'); ?> And got the same behavior. But if I put this Javascript without the headScript, it just works fine, include once. <script src="js/dashboard.min.js"></script> // And the output Test [2, 1, 0, 0, 0, 0, 0] What I can see is that the first include is made when page is loaded and the second some seconds after (2 or 3 seconds). Someone already faced this behavior? If yes, Did Solve it? How? A: I believe the problem is that you are echoing out the headScript. Try removing your echo statement, and I believe it will work fine. Use this: <?php $this->headScript()->appendFile($this->basePath('js/dashboard.min.js')); ?> Instead of this: <?php echo $this->headScript()->appendFile($this->basePath('js/dashboard.min.js')); ?>
doc_23525975
var items = { knife: { name: "Knife" } }; var inventory = {}; //document.write(inventory....); Or am I not understanding something and making everything wrong? maybe objects is wrong choice? I want output just to print item name like knife. But not from var items - Print it from inventory Everything should work like picking up item from ground. A: You are probably using the wrong data structure for your inventory, unless you want to be able to pickup a single item per kind, you should be using an array. var inventory = []; //empty inventory inventory.push(items.knife); //pickup a knife inventory.push(items.knife); //pickup another knife Loop over the inventory and alert the item names: for (var i = 0, len = inventory.length; i < len; i++) { alert(inventory[i].name); } Please note that the objects in the inventory are references to the items.knife object. If you want to clone those objects instead, have a look at What is the most efficient way to deep clone an object in JavaScript?.
doc_23525976
This is my signal @receiver(post_save, sender=ChannelGroup) def channel_list_signal(sender, instance, created, **kwargs): try: print("signals") channel_layer = get_channel_layer() print(channel_layer) channel_layer.group_send( "channellist", { 'type': 'send_notification', 'message': "Done", }) print("return 'Done'") return "Done" except Exception as e: raise Exception(f"Something went wrong in channel_list signal {e}") This is my consumer class ListChannelConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.group_name = "channellist" self.channel_layer = None self.msg = None self.channels = [] # self.connected = False async def connect(self): user_id = self.scope["url_route"]["kwargs"]["user_id"] is_user_present = await check_user(user_id) print(self.channel_layer) # group_id = sender + receiver if is_user_present: self.user_name = is_user_present.username await self.channel_layer.group_add( "channellist", "temp" ) await self.accept() channel = await get_channels(is_user_present.username) await self.send(text_data=json.dumps({ "payload": "connected", "Channels": channel }, default=str)) else: raise Exception(f"User not present in database or private chat does not exists") async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def send_notification(self, event): print(event) event_data = QueryDict.dict(event) channels = event_data.get('message') # Send message to WebSocket self.channels = await get_channels(self.user_name) await self.send(text_data=json.dumps({ "Success": "channels", "message": channels })) What i am trying to achieve is i want to trigger send_notification event whenever i create new channel in my db but when i tried so it is not working actually i try to check the what channel layer has been used with pring channel_layer its same. but when i print channel_layer.group_send it has diff coroutine at diff layer. Can anyone help me how can i do or what mistake i am making I am using in memory channel layer
doc_23525977
When the input looses focus, the previous text is restored. When pressing return (keyCode 13), the new text is saved and will be written in the row. Now, for the users who don't know to press return for saving the text, I want to add a "Save" button right next to the input field. But when pressing it, the blur event of the input field is getting fired first, discarding the changes. So is there an easy way, that the .click() event of the button can cancel the .blur() event on the input field? Perhaps an "don't execute other events" or can I perhaps see in the blur event, which events will get called next to cancel it? Here is a jsfiddle to see what I mean: http://jsfiddle.net/ykY5X/ (I'm working in Firefox (latest Nightly), where the button click won't work. I just tested the jsfiddle also in chrome, where also the keyup won't work as expected.) $('#showEdit').click(function() { $('#row').data('text',$('#row').text()); $('#row').html('<input type="text" id="editInput" /> <span id="editSave">Save</span>'); $('#editInput').val($('#row').data('text')).focus(); }); $('#row').delegate('#editInput','keyup',function(e) { e.stopPropagation(); var keycode = e.keyCode || e.which; if (keycode == 13) $('#editSave').click(); }).delegate('#editSave','click',function(e) { e.stopPropagation(); $('#row').text($('#editInput').val()); }).delegate('#editInput','blur',function() { $('#row').text($('#row').data('text')); }); A: You can use some delay before the code inside blur event handler gets executed. On Save button click you can cancel the blur timer so that it will not be executed. Working demo var blurTimer; $('#showEdit').click(function() { $('#row').data('text',$('#row').text()); $('#row').html('<input type="text" id="editInput" /> <span id="editSave">Save</span>'); $('#editInput').val($('#row').data('text')).focus(); }); $('#row').delegate('#editInput','keyup',function(e) { e.stopPropagation(); var keycode = e.keyCode || e.which; if (keycode == 13){ $('#editSave').click(); } }).delegate('#editSave','click',function(e) { clearTimeout(blurTimer); $('#row').text($('#editInput').val()); }).delegate('#editInput','blur',function() { blurTimer = setTimeout(function(){ $('#row').text($('#row').data('text')); }, 200); }); A: My final working solution is this: $('#showEdit').click(function() { $('#row').data('textOriginal',$('#row').text()); $('#row').data('textSave',$('#row').text()); $('#row').html('<input type="text" id="editInput" /> <span id="editSave">Save</span>'); $('#editInput').val($('#row').data('textOriginal')).focus(); }); $('#row').delegate('#editInput','keyup',function(e) { e.stopPropagation(); var keycode = e.keyCode || e.which; if (keycode == 13) { $('#row').data('textSave',$(this).val()); $('#editSave').click(); } }).delegate('#editSave','mousedown',function() { $('#row').data('textSave',$('#editInput').val()); }).delegate('#editSave','click',function(e) { e.stopPropagation(); if ($('#row').data('textOriginal') == $('#row').data('textSave')) { $('#row').text($('#row').data('textOriginal')); return; } $('#row').text($('#row').data('textSave')); }).delegate('#editInput','blur',function() { $('#editSave').click(); }); http://jsfiddle.net/RSUdx/ A: I think u can try this: $('#showEdit').click(function() { $('#row').data('text',$('#row').text()); $('#row').html('<input type="text" id="editInput" /> <span id="editSave">Save</span>'); $('#editInput').val($('#row').data('text')).focus(); }); $('#row').delegate('#editInput','keyup',function(e) { e.stopPropagation(); var keycode = e.keyCode || e.which; if (keycode == 13) $('#editSave').click(); }).delegate('#editSave','click',function(e) { e.stopPropagation(); $('#row').text($('#editInput').val()); }).delegate('#editInput','blur',function() { if($('#editSave').click()) $('#row').text($('#editInput').val()); else $('#row').text($('#row').data('text')); }); A: .unbind allows u to unbind.[docs] EDIT Use keydown in place of keyup
doc_23525978
Please have a look at HTML and CSS and let me know if anyone can help? <div class="navigation"> <li class="active"> <a href="#">home</a> </li> <li> <a href="#">about</a> </li> <li> <a href="#">products</a> <div> <a href="#">product 1</a> <div> <a href="#">sub sub</a> </div> <a href="#">product 2</a> <a href="#">product 3</a> </div> </li> <li> <a href="#">services</a> </li> <li> <a href="#">FAQ</a> </li> </div> CSS is here: .navigation { float: right; list-style: none; margin: 110px 0 0; padding: 0; } .navigation li { font-family: "Segoe UI Web Regular","Segoe UI","Helvetica Neue",Arial; font-size: 20px; color: Maroon; float: left; margin-left: 50px; position: relative; margin-bottom: 40px; z-index:999; } .navigation li > a { color: #505050; text-decoration: none; } .navigation li:hover > a { color:#D30404; } .navigation li > div a { color: #505050; display: block; text-decoration: none; font-size: 17px; padding: 4px; margin-top: 2px; } .navigation li:hover > div { color: #D30404; display: block; } .navigation li > div a:hover { color: #fff; background-color: #D30404; } .navigation li > div { background-color:rgb(250, 250, 250); display: none; width: 110px; position: absolute; } .navigation li div div a { background-color:rgb(250, 250, 250); display: none; width: 110px; position: relative; } .navigation li div:hover > div a { display: block; position: absolute; margin-left: 110px; top: -2px; } A: Got it! (Forgive me for changing your code so much.) http://jsfiddle.net/K7kPJ/4/ .navigation { list-style: none; margin: 0; padding: 0; } .navigation li { font-family: "Segoe UI Web Regular","Segoe UI","Helvetica Neue",Arial; font-size: 20px; color: Maroon; float: left; margin-left: 50px; position: relative; margin-bottom: 40px; z-index:999; } .navigation li > a { color: #505050; text-decoration: none; display:inline-block; height:30px; } .navigation li:hover > a { color:#D30404; } .navigation li > div a { color: #505050; display: block; text-decoration: none; font-size: 17px; padding: 4px; } .navigation li > div a:hover { color: #fff; background-color: #D30404; } .navigation li > div { background-color:rgb(250, 250, 250); display: none; width: 110px; position: absolute; } .navigation li div div { background-color:rgb(250, 250, 250); display: none; width: 110px; position: absolute; left:110px; top:0; } .navigation li a:hover + div, .navigation li div:hover { display: block; }
doc_23525979
Public WithEvents DataPort As New IO.Ports.SerialPort Public Function ConnectPort(ByVal PrtName As String) Try DataPort.PortName = PrtName DataPort.BaudRate = 115200 DataPort.Parity = IO.Ports.Parity.None DataPort.StopBits = IO.Ports.StopBits.One DataPort.DataBits = 8 DataPort.Open() AddHandler Me.DataPort.DataReceived, New SerialDataReceivedEventHandler(AddressOf comPort_DataReceived) Catch ex As Exception MsgBox(ex.ToString) End Try Public Sub comPort_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs) Dim RecievedMessage As String = DataPort.ReadExisting() ModemResponse(RecievedMessage) End Sub A: I believe you can connect multiple modem, for that you can make your application multithreaded. In this case each thread will represent to one modem object but will share the same code also. A: You can copy and paste the code 10 times (changing the port number/name each time), but a better approach would be to use a for loop to create the 10 ports. You then need your event handler to know which port the data has arrived from (because your single handler will be called by allthe ports) - you can use sender or possibly may be able to get the port number from the event args. Note that there is no need to deliberately make your code 'multi threaded' because the serial port will do this for you - the event handler will be called back on different thread(s) as data arrives. As long as your event handler doesn't do anything non-thread-safe (such as storing data from different ports in the same place) you won't need to do anything specific to make it multithreaded.
doc_23525980
up an text-based ADO.NET command. How do I do this? I have been following the below link: http://damieng.com/blog/2008/07/30/linq-to-sql-log-to-debug-window-file-memory-or-multiple-writers And have added the DebugTextWriter class to my project. So, now, in my code I have the following which doesn't really do anything and I don't think its right: using(WorkbookDataContext dc = _conn.GetContext()) { if(profile.ProfileId > 0) { dc.Profiles.Attach(profile, true); } else { dc.Profiles.InsertOnSubmit(profile); } dc.Log = new DebugTextWriter(); #if DEBUG dc.Log = new System.IO.StreamWriter("linq-to-sql.log") { AutoFlush = true }; #endif dc.SubmitChanges(); } Any ideas what I am doing wrong and/or how to inspect my LINQ insert statement correctly? Thanks A: How to: Display Generated SQL (LINQ to SQL) You can view the SQL code with the Log property. Example: use the Log property to display SQL code in the console window before the code is executed. You can use this property with query, insert, update & delete commands. db.Log = Console.Out; IQueryable<Customer> custQuery = from cust in db.Customers where cust.City == "London" select cust; foreach(Customer custObj in custQuery) { Console.WriteLine(custObj.CustomerID); } These lines from the console window are what you see when you execute the C# code above. SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactT itle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Coun try], [t0].[Phone], [t0].[Fax] FROM [dbo].[Customers] AS [t0] WHERE [t0].[City] = @p0 -- @p0: Input String (Size = 6; Prec = 0; Scale = 0) [London] -- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.20810.0 AROUT BSBEV CONSH EASTC NORTS SEVES Alternately, you can use the LINQ to SQL Debug Visualizer to hover over a LINQ expression while in the VS 2008 debugger, and then inspect the raw SQL that the ORM will execute at runtime when evaluating the LINQ query expression.
doc_23525981
Here's the code: <script type="text/javascript" language="Javascript"> function doSum() { var a = document.getElementsByName("a").value; var b = document.getElementsByName("b").value; var sum = a + b; document.getElementById("sum").value = sum; } </script> <form action="" method="POST"> <br/>a:<br/> <input type="text" name="a" onblur='doSum()' value="0" size="5" /> <br/>b:<br/> <input type="text" name="b" onblur='doSum()' value="0" size="5" /> <br/>Ergebnis<br/> <input type="text" id='sum' value='' size="50" disabled/> </form> Sorry for that noob question, but what I'am doing wrong? Thanks for any help! A: use getElementById and give each of those an Id. getElementsByName returns an array. By the way.. it's not a bad question. It's a common error-- one that is addressed in a way by using jQuery which deals in wrapped sets. A: Fields in JavaScript are all strings you need int, also .getElementsByName returns an array, you probably need the first element, so: var a = parseInt(document.getElementsByName("a")[0].value, 10); var b = parseInt(document.getElementsByName("b")[0].value, 10); A: getElementsByName returns multiple elements, hence the plural Elements. You need to get the property of the first element found: var a = document.getElementsByName('a')[0].value; getElementsByName returns a NodeList: this is a set of all the elements found with that name. It is like an array in that you can use numeric indexes (like [0]) to access the elements found and in that there is a length property; no other array-like functionality is available. Furthermore, the value property will always be a string if it is set. The + operator is the addition operator when the values are numbers; if they are strings, it is the concatenation operator. "1" + "2" is equal to "12" in Javascript. You need to use parseInt to convert them to numbers: var a = document.getElementsByName('a')[0].value; a = parseInt(a, 10); // parse as a number in base 10 A: getElementsByTagName returns a node list: function doSum() { var a = document.getElementsByName("a")[0].value; var b = document.getElementsByName("b")[0].value; var sum = parseInt(a, 10) + parseInt(b, 10); document.getElementById("sum").value = sum; } So you will need to index it. In addition in order not to do a string concate, parseInt with radix 10 is needed. Unless you plan to accept octal values in your calculator. A: Give ids to your inputs and identify them uniquely using document.getElementById. Then, obtain their decimal int values using parseInt with the radix parameter set to 10 and display the result as you currently do. <script type="text/javascript" language="Javascript"> function doSum() { var a = parseInt(document.getElementById("a").value, 10); var b = parseInt(document.getElementById("b").value, 10); var sum = a + b; document.getElementById("sum").value = sum; } </script> <form action="" method="POST"> <br/>a:<br/> <input type="text" id="a" onblur='doSum()' value="0" size="5" /> <br/>b:<br/> <input type="text" id="b" onblur='doSum()' value="0" size="5" /> <br/>Ergebnis<br/> <input type="text" id='sum' value='' size="50" disabled/> </form> getElementsByName returns a list of elements and you'd have to refer to the one you want through an index, even if the list contains only one element. getElementById on the other hand, returns an uniquely identified element, by its id. A: getElementsByName returns an array which gives you the wrong data type for what you are trying to do. try: function doSum() { var a = document.getElementById("a").value; var b = document.getElementById("b").value; var sum = a + b; document.getElementById("sum").value = sum; } </script> <form action="" method="POST"> <br/>a:<br/> <input id="a" type="text" name="a" onblur='doSum()' value="0" size="5" /> <br/>b:<br/> <input id="b" type="text" name="b" onblur='doSum()' value="0" size="5" /> <br/>Ergebnis<br/> <input type="text" id='sum' value='' size="50" disabled/> </form> A: OK, two issues, your a fetching the valurs of a and b using getElementsByName which returns an array of values (since there could be many). Use getElementsById and put ids in the HTML. Also the value properties will be strings so you will need to convert to numbers before doing your addition. A: a and b are strings so : function doSum() { var a = parseInt(document.getElementsByName("a").value); var b = parseInt(document.getElementsByName("b").value); var sum = a + b; document.getElementById("sum").value = sum; }
doc_23525982
A: Account > Privacy Settings > Apps and Websites (Edit your settings) In this page you can just delete apps. This way user can deactivate/disconnect websites/apps.
doc_23525983
Sure enough. The message box pops up when using Start With Debugging. Nothing happens when I click the button with using Start Without Debugging. Some research pointed me at: [ComVisibleAttribute(true)] public enum UIPermissionWindow { AllWindows } I added that and still not pop-up from any message boxes. The project is as basic as possible for troubleshooting. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; [ComVisibleAttribute(true)] public enum UIPermissionWindow { AllWindows } namespace Form462 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) => MessageBox.Show("Help!"); } } A: Windows corruption is clearly the culprit. MessageBox.Show() works perfectly normal on another server. One other odd thing on this server, Can't seem to open dialog boxes in Visual Studio. File --> Open ---> New Project Solution. Nothing happens. I see the little Ready Icon in the way bottom left blink, nothing else happens. I have no updates for Visual Studio or windows.
doc_23525984
Both EventLogger and ErrorLogger logged in to textfile. Also I create console appender and appended it to the root. My problem is when I use EventLogger or ErrorLogger it both write to the console and to the text file also. I need to avoid that. Can some one please help me. Following I have showed you the xml file <?xml version="1.0" encoding="UTF-8" ?> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="ErrorAPPENDER" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="./log/FIX5SvrError.log"/> <param name="Append" value="true"/> <param name="DatePattern" value="'.'yyyy-MM-dd"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{HH:mm:ss,SSS} %-4r [%t] %-5p %x - %m%n" /> </layout> </appender> <appender name="EventAPPENDER" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="./log/FIX5SvrEvent.log"/> <param name="Append" value="true"/> <param name="DatePattern" value="'.'yyyy-MM-dd"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{HH:mm:ss,SSS} %-4r [%t] %-5p %x - %m%n" /> </layout> </appender> <appender name="ConsoleAPP" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%m%n"/> </layout> </appender> <logger name="ErrorLogger"> <level value="debug"/> <appender-ref ref="ErrorAPPENDER" /> </logger> <logger name="EventLogger"> <level value="debug"/> <appender-ref ref="EventAPPENDER" /> </logger> <root> <priority value ="debug" /> <appender-ref ref="ConsoleAPP" /> </root> </log4j:configuration> A: For the loggers whose output you don't want percolating up, you need to set additivity = false. <logger name="ErrorLogger" additivity="false"> <level value="debug"/> <appender-ref ref="ErrorAPPENDER" /> </logger> <logger name="EventLogger" additivity="false"> <level value="debug"/> <appender-ref ref="EventAPPENDER" /> </logger> Search for additivity in the manual for more details.
doc_23525985
<camelContext id="cbr-example-context" xmlns="http://camel.apache.org/schema/blueprint"> <route id="_route1"> <from id="_from1" uri="file:///d:/in"/> <to id="_to2" uri="file:///E:/out"/> </route> </camelContext> i want to Transform XMl to another xml format. assume i have a logic in ats.emvo.transform.TransformXml java file how do i integrated to transform tis in camel context input (file:///d:/in) is xml file and i want to save it as another location as xml. i already add this file as bean class to camel A: You can invoke your bean directly in your routing logic. Just make sure your bean is correctly referenced. With Spring XML, the syntax looks like this: <route id="_route1"> <from id="_from1" uri="file:///d:/in"/> <bean ref="myBeanName" method="doTransform"/> <to id="_to2" uri="file:///E:/out"/> </route> You may also want to check the Apache Camel documentation on the matter: http://camel.apache.org/message-translator.html
doc_23525986
TbleProduct ProductID ProductDescription CaseWeight TbleOrder OrderID OrderDate OrderQty TbleInventory ProductID QtyonHand TbleProduction ProductionDate ProductCode ProductionQty What I want to create a query which show, how much each product is on hand, and how many order are there for certain product, so can be schedule to produce. Any help will be greatly appreciated. Thanks A: Firstly, you need design the table structure reasonably, the order table should be, OrderID OrderDate OrderQty ProductID Production table should be, ProductionID ProductionDate ProductID ProductionQty Then your application need maintain/update Inventory table based on order and production flow. On hand product query is simple, select ProductID, QtyonHand from inventory How many order for specific product, select sum(OrderQty) from order where ProductID=your specific product id
doc_23525987
I have tried <context:component-scan base-package="z.y.z.service" base-package="x.y.z.controller" /> and <context:component-scan base-package="x.y.z.service, x.y.z.controller" /> and <context:component-scan base-package="x.y.z.service" /> <context:component-scan base-package="x.y.z.controller" /> but got error: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [x.y.z.dao.daoservice.LoginDAO] found for dependency: A: Another general Annotation approach: @ComponentScan(basePackages = {"x.y.z"}) A: Annotation Approach @ComponentScan({ "x.y.z", "x.y.z.dao" }) A: A delayed response but to give multiple packages using annotation based approach we can use as below: @ComponentScan({"com.my.package.one","com.my.package.subpackage.two","com.your.package.supersubpackage.two"}) A: You can add multiple base packages (see axtavt's answer), but you can also filter what's scanned inside the base package: <context:component-scan base-package="x.y.z"> <context:include-filter type="regex" expression="(service|controller)\..*"/> </context:component-scan> A: The following approach is correct: <context:component-scan base-package="x.y.z.service, x.y.z.controller" /> Note that the error complains about x.y.z.dao.daoservice.LoginDAO, which is not in the packages mentioned above, perhaps you forgot to add it: <context:component-scan base-package="x.y.z.service, x.y.z.controller, x.y.z.dao" /> A: <context:component-scan base-package="x.y.z"/> will work since the rest of the packages are sub packages of "x.y.z". Thus, you dont need to mention each package individually. A: If x.y.z is the common package then you can use: <context:component-scan base-package="x.y.z.*"> it will include all the package that is start with x.y.z like: x.y.z.controller,x.y.z.service etc. A: For Example you have the package "com.abc" and you have multiple packages inside it, You can use like @ComponentScan("com.abc")
doc_23525988
How do I do that? Is there TinyMCE server side command for that? A: You can check the current user's membership in a role and then enable TinyMCE for a given textarea with this sort of approach: @if (HttpContext.Current.User.IsInRole("Administrator")) { <script type="text/javascript"> $(function() { $('#mytextarea').tinymce({ // tinymce config }); }); </script> } You may also want to do the role check in your controller and pass the value as part of a ViewModel or the ViewBag.
doc_23525989
'heat.exe - Bad Image' The application or DLL c:\path\to\file.tlb is not a valid Windows image. Please check this against your installation diskette. But then after we press 'ok', it continues on and successfully generates It looks like this bug report on the wix bugboard says it was fixed in a release previous to mine, but it seems not to be. They say that the error occurs because it tries to load it as a DLL first (which fails) but then continues on to do the right thing. This is happening on Windows XP SP3. Anyone know of a workaround for this? A: Try a later build. There have been significant bug fixes to heat since 4805 build.
doc_23525990
I need to sort everything by port, and each port has a pair(A,B,C,D) atleast once. when its sorted, i need to sort even more - i need to sort each pair in exact port. Currently i have select that does everything that i need but just with a length. I want to change this fragment so it could check - if length = N/A, then it takes length_to_fault and if length_to_fault = N/A, then it takes length. My idea is just to combine these 2 columns into 1. Also each record has value on one column only(it can be length or length_to_fault). So far i have this- Select d.* from (select d.*, lead(length::float) over (partition by port_nbr, pair order by d.add_date) as next_length from diags d where length !='N/A' ) d This works perfectly, but there is records that has N/A in length, but value is inside length_to_fault so this select doesn't take that record. Is there a way to edit this fragment to include length_to_fault too? Maybe i can sum these two columns into one? Also length/length_to_fault is chars in database, so i must change it to float in this select. A: You can use a case expression: Select d.* from (select d.*, lead( (case when length <> 'N/A' then length else length_to_fault end)::float) over (partition by port_nbr, pair order by d.add_date) as next_length from diags d ) d
doc_23525991
After a successful login, how to stop sending the user to localhost/login cause he's already logged in, but send him instead to a localhost/index where there's a logout button. Video reference (min 00:48) https://youtu.be/DcB1Ge0HQ4I A: That's a simple task ,,,did you create $_SESSION['loggedin'] = true;
doc_23525992
I need to check the old table for members who left and put these (who left) to a new table. So basically: * *if B2 != any value in column A(on Sheet2) copy row 2 (from Sheet1) to A2(Sheet3); *if B3 != any value in column A(on Sheet2) copy row 3 (from Sheet1) to the next free row on A(Sheet3); Alternatively, deleting rows on the first table and skipping the creation of Sheet3 is possible as well. I mustn't use scripts, so I hope there is a function only solution possible. If it helps, Sheet2 is variable, I can put the values from column A to Column B (or any other). I tried =search, =if, =not, =vlookup and even failed more horribly on =query. A: if B2 != any value in column A(on Sheet2) copy row 2 (from Sheet1) to A2(Sheet3) Use filter(), like this: =filter(Sheet1!A2:C, isna(match(Sheet1!B2:B, Sheet2!A2:A, 0)))
doc_23525993
Exporting is working fine but while I add code for customization its showing error. here is my code: window["JSZip"] = JSZip; $('#trackerDataTable').DataTable({ dom: 'Bfrtip', buttons: [ { extend: 'excel', text: '<i></i>&nbsp;Export to Excel &nbsp;', filename: 'Timecards', extension: '.xlsx', exportOptions: { columns: ':visible' }, customize: function (xlsx) { debugger; var sheet = xlsx.xl.worksheets['sheet1.xml']; $('row c[r^="C"]', sheet).attr('s', '50'); } }, ] }); Here in the above code xlsx.xl is showing below error : It would be great if you can help me here to make it work. Thank you in advance. A: I found the solution now. I created a separate function for the function. I am using typescript here. window["JSZip"] = JSZip; $('#trackerDataTable').DataTable({ dom: 'Bfrtip', buttons: [ { extend: 'excel', className: 'btn-primary', text: '&nbsp; Export to Excel &nbsp;', filename: 'Timecards', extension: '.xlsx', exportOptions: { columns: ':visible' }, customize: function (xlsx) { debugger; ExportTimecardsWebPart.exportExcel(xlsx); // create separate function } // customize: function(xlsx) { // debugger; // var sheet = xlsx.xl.worksheets['sheet1.xml']; // $('row c[r^="C"]', sheet).attr('s', '50'); // } }, ], }); public static exportExcel(xlsx: any): void { debugger; var sheet = xlsx.xl.worksheets['sheet1.xml']; $('row c[r^="C"]', sheet).attr('s', '50'); }
doc_23525994
- name: Build and push the images run: | for versionFilePath in $(git diff-tree --no-commit-id --name-only -r ${{ github.sha }} ${{ github.event.before }} | grep "VERSION"); do folder=${versionFilePath%"/VERSION"} IMAGE_NAME=${folder##*/} tmpName="image-$RANDOM" docker build $folder --file $folder/Dockerfile --tag $tmpName IMAGE_ID=${{ secrets.DOCKER_REGISTRY_URL }}/${{ secrets.REPOSITORY }}/$IMAGE_NAME VERSION=$(cat $versionFilePath) echo IMAGE_ID=$IMAGE_ID echo VERSION=$VERSION docker tag $tmpName $IMAGE_ID:$VERSION docker push $IMAGE_ID:$VERSION done; - name: Download task definition run: | aws ecs describe-task-definition --task-definition service \ --query taskDefinition > task-definition.json - name: Fill in the new image ID in the Amazon ECS task definition id: task-def uses: aws-actions/amazon-ecs-render-task-definition@v1 with: task-definition: task-definition.json container-name: application image: ${{ steps.build-image.outputs.image }} - name: Deploy Amazon ECS task definition uses: aws-actions/amazon-ecs-deploy-task-definition@v1 with: task-definition: ${{ steps.task-def.outputs.task-definition }} service: ${{ secrets.ECS_SERVICE }} cluster: ${{ secrets.ECS_CLUSTER }} wait-for-service-stability: true I am able to build the images successfully. However, when multiple images are built, the ${{ steps.build-image.outputs.image }} gets only the name of the image that was last built. Is it possible to store the output in an array? A: From aws-actions/amazon-ecs-render-task-definition issues 72, this would not be supported at the moment within the same task. The README mentions: If your task definition file holds multiple containers in the containerDefinitions section which require updated image URIs, chain multiple executions of this action together using the output value from the first action for the task-definition input of the second So right now, that action would only consider one image name, not multiple (within a given task).
doc_23525995
Thank you for your help, Ana A: Which data set is it having problems loading? I was able to load the TargetScan data set and the miR2Disease data set without any issues, although I do have a machine with 32Gb of RAM. Could it be that it was trying to create a view? That network has 500,000 edges, so creating a view would be somewhat intensive. P.S. Loading the datasets took about 8 seconds on my machine, so something is definitely wrong. What version of Cytoscape are you running?
doc_23525996
$string = " { \"name\": \"flare\", \"children\": [ { \"name\": \"analytics\", \"children\": [ { \"name\": \"cluster\", \"children\": [ {\"name\": \"AgglomerativeCluster\", \"size\": 3938}, {\"name\": \"CommunityStructure\", \"size\": 3812}, {\"name\": \"HierarchicalCluster\", \"size\": 6714}, {\"name\": \"MergeEdge\", \"size\": 743} ] } ] } ] } "; A: Use json_decode() for this: $obj = json_decode($string); var_dump($obj); Output: class stdClass#1 (2) { public $name => string(5) "flare" public $children => array(1) { [0] => class stdClass#2 (2) { public $name => string(9) "analytics" public $children => array(1) { ... } } } } A: There's no such thing as a JSON object. What you have is a JSON Text expressed as a PHP string literal. If you want to parse it into a PHP object, then use json_decode($string). If you want to parse it into a JavaScript object, then you have to pass the string to JavaScript somehow. That might involve printing it into the response to an HTTP request, passing it to V8 or some other technique depending on what exactly you want to achieve with it.
doc_23525997
I have next config: Nginx Frontend -> Varnish Cache -> Varnish backend Network configured like this: All request to my real IP for ports :80 and :443 are translated to local IP 192.168.1.70 to Nginx. Nginx transfered all requests from 80 to 443. Then all request goes to Varnish. if there's no cache Varnish asks backend. 4 config files for nginx: frontend-domain1.com frontend-domain2.com Configs of frontend is similar except "server_name" "proxy_set_header Host" options server { listen 192.168.1.70:80; server_name domain1.com; return 301 https://$server_name$request_uri; } server { listen 192.168.1.70:443 ssl; server_name domain1.com; keepalive_timeout 60 60; gzip on; gzip_comp_level 1; gzip_min_length 512; gzip_buffers 8 64k; gzip_types text/plain; gzip_proxied any; ssl on; ssl_stapling on; resolver 8.8.8.8 8.8.4.4; ssl_prefer_server_ciphers on; ssl_session_cache shared:SSL:10m; ssl_session_timeout 5m; ssl_certificate /chain.crt; ssl_certificate_key /private.key; ssl_dhparam /dhparams.pem; ssl_protocols TLSv1.2 TLSv1.1 TLSv1; ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:E$ add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains'; location / { proxy_pass http://127.0.0.1:6081/; proxy_set_header Host domain1.com; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-Port 443; } } backend-domain1.com backend-domain2.com Configs of backend is similar except server_name option server { listen 127.0.0.1:81; root /web/sites/domain1; index index.php; gzip on; gzip_comp_level 1; gzip_min_length 512; gzip_buffers 8 64k; gzip_types text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml; gzip_proxied any; server_name domain1.com; location ~ /\. { deny all; } location / { try_files $uri $uri/ /index.php?$args; } rewrite /wp-admin$ $scheme://$host$uri/ permanent; location ~ \.php$ { try_files $uri =404; location ~* /(?:uploads|files)/.*\.php$ { deny all; } rewrite /wp-admin$ $scheme://$host$uri/ permanent; location ~ \.php$ { try_files $uri =404; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass unix:/var/run/php7.0-fpm.sock; } } Varnish Configs: default.vcl vcl 4.0; backend default { .host = "127.0.0.1"; .port = "81"; } acl purge { "localhost"; "127.0.0.1"; "192.168.1.70"; } sub vcl_recv { if (req.method == "PURGE") { if (!client.ip ~ purge) { return(synth(405, "This IP is not allowed to send PURGE requests.")); } return (purge); } } include "/etc/varnish/domain1.vcl"; include "/etc/varnish/domain2.vcl"; domain1.vcl and domain2.vcl differs with: "req.http.host" sub vcl_recv { if (req.http.host == "domain1.com") { if (req.url !~ "^/wp-(login|admin)") { unset req.http.cookie; } } set req.http.host = regsub(req.http.host, "^www\.", ""); set req.http.host = regsub(req.http.host, ":[0-9]+", ""); set req.http.Cookie = regsuball(req.http.Cookie, "_ga=[^;]+(; )?", ""); set req.http.Cookie = regsuball(req.http.Cookie, "_gat=[^;]+(; )?", ""); if (req.http.Authorization || req.method == "POST") { return (pass); } if (req.url ~ "wp-(login|admin)" || req.url ~ "preview=true") { return (pass); } if (req.url ~ "sitemap" || req.url ~ "robots") { return (pass); } set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(_[_a-z]+|has_js)=[^;]*", ""); set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", ""); set req.http.Cookie = regsuball(req.http.Cookie, "__qc.=[^;]+(; )?", ""); set req.http.Cookie = regsuball(req.http.Cookie, "wp-settings-1=[^;]+(; )?", ""); set req.http.Cookie = regsuball(req.http.Cookie, "wp-settings-time-1=[^;]+(; )?", ""); set req.http.Cookie = regsuball(req.http.Cookie, "wordpress_test_cookie=[^;]+(; )?", ""); # if (req.http.cookie ~ "^ *$") { # unset req.http.cookie; # } if (req.url ~ "\.(css|js|png|gif|jp(e)?g|swf|ico|woff|svg|htm|html)") { unset req.http.cookie; if (req.http.Cookie ~ "wordpress_" || req.http.Cookie ~ "comment_") { return (pass); } if (!req.http.cookie) { unset req.http.cookie; } if (req.http.Authorization || req.http.Cookie) { # Not cacheable by default return (pass); } return (hash); } sub vcl_pass { return (fetch); } sub vcl_hash { hash_data(req.url); return (lookup); } sub vcl_backend_response { unset beresp.http.Server; unset beresp.http.X-Powered-By; if (bereq.url ~ "sitemap" || bereq.url ~ "robots") { set beresp.uncacheable = true; set beresp.ttl = 30s; return (deliver); } if (bereq.url ~ "\.(css|js|png|gif|jp(e?)g)|swf|ico|woff|svg|htm|html") { unset beresp.http.cookie; set beresp.ttl = 7d; unset beresp.http.Cache-Control; set beresp.http.Cache-Control = "public, max-age=604800"; set beresp.http.Expires = now + beresp.ttl; } if (bereq.url ~ "wp-(login|admin)" || bereq.url ~ "preview=true") { set beresp.uncacheable = true; set beresp.ttl = 30s; return (deliver); } if (!(bereq.url ~ "(wp-login|wp-admin|preview=true)")) { unset beresp.http.set-cookie; } if ( bereq.method == "POST" || bereq.http.Authorization ) { set beresp.uncacheable = true; set beresp.ttl = 120s; return (deliver); } if ( bereq.url ~ "\?s=" ){ set beresp.uncacheable = true; set beresp.ttl = 120s; return (deliver); if ( beresp.status != 200 ) { set beresp.uncacheable = true; set beresp.ttl = 120s; return (deliver); } set beresp.ttl = 1d; set beresp.grace = 30s; return (deliver); } sub vcl_deliver { unset resp.http.X-Powered-By; unset resp.http.Server; unset resp.http.Via; unset resp.http.X-Varnish; return (deliver); } If i uncomment # if (req.http.cookie ~ "^ *$") { # unset req.http.cookie; # } it shows index for First opened domain. and ignored second domain. all other links works perfectly. If i restart varnish and ask second domain, - it will not show first domain homepage. Main question: how to configure varnish properly to understand both of domains? rus: как корректно заставвить варниш обрабатівать два\несколько домена\доменов? A: Versions of software: varnish-4.1.1 revision 66bb824 nginx version: nginx/1.10.3 PHP 7.0-fpm OS: Ubuntu 16.04.3 LTS A: Varnish is a transparent HTTP proxy so it doesn't really care what and how many domains you pass through it. It will forward the same Host header that was sent by browser to your backend (nginx). Thus, you only have to make sure that your nginx configuration (or whatever webserver congifuration) will listen on desired domain names. So make sure that your listen directive in nginx is equal to the domain names that you access the websites with in your browser. As simple as that. In the SSL termination server blocks, the following will help to avoid hardcoding of domain name: proxy_set_header Host $host; P.S. Ну ты и наваял :)
doc_23525998
CFLAGS = -Wall LDFLAGS = -g CC = gcc SRCS = p4a.c p4b.c p4static: p4a.c gcc $(LDFLAGS) -o $@ $< -static -L. -lpthread p4dynlink: p4a.c @echo "this doesn't print/echo/execute" gcc $(LDFLAGS) -o p4dynlink $< -L. -lpthread I'm using tab instead of spaces. Here is the outputs: mike@elementary:~/p4$ make gcc -g -o p4static p4a.c -static -L. -lpthread mike@elementary:~/p4$ make make: `p4static' is up to date. A: From How make Processes a Makefile: By default, make starts with the first target (not targets whose names start with ‘.’). This is called the default goal. [....] Thus, when you give the command: make make reads the makefile in the current directory and begins by processing the first rule. So when you type make make tries to build your p4static target which doesn't have an echo line. And the next time you run make it says that target is up to date and has nothing to do. To build p4dynlink you need to tell make to build that target make p4dynlink. You can set the default goal manually (in the makefile) with .DEFAULT_GOAL: # Set our own. .DEFAULT_GOAL := foo But convention is usually to create an all target as the first target and have it "Do the Right Thing" by default. So in your case, assuming you wanted both targets built by default, you would use: all: p4static p4dynlink
doc_23525999
$from = 'shahrushabh1996@gmail.com'; $config = array( 'protocol'=>'smtp', 'smtp_host'=>'ssl://smtp.googlemail.com', 'smtp_port'=>'465', 'smtp_user'=>'shahrushabh1996@gmail.com', 'smtp_pass'=>'********', 'mailtype'=>'html', 'charset'=>'UTF-8' ); $this->load->library('email', $config); $this->email->set_newline("\r\n"); $this->email->to($personemail); $this->email->from($from); $this->email->subject('it is a demo email by Rushabh Shah'); $this->email->message('demo message'); if(!$this->email->send()){ show_error($this->email->print_debugger()); } else{ echo 'email is sent'; } Error: Unable to send email using PHP mail(). Please help me how to resolve following error? this method is working fine in different controller but not working in this controller how to resolve it? please help me. A: Try this $config = array( 'protocol' => 'smtp', 'smtp_host' => 'ssl://smtp.googlemail.com', 'smtp_port' => '465', 'smtp_user' => 'xxxx@gmail.com', 'smtp_pass' => 'xxxxx', 'mailtype' => 'html', 'starttls' => true, 'newline' => "\r\n" ); $this->load->library('email', $config); $this->email->from('someuser@gmail.com', 'Test'); $this->email->to('test@test.com'); $this->email->subject('Test Email'); $this->email->message('Hello World'); $this->email->send();