text
stringlengths
14
21.4M
Q: What gcc option enables loop unrolling for SSE intrinsics with immediate operands? This question relates to gcc (4.6.3 Ubuntu) and its behavior in unrolling loops for SSE intrinsics with immediate operands. An example of an intrinsic with immediate operand is _mm_blend_ps. It expects a 4-bit immediate integer which can only be a constant. However, using the -O3 option, the compiler apparently automatically unrolls loops (if the loop counter values can be determined at compile time) and produces multiple instances of the corresponding blend instruction with different immediate values. This is a simple test code (blendsimple.c) which runs through the 16 possible values of the immediate operand of blend: #include <stdio.h> #include <x86intrin.h> #define PRINT(V) \ printf("%s: ", #V); \ for (i = 3; i >= 0; i--) printf("%3g ", V[i]); \ printf("\n"); int main() { __m128 a = _mm_set_ps(1, 2, 3, 4); __m128 b = _mm_set_ps(5, 6, 7, 8); int i; PRINT(a); PRINT(b); unsigned mask; __m128 r; for (mask = 0; mask < 16; mask++) { r = _mm_blend_ps(a, b, mask); PRINT(r); } return 0; } It is possible compile this code with gcc -Wall -march=native -O3 -o blendsimple blendsimple.c and the code works. Obviously the compiler unrolls the loop and inserts constants for the immediate operand. However, if you compile the code with gcc -Wall -march=native -O2 -o blendsimple blendsimple.c you get the following error for the blend intrinsic: error: the last argument must be a 4-bit immediate Now I tried to find out which specific compiler flag is active in -O3 but not in -O2 which allows the compiler to unroll the loop, but failed. Following the gcc online docs at https://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/Overall-Options.html I executed the following commands: gcc -c -Q -O3 --help=optimizers > /tmp/O3-opts gcc -c -Q -O2 --help=optimizers > /tmp/O2-opts diff /tmp/O2-opts /tmp/O3-opts | grep enabled which lists all options enabled by -O3 but not by -O2. When I add all of the 7 listed flags in addition to -O2 gcc -Wall -march=native -O2 -fgcse-after-reload -finline-functions -fipa-cp-clone -fpredictive-commoning -ftree-loop-distribute-patterns -ftree-vectorize -funswitch-loops blendsimple blendsimple.c I would expect that the behavior is exactly the same as with -O3. However, the compiler complains that "the last argument must be a 4-bit immediate". Does anyone have an idea what the problem is? I think it would be good to know which flag is required to enable this type of loop unrolling so that it can be activated selectively using #pragma GCC optimize or by a function attribute. (I was also surprised that -O3 obviously doesn't even enable the unroll-loops option). I would be grateful for any help. This is for a lecture on SSE programming I give. Edit: Thanks a lot for your comments. jtaylor seems to be right. I got my hand on two newer versions of gcc (4.7.3, 4.8.2), and 4.8.2 complains on the immediate problem regardless of the optimization level. Moverover, I later noticed that gcc 4.6.3 compiles the code with -O2 -funroll-loops, but this also fails in 4.8.2. So apparently one cannot trust this feature and should always unroll "manually" using cpp or templates, as Jason R pointed out. A: I am not sure if this applies to your situation, since I am not familiar with SSE intrinsics. But generally, you can tell the compiler to specifically optimize a section of code with : #pragma GCC push_options #pragma GCC optimize ("unroll-loops") do your stuff #pragma GCC pop_options Source: Tell gcc to specifically unroll a loop
Q: Is it possible to include a list in a DbSet? WCF Service Demo Code public List<Message> GetMessages(string userAddress) { return this.projectContext.Messages.Include("Contacts").ToList(); } Message Class public class Message { public int Id { get; set; } public string Text { get; set; } public List<Contact> Contacts { get; set; } } When i try to consume that method on client side i get the next error: A: If you make the Contact an Entity, you can include the contact entity in your context and map it via a foreign key to from Message Entity.
Q: left_join per group and add group value when missing I am wondering how to do a kind of left_join per group (which is not possible in dplyr for what I understand) and for which I would replace the missing value for the group value by the value of the group Here is what I mean: Starting from the following: ref group value B group1 3 C group1 4 D group1 3 A group2 6 C group2 5 I woudl like to add to the missing letters to ref (from A to F) for each group so it would be something like that: ref group vol A NA NA B group1 3 C group1 4 D group1 3 E NA NA F NA NA A group2 6 B NA NA C group2 5 D NA NA E NA NA F NA NA then replace (or at the same time) replace NA in group by the group value it belongs to.. ref group vol A group1 NA B group1 3 C group1 4 D group1 3 E group1 NA F group1 NA A group2 6 B group2 NA C group2 5 D group2 NA E group2 NA F group2 NA here is the initial data: db <- structure(list(ref = c("B", "C", "D", "A", "C"), group = c("group1", "group1", "group1", "group2", "group2"), vol = c(3, 4, 3, 6, 5)), class = "data.frame", .Names = c("ref", "group", "vol"), row.names = c(NA, -5L)) and the reference letters: vars_to_add <- structure(list(ref = c("A", "B", "C", "D", "E", "F")), class = "data.frame", .Names = "ref", row.names = c(NA, -6L)) I could have a function filtering for each group and doing a left_join then replacing the value and then appending each group again into one data frame but maybe there is a smart way... I could also define the groups in the vars_to_add but that's not viable for scaling up with more groups... thanks A: We can use complete library(dplyr) library(tidyr) complete(db, ref = vars_to_add$ref, group) %>% arrange(group) # A tibble: 12 x 3 # ref group value # <chr> <chr> <int> # 1 A group1 NA # 2 B group1 3 # 3 C group1 4 # 4 D group1 3 # 5 E group1 NA # 6 F group1 NA # 7 A group2 6 # 8 B group2 NA # 9 C group2 5 #10 D group2 NA #11 E group2 NA #12 F group2 NA
Q: Android - Working with Multidimensional String Arrays I'm having trouble working with multidimensional strings arrays and would appreciate any clarity. I'll post a sample code below that I wrote just to play around with to get an idea of how multidimensional string arrays work. I wrote in comments what I expect to be happening and what I expect the result to be, but isn't. My questions is pretty much why isn't it working the way I am thinking, it should create the matrix [1][2][3] [4][5][6] Also an additional question, if I have the 2x3 martrix already setup, how can I reassign the value in a specific element, for example [1][1], or do I have to call the row and assign it to a variable. This whole sample code is for me to learn how to assign elements in a multidimensional string array and then reassign them. These string array lists, I do not know the dimension ahead of time and the values change, there I need to use the .add method and eventually .set. Thank you in advance for any help, amazing community it seems to be at Stack Overflow TextView displayanswer; String text0, text1, text2, text3, text4, text5, text6; ArrayList<String> column = new ArrayList<String>(); ArrayList<ArrayList<String>> row = new ArrayList<ArrayList<String>>(); @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.test1); displayanswer = (TextView) findViewById(R.id.textView1); //Creates Matrix in column variable of [1][2][3] column.add("1"); column.add("2"); column.add("3"); row.add(column); //Creates Matrix in row variable of [1][2][3] row.add(column); //Creates 2 dimension matrix of [1][2][3] // [1][2][3] column.set(0, "4"); //column variable Matrix becomes [4][2][3] column.set(1, "5"); //column variable Matrix becomes [4][5][3] column.set(2, "6"); //column variable Matrix becomes [4][5][6] row.set(1,column); //2 dimensional matrix becomes [1][2][3] //[4][5][6] column = row.get(0); //get first row of 2 row matrix, should be[1][2][3] //Assigning first row elements to text strings text0 = column.get(0); text1 = column.get(1); text2 = column.get(2); column = row.get(1); //gets second row of 2 row matrix, should be [4][5][6] //Assigning second row elements to text strings text3 = column.get(0); text4 = column.get(1); text5 = column.get(2); //should give me 123456 but instead I get 456456??? displayanswer.setText(""+text0 +text1 +text2 +text3 +text4 +text5); } } A: I guess you're making the assumption that when you add something to a list, it creates a copy of the data. However, that's not the case. The list will contain a reference to the data you're adding, not (a copy of) the actual content itself. So even though the comments below are correct, because you're adding the 'column' object twice ... row.add(column); //Creates Matrix in row variable of [1][2][3] row.add(column); //Creates 2 dimension matrix of [1][2][3] ... both list entries will refer to the same object. Then, by attempting to change the values of one column, you're actually changing the referenced object and thus you're changing both entries. That's why you end up with "456456". This will actually affect both columns, since the same object is referenced on the first two positions: column.set(0, "4"); //column variable Matrix becomes [4][2][3] column.set(1, "5"); //column variable Matrix becomes [4][5][3] column.set(2, "6"); //column variable Matrix becomes [4][5][6] The following is not true: row.set(1,column); //2 dimensional matrix becomes [1][2][3] //[4][5][6] Both entries change (because both refer to the same object), hence you end up with: [4][5][6] [4][5][6] To 'fix' this, make sure you create a new 'column' object before adding the second column. Alternatively, if you prefer to keep modifying the same object, make sure you add a copy of the data to the list. For example: //Creates Matrix in column variable of [1][2][3] column.add("1"); column.add("2"); column.add("3"); row.add(new ArrayList<String>(column)); row.add(new ArrayList<String>(column)); After that, you can safely change column without affecting the content of the list. You can also manipulate the list content directly, simply because we added copies of the data as rows, so every entry points a different object. Hope that makes sense. On a side note: I'd probably consider creating an actual Matrix class if you're planning on doing more complex things. Lists aren't particularly ideal for representing a matrix. Alternatively there are probably heaps of matrix implementations around you can learn from or borrow. Just a thought. :) A: Look at what you did with: column.add("1"); column.add("2"); column.add("3"); and column.set(0, "4"); //column variable Matrix becomes [4][2][3] column.set(1, "5"); //column variable Matrix becomes [4][5][3] column.set(2, "6"); //column variable Matrix becomes [4][5][6] This is why you are seeing 456 because you are overwriting the indexes 0, 1 and 2 with 4, 5 and 6 I made a test script for you so that you can understand it better: import java.util.ArrayList; public class Initialize { static ArrayList<String> column = new ArrayList<String>(); static ArrayList<String> newColumn = null; static ArrayList<ArrayList<String>> row = new ArrayList<ArrayList<String>>(); public static void main(String[] str){ // Stuffing the column ArrayList for later use for( int i = 1; i <= 6; i++ ){ column.add( Integer.toString(i) ); if( i == 6 ){ row.add( column ); break; } } for( int rowsCounter = 0; rowsCounter < row.size(); rowsCounter++ ){ //this is where you can print the row content System.out.println( "Row index: " + rowsCounter ); //passing the row content to a new ArrayList so that we can print the elements for the next loop if( newColumn == null ){ newColumn = new ArrayList<String>(); } newColumn = row.get(rowsCounter); for( int colsCounter = 0; colsCounter < column.size(); colsCounter++ ){ //this is where you can print the column content System.out.println( "Column index: " + colsCounter + " | value: " + column.get(colsCounter) ); } } } } Just try to repeat it if you still don't understand and ask for help if you're stuck! Good luck! A: With the help of MH's answer, I was able to come up with a simple example: (The biggest problem I had was the same as the OP's: An array list with an inner array list only creates a reference, NOT a COPY! My example below creates a copy) //Create list objects ArrayList<String> innerArray = new ArrayList<String>(); //Columns with data ArrayList<ArrayList<String>> outterArray = new ArrayList<ArrayList<String>>(); //Rows with columns //Populate row 1 innerArray.add("Row1: Column1"); //column1 innerArray.add("Row1: Column2"); //column2 innerArray.add("Row1: Column3"); //column3 outterArray.add(new ArrayList<String>(innerArray)); //add contents to main array innerArray.clear(); //clear contents since we added it to main array and want it empty for next row //Populate row 2 innerArray.add("Row2: Column1"); //column1 innerArray.add("Row2: Column2"); //column2 innerArray.add("Row2: Column3"); //column3 outterArray.add(new ArrayList<String>(innerArray)); //add contents to main array innerArray.clear(); //clear contents since we added it to main array and want it empty for next row //Display all data from array int index=0; for(ArrayList<String> row : outterArray){ Log.w(TAG,"(Row"+index+") " + row.get(0) + " | "+row.get(1)+ " | "+row.get(2)); index++; }
Q: Clean way of adding .ebextensions to Spring Boot Jar using Gradle Is there a clean way of adding additional root folders to a Spring Boot Jar file generated using the default bootRepackage. In my case I need the .ebextenions folder for AWS beanstalk. I know I can hack it -- for example add another task after bootRepackage to unzip, repackage (again), and re-zip. Is there a cleaner way ? Thanks .. the 2 ways that I've tried (that don't work) : jar { from('src/main/ebextensions') { into('ebextensions') } } bootRepackage { from('src/main/ebextensions') { into('ebextensions') } } A: For Spring Boot 2 (Gradle) if .ebextensions is located at the root of your project, use the following task: bootJar { from('./.ebextensions') { into '.ebextensions' } } or bootWar { from('./.ebextensions') { into '.ebextensions' } } This way Gradle will copy .ebextensions into the root of the application package. But if you prefer convention over configuration, move .ebextensions folder inside src/main/resources. The content of resources directory is packaged automatically in /BOOT-INF/classes/ (no scripting required). And the .ebextensions directory will be discovered by EB deployment scripts when unpacked. A: I'm still working on deploying Spring Boot to EBS myself... I think the folder has to be called .ebextensions (notice the leading dot). So you would say into('./.ebextensions') instead of into('ebextensions'). Alternatively, you might try uploading a ZIP file containing your JAR and your .ebextensions folder: task zip(type: Zip, dependsOn: bootRepackage) { from ('./.ebextensions') { into '.ebextensions' } from (jar.outputs.files) { into '.' } destinationDir project.buildDir } A: With Grails 3, I use gradle clean dist to create a .zip file containing a .war for EB distribution, and use a Procfile to describe the Spring Boot command line. An .ebextensions folder is in the base directory of my project, and projectName and projectVersion are variables defined in the build.gradle file: task dist(type: Zip) { from war.outputs.files from "src/staging/Procfile" // this file allows us to control how ElasticBeanstalk starts up our app on its Java SE platform from('./.ebextensions') { into '.ebextensions' } rename { String fileName -> if (fileName == "${projectName}-${projectVersion}.war".toString()) { fileName.replace("${projectName}-${projectVersion}", "application") } else { fileName } } } dist.dependsOn assemble where the contents of the Procfile in src/staging looks like this: web: java -jar application.war A: If you move your src/main/ebextensions folder to src/main/resources/.ebextensions, it will be automatically copied by the jar task to the root of the .jar (along with any other files in /resources), where EBS expects it, without any additional scripting. That's about as clean as you can get! A: I have my .ebextensions at the root of my project. This seems to work for me. war { from ('./.ebextensions') { into '.ebextensions' } } A: Sept 2021 I tried to add the .ebextensions folder in my jar but is seems elastic beanstalk doesn't like it anymore. Instead, I had to create a zip file with the jar and the .ebextensions folder inside. Like this ~/myapp.zip |-- myapp.jar |-- .ebextensions/ Doc Here is my gradle kts code: val jarFilename = "myapp.jar" val packageZip by tasks.register<Zip>("packageZip") { dependsOn("bootJar") archiveFileName.set("myapp.zip") destinationDirectory.set(layout.buildDirectory.dir("libs")) from("$buildDir/libs/$jarFilename") from("../.ebextensions") { into(".ebextensions") } from("../.platform") { into(".platform") } } tasks.register<Delete>("cleanLibs") { delete("$buildDir/libs/") } tasks.named<BootJar>("bootJar") { dependsOn("cleanLibs") this.archiveFileName.set(jarFilename) finalizedBy(packageZip) }
Q: SQL: will SERIABLIZABLE insert visable to other non-serizable transaction Let's say, we have transaction t1 who inserts a row into a table at SERIABLIZABLE level. Now there is another transaction t2 who is not at SERIABLIZABLE level and it selects all rows from the same table by select * from table_foo My question is before t1 commit/release the lock, will t2 see the row insert by t1? A: My question is before t1 commit/release the lock, will t2 see the row insert by t1? What t2 sees depends entirely on the isolation level of t2. It has nothing to do with the isolation level of t1. To see how it works, open two terminal windows, and make two connections to a MySQL database. Assume the table "test" exists, and has two rows. Term 1 Term 2 set transaction isolation level serializable; set transaction isolation level read uncommitted; select count(*) as num_rows from test; +----------+ | num_rows | +----------+ | 2 | +----------+ 1 row in set (0.00 sec) start transaction; insert into test values ('2013-01-02 08:00', '2013-01-02 08'); select count(*) as num_rows from test; +----------+ | num_rows | +----------+ | 3 | +----------+ 1 row in set (0.00 sec) rollback; select count(*) as num_rows from test; +----------+ | num_rows | +----------+ | 2 | +----------+ 1 row in set (0.00 sec) To make sure Term 2 doesn't see the uncommitted rows from Term 1's INSERT statement until they're committed, use any isolation level besides READ UNCOMMITTED in Term 2. A: Assuming that T1 executes before T2; T2 will not see the rows because T2 waits for T1. When T1 starts to execute, It locks the table to assure the maximun isolation level which means that no other transaction will execute on this table until T1 completes. If any other transaction try to use the table (in this case T2), it will have to wait. Therefore, T1 and T2 will never execute at the same time (concurrently). e.g.: T2 waits for T1 when T1 completes T2 executes T2 will see the rows inserted by T1 (It's too long for comments area) Yes, if you really need execute each transaction in a secuential way the alternative could be to set SERIALIZABLE as database's isolation level. Theorically each transaction should to execute in isolation (for achieving the I of ACID properties) but in practice this has not much sense. It's all about a performance issue. A high concurrency application's database could not execute properly in this way. The idea is to achieve balancing between isolation and performance. When the isolation level is decreased (e.g. COMMITTED READ that generally is the default isolation level) some kind of problems can appear: lost updates, non-repetable read, phantom read. Usually this risk is acceptable and it can be also controlled rising the isolation level only at certain transactions that have to deal with these situations.
Q: How to select items when scrolling on RecyclerView GridLayout? I've tried to achieve an interaction like the one on the Samsung calendar samsung calendar app I understand that you have to work with the Touch Event (I saw it in the Android documentation) but I still can't get to do that interaction. @Override public void onLongClick(View view, int position) { view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return false; } }); } A: public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener { private GestureDetector gestureDetector; private ClickListener clickListener; public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) { this.clickListener = clickListener; gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } @Override public void onLongPress(MotionEvent e) { View child = recyclerView.findChildViewUnder(e.getX(), e.getY()); if (child != null && clickListener != null) { clickListener.onLongClick(child, recyclerView.getChildPosition(child)); } } @Override public boolean onDown(MotionEvent e) { View child = recyclerView.findChildViewUnder(e.getX(), e.getY()); if (child != null && clickListener != null) { clickListener.onDown(child, recyclerView.getChildPosition(child), e); } return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return super.onScroll(e1, e2, distanceX, distanceY); } }); } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { View child = rv.findChildViewUnder(e.getX(), e.getY()); if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) { clickListener.onClick(child, rv.getChildPosition(child)); } return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { View child = rv.findChildViewUnder(e.getX(), e.getY()); if (child != null && clickListener != null) { clickListener.onTouchEvent(rv, e, rv.getChildPosition(child)); } } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } public interface ClickListener { void onClick(View view, int position); void onLongClick(View view, int position); void onTouchEvent(RecyclerView rv, MotionEvent e, int childPosition); void onDown(View view, int position, MotionEvent e); } } it's my Listener I have implemented
Q: Image created by filestream do not appear in my HTML - MVC I am writing a web based app that lets the user crop an image then save it to his/her computer then show it in the html. I am successful on cropping the image and saving it into the computer however I am having problems displaying it in the html. It does not show anything. Here is the code in my controller that saves the cropped image: string base64 = Request.Form["imgCropped"]; byte[] bytes = Convert.FromBase64String(base64.Split(',')[1]); using (FileStream stream = new FileStream(@"D:\CroppedPhotos\myPhoto.jpg", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) { using (BinaryWriter bw = new BinaryWriter(stream)) { bw.Write(bytes); bw.Close(); } stream.Close(); } Note: the image is from an html canvas. I put value in imgCropped by using the canvas.toDataURL Here is the code in my html that should show the cropped image: <img src="D:\CroppedPhotos\myPhoto.jpg" width="424" height="476"> A: I solved this by copying the generated image in the solutions folder. Turns out (to my case) that the generated images should be inside the solution for it to work and be displayed in the browser. <img src='/Content/Cropped/" + data + ".jpg'>
Q: Need some help understanding nodejs and socket.io Sorry for the rather ignorant question, but I'm a bit confused regarding these two technologies. I wrote a webserver in C# that uses Fleck and everything works great but I realized I probably couldn't find a hosting provider that would run .NET applications. I want to use websockets and I found socket.io to be really popular but I'm not sure exactly what it is. Correct me if I'm wrong, but, is it just like writing a server in javascript and you run the javascript file with the node.exe application and then the server is running? How do people find hosting providers that will provide that sort of service? Lastly, is socket.io just an extension of nodejs? Do you have to code your server in javascript when you use socket.io? Again, sorry for the very novice questions but I'm just trying to understand a few basic things before I continue. Thanks. A: There are a few companies that will host your node application. Its not the same as your transitional web hosts where you provide them with files and they serve the files for you. When working with node you're writing the actual web server. Some of the popular ones around are below: * *https://devcenter.heroku.com/articles/nodejs *http://nodejitsu.com/ *http://nodester.com/ @Roest: A virtual server sounds intriguing. What are the pros and cons of such an approach? Also, considering how popular nodejs is how can its webserver hosting support be so limited? How do people use it? When working with a virtual server you have full rain over what your running on the server. Pros Freedom, you get to pick all the software you want to run on your machine. A lot of the times when working with nodejs you're going to want some custom software to be running along side your application. Most of the time this is your database layer, which ever you choose. Cons YOU have to maintain it. Like @Roest stated, this isn't much of a con for most people as this ties directly into the freedom a virtual server gives you but it is something you need to take into account. I think the reason you see limited support for nodejs is because its relatively new, and its so easy to setup yourself. I want to use websockets and I found socket.io to be really popular but I'm not sure exactly what it is. Correct me if I'm wrong, but, is it just like writing a server in javascript and you run the javascript file with the node.exe application and then the server is running? That's pretty much exactly what nodejs is, or at least how you use it. Nodejs itself is Google's V8 javascript engine running on your server, along with a large number of libraries and C bindings that allow you to interact with your server in a way that the V8 engine won't let you. This is an example of a webserver in nodejs (A very limited one) 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/'); It just responses Hello World to every request and always returns a 200 status code. Going from something like this to a simple file server is fairly easy and quick, but a few people have already tackled this problem for you. http://expressjs.com/ - Very powerful web server, but still gives you a lot of freedoms. https://github.com/nodeapps/http-server - Simple web server, I use it mainly as a command line tool to instantly server files over http. Lastly, is socket.io just an extension of nodejs? Do you have to code your server in javascript when you use socket.io? Again, sorry for the very novice questions but I'm just trying to understand a few basic things before I continue. Thanks. socket.io among many others is a module of nodejs. Depending on your definition of extension it may be the wrong word to use. Most of the time when using socket.io you'r going to be using an existing http server and then extending, or wrapping your server with socket.io. I wrote a previous explanation of how nowjs does this. My guess is socket.io is very similar. To answer the bulk of that question: Yes, you will still be writing your code in javascript. You will just be utilizing the socket.io API. A: @travis has already covered everything you need to know about node and socket.io I'd only like to say that you don't have to buy a special hosting dedicated for node. My game is hosted on VPS with Ubuntu I find it really easy to deploy and maintain. There is a package for Ubuntu and instalation takes literally four lines of copy/paste https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager ps: I am not using socket.io but einaros/ws library which I find much less overblown.
Q: How to edit the size of the graph? May I ask how do i adjust the size of the graph? This is my code. import matplotlib.pyplot as plt fig=plt.figure() ax=fig.add_subplot(111) ax.plot(mean, median, marker="s", linestyle="") for i, txt in enumerate(words): ax.annotate(txt, (mean[i],median[i])) ax.set_xlabel("median") ax.set_ylabel("mean") plt.show() I tried to use fig,ax=plt.subplots(figsize=(20,10)) but failed. A: You first must have code that can execute, prior to tweaking the size of a figure: (I added dummy data, and now it works) import matplotlib.pyplot as plt if __name__ == '__main__': fig = plt.figure() ax = fig.add_subplot(111) mean, median = [1, 2, 3], [4, 5, 6] # dummy data ax.plot(mean, median, marker="s", linestyle="") for i, txt in enumerate(['a', 'b', 'c']): ax.annotate(txt, (mean[i], median[i])) ax.set_xlabel("median") ax.set_ylabel("mean") fig, ax = plt.subplots(figsize=(10, 10)) # size in inches plt.show() A: you can basically do this: from pylab import rcParams rcParams[figure.figsize] = (5,4) # Size in inches Then you may continue with your code :)
Q: EntityManager.find behavior with an object containing 2 id as primary key I'm starting to step into the Java world and I'm having troubles to understand this. I'm using JPA to interact with my database with JPQL. I have a persistent class like this one : @Entity @Table(name="C_A_T") @NamedQuery(name="CAT.findAll", query="SELECT c FROM CAT c") public class CAT implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId private CATPK id; private String offer; @Temporal(TemporalType.DATE) @Column(name="MODIF_DATE") private Date modifDate; public CAT() {} public CATPK getId() {return id;} public void setId(CATPK id) {this.id = id;} public String getOffer() {return offer;} public void setOffer(String offer) {this.offer = offer;} public Date getModifDate() {return modifDate;} public void setModifDate(Date modifDate) {this.modifDate= modifDate;} /* ... */ } The class CATPK represents a primary key of an instance of CAT : @Embeddable public class CATPKimplements Serializable { //default serial version id, required for serializable classes. private static final long serialVersionUID = 1L; @Column(name="ID_CAT") private String idCAT; @Column(name="ID_DEMANDE") private String idDemande; public CATPK() {} public String getIdCAT() {return this.idCAT;} public void setIdCAT(String idCAT) {this.idCat= idCat;} public String getIdDemande() {return this.idDemande;} public void setIdDemande(String idDemande) {this.idDemande = idDemande;} /* ...*/ } So basicly, the primay key is made of 2 different ID. Now, sometimes, before inserting a CAT in my database I checked if it is not already in the C_A_T table : EntityManagerFactory emf = Persistence.createEntityManagerFactory("cie"); em = emf.createEntityManager(); em.getTransaction().begin(); // inCAT is an instance of CAT on which there is a complete primary key CATPK (made of 2 id) CAT CATinDB = em.find( CAT.class, inCAT.getId() ); if (null == CATinDB) em.persist(inCAT); // CAT created em.getTransaction().commit(); em.close(); Now, the problem is that the line em.find( CAT.class, inCAT.getId() ); doesn't return null when it should. For instance, CATinDB can contain a row when I actually have no rows with the right idCAT and idDemande. So will find consider that it is found with only one id of the catPK matching ? In the end, I changed the line : if (null == CATinDB) into : if (null == CATinDB || CATinDB.getId().getIdCAT() != inCAT.getId().getIdCAT() || CATinDB.getId().getIdDemande() != inCAT.getId().getIdDemande()) Not really sure why find wasn't returning null when I had no records matching the 2 id. A: Actually, I just needed to restart my weblogic server. Looks like the data source is not dynamically updated when I update the database.
Q: Slightly move x- or y-axis tick label in pgfplots In the MWE below, I'd like to move the x-axis labels slightly away from each other horizontally and the y-axis labels slightly away from each other vertically, to avoid overlapping. How can I do this? I tried adding a \quad to the first extra x tick label, which more or less worked, but it seems inelegant, and it doesn't work for the y-axis. \documentclass{standalone} \usepackage{tikz} \usepackage{pgfplots} \pgfplotsset{compat=1.10} \begin{document} \begin{tikzpicture} \newcommand\CONSTH{326.4887} \newcommand\CONSTS{205.0669} \newcommand\CONSTgS{193.1713} \newcommand\CONSTHd{300} \newcommand\CONSTmu{200} \begin{axis}[ axis lines=left, scaled ticks=false, xtick=\empty, ytick=\empty, xmin=165, xmax=250, ymin=0, extra x ticks={\CONSTmu, \CONSTS}, extra x tick labels={$\lambda L$, $S^*$}, extra y ticks={\CONSTH, \CONSTHd}, extra y tick labels={$H(Q)$, $H_d(Q)$} ] \addplot[ticks=none] coordinates {(170,400) (\CONSTmu,0) (245,400)}; \addplot[ticks=none,domain=170:245] {0.1*(x-\CONSTS)^2 + \CONSTgS}; % x axis labels \addplot[dashed] coordinates {(\CONSTS,0) (\CONSTS,\CONSTgS)}; % y axis labels \addplot[dashed] coordinates {(0,\CONSTH) (245,\CONSTH)}; \addplot[dashed] coordinates {(0,\CONSTHd) (245,\CONSTHd)}; \end{axis} \end{tikzpicture} \end{document} Edit: Replaced data from tables with formulas. A: You can use \raisebox to move box containing y tick label, for x tick label you can use as you mentioned \quad or moving the two x tick label with \kern \documentclass{standalone} \usepackage{tikz} \usepackage{pgfplots} \pgfplotsset{compat=1.10} \begin{document} \begin{tikzpicture} \newcommand\CONSTH{326.4887} \newcommand\CONSTS{205.0669} \newcommand\CONSTgS{193.1713} \newcommand\CONSTHd{300} \newcommand\CONSTmu{200} \begin{axis}[ axis lines=left, scaled ticks=false, xtick=\empty, ytick=\empty, xmin=165, xmax=250, ymin=0, extra x ticks={\CONSTmu, \CONSTS}, extra x tick labels={\kern-1mm $\lambda L$,\kern1mm $S^*$}, extra y ticks={\CONSTH, \CONSTHd}, extra y tick labels={\raisebox{2mm}{$H(Q)$},\raisebox{-3mm}{$H_d(Q)$}}, ] \addplot[ticks=none] coordinates {(170,400) (\CONSTmu,0) (245,400)}; \addplot[ticks=none,domain=170:245] {0.1*(x-\CONSTS)^2 + \CONSTgS}; % x axis labels \addplot[dashed] coordinates {(\CONSTS,0) (\CONSTS,\CONSTgS)}; % y axis labels \addplot[dashed] coordinates {(0,\CONSTH) (245,\CONSTH)}; \addplot[dashed] coordinates {(0,\CONSTHd) (245,\CONSTHd)}; \end{axis} \end{tikzpicture} \end{document} Output
Q: Android client-server application works only on the same network I'm trying to create a client-server application using Android. I succeeded in making it work on the same network. But it doesn't work otherwise. The client's socket doesn't connect to the server's. So I thought it may be because the port is closed. is it possible that that is the cause? And if so how can I open the port in my Android application?
Q: Return StreamReader to Beginning when his BaseStream has BOM I'm looking for an infallible way to reset an StreamReader to beggining, particularly when his underlying BaseStream starts with BOM, but must also work when no BOM is present. Creating a new StreamReader which reads from the beginning of the stream is also acceptable. The original StreamReader can be created with any encoding and with detectEncodingFromByteOrderMarks set either to true or false. Also, a read can have been done or not prior calling reset. The Stream can be random text, and files starting with bytes 0xef,0xbb,0xbf can be files with a BOM or files starting with a valid sequence of characters (for example if ISO-8859-1 encoding is used), depending on the parameters used when the StreamReader was created. I've seen other solutions, but they don't work properly when the BaseStream starts with BOM. The StreamReader remembers that it has already detected the BOM, and the first character that is returned when a read is performed is the special BOM character. Also I can create a new StreamReader, but I can't know if the original StreamReader was created with detectEncodingFromByteOrderMarks set to true or set to false. This is what I have tried first: //fails with TestMethod1 void ResetStream1(ref StreamReader sr) { sr.BaseStream.Position = 0; sr.DiscardBufferedData(); } //fails with TestMethod2 void ResetStream2(ref StreamReader sr) { sr.BaseStream.Position = 0; sr = new StreamReader(sr.BaseStream, sr.CurrentEncoding, true); } //fails with TestMethod3 void ResetStream3(ref StreamReader sr) { sr.BaseStream.Position = 0; sr = new StreamReader(sr.BaseStream, sr.CurrentEncoding, false); } And those are the thest methods: Stream StreamWithBOM = new MemoryStream(new byte[] {0xef,0xbb,0xbf,(byte)'X'}); [TestMethod] public void TestMethod1() { StreamReader sr=new StreamReader(StreamWithBOM); int before=sr.Read(); //reads X ResetStream(ref sr); int after=sr.Read(); Assert.AreEqual(before, after); } [TestMethod] public void TestMethod2() { StreamReader sr = new StreamReader(StreamWithBOM,Encoding.GetEncoding("ISO-8859-1"),false); int before = sr.Read(); //reads ï ResetStream(ref sr); int after = sr.Read(); Assert.AreEqual(before, after); } [TestMethod] public void TestMethod3() { StreamReader sr = new StreamReader(StreamWithBOM, Encoding.GetEncoding("ISO-8859-1"), true); int expected = (int)'X'; //no Read() done before reset ResetStream(ref sr); int after = sr.Read(); Assert.AreEqual(expected, after); } Finally, I found a solution (see my own answer) which passes all 3 tests, but I want to see if a more ellegant or fast solution is possible. A: //pass all 3 tests void ResetStream(ref StreamReader sr){ sr.Read(); //ensure that BOM is detected if configured to do so sr.BaseStream.Position=0; sr=new StreamReader(sr.BaseStream, sr.CurrentEncoding, false); } A: This does the trick without needing to create a new StreamReader: void ResetStream(StreamReader sr) { sr.BaseStream.Position = sr.CurrentEncoding.GetPreamble().Length; sr.DiscardBufferedData(); } GetPreamble() will return an empty byte array if there is no BOM. This should work with or without the BOM because the UTF8Encoding class (and others, e.g. UTF32Encoding, UnicodeEncoding) has an internal field which tracks whether the BOM is included and is set by the StreamReader when you first do a Read(). However, it seems you need to pass in an Encoding to the StreamReader constructor with the BOM identifier flag turned off, and it will then correctly detect the presence of the BOM. If you just simply pass the stream as the only parameter, as in TestMethod1 above, then for some reason it sets the CurrentEncoding to UTF8 with BOM even if your stream has no BOM. Setting the detectEncodingFromByteOrderMarks to true does not help either, as this defaults to true. The tests below both pass, because default for UTF8Encoding is to have BOM off. Stream StreamWithBOM = new MemoryStream(new byte[] { 0xef, 0xbb, 0xbf, (byte)'X' }); Stream StreamWithoutBOM = new MemoryStream(new byte[] { (byte)'X' }); [TestMethod] public void TestMethod4() { StreamReader sr = new StreamReader(StreamWithBOM, new UTF8Encoding()); int before = sr.Read(); //reads X ResetStream(sr); int after = sr.Read(); Assert.AreEqual(before, after); } [TestMethod] public void TestMethod5() { StreamReader sr = new StreamReader(StreamWithoutBOM, new UTF8Encoding()); int before = sr.Read(); //reads X ResetStream(sr); int after = sr.Read(); Assert.AreEqual(before, after); }
Q: Isolate digital switching from audio circuit I'm using an L298 H-Bridge to drive a DC motor. The motor is spinning a magnet across a guitar pickup at ~30 Hz. That signal is then amplified and sent to a speaker. However, the output signal also contains a fairly constant (and loud) sound at ~10 kHz. I believe this is coming from the L298 H-Bridge's switching circuitry. Obviously I don't have the H-bridge connected in the audio circuit. But that switching signal is making its way into the audio at some stage, either from the pickup coil, the op-amp amplifier or the wires themselves. I don't think a band-reject filter is the answer here. What physical things can I do to get rid of this noise?
Q: Radio button disabled when clicked I have a form with different answers. One of my form control is a radio button. When I click on one of this radio button all the others radio button enable. <form [formGroup]="formAnswers"> <!-- body risposte --> <div *ngFor="let answer of questions.answers; let n = index;" class="row mb-1 border-bottom"> <!-- checkbox --> <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 text-left form-check form-check-inline pl-1"> <input formControlName="idAnswerRadio" class="form-check-input cursor-pointer radio-button" type="radio" (click)="manageAnswer(n)"> </div> <div class="col-xs-9 col-sm-9 col-md-9 col-lg-9 text-left risposta-wrap"> {{answer.text}} </div> <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 text-center"> {{answer.value}} </div> </div> </form> createFormAnswer(questions?: Questions[]) { for (let i = 0; i < domande.length; i++) { // other formcontrols questions for (let n = 0; n < questions[i].answers.length; n++) { this.formAnswers = this.formBuilder.group({ idAnswerRadio: [] }) } } } The code above is the code for creating the form for the answer. Unfortunatly I can't add on stackblitz A: You can bind into a conditional disable property in order to change each one of the radio buttons. Also, you can listen to changes on the "main" radio button to react when its value changes. EXAMPLE: Typescript file: private isAnswerRadio: boolean = false; public formAnswers: FormGroup = new FormGroup({ 'isAnswerRadio': new FormControl(...), // Other form controls (Initially disabled) '...': new FormControl(...), ... }); ngOnInit() { this.formAnswers.get('isAnswerRadio').valueChanges.subscribe(newData => { if(newData === ...) { // If equals to the desired selection of the radio button this.isAnswersRadio = true; } }); } getDisabled(): boolean { return this.isAnswerRadio; } HTML file: <input formControlName="idAnswerRadio" class="form-check-input cursor-pointer radio-button" type="radio" (click)="manageAnswer(n)"> <!-- Other inputs... --> <input [disabled]="getDisabled()">
Q: reset root pass on xen guest using physical disk I've found a few tutorials to reset the password on a xen guest using image files, such as this one: http://www.howtoforge.com/forums/showthread.php?t=28779 However I haven't had any luck with examples of modifying this to work with physical disks. This guest is currently running. I'd appreciate it if you could start from listing the command to shutdown the guest from the host, all the way through to restarting the xen guest after it's root password has been changed. also, not sure what this means, but on my local machine "xm" is the command used to interact with xen, not xe like I've seen in most tutorials. Here is the disk line of the xen config file: disk = [ "phy:/dev/sdb1,xvda,w" ] Thanks, -Eric A: Shutdown the guest using something like xm shutdown <guest> Check so it is shutdown xm top That path hints that it's not an LVM, but a physical disk. This is a job for libguestfs. Make sure you have it installed. First you check what filesystems you have in that block device: virt-filesystems -a /dev/sdb1 Then you mount the root filesystem: guestmount -a /dev/sdb1 -m /dev/<whateverhappenstoberoot> --rw /mnt Change root directory: chroot /mnt/ Update your passwords passwd root And then you restore everything logout unmount /mnt/ xm create /etc/xen/vm/<guest> A: You can actually get by without installing guestfs tools by doing some manual work instead. Follow pehrs's advice up to the virt-filesystems command (without including it), then run this: parted -s /dev/sdb1 unit B print This should give you a table listing offsets, like this: Number Start End Size Type File system Flags 1 32256B 2467583999B 2467551744B primary ext2 2 2467584000B 3981035519B 1513451520B primary ext3 3 3981035520B 3989260799B 8225280B primary lba 4 3989260800B 3997486079B 8225280B primary The one you need to mount would probably have an ext3 filesystem on it. You can also check for the right number by running mount in the guest and looking for the device for the / partition. Take the number from the 'Start' column minus the B and try this: mkdir /mnt/test mount -o loop,rw,offset=NUMBER_GOES_HERE /dev/sdb1 /mnt/test Then proceed with chroot /mnt/test. All the rest stays the same apart from this change from using /mnt to using /mnt/test - I don't like mounting anything directly on top of /mnt. Reference: http://www.andremiller.net/content/mounting-hard-disk-image-including-partitions-using-linux A: @Eric The default CentOS repos don't contain the libguestfs tools -- however the epel repository does. In this case, what I'd usually do is set up the epel repository, but then disable it, and only enable it to install specific packages packages.. Like so: * *rpm -ivh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpm *disable the repository by setting "enabled=0" in each section of /etc/yum.repos.d/epel.repo *yum –enablerepo=epel install That said, I'm not sure exactly which of the packages you will need. http://libguestfs.org/ seems to suggest installing "*guestf*", but that will more than likely install much more than you really need.
Q: MassTransmit - Distributed Messaging Model - Reliable/Durable - NServiceBus too expensive I would like to use MassTransmit similar to NServiceBus, every publisher and subscriber has a local queue. However I want to use RabbitMQ. So do all my desktop clients have to have RabbitMQ installed, I think so, then should I just connect the 50 desktop clients and 2 servers into a cluster? I know the two servers must be in the same cluster. However 50 client nodes, seems a bi tmuch to put in one cluster.....Or should I shovel them or Federate them to the server cluster exchange? The desktop machine send messages like: LockOrder, UnLock Order. The Servers are dealing with backend hl7 messages. Any help and advice here is much appreciated, this is all on windows machines. Basically I am leaving NServiceBus behind, as it is now too expensive, they aiming it at large corporations with big budgets, hence Masstransmit. However I want reliable/durable messaging, hence local queues on ALL publishers and ALL subscribers. The desktops also use CQS to update their views. A: should I just connect the 50 desktop clients and 2 servers into a cluster? Yes, you have to connected your clients to the cluster. However 50 client nodes, seems a bi tmuch to put in one cluster. No, (or it depends how big are your servers) 50 clients is a small number Or should I shovel them or Federate them to the server cluster exchange? The desktop machine send messages like: LockOrder, UnLock Order. I think it's better the cluster, because federation and shovel are asynchronous, it means that your LockOrder could be not replicated in time. However I want reliable/durable messaging, hence local queues on ALL publishers and ALL subscribers Withe RMQ you can create a persistent queue and messages, and it is not necessary if the client(s) is connected. It will get the messages when it will connect to the broker. I hope it helps. A: I have a FOSS ESB rpoject called Shuttle, if you would like to give it a spin: https://github.com/Shuttle/shuttle-esb I haven't used NServiceBus for a while and actually started Shuttle when it went commercial. The implementation is somewhat different from NServiceBus. I don't know MassTransit at all, though. Currently process managers (sagas) have to be hand-rolled in Shuttle whereas MassTransit and NServiceBus have this incorporated. If I do get around to adding sagas I'll be adding them as a Module that can be plugged into the receiving pipeline. This way one could have various implementations and choose the flavour you like :) Back to your issue. Shuttle has the concept of an optional outbox for queuing technologies like RabbitMQ. Shuttle does have a RabbitMQ implementation. I believe the outbox works somewhat like 'shovel' does. So the outbox would be local and sending messages would first go to the outbox. It would periodically try to send messages on to the recipients and, after a configurable number of attempts, send the message to an error queue. It can then be returned to the outbox for further attempts, or even moved directly to the recipient queue once it is up. Documentation here: http://shuttle.github.io/shuttle-esb/
Q: need help. instead of ascii value,4 million+ most of those chars appears like some random numbers instead of their ascii value, why is that? and why it still working? #include <stdio.h> #include <conio.h> #define SIZE 10 void arrayFiller(int v[]); void charTimes(int v[]); void arrayPrinter(int v[]); void CharlessOn(int v[]); void stringToDigit(char string_num[]); int main() { int vec[SIZE]; char string_num[50]; arrayFiller(vec); arrayPrinter(vec); charTimes(vec); CharlessOn(vec); gets(string_num); stringToDigit(string_num); } void arrayFiller(int v[]) { printf("Please write down first a character and then number and repeat it 5 times, \nThe character represents the character you want to print,\nAnd the number is the number of times the character will be printed.\n"); for (int i = 0; i < SIZE; i++) { int checker = 0; if (i % 2 == 0 || i == 0) { scanf("%c", &v[i]); } else { do { if (checker>0) printf("The number must be between 1 and 10,Try again please.\n"); scanf("%d", &v[i]); checker++; } while (v[i] < 1 || v[i]>10); getchar(); } } } void charTimes(int v[]) { int k = 1; printf("\nHere is the Char few times\n"); for (int i = 0; i < SIZE; i += 2) { for (int j = 0; j < v[k]; j++) { printf("%c,", v[i]); } k += 2; } } void arrayPrinter(int v[]) { printf("\n here is your array:\n"); for (int i = 0; i < SIZE; i++) { printf("%d,", v[i]); } } void CharlessOn (int v[]) { int charless,k = 1; printf("\nPlease write down the character you want to get rid of:\n"); scanf("%c", &charless); printf("%d", charless); printf("\nHere is the string without the char you chose:\n"); for (int i = 0; i < SIZE; i += 2) { for (int j = 0; j < v[k]&& v[i]!=charless; j++) { printf("%c,", v[i]); } k += 2; } } void stringToDigit(char string_num[]){ int holder=0,number=0; for(int i = 0; string_num[i] != NULL;i++){ number*=10; holder=string_num[i]; holder-=48; number+=holder; } printf("the number is %d",number); } it was pretty finished for my homework lets say but i missed one question so i am redoing it, and i found out an problem, the first e that i wrote has strage value while the second e that has starge value aswell doesnt much the first e A: In scanf("%c", &v[i]), you are supposed to pass the address of a char for %c, but &v[i] is the address of an int. scanf has filled in one byte of v[i] and left the rest uninitialized. Modify your code to pass the address of a char to scanf for %c. A: In addition to first answer. Looking into function arrayFiller, if (i % 2 == 0 || i == 0) is redundant. It is identically the same as if (i % 2 == 0) When checking the value of a character it should be treated as a character, you must compare with chars, '1' is not the same as 1, also the digits starts from 0 to 9 instead of 1 to 10. So instead of instead of while (v[i] < 1 || v[i]>10); you should compare like while (v[i] < '0' || v[i]>'9');. I don't understand the full meaning of all your functions. You have to provide some more details on what is the expected correct behavior of your code.
Q: JWT and Azure AD to secure Spring Boot Rest API I have a Spring Boot Rest Api with JWT integration. Currently from Postman, I make a POST request to authenticate endpoint, including username and password, and obtain an access token. But can Azure AD be used along with JWT, instead of hardcoded user details ? A: When you obtain token with username and password, that bases on Resource Owner Password Credentials flow. This flow requires a very high degree of trust in the application, and carries risks which are not present in other flows. I'm not sure what you mean about Azure AD with JWT. If you would like to obtain access token with a signed-in user(not hardcoded user details), auth code flow is better for you. You could also request an access token in Postman. POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token client_id=xxx &scope=https://graph.microsoft.com/mail.read &code=<authorization_code from "/authorize" endpoint> &redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F &grant_type=authorization_code If you would like to obtain access token without users, you could use client credentials flow. In the client credentials flow, permissions are granted directly to the application itself by an administrator, so you must use application permissions. POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token client_id=xxx &scope=https://graph.microsoft.com/.default &client_secret=xxxx &grant_type=client_credentials
Q: i have a issue in parse php sdk I want to retrieve all data from back4app and show it in laravel php application, but I'm facing an error when I compact $result into a view. The error is "array to string conversion" and code returns a lot of objects. I don't know how I loop them in a foreach clause. The laravel code: public function getplaterating() { //i dnt have connection problem connection is working ParseClient::setServerURL('https://parseapi.back4app.com', '/'); $query = new ParseQuery("PlateRating"); $query->equalTo("All",true); $results = $query->find(); return print_r($results); } A: According to this PHP SDK documentation, you can do something like: for ($i = 0; $i < count($results); $i++) { $object = $results[$i]; echo $object->getObjectId() . ' - ' . $object->get('name'); }
Q: How can I add a part of log message inside the Datadog notification? I have been trying to include log message body inside the notification, but couldn't. The actual log contains all the attributes in the 'Event Attributes' properly, but I couldn't find a way to include the value of the attributes in the notification body. For example, the target log contains an event attribute 'thread_name' with a value of '123'. But when I tried to use that value in the notification body with {{thread_name}} or {{thread_name.name}}, it never shows in the actual notification email. In the reference docs, I couldn't find how to get the message attribute values, except for the predefined variables. Is it even possible to include log message values in the notification? A: The log message can now be referenced by using {{log.message}}. You can also reference additional variables like {{log.attributes}} and {{log.tags}}. More details are here: https://docs.datadoghq.com/monitors/notify/variables/?tab=is_alert#matching-attributetag-variables
Q: It is possible to prevent a page load using javascript I am trying to use javascript to return a query parameter to a client that posted the query. I capture the query parameter and then perform a document.write(parameter) command. However, the client is receiving back both the document.write data and also the HTML page content which renders the callback invalid as the client only expects back the parameter. So how can I prevent from sending back the web page contents after I perform the document.write so I only return the parameter value instead? Below is my javascript. The web page is created as an .aspx file. <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> // function returnCallback() { var parm = location.search; var qs=parm.split("&"); for (var i=0; i < qs.length; i++) { var pos = qs[i].indexOf('challenge'); if (pos > -1) { var qsarray = qs[i].split("="); var challenge = qsarray[1]; document.write(challenge); } } </script> </head> <body> <form id="form1" runat="server"> <div> <textarea id="text1" cols="80" rows="20"></textarea> </div> </form> </body> </html> A: At a quick glance I can see nothing wrong with your code, I am assuming the problem lies with the page you are calling, it should only return the needed data as you are just capturing what it throws.
Q: Read a file relative to a class successor's definition Say I have an interface class Base intended to be inherited. I need to define a static method in Base that would read and print a text file next to a successor's definition. My attempt was as follows. Example structure: .../module/ __init__.py Base.py A/ __init__.py A.py file.txt B/ __init__.py B.py file.txt Base.py: import os.path class Base: @staticmethod def print_file(): file = os.path.join(os.path.dirname(__file__), 'file.txt') with open(file, 'r') as f: print(f.read()) A.py (same for B.py): from module.Base import Base class A(Base): pass When I import A class and call A.print_file(), this code attempts to read .../module/file.txt and not .../module/A/file.txt, as __file__ seems to be calculated against Base.py and not A.py. Is there a way to read A/file.txt and B/file.txt in the static method without additional code in A.py and B.py? A: From the docs: __file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute may be missing for certain types of modules, such as C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file. Thus having __file__ point to Base.py makes sense as this is where the module Base initially is loaded from. An appropriate choice here could be getfile from the inspect package: inspect.getfile(object): Return the name of the (text or binary) file in which an object was defined. import os import inspect class Base: @classmethod def print_file(cls): file = os.paht.join( os.path.dirname(inspect.getfile(cls)), 'file.txt' ) with open(file, 'r') as f: print(f.read())
Q: How to make this floating views animation How to make this floating views animation in swift uikit with uiviews * *each views doesn't collapse each other. *each view position is random to 16 px and slow moving. I have tried with this code and calling push function several times import UIKit lazy var collision: UICollisionBehavior = { let collision = UICollisionBehavior() collision.translatesReferenceBoundsIntoBoundary = true collision.collisionDelegate = self collision.collisionMode = .everything return collision }() lazy var itemBehaviour: UIDynamicItemBehavior = { let behaviou = UIDynamicItemBehavior() behaviou.allowsRotation = false return behaviou }() func addingPushBehaviour(onView view: UIDynamicItem ,animationAdded: Bool = false) { let push = UIPushBehavior(items: [view], mode: .instantaneous) push.angle = CGFloat(arc4random()) push.magnitude = 0.005 push.action = { [weak self] in self?.removeChildBehavior(push) } addChildBehavior(push) } func addItem(withItem item: UIDynamicItem) { collision.addItem(item) itemBehaviour.addItem(item) addingPushBehaviour(onView: item) } override init() { super.init() addChildBehavior(collision) addChildBehavior(itemBehaviour) } var mainView: UIView? convenience init(animator: UIDynamicAnimator , onView: UIView) { self.init() self.mainView = onView animator.addBehavior(self) } A: Set up your views as square, using backroundColor and cornerRadius = height/2 to get the circular colored view look you show in your example. Create UIView animations using UIViewPropertyAnimator with a several second duration, where you animate each of your views to a location that is a random distance from it's "anchor" location by < 16 pixels in each dimension. (Google creating animations using UIViewPropertyAnimator. You should be able to find plenty of examples online.) A: Correct me if I'm wrong, but it sounds like there are two tasks here: 1) randomly populate the screen with non-overlapping balls, and 2) let those balls float around such that they bounce off each other on collision. If the problem is that the animations are jerky, then why not abandon UIDynamicAnimator and write the physics from scratch? Fiddling with janky features in Apple's libraries can waste countless hours, so just take the sure-fire route. The math is simple enough, plus you can have direct control over frame rate. Keep a list of the balls and their velocities: var balls = [UIView]() var xvel = [CGFloat]() var yvel = [CGFloat]() let fps = 60.0 When creating a ball, randomly generate a position that does not overlap with any other ball: for _ in 0 ..< 6 { let ball = UIView(frame: CGRect(x: 0, y: 0, width: ballSize, height: ballSize)) ball.layer.cornerRadius = ballSize / 2 ball.backgroundColor = .green // Try random positions until we find something valid while true { ball.frame.origin = CGPoint(x: .random(in: 0 ... view.frame.width - ballSize), y: .random(in: 0 ... view.frame.height - ballSize)) // Check for collisions if balls.allSatisfy({ !doesCollide($0, ball) }) { break } } view.addSubview(ball) balls.append(ball) // Randomly generate a direction let theta = CGFloat.random(in: -.pi ..< .pi) let speed: CGFloat = 20 // Pixels per second xvel.append(cos(theta) * speed) yvel.append(sin(theta) * speed) } Then run a while loop on a background thread that updates the positions however often you want: let timer = Timer(fire: .init(), interval: 1 / fps, repeats: true, block: { _ in // Apply movement for i in 0 ..< self.balls.count { self.move(ball: i) } // Check for collisions for i in 0 ..< self.balls.count { for j in 0 ..< self.balls.count { if i != j && self.doesCollide(self.balls[i], self.balls[j]) { // Calculate the normal vector between the two balls let nx = self.balls[j].center.x - self.balls[i].center.x let ny = self.balls[j].center.y - self.balls[i].center.y // Reflect both balls self.reflect(ball: i, nx: nx, ny: ny) self.reflect(ball: j, nx: -nx, ny: -ny) // Move both balls out of each other's hitboxes self.move(ball: i) self.move(ball: j) } } } // Check for boundary collision for (i, ball) in self.balls.enumerated() { if ball.frame.minX < 0 { self.balls[i].frame.origin.x = 0; self.xvel[i] *= -1 } if ball.frame.maxX > self.view.frame.width { self.balls[i].frame.origin.x = self.view.frame.width - ball.frame.width; self.xvel[i] *= -1 } if ball.frame.minY < 0 { self.balls[i].frame.origin.y = 0; self.yvel[i] *= -1 } if ball.frame.maxY > self.view.frame.height { self.balls[i].frame.origin.y = self.view.frame.height - ball.frame.height; self.yvel[i] *= -1 } } }) RunLoop.current.add(timer, forMode: .common) Here are the helper functions: func move(ball i: Int) { balls[i].frame = balls[i].frame.offsetBy(dx: self.xvel[i] / CGFloat(fps), dy: self.yvel[i] / CGFloat(fps)) } func reflect(ball: Int, nx: CGFloat, ny: CGFloat) { // Normalize the normal let normalMagnitude = sqrt(nx * nx + ny * ny) let nx = nx / normalMagnitude let ny = ny / normalMagnitude // Calculate the dot product of the ball's velocity with the normal let dot = xvel[ball] * nx + yvel[ball] * ny // Use formula to calculate the reflection. Explanation: https://chicio.medium.com/how-to-calculate-the-reflection-vector-7f8cab12dc42 let rx = -(2 * dot * nx - xvel[ball]) let ry = -(2 * dot * ny - yvel[ball]) // Only apply the reflection if the ball is heading in the same direction as the normal if xvel[ball] * nx + yvel[ball] * ny >= 0 { xvel[ball] = rx yvel[ball] = ry } } func doesCollide(_ a: UIView, _ b: UIView) -> Bool { let radius = a.frame.width / 2 let distance = sqrt(pow(a.center.x - b.center.x, 2) + pow(a.center.y - b.center.y, 2)) return distance <= 2 * radius } Result https://imgur.com/a/SoJ0mcL Let me know if anything goes wrong, I'm more than happy to help.
Q: How can I add more workspaces? Possible Duplicate: How can I reduce or increase the number of workspaces in Unity? I have searched and read through other answers, but I couldn't find one. I can't change then number of workspaces. Compiz desktop size in general settings doesn't work. I've tried some gconf commands, but that doesn't work either.
Q: Trying to return the amount of "Three of a kind" in a poker hand that run 16000 times bool Hand::isFlush() { if(cardVector[0].suit=cardVector[1].suit=cardVector[2].suit=cardVector[3].suit=cardVector[4].suit)return true; return false; } bool Hand :: isThreeOfKind() { if (cardVector[4].rank=cardVector[3].rank, // comparing card 5 to 4, then card 5 to 3. cardVector[4].rank=cardVector[2].rank) { return true; } return false; if (cardVector[3].rank=cardVector[2].rank, //comparing card 4 to 3 and the card 4 to 2 cardVector[3].rank=cardVector[1].rank) { return true; } return false; if (cardVector[2].rank=cardVector[1].rank, cardVector[2].rank=cardVector[0].rank) //comparing card 3 to 2 and the card 3 to 1 { return true; } return false;} int main () { cout<< "welcome" << endl; Deck deck; float flushCount=0; float threeKind=0; float count= 16000; for(int i=0;i<count;i++) { deck.shuffle(); Hand hand=deck.dealHand(); if(hand.isFlush())flushCount++; } for (int j=0;j<count;j++) { Hand hand=deck.dealHand(); if (hand.isThreeOfKind())threeKind++; } cout << "The amount of flushes in a game run 160000 times is..."<< endl; cout << flushCount << endl; cout << (flushCount/count)*100 << endl; cout << " Your have this many "<< threeKind << endl; system("pause"); return 0; } When I run the code I get the value of threeKind equal to the value of count. What I am trying to do is get the amount of three of kind in a hand of 5 cards. I feel like the logic in Hand::isThreeOfKind() may not be correct? I am trying to repeat what i did for bool Hand::isFlush(). A: This is untested because I don't have the declarations of Hand, Deck, and presumably Card, but it should give you an idea of a way to test for different hands. As noted above, there were several issues in your code like not using == to test equality and using commas instead of logical operators (&&, ||) in your if checks. In general it is better to just have a single Score function that returns a different value for each type of hand (high_card, one_pair, two_pair, three_of_a_kind, flush, etc.) rather than having to test each hand multiple times. It lets you compare hands easily by their score and greatly reduces the amount of duplicate work you need to do like counting the ranks and suits. Sorting the hand is also a good idea since it simplifies testing for straights as you can just test for the spread between the ranks of first and last cards once you've eliminated the rest of the scoring hands. bool Hand::isFlush() { for(int i = 1; i < 5; ++i) { if(cardVector[i].suit != cardVector[0].suit) { return false; } } return true; } bool Hand::isThreeOfKind() { //This is 16 because I don't know if your ranks start at 0 or 2 int counts[16] = {0}; for(int i = 0; i < 5; ++i) { ++counts[cardVector[i].rank]; } //This is just to give you an idea of how having single score function //can eliminate work. If you only want to test for 3 of a kind then //you don't need the pairs and fours tests and counts int num_pairs = 0; int num_threes = 0; int num_fours = 0; for(int i = 0; i < 16; ++i) { if(counts[i] == 2) { ++num_pairs; } else if(counts[i] == 3) { ++num_threes; } else if(counts[i] == 4) { ++num_fours; } } if(num_threes == 1) { return true; } return false; }
Q: Matlab: How to insert zeros in specific places of vector Can someone help me with the following problem in Matlab? I have a first vector containing the elements values. For example, [2 8 4 9 3]. And a second one with the desired places in a second vector. For example, [0 0 1 0 0 0 0 1 1 0 0 1 0 0 1]. Now I want to put the values from the first vector on the positions of the second one to end up with [0 0 2 0 0 0 0 8 4 0 0 9 0 0 3]. What is the most efficient way of doing this when the size of the vector can be very large. (then thousands of elements)? A: You can consider the y values as logical indicators, then use logical indexing to set those values to the values in x. x = [2 8 4 9 3]; y = [0 0 1 0 0 0 0 1 1 0 0 1 0 0 1]; y(logical(y)) = x; Alternatively, you could use y(y==1) = x; A: Use self-indexing: % Your values: V = [2 8 4 9 3]; % The desired locations of these values: inds = [0 0 1 0 0 0 0 1 1 0 0 1 0 0 1]; % index the indices and assign inds(inds>0) = V
Q: How to skip Registeration Screen in Android? I am making Registeration/Login module in Android locally, using Sqlite database.Here is the code : public class Registration extends Activity { Button btnRegister; Button btnLinkToLogin; EditText inputFullName; //EditText inputEmail; EditText inputPassword; TextView registerErrorMsg; DbManager manager = new DbManager(this); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); // Assignment of UI fields to the variables inputFullName = (EditText) findViewById(R.id.registerName); //inputEmail = (EditText) findViewById(R.id.registerEmail); inputPassword = (EditText) findViewById(R.id.registerPassword); btnRegister = (Button) findViewById(R.id.btnRegister); // btnRegister.setOnClickListener(this); btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen); registerErrorMsg = (TextView) findViewById(R.id.register_error); setActionBar(); //set OnClickListener btnRegister.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { final String user_name = inputFullName.getText().toString(); // final String email = inputEmail.getText().toString(); final String password = inputPassword.getText().toString(); boolean invalid = false; if(user_name.equals("")&&password.equals("")) { invalid = true; Toast.makeText(getApplicationContext(), "Please enter necessary credentials", Toast.LENGTH_SHORT).show(); } else if(password.equals("")) { invalid = true; Toast.makeText(getApplicationContext(), "Please enter your Password", Toast.LENGTH_SHORT).show(); } else if(user_name.equals("")) { invalid = true; Toast.makeText(getApplicationContext(), "Please enter your user name", Toast.LENGTH_SHORT).show(); } else if(invalid == false){ String User[] = {user_name,password}; // manager=new DbManager(this);) //if(manager.Login(email, password).equals(true)); if (manager.Register(user_name, password)) { if(user_name.equalsIgnoreCase(user_name)&&password.equalsIgnoreCase(password)) { Toast.makeText(Registration.this, "Already registered, please login", Toast.LENGTH_SHORT).show(); } } else{ Toast.makeText(Registration.this, "Successfully registered", Toast.LENGTH_LONG).show(); manager.Insert_Values_User(User); Intent i_register = new Intent(Registration.this, login.class); startActivity(i_register); finish(); } } } }); // Link to Login Screen btnLinkToLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(getApplicationContext(), login.class); startActivity(i); // Close Registration View finish(); } }); } Login class is : public class login extends Activity { Button btnLogin; Button btnLinkToRegister; EditText inputPassword; TextView loginErrorMsg; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Importing all assets like buttons, text fields // inputUserName = (EditText) findViewById(R.id.user_name); inputPassword = (EditText) findViewById(R.id.loginPassword); btnLogin = (Button) findViewById(R.id.btnLogin); btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen); loginErrorMsg = (TextView) findViewById(R.id.login_error); setActionBar(); // If login is successful btnLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { //Check Login // final String user_name = inputUserName.getText().toString(); final String password = inputPassword.getText().toString(); DbManager users = new DbManager(login.this); boolean invalid = false; if(password.equals("")) { invalid = true; Toast.makeText(getApplicationContext(), "Please enter password ", Toast.LENGTH_SHORT).show(); } else if(users.Login(password)){ if(password.equalsIgnoreCase(password)) { Toast.makeText(login.this, "Successfully logged in", Toast.LENGTH_SHORT).show(); Intent i = new Intent(getApplicationContext(), MainActivity.class); startActivity(i); finish(); } } else Toast.makeText(login.this,"Invalid Password", Toast.LENGTH_SHORT).show(); users.close(); } }); // Link to Register Screen btnLinkToRegister.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(getApplicationContext(), Registration.class); startActivity(i); finish(); } }); } I want Registration screen to be appeared, only if user is not registered. If he is regstered then application should directly open Login screen. I have searched, but i could n't find how to that?? Any useful help will be appreciated. A: You can use shared preference for that.. Like this.. SharedPreferences wmbPreference; SharedPreferences.Editor editor; in onCreate wmbPreference = PreferenceManager.getDefaultSharedPreferences(this); boolean isActivated=wmbPreference.getBoolean("ISACTIVATED", false); If ISACTIVATED is false then you can show the login screen else skip it.. And you can edit the shared preference once the user is logged in like this.. editor = wmbPreference.edit(); editor.putBoolean("ISACTIVATED", true); editor.commit(); A: You can do something like this : public static String KEY = "SESSION"; // Method to store the preference : public static void saveUserId(String mUserId, Context context) { Editor editor = context .getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit(); editor.putString("mUserId", mUserId); editor.commit(); } // Method to get the preferences : public static String getUserId(Context context) { SharedPreferences savedSession = context.getSharedPreferences(KEY, Activity.MODE_PRIVATE); return savedSession.getString("mUserId", ""); } Keep the above methods in your app's Utils class to keep the code organized. You can save the preference like this once the user logged in: Utils.saveUserId("your id",YourActivity.this); To check whether the user is logged in, You can do something like this. If (Utils.getUserId(YourActivity.this).equals("")) { // User has not logged in. Show Registration screen here. } else { // User logged in : Skip Registration screen here. } A: Hi good to hear that you new to Android App Development. We can do this by the help of Shared Preferences. Shared preference is local db which user could not able to view like sqlite db. It not a much tough to create. Do the following steps One By One. Add if not already available in Android Manifest.xml file under <android:name="com.yourpackage.MiApplication"> Add this one More class that I have created for you. import android.app.Application; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class MiApplication extends Application { public static final String PREFERENCE_NAME = "misession"; private static final String SESSION_KEY = "login_status"; private static SharedPreferences miPreferences; private static Editor miEditor; @Override public void onCreate() { super.onCreate(); miPreferences = getSharedPreferences(PREFERENCE_NAME, MODE_PRIVATE); miEditor = miPreferences.edit(); } public static void setSession(boolean session) { miEditor.putBoolean(SESSION_KEY, session); miEditor.commit(); } public static boolean getSession() { return miPreferences.getBoolean(SESSION_KEY, false); } } use setSession and set to true when you successfully logged in. and use the getSession to check the login status. if true then open main page else open reg. page. Note: <android:name="com.yourpackage.MiApplication">this line is important.
Q: How to filter rows in agGrid based on display value? I have agGrid which contains column that has used refData property. It is displaying as "Yes" or "No" but has underlying value as "1" or "0". I want to filter the column by data but it is not giving any result when filter by "Yes" or "No". However filter starts working when I put underlying data i.e. 1 or 0. HTML File <ag-grid-angular class="ag-theme-balham" [rowData]="categoryRowData" [columnDefs]="categoryColDef" [domLayout]="domLayout" (gridReady)="onGridReady($event)"> </ag-grid-angular> TS File export class CategoryComponent implements OnInit{ private domLayout; private objCategoryEditor = {}; categoryColDef ; constructor() { this.getCategoryMapping(); this.createCategoryColDefinition(); } ngOnInit() { this.domLayout = "autoHeight"; } onGridReady(params: any) { params.api.sizeColumnsToFit(); params.api.resetRowHeights(); } createCategoryColDefinition() { this.categoryColDef = [ { headerName: 'Is Subcategory', field: 'IsSubcategoryText', resizable: true,filter:true, editable: function (params: any) { return true; }, cellEditor: "agSelectCellEditor", cellEditorParams: { values: this.extractValues(this.objCategoryEditor), }, refData: this.objCategoryEditor, } ]} getCategoryMapping() { this.objCategoryEditor["0"] = "No"; this.objCategoryEditor["1"] = "Yes"; this.createCategoryColDefinition(); } extractValues(mappings) { return Object.keys(mappings); } } When filter by "No" then it is returning no rows:- When filter by 0 then it is returning rows:- How to customize the filtering so that it start returning rows when filter by "Yes" or "No"? Please help on this. A: I would use a filterValueGetter in column definition something like this - filterValueGetter: this.customfilterValueGetter here is a simple implementation of customfilterValueGetter customfilterValueGetter(params) { if(params.data) { return this.objCategoryEditor[params.data.IsSubcategoryText]; } } As per docs - filterValueGetter(params) Function or expression. Gets the value for filtering purposes. Plunkr here. Checkout the Retail Price column A: Instead of creating an object key with 0 and 1 use yes and No properties itself like below, which will help you to solve this issue getCategoryMapping() { this.objCategoryEditor["No"] = "No"; this.objCategoryEditor["Yes"] = "Yes"; this.createCategoryColDefinition(); }
Q: looping through the alphabet as String I want to loop through the alphabet with a for loop and add each letter to my HashMap for(char alphabet = 'A'; alphabet <= 'Z';alphabet++) { System.out.println(alphabet); } doesn't work for me, because my HashMap is of form HashMap<String, HashMap<String, Student>> hm; I need my iterator to be a string, but for(String alphabet = 'A'; alphabet <= 'Z';alphabet++) { System.out.println(alphabet); } doesn't work. Basically, I want to do this: for i from 'A' to 'Z' do hm.put(i, null); od Any ideas? A: Basically convert the char to a string, like this: for(char alphabet = 'A'; alphabet <= 'Z';alphabet++) { hm.put(""+alphabet, null); } Although ""+alphabet is not efficient as it boils down to a call to StringBuilder The equivalent but more effective way can be String.valueOf(alphabet) or Character.toString(alphabet) which are actually the same. A: You cannot assign a char to a String, or to increment a string with ++. You can iterate on the char the way you did in your first sample, and convert that char to a String, like this: for(char letter = 'A'; letter <= 'Z'; letter++) { String s = new String(new char[] {letter}); System.out.println(s); } A: First problem: When you work with a HashMap, you are supposed to map a key to a value. You don't just put something in a hash map. The letter you wanted to put, is it a value? Then what is the key? Is it a key? Then what is the value? You might think that using "null" as a value is a good idea, but you should ask yourself: in that case, should I use a map at all? Maybe using a HashSet is a better idea? The second problem is that a HashMap, like all java collections, only takes objects - both as keys and as values. If you want to use a character as a key, you could define your map as Map<Character,Map<String,Student>>, which will auto-box your character (convert it to an object of type Character) or you could convert the character to a string using Character.toString(alphabet); A: In Java 8 with Stream API, you can do this. IntStream.rangeClosed('A', 'Z').mapToObj(var -> String.valueOf((char) var)).forEach(System.out::println);
Q: Convergence of a series of functions in L^p I found some problems in solving this exercise: Find $p>1$ such that the series $\sum_n f_n$ converges in $L^p(\mathbb{R})$ (with lebesgue measure) where: \begin{equation} f_n(x)=\dfrac{1}{1+n^2\sqrt{x}}\chi_{[\exp(2n),2\exp(2n+2)]} \end{equation} My idea was to calculate the $L^p$ norm of the previous function and find for which values of $p$ the series $\sum_{n=1}^{\infty}\|f_n\|_p$ is convergent, then knowing that $(L^p,\|\|_p)$ is a Banach space the series $\sum_n f_n$ has to be convergent in $L^p$. The problem is that the calculation on the $L^p$-norm of $f_n$ seems to be too much complicate. Can someone help me? A: Instead of trying to calculate the $L^p$ norm, try to find an upper bound and lower bound. I find $$ \frac{e^{2n}(2e^2-1)}{(1+n^2\sqrt{2}e^{n+1})^p}\leq \|f\|_p\leq \frac{e^{2n}(2e^2-1)}{(1+n^2e^{n})^p}\leq \frac{e^{2n}(2e^2-1)}{n^{2p}e^{np}} $$ And it is enough to conclude on the convergence or divergence of the serie of the norm (and since the fonction are positive, of the potential divergence of the serie of fonction) A: We can write \begin{align} f_n(x)&=\dfrac{1}{1+n^2\sqrt{x}}\chi_{[\exp(2n),2\exp(2n+2)]}\\[0.3cm] &=\dfrac{1}{1+n^2\sqrt{x}}\chi_{[\exp(2n),\exp(2n+2)]}+\dfrac{1}{1+n^2\sqrt{x}}\chi_{[\exp(2n+2),2\exp(2n+2)]}. \end{align} Because everything is positive, the convergence of $\sum f_n$ is equivalent to the convergence of the two series on the right. The advantage is the the series from the right have terms with disjoint support. So \begin{align} \bigg\|\sum_{n=m}^k\dfrac{1}{1+n^2\sqrt{x}}\chi_{[\exp(2n),2\exp(2n+2)]}\bigg\|_p^p &=\int_0^\infty\sum_{n=m}^k\dfrac{1}{(1+n^2\sqrt{x})^p}\chi_{[\exp(2n),2\exp(2n+2)]}\,dx\\[0.3cm] &=\sum_{n=m}^k\int_{e^{2n}}^{e^{2n+2}}\dfrac{1}{(1+n^2\sqrt{x})^p}\,dx\\[0.3cm] \end{align} Using the obvious lower and upper bounds for the integrand, $$ \sum_{n=m}^k \dfrac{e^{2n}(e^2-1)}{(1+n^2e^{n+1})^p}\,dx\leq\sum_{n=m}^k\int_{e^{2n}}^{e^{2n+2}}\dfrac{1}{(1+n^2\sqrt{x})^p}\,dx\leq\sum_{n=m}^k \dfrac{e^{2n}(e^2-1)}{(1+n^2e^{n+1})^p}\,dx. $$ The other series behaves similarly. Now you can simply study the convergence of the numeric series.
Q: How to mock StorageOptions.newBuilder() Can you help me in mocking StorageOptions.newBuilder() Code to be Mocked: StorageOptions.newBuilder.setProjectId("Test").build().getService() Code I have written: Storage mockStorage = Mockito.mock(Storage.class); MockedStatic<StorageOptions> storageOptionsMock = Mockito.mockStorage(StorageOptions.class); storageOptionsMock.when( ()-> StorageOptions.newBuilder().setProjectId("Test").build().getService()).thenReturn(mockStorage); Error: org.mockito.exceptions.misusing.WrongTypeOfReturnValue: Storage$MockitoMock$1939527098 cannot be returned by newBuilder() newBuilder() should return Builder A: Since you are chaining a lot of method calls, you can use Mockito.RETURNS_DEEP_STUBS to instruct Mockito to return all the required intermediate stubs/mocks. Storage mockStorage = Mockito.mock(Storage.class); MockedStatic<StorageOptions> storageOptionsMock = Mockito.mockStatic(StorageOptions.class, Mockito.RETURNS_DEEP_STUBS); storageOptionsMock.when(()-> StorageOptions.newBuilder() .setProjectId("Test") .build() .getService()) .thenReturn(mockStorage); assertThat(StorageOptions.newBuilder() .setProjectId("Test") .build() .getService()) .isEqualTo(mockStorage); But since this is considered an anti pattern, you may want to refactor your code to avoid this.
Q: Plot black and white mandelbrot set Below code is taken from here. I am trying to make following change to the code below If c is not part of the set, plot a white pixel, and if it is part of the set, plot a black pixel. I am getting this output: But I want to plot a black and white mandelbrot image like this: Use the imshow command to plot your image Can anyone help ? m=601; n=401; count_max = 200; %Change the range of x's and y's here x_max = 1; x_min = - 2; y_max = 1; y_min = - 1; % % Create an array of complex sample points in [x_min,x_max] + [y_min,y_max]*i. % I = ( 1 : m ); J = ( 1 : n ); X = ( ( I - 1 ) * x_max + ( m - I ) * x_min ) / ( m - 1 ); Y = ( ( J - 1 ) * y_max + ( n - J ) * y_min ) / ( n - 1 ); [ Zr, Zi ] = meshgrid ( X, Y ); C = complex ( Zr, Zi ); % % Carry out the iteration. % epsilon = 0.001; Z = C; ieps = 1 : numel ( C ); %Iterate through 1 to maximum no. of iterations for i = 1 : count_max Z(ieps) = Z(ieps) .* Z(ieps) + C(ieps); W(ieps) = exp ( - abs ( Z(ieps) ) ); ieps = ieps ( find ( epsilon < W(ieps) ) ); end % % Display the data. % d = log ( abs ( Z ) ); t = delaunay ( Zr, Zi ); % % To see individual pixels, use 'flat' color. % h = trisurf ( t, Zr, Zi, d, 'FaceColor', 'flat', 'EdgeColor', 'flat' ); % h = trisurf ( t, Zr, Zi, d, 'FaceColor', 'interp', 'EdgeColor', 'interp' ); view ( 2 ) axis equal axis on title_string = sprintf ( 'Mandelbrot set, %d x %d pixels, %d iterations', ... m, n, count_max ); title ( title_string ) xlabel ('Real Axis'); ylabel ('Imaginary Axis'); % Terminate. A: The difference of belonging to the set and not belonging to the set is nothing else than epsilon < W(ieps) and you are already using that in your code. The colorinformation in the plot is coming from the fourth argument of trisurf ( t, Zr, Zi, d,...). So I suggest to do the following before the trisurf command: d(1 : numel ( C )) = 1; d(ieps) = 0; This first sets all elements to 1 and then sets those elements to zero that are part of the set, according to the condition that was already calculated in the last iteration of the convergence test. To plot black and white, just use colormap gray after the trisurf. Hope that helps.
Q: Java XML parsing error : Content is not allowed in prolog My code write a XML file with the LSSerializer class : DOMImplementation impl = doc.getImplementation(); DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS","3.0"); LSSerializer ser = implLS.createLSSerializer(); String str = ser.writeToString(doc); System.out.println(str); String file = racine+"/"+p.getNom()+".xml"; OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file),"UTF-8"); out.write(str); out.close(); The XML is well-formed, but when I parse it, I get an error. Parse code : File f = new File(racine+"/"+filename); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(f); XPathFactory xpfactory = XPathFactory.newInstance(); XPath xp = xpfactory.newXPath(); String expression; expression = "root/nom"; String nom = xp.evaluate(expression, doc); The error : [Fatal Error] Terray.xml:1:40: Content is not allowed in prolog. 9 août 2011 19:42:58 controller.MakaluController activatePatient GRAVE: null org.xml.sax.SAXParseException: Content is not allowed in prolog. at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:249) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284) at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:208) at model.MakaluModel.setPatientActif(MakaluModel.java:147) at controller.MakaluController.activatePatient(MakaluController.java:59) at view.ListePatientsPanel.jButtonOKActionPerformed(ListePatientsPanel.java:92) ... Now, with some research, I found that this error is dure to a "hidden" character at the very beginning of the XML. In fact, I can fix the bug by creating a XML file manually. But where is the error in the XML writing ? (When I try to println the string, there is no space before ths Solution : change the serializer I run the solution of UTF-16 encoding for a while, but it was not very stable. So I found a new solution : change the serializer of the XML document, so that the encoding is coherent between the XML header and the file encoding. : DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); String file = racine+"/"+p.getNom()+".xml"; OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file),"UTF-8"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.transform(domSource, new StreamResult(out)); A: But where is the error in the XML writing ? Looks like the error is not in the writing but the parsing. As you have already discovered there is a blank character at the beginning of the file, which causes the error in the parse call in your stach trace: Document doc = builder.parse(f); The reason you do not see the space when you print it out may be simply the encoding you are using. Try changing this line: OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file),"UTF-8"); to use 'UTF-16' or 'US-ASCII' A: I think that it is probably linked to BOM (Byte Order Mark). See Wikipedia You can verify with Notepad++ by example : Open your file and check the "Encoding" Menu to see if you're in "UTF8 without BOM" or "UTF8 with BOM". A: Using UTF-16 is the way to go, OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fileName),"UTF-16"); This can read the file with no issues A: Try this code: InputStream is = new FileInputStream(file); Document doc = builder.parse(is , "UTF-8");
Q: How to prefix any output in a bash script? When a script runs, commands in it may output some text to stdout/stderr. Bash itself may also output some text. But if a few scripts are running at the same time, it is hard to identify where does an error come from. So is it possible to insert a prefix to all output of the script? Something like: #!/bin/bash prefix 'PREFIX' &2 echo "wrong!" >&2 Then: $ ./script.sh PREFIXwrong! A: One option in bash is to do this by redirecting to process substitutions, something like this: ./script.sh > >(sed 's/^/script: /') 2> >(sed 's/^/script (err): /' >&2) This has the problem that output may be out of order (as Charles Duffy mentioned in a comment). It's also really annoyingly unweildy. But you could make a wrapper function for it: prefixwith() { local prefix="$1" shift "$@" > >(sed "s/^/$prefix: /") 2> >(sed "s/^/$prefix (err): /" >&2) } prefixwith "From script" ./script.sh Or make it even simpler by having it use the command name as a prefix: prefixoutput() { local prefix="From ${1##*/}" "$@" > >(sed "s/^/$prefix: /") 2> >(sed "s/^/$prefix (err): /" >&2) } prefixoutput ./script.sh A: You can redirect stderr/stdout to a process substitution that adds the prefix of choice. For example, this script: #! /bin/bash exec > >(trap "" INT TERM; sed 's/^/foo: /') exec 2> >(trap "" INT TERM; sed 's/^/foo: (stderr) /' >&2) echo foo echo bar >&2 date Produces this output: foo: foo foo: (stderr) bar foo: Fri Apr 27 20:04:34 IST 2018 The first two lines redirect stdout and stderr respectively to sed commands that add foo: and foo: (stderr) to the input. The calls to the shell built-in command trap make sure that the subshell does not exit when terminating the script with Ctrl+C or by sending the SIGTERM signal using kill $pid. This ensures that your shell won't forcefully terminate your script because the stdout file descriptor disappears when sed exits because it received the termination signal as well. Effectively you can still use exit traps in your main script and sed will still be running to process any output generated while running your exit traps. The subshell should still exit after your main script ends so sed process won't be left running forever. A: You could pipe the output through some way of replacing lines: some long running stuff | sed -e 's/^/Some said: /;' Also check 24337 Or just direct separate outputs to separate files/screen(1) tabs/tabs in your terminal/...
Q: Server and JRE are set to TLS 1.2 but Coldfusion 9 still trying to use TLS 1.0 I'm not 100% sure what's going on however we have a Coldfusion 9 server that connects to a web service. the web service has made the changes to only allow connections via TLS 1.2. We thought we were ok because we set the server to only use TLS 1.2 and we set the JRE (1.7) to use tls 1.2. However in the Coldfusion Administrator -> Web services when I try to refresh the web service connection it still tries to connect via TLS 1.0 (confirmed using wireshark). Anyone that is well versed in coldfusion configuration able to point me in the right direction to understand why this is happening? Thank you Edit: A: Upgrade your JDK/JRE to use 1.8 and that will solve this problem. For basic instructions, read my answer on this question: How to add TLS 1.2 in cfhttp tag in ColdFusion 10 The CF9 server that I support is running on Server JRE 1.8u172. A: Following Miguel-F's link and a few others, I discovered that CF 9 will ignore -Dhttps.protocols=TLSv1.2 for every version of JDK 7 until JDK 7u171 b31, but then JDK 7u181 enables TLSv1.2 by default (just like JDK 8). The only hurdle is that any JDK past 7u80 is behind an Oracle paid support wall. I managed to find someone with access and it tested just fine using PayPal's TLS Test site: <cfhttp url="https://tlstest.paypal.com/" result="test"> <cfdump var="#test#"> This returns a CFHTTP dump with PayPal_Connection_OK when a TLSv1.2 connection is used. JDK 8u172 will also work with CF 9.0.2 w/ all hot fixes, but I'd rather not risk the regression testing jumping to the next major version. A: Very late answer, but you can't go wrong using cfx_http5. Better than cfhttp in every way.
Q: Create CDFU in 2010 example? Recently migrated from SP 2007 to 2010, the CDFU workflows did got well in the migration so I am rebuilding them. The steps/logic must be different than SPD 2007. Want to send point of contact an email task to select from a list of choices say Apples, Oranges, or Bananas. I can get the email to fire off, the user can select the choice, but then the only value I am getting back seems like a ListID number. I can't figure out how to pass the selection back to my project list. I presumed the task list would show the selection but it doesn't Is there something missing where the task list isn't being updated so I can't update the project list since the task list is null? Anyone have screenshots or step by step of a simple CDFU??
Q: How to select button appearing in a new pop-up window in capybara? <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html style=""> <head> <body class="hasMotif lookupTab LookupSearchFrame brandNoBgrImg" onfocus="if(this.bodyOnFocus)bodyOnFocus();" onload="if(this.bodyOnLoad)bodyOnLoad();" onbeforeunload="if(this.bodyOnBeforeUnload){var s=bodyOnBeforeUnload();if(s)return s;}" onunload="if(this.bodyOnUnload)bodyOnUnload();"> <form id="theForm" target="resultsFrame" onsubmit="if (window.ffInAlert) { return false; }" name="theForm" method="GET" action="/_ui/common/data/LookupResultsFrame"> <input id="lkfm" type="hidden" value="editPage" name="lkfm"> <input id="lknm" type="hidden" value="Account" name="lknm"> <input id="lktp" type="hidden" value="001" name="lktp"> <div class="lookup"> <div class="bPageTitle"> <div class="pBody"> <label class="assistiveText" for="lksrch">Search</label> <input id="lksrch" type="text" value="" size="20" placeholder="Search..." name="lksrch" maxlength="80"> ### <input class="btn" type="submit" title="Go!" name="go" value=" Go! "> ### <input class="btn" type="button" title="New" onclick="javascript:top.resultsFrame.location='LookupResultsFrame?lktp=001&lkfm=editPage&lknm=Account&lksrch=&lkenhmd=SEARCH_NAME&lknew=1&igdp=0'" name="new" value=" New "> <div class="bDescription">You can use "*" as a wildcard next to other characters to improve your search results.</div> </div> </div> </form> This above is the code for content of pop-up window and i have to select the Go button. My code is as follows: #Get the main window handle main = page.driver.browser.window_handles.first #Get the popup window handle popup = page.driver.browser.window_handles.last #Then switch control between the windows page.driver.browser.switch_to.window(popup) page.driver.browser.switch_to.frame("searchFrame") # within(".pBody") do # find("go").click # end #find("#theForm").first("div").all("div")[2].all("input")[2].click #find(:xpath, "//*[@id='theForm']/div/div[2]/input[2]").click I've tried within method and find method, using xpath to click the Go button but the error i get is "stale element reference: element is not attached to the page document". Help me out, please? A: Step one is to to stop using driver specific methods and use the Capybara API provided for working with windows. Assuming you are in the current session you can do popup = window_opened_by do click_link 'open new window' # whatever action opens the popup window end within_window(popup) do click_button('Go!') end Note - this isn't handling any 'searchFrame' frame that you attempt to switch to, but that frame isn't shown in the HTML either, so it's not exactly clear whats going on there - if the frame is in the popup window then you would use `#within_frame' provided by Capybara to switch to the frame inside the within_window block like within_window(popup) do within_frame('searchFrame') do click_button('Go!') end end
Q: It is possible to use properties in a Dictionary in .NET From a third-party program, I get an list of results, as follows: +--------+-----------+-------------+ + Name + Property + Prop. value + +--------+-----------+-------------+ + foo + prop1 + value1 + +--------+-----------+-------------+ + foo + prop2 + value2 + +--------+-----------+-------------+ There is a dozen property and each of those may or may not exist. The aim is to create .NET object from these. Right now, I use LINQ to populate objects (sorry, VB, but it is quite straightforward): New myClass With { .myprop1 = (From o In query.rows where o.name = 'foo' and o.col(1) = 'prop1' select o.col(2)).FirstOrDefault ... .myprop12 = (From o In query.rows where o.name = 'foo' and o.col(1) = 'prop12' select o.col(2)).FirstOrDefault So I have basically the same line of code 12 times. I would like to simplify it. I have in mind something like a Dictionary(Property, String), where I could define myprop1 <-> prop1 .... myprop12 <-> prop12 And then loop over this. I haven't figured out how to do it. Is this possible? Is there any other way to make this kind of assignements less tedious? A: Sorry, but I'm going to have to do this in C#... (I haven't tested this, but it shouldbe close..) myClass foo = new myClass(); var fields = from o in query.rows where o.name == "foo" select new {Property=o.col(1), Value = o.col(2) }; foreach(var prop in foo.GetType().GetProperties()) { var fld = fields.FirstOrDefault(f=>f.Property == prop.Name); if (fld != null) prop.SetValue(foo, fld.Value); } Note, this assumes that the property name is myClass is the same as the field name, which is apparently not the case. Mapping is best handled by a Dictionary, which you'd probably have to created manually: var FieldByProperty = new Dictionary<string, string>(); FieldByProperty .Add["myprop1", "prop1"); FieldByProperty .Add["myprop2", "prop2"); // : foreach(var prop in foo.GetType().GetProperties()) { var fldName = FieldByProperty[prop.Name]; var fld = fields.FirstOrDefault(f=>f.Property == fldName); if (fld != null) prop.SetValue(foo, fld.Value); }
Q: How to preserve the accuracy of a floating point literal in Rust when using generics? What's a reasonable strategy for preserving the accuracy of a floating point literal in Rust when using generics? As an example, consider the following code: // External functions use std::fmt::LowerExp; // Some random struct parameterized on a float type struct Foo<Float> { x: Float, y: Float, } // Some random, generic function fn bar<Float>(x: Float) where Float: LowerExp + From<f32>, { let foo = Foo::<Float> { x, y: 0.45.into() }; println!("x = {:.16e} y = {:.16e}", foo.x, foo.y); } fn main() { bar::<f32>(0.45); bar::<f64>(0.45); } Here, we get the output: x = 4.4999998807907104e-1 y = 4.4999998807907104e-1 x = 4.5000000000000001e-1 y = 4.4999998807907104e-1 This makes sense. The first 0.45 was parsed knowing whether or not we were an f32 or an f64. However, the second was parsed as an f32 in both cases because of the trait From<f32>. Now, I'd like the output to be x = 4.4999998807907104e-1 y = 4.4999998807907104e-1 x = 4.5000000000000001e-1 y = 4.5000000000000001e-1 where y is parsed and set using the precision of the generic Float. One attempt to do that is by adding an additional trait of From<f64>. However, this is not satisfied by f32, so we get a compiler error. If we remove that use case and run the code: // External functions use std::fmt::LowerExp; // Some random struct parameterized on a float type struct Foo<Float> { x: Float, y: Float, } // Some random, generic function fn bar<Float>(x: Float) where //Float: LowerExp + From<f32>, Float: LowerExp + From<f32> + From<f64>, { let foo = Foo::<Float> { x, y: 0.45.into() }; println!("x = {:.16e} y = {:.16e}", foo.x, foo.y); } fn main() { //bar::<f32> (0.45); bar::<f64>(0.45); } we get what we want: x = 4.5000000000000001e-1 y = 4.5000000000000001e-1 at the expense of no longer working for f32. Alternatively, it's been suggested that we can use the num crate. Unfortunately, unless I'm missing something, this appears to run into an issue with double rounding. The program: // External functions use num::FromPrimitive; use std::fmt::LowerExp; // Some random struct parameterized on a float type struct Foo<Float> { x: Float, y: Float, } // Some random, generic function fn bar<Float>(x: Float) where Float: LowerExp + FromPrimitive, { let foo = Foo::<Float> { x, y: <Float as FromPrimitive>::from_f64( 0.5000000894069671353303618843710864894092082977294921875, ) .unwrap(), }; println!("x = {:.16e} y = {:.16e}", foo.x, foo.y); } fn main() { bar::<f32>(0.5000000894069671353303618843710864894092082977294921875f32); bar::<f64>(0.5000000894069671353303618843710864894092082977294921875f64); } Produces x = 5.0000005960464478e-1 y = 5.0000011920928955e-1 x = 5.0000008940696716e-1 y = 5.0000008940696716e-1 This is problematic because x and y differ in the f32 case. Anyway, is there a reasonable strategy for insuring the floating point literal is converted the same in both cases?
Q: Elasticsearch Bulk Index JSON Data I am trying to bulk index a JSON file into a new Elasticsearch index and am unable to do so. I have the following sample data inside the JSON [{"Amount": "480", "Quantity": "2", "Id": "975463711", "Client_Store_sk": "1109"}, {"Amount": "2105", "Quantity": "2", "Id": "975463943", "Client_Store_sk": "1109"}, {"Amount": "2107", "Quantity": "3", "Id": "974920111", "Client_Store_sk": "1109"}, {"Amount": "2115", "Quantity": "2", "Id": "975463798", "Client_Store_sk": "1109"}, {"Amount": "2116", "Quantity": "1", "Id": "975463827", "Client_Store_sk": "1109"}, {"Amount": "648", "Quantity": "3", "Id": "975464139", "Client_Store_sk": "1109"}, {"Amount": "2126", "Quantity": "2", "Id": "975464805", "Client_Store_sk": "1109"}, {"Amount": "2133", "Quantity": "1", "Id": "975464061", "Client_Store_sk": "1109"}, {"Amount": "1339", "Quantity": "4", "Id": "974919458", "Client_Store_sk": "1109"}, {"Amount": "1196", "Quantity": "5", "Id": "974920538", "Client_Store_sk": "1109"}, {"Amount": "1198", "Quantity": "4", "Id": "975463638", "Client_Store_sk": "1109"}, {"Amount": "1345", "Quantity": "4", "Id": "974919522", "Client_Store_sk": "1109"}, {"Amount": "1347", "Quantity": "2", "Id": "974919563", "Client_Store_sk": "1109"}, {"Amount": "673", "Quantity": "2", "Id": "975464359", "Client_Store_sk": "1109"}, {"Amount": "2153", "Quantity": "1", "Id": "975464511", "Client_Store_sk": "1109"}, {"Amount": "3896", "Quantity": "4", "Id": "977289342", "Client_Store_sk": "1109"}, {"Amount": "3897", "Quantity": "4", "Id": "974920602", "Client_Store_sk": "1109"}] I am using curl -XPOST localhost:9200/index_local/my_doc_type/_bulk --data-binary --data @/home/data1.json When I try to use the standard bulk index API from Elasticsearch I get this error error: {"message":"ActionRequestValidationException[Validation Failed: 1: no requests added;]"} Can anyone help with indexing this type of JSON? A: A valid Elasticsearch bulk API request would be something like (ending with a newline): POST http://localhost:9200/products_slo_development_temp_2/productModel/_bulk { "index":{ } } {"RequestedCountry":"slo","Id":1860,"Title":"Stol"} { "index":{ } } {"RequestedCountry":"slo","Id":1860,"Title":"Miza"} Elasticsearch bulk api documentation: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html This is how I do it I send a POST http request with the uri valiable as the URI/URL of the http request and elasticsearchJson variable is the JSON sent in the body of the http request formatted for the Elasticsearch bulk api: var uri = @"/" + indexName + "/productModel/_bulk"; var json = JsonConvert.SerializeObject(sqlResult); var elasticsearchJson = GetElasticsearchBulkJsonFromJson(json, "RequestedCountry"); Helper method for generating the required json format for the Elasticsearch bulk api: public string GetElasticsearchBulkJsonFromJson(string jsonStringWithArrayOfObjects, string firstParameterNameOfObjectInJsonStringArrayOfObjects) { return @"{ ""index"":{ } } " + jsonStringWithArrayOfObjects.Substring(1, jsonStringWithArrayOfObjects.Length - 2).Replace(@",{""" + firstParameterNameOfObjectInJsonStringArrayOfObjects + @"""", @" { ""index"":{ } } {""" + firstParameterNameOfObjectInJsonStringArrayOfObjects + @"""") + @" "; } The first property/field in my JSON object is the RequestedCountry property that's why I use it in this example. productModel is my Elasticsearch document type. sqlResult is a C# generic list with products. A: This answer is for Elastic Search 7.x onwards. _type is deprecated. As others have mentioned, you can read the file programatically, and construct a request body as described below. Also, I see that each of your json object has the Id attribute. So, you could set the document's internal id (_id) to be the same as this attribute. Updated _bulk API would look like this: HTTP Method: POST URI: /<index_name>/_bulk Request body (should end with a new line): {"index":{"_id": "975463711"}} {"Amount": "480", "Quantity": "2", "Id": "975463711", "Client_Store_sk": "1109"} {"index":{"_id": "975463943"}} {"Amount": "2105", "Quantity": "2", "Id": "975463943", "Client_Store_sk": "1109"} A: As of today, 6.1.2 is the latest version of ElasticSearch, and the curl command that works for me on Windows (x64) is curl -s -XPOST localhost:9200/my_index/my_index_type/_bulk -H "Content-Type: application/x-ndjson" --data-binary @D:\data\mydata.json The format of the data that should be present in mydata.json remains the same as shown in @val's answer A: What you need to do is to read that JSON file and then build a bulk request with the format expected by the _bulk endpoint, i.e. one line for the command and one line for the document, separated by a newline character... rinse and repeat for each document: curl -XPOST localhost:9200/your_index/_bulk -d ' {"index": {"_index": "your_index", "_type": "your_type", "_id": "975463711"}} {"Amount": "480", "Quantity": "2", "Id": "975463711", "Client_Store_sk": "1109"} {"index": {"_index": "your_index", "_type": "your_type", "_id": "975463943"}} {"Amount": "2105", "Quantity": "2", "Id": "975463943", "Client_Store_sk": "1109"} ... etc for all your documents ' Just make sure to replace your_index and your_type with the actual index and type names you're using. UPDATE Note that the command-line can be shortened, by removing _index and _type if those are specified in your URL. It is also possible to remove _id if you specify the path to your id field in your mapping (note that this feature will be deprecated in ES 2.0, though). At the very least, your command line can look like {"index":{}} for all documents but it will always be mandatory in order to specify which kind of operation you want to perform (in this case index the document) UPDATE 2 curl -XPOST localhost:9200/index_local/my_doc_type/_bulk --data-binary @/home/data1.json /home/data1.json should look like this: {"index":{}} {"Amount": "480", "Quantity": "2", "Id": "975463711", "Client_Store_sk": "1109"} {"index":{}} {"Amount": "2105", "Quantity": "2", "Id": "975463943", "Client_Store_sk": "1109"} {"index":{}} {"Amount": "2107", "Quantity": "3", "Id": "974920111", "Client_Store_sk": "1109"} UPDATE 3 You can refer to this answer to see how to generate the new json style file mentioned in UPDATE 2. UPDATE 4 As of ES 7.x, the doc_type is not necessary anymore and should simply be _doc instead of my_doc_type. As of ES 8.x, the doc type will be removed completely. You can read more about this here
Q: Why can't Fedora start my (hard wired) network? FYI: I've asked this on Superuser but not luck so I'm trying here. I'm not sure which it is more relevant to. I have a hard-wired Ethernet card/cable to my hub. I start Fedora 23 but there's no network, why? So I've checked that the card exists:- [root@localhost ~]# lspci | grep Ether 00:0b.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL-8100/8101L/8139 PCI Fast Ethernet Adapter (rev 10) [root@localhost ~]# lspci -vm -s 00:0b.0 Device: 00:0b.0 Class: Ethernet controller Vendor: Realtek Semiconductor Co., Ltd. Device: RTL-8100/8101L/8139 PCI Fast Ethernet Adapter SVendor: Packard Bell B.V. SDevice: Device e012 Rev: 10 Then I try to start the network (fyi systemctl restart network.service has the same output)... [root@localhost ~]# service network start Starting network (via systemctl): Job for network.service failed because the control process exited with error code. See "systemctl status network.service" and "journalctl -xe" for details. [FAILED] The result of the suggested command (systemctl status network.service above) is... [root@localhost ~]# systemctl status network.service ● network.service - LSB: Bring up/down networking Loaded: loaded (/etc/rc.d/init.d/network) Active: failed (Result: exit-code) since Sun 2015-11-08 19:40:26 GMT; 30s ago Docs: man:systemd-sysv-generator(8) Process: 3072 ExecStart=/etc/rc.d/init.d/network start (code=exited, status=1/FAILURE) Nov 08 19:40:23 localhost.localdomain network[3072]: Could not load file '/etc/sysconfig/network-scripts/ifcfg-lo' Nov 08 19:40:24 localhost.localdomain network[3072]: Could not load file '/etc/sysconfig/network-scripts/ifcfg-lo' Nov 08 19:40:25 localhost.localdomain network[3072]: Could not load file '/etc/sysconfig/network-scripts/ifcfg-lo' Nov 08 19:40:25 localhost.localdomain network[3072]: [ OK ] Nov 08 19:40:26 localhost.localdomain network[3072]: Bringing up interface enp0s11: Error: Connection activation failed: No suitable device found for this connection. Nov 08 19:40:26 localhost.localdomain network[3072]: [FAILED] Nov 08 19:40:26 localhost.localdomain systemd[1]: network.service: Control process exited, code=exited status=1 Nov 08 19:40:26 localhost.localdomain systemd[1]: Failed to start LSB: Bring up/down networking. Nov 08 19:40:26 localhost.localdomain systemd[1]: network.service: Unit entered failed state. Nov 08 19:40:26 localhost.localdomain systemd[1]: network.service: Failed with result 'exit-code'. Then I came across some suggestions on here that I check the contents of network-scipts and ifcfg-enp0s11, the one that failed above seems to be the one I'm looking for, the MAC address is the same as the one listed in ifconfig -a for that named device [root@localhost ~]# more /etc/sysconfig/network-scripts/ifcfg-enp0s11 HWADDR=00:13:D4:86:EB:18 TYPE=Ethernet BOOTPROTO=dhcp DEFROUTE=yes PEERDNS=yes PEERROUTES=yes IPV4_FAILURE_FATAL=no IPV6INIT=yes IPV6_AUTOCONF=yes IPV6_DEFROUTE=yes IPV6_PEERDNS=yes IPV6_PEERROUTES=yes IPV6_FAILURE_FATAL=no NAME=enp0s11 UUID=b7fce5e7-b3aa-4e95-a014-8661889e9cce ONBOOT=yes My other options in network-scripts were ifcfg-enp0s11 ifdown-ippp ifdown-routes ifup ifup-ipv6 ifup-ppp ifup-tunnel ifcfg-lo ifdown-ipv6 ifdown-sit ifup-aliases ifup-isdn ifup-routes ifup-wireless ifdown ifdown-isdn ifdown-Team ifup-bnep ifup-plip ifup-sit init.ipv6-global ifdown-bnep ifdown-post ifdown-TeamPort ifup-eth ifup-plusb ifup-Team network-functions ifdown-eth ifdown-ppp ifdown-tunnel ifup-ippp ifup-post ifup-TeamPort network-functions-ipv6 But ifup eth, ifup eth1, ifup eth2, ifup enp0s11 and ifup lo all say there's no config found?! [root@localhost ~]# ifup eth /usr/sbin/ifup: configuration for eth not found. Usage: ifup <device name> I partially understand that the ifup commands are not really used anymore because of NetworkManager, which is running... [root@localhost ~]# systemctl status NetworkManager.service ● NetworkManager.service - Network Manager Loaded: loaded (/usr/lib/systemd/system/NetworkManager.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2015-11-08 19:35:13 GMT; 33min ago Main PID: 905 (NetworkManager) CGroup: /system.slice/NetworkManager.service └─905 /usr/sbin/NetworkManager --no-daemon Nov 08 19:35:30 localhost.localdomain NetworkManager[905]: <info> (virbr0): device state change: secondaries -> activated (reason 'none') [90 100 0] Nov 08 19:35:30 localhost.localdomain NetworkManager[905]: <info> (virbr0): Activation: successful, device activated. Nov 08 19:35:35 localhost.localdomain NetworkManager[905]: <info> (virbr0-nic): link disconnected (calling deferred action) Nov 08 19:36:57 localhost.localdomain NetworkManager[905]: <info> use BlueZ version 5 Nov 08 19:40:31 localhost.localdomain NetworkManager[905]: <info> connectivity: check for uri 'http://fedoraproject.org/static/hotspot.txt' failed with 'Error resolving 'fedoraproject.org': Name or service not known' Nov 08 19:45:31 localhost.localdomain NetworkManager[905]: <info> connectivity: check for uri 'http://fedoraproject.org/static/hotspot.txt' failed with 'Error resolving 'fedoraproject.org': Name or service not known' Nov 08 19:50:31 localhost.localdomain NetworkManager[905]: <info> connectivity: check for uri 'http://fedoraproject.org/static/hotspot.txt' failed with 'Error resolving 'fedoraproject.org': Name or service not known' Nov 08 19:55:31 localhost.localdomain NetworkManager[905]: <info> connectivity: check for uri 'http://fedoraproject.org/static/hotspot.txt' failed with 'Error resolving 'fedoraproject.org': Name or service not known' Nov 08 20:00:31 localhost.localdomain NetworkManager[905]: <info> connectivity: check for uri 'http://fedoraproject.org/static/hotspot.txt' failed with 'Error resolving 'fedoraproject.org': Name or service not known' Nov 08 20:05:31 localhost.localdomain NetworkManager[905]: <info> connectivity: check for uri 'http://fedoraproject.org/static/hotspot.txt' failed with 'Error resolving 'fedoraproject.org': Name or service not known' Any ideas why I have no network?
Q: Common methods for different page objects in Cucumber Question with respect to common methods for different page objects in Cucumber Has anyone worked upon creating common methods which can be used across different page objects in cucumber. Example: Click method. I specify page objects in feature file (And I click on object o). This in turns calls the step defination. In step defination, we have written a generic method for click (object o.click()) We also have a separate class where all the page objects are defined (eg: xpath of object o). Now the question is how to integrate, these page objects with the common step defination of click method. If this is achievable, we only require to change the steps in feature file for different objects(object o to object b). Single click method will work for all different page objects, we just need to add xpath of these objects in common page object class. Anyone worked upon achieving this ? A: Its totally depend on your project framework in which you want to setup. Yes it possible Example: PageOjectclass: WebDriver driver = null; private WebElement element = null; private By By = null; public PageOjectclass(WebDriver driver) { this.driver = driver; } public static WebElement button_submit() throws Exception { try { element = driver.findElement(By.xpath("//h1[@class='txtCenter white ico30']")); } catch (Exception e) { AutomationLog.error("HomePageHeader Element not found"); throw (e); } return element; } CommonClass public static void Customclick(WebElement e) { e.click(); } StepDefinationClass @When("^testing$") public void test() throws Throwable { CommonClass.Customclick(PageOjectclass.button_submit()); } Just take care of passing the webdriver initialized object, pass them with constructor etc
Q: Kotlin Mock Spring boot test can't compile So I have the following test @Test fun `when save claims is called with email saved to that profile` () { //arrange given(profileRepository.findProfileByEmail(anyString())).willAnswer { daoProfile } given(patientRepository.findById(anyInt())).willAnswer { Optional.of(daoPatient) } given(claimRepository.saveAll(anyList())).willAnswer { mutableListOf(daoClaim) } //act val result = claimService.saveClaimsForEmail(listOf(dtoClaim), "[email protected]") //assert assert(result != null) assert(result?.isNotEmpty() ?: false) verify(claimRepository).saveAll(anyList()) } The line given(claimRepository.saveAll(anyList())).willAnswer { mutableListOf(daoClaim) } gives the folowing error e: org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Failed to generate expression: KtBlockExpression File being compiled at position: (217,71) in /Users/archer/Work/masterhealth/master_billing/src/test/kotlin/com/masterhealthsoftware/master_billing/data/service/ClaimServiceTest.kt The root cause java.lang.IllegalStateException was thrown at: org.jetbrains.kotlin.codegen.state.KotlinTypeMapper$typeMappingConfiguration$1.processErrorType(KotlinTypeMapper.kt:113) ... Caused by: java.lang.IllegalStateException: Error type encountered: (???..???) (FlexibleTypeImpl). at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper$typeMappingConfiguration$1.processErrorType(KotlinTypeMapper.kt:113) When the line is removed, it compiles but the test fails for obvious reasons. claimRespoitory is annotated @MockBean at the top of the test class, and is a JpaInterface. Line 217 is the start of the function. I've also trie using when and other various willReturn or willAnswer.... Any idea why? A: I was facing the same issue when using Mockito any(). Changing it to ArgumentMatchers.any(YourClass::class.java)) solved the compilation error, there is a deprecated ArgumentMatchers.anyListOf(YourClass::class.java) that might do the job.
Q: Displaying uploaded image only works every other time I'm working on a user account system for my website. I want users to be able to upload a custom profile picture. Currently, it displays a preview of the uploaded image. But it only works every other time. I can't seem to fix it. Here is my code: <img id="pfp-img" src="<?php echo (empty($row["pfp"]) ? "https://www.media.yoo-babobo.com/images/user.png" : $row["pfp"]); ?>" alt="Your profile picture" onclick="$('#pfp').trigger('click');" style="width: 150px; height: auto; border-radius: 100%; cursor: pointer;" /> <input type="file" id="pfp" name="pfp" placeholder="Profile Picture" capture="user" accept="image/*" style="display: none;" /> And here is the javascript: $("#pfp").on("input change", e => { var canvas = $('<canvas width="150" height="150" style="display: none;">'); $("body").append(canvas); var ctx = document.querySelector("canvas").getContext("2d"); var img = new Image(); img.onload = function() { ctx.drawImage(img, 0, 0, 150, 150); } img.src = window.URL.createObjectURL(e.target.files[0] || "<DEFAULT PROFILE PICTURE>"); var data_uri = document.querySelector("canvas").toDataURL("image/png"); document.getElementById("pfp-img").src = data_uri; canvas.remove(); }) Is there anything I'm doing wrong? And are there any better ways to do this?
Q: If $n\geq3$, show that if $\alpha \in S_n$ commutes with every $\beta \in S_n$, then $\alpha = (1)$ I've been stuck in this problem for a while and I don't really know how to start. I was thinking in something like this: Suppose that $\alpha \beta=\beta \alpha$ and $\alpha\neq{(1)}$, then $\alpha, \beta$ are disjoint permutations. Suppose that exists $i,j$ such that $\alpha(i)=j$ then $\beta(i)=i$, and $\alpha(\beta(i))=j$ but $\beta(\alpha(i))=\beta(j)=j$. I don't know what I'm missing or if I'm doing something that doesn't make sense. Any hint on how should I start would be really appreciated. A: Suppose the permutation $\alpha\ne(1)$. So for some $i$ we have $\alpha(i)=j$ with $j\ne i$. We now consider two cases. Case 1. $\alpha(j)=i$. Take $k\ne i$ and $k\ne j$. If we apply $(ik)$ followed by $\alpha$, then $j$ goes to $i$. But if we apply $\alpha$ followed by $(ik)$, then $j$ goes to $k$. So the transposition $(ik)$ does not commute with $\alpha$. Case 2. $\alpha(j)=k$ where $k\ne i$ and $k\ne j$. If we apply $(jk)$ followed by $\alpha$, then $i$ goes to $j$. But if we apply $\alpha$ followed by $(jk)$, then $i$ goes to $k$. So $(jk)$ does not commute with $\alpha$.
Q: Core Motion - Convert local euler angles to another reference system I got a problem with the maths involved in converting local Euler angles into the angles of another reference system. Lets say we have an iPhone aligned with the axis of an vehicle and I want to measure the roll angle, then the roll angle of the iPhone equals the roll angle of the device. But what if the iPhone is mounted tilt. In this case I would have to convert the local Euler angles to another reference frame (e.g. the cars). Could someone please point me in the right direction? A: I assume you want to know the roll of the car, rather than the phone. The phone needs to known the initial reference frame. So, suppose you line up the phone with the car at the start. Then press a button on the phone. At that button press, in your code store the attitude that you get from CMDeviceMotion. If you want to know the roll of the car at any point after that, take the current attitude from CMDeviceMotion. Then call multiplyByInverseOfAttitude: on it, supplying the initial reference frame as parameter. That will give you the difference between the initial reference frame and the current one. If you take the roll property from that, it should be the roll angle of the car.
Q: window.location.href = "prefs:root=Settings" not work in iOS 10 I want to open iPhone setting app in Safari. <script type="text/javascript"> window.location.href = "prefs:root=General&path=ManagedConfigurationList" </script> It is working in iOS 9, but it is not working in iOS 10. A: Just replace "prefs" to "App-Prefs" for iOS 10
Q: WPF C# Textbox text change update in ViewModel Hello I am working on a simple MVVM project; a simple text/config editor that loads a config file and then it checks in the ViewModel in case the file has been changed, it enables the Save menu item simply by binding a boolean property. But here comes a problem, where I can't find any property in the textbox control that could be bound to a vm property in case a change happens in the text. I have managed to somehow simulate this by creating an event in the code-behind : (DataContext as AnalizeSectionViewModel).ContentChanged = true; The event is fired on any text change. But I would like to bind a property from the textbox, something like: IsModified="{Binding ContentChanged}" Can such a thing be done? A: You should be able to just bind the Text textbox property to your model via binding Text="{Binding MyViewModelProperty}" Anytime the text in your textbox changes your property in your model will change which will allow you to do 'stuff' when that occurs. This will fire the property changed event when the user moves to out of the field. Now, if the intent is for it to fire each time the user types then you can explicitly tack on the UpdateSourceTrigger="PropertyChanged" By setting it to PropertyChanged, you will get a notification each and every time the text changes.
Q: Dash panel is not visible Possible Duplicate: Unity doesn't load, no Launcher, no Dash appears I recently upgraded Ubuntu from version 11.04 to 11.10. After about two days of using this new version the Dash didn't appear on the top, and I wasn't able to access the programs that I use. Let me describe: The bar on the top with the clock and Internet connections is not there. The only remains are the notification messages that a connection has been found, which allows me to connect to the Internet; and the menus from what appear to be a nautilus application but I'm not sure, they read File Edit View Go Bookmarks Help, and they open my Home Folder. The icons of my favourite applications are not there, and I am unable to access them wit Alt+F2 or the Super key. The only thing that's available is the Terminal with the shortcut Ctrl+Alt+T. By the way, in order to keep using the computer I had to run the Ubuntu 2D version at the beginning, but as you would imagine that is not optimal since I was already looking forward to the new features of Ubuntu 11.10. A: Try sudo apt-get install ubuntu-desktop, which should reinstall all of Unity's features. A: [from the original question asker] It turns out I accidentally uninstalled the Unity plugin in CompizConig Settings Manager. I renabled the Unity plugin in the same application.
Q: HTML Purifier: Removing an element conditionally based on its attributes As per the HTML Purifier smoketest, 'malformed' URIs are occasionally discarded to leave behind an attribute-less anchor tag, e.g. <a href="javascript:document.location='http://www.google.com/'">XSS</a> becomes <a>XSS</a> ...as well as occasionally being stripped down to the protocol, e.g. <a href="http://1113982867/">XSS</a> becomes <a href="http:/">XSS</a> While that's unproblematic, per se, it's a bit ugly. Instead of trying to strip these out with regular expressions, I was hoping to use HTML Purifier's own library capabilities / injectors / plug-ins / whathaveyou. Point of reference: Handling attributes Conditionally removing an attribute in HTMLPurifier is easy. Here the library offers the class HTMLPurifier_AttrTransform with the method confiscateAttr(). While I don't personally use the functionality of confiscateAttr(), I do use an HTMLPurifier_AttrTransform as per this thread to add target="_blank" to all anchors. // more configuration stuff up here $htmlDef = $htmlPurifierConfiguration->getHTMLDefinition(true); $anchor = $htmlDef->addBlankElement('a'); $anchor->attr_transform_post[] = new HTMLPurifier_AttrTransform_Target(); // purify down here HTMLPurifier_AttrTransform_Target is a very simple class, of course. class HTMLPurifier_AttrTransform_Target extends HTMLPurifier_AttrTransform { public function transform($attr, $config, $context) { // I could call $this->confiscateAttr() here to throw away an // undesired attribute $attr['target'] = '_blank'; return $attr; } } That part works like a charm, naturally. Handling elements Perhaps I'm not squinting hard enough at HTMLPurifier_TagTransform, or am looking in the wrong place(s), or generally amn't understanding it, but I can't seem to figure out a way to conditionally remove elements. Say, something to the effect of: // more configuration stuff up here $htmlDef = $htmlPurifierConfiguration->getHTMLDefinition(true); $anchor = $htmlDef->addElementHandler('a'); $anchor->elem_transform_post[] = new HTMLPurifier_ElementTransform_Cull(); // add target as per 'point of reference' here // purify down here With the Cull class extending something that has a confiscateElement() ability, or comparable, wherein I could check for a missing href attribute or a href attribute with the content http:/. HTMLPurifier_Filter I understand I could create a filter, but the examples (Youtube.php and ExtractStyleBlocks.php) suggest I'd be using regular expressions in that, which I'd really rather avoid, if it is at all possible. I'm hoping for an onboard or quasi-onboard solution that makes use of HTML Purifier's excellent parsing capabilities. Returning null in a child-class of HTMLPurifier_AttrTransform unfortunately doesn't cut it. Anyone have any smart ideas, or am I stuck with regexes? :) A: Success! Thanks to Ambush Commander and mcgrailm in another question, I am now using a hilariously simple solution: // a bit of context $htmlDef = $this->configuration->getHTMLDefinition(true); $anchor = $htmlDef->addBlankElement('a'); // HTMLPurifier_AttrTransform_RemoveLoneHttp strips 'href="http:/"' from // all anchor tags (see first post for class detail) $anchor->attr_transform_post[] = new HTMLPurifier_AttrTransform_RemoveLoneHttp(); // this is the magic! We're making 'href' a required attribute (note the // asterisk) - now HTML Purifier removes <a></a>, as well as // <a href="http:/"></a> after HTMLPurifier_AttrTransform_RemoveLoneHttp // is through with it! $htmlDef->addAttribute('a', 'href*', new HTMLPurifier_AttrDef_URI()); It works, it works, bahahahaHAHAHAHAnhͥͤͫ̀ğͮ͑̆ͦó̓̉ͬ͋h́ͧ̆̈́̉ğ̈́͐̈a̾̈́̑ͨô̔̄̑̇g̀̄h̘̝͊̐ͩͥ̋ͤ͛g̦̣̙̙̒̀ͥ̐̔ͅo̤̣hg͓̈́͋̇̓́̆a͖̩̯̥͕͂̈̐ͮ̒o̶ͬ̽̀̍ͮ̾ͮ͢҉̩͉̘͓̙̦̩̹͍̹̠̕g̵̡͔̙͉̱̠̙̩͚͑ͥ̎̓͛̋͗̍̽͋͑̈́̚...! * manic laughter, gurgling noises, keels over with a smile on her face * A: The fact that you can't remove elements with a TagTransform appears to have been an implementation detail. The classic mechanism for removing nodes (a smidge higher-level than just tags) is to use an Injector though. Anyway, the particular piece of functionality you're looking for is already implemented as %AutoFormat.RemoveEmpty A: For perusal, this is my current solution. It works, but bypasses HTML Purifier entirely. /** * Removes <a></a> and <a href="http:/"></a> tags from the purified * HTML. * @todo solve this with an injector? * @param string $purified The purified HTML * @return string The purified HTML, sans pointless anchors. */ private function anchorCull($purified) { if (empty($purified)) return ''; // re-parse HTML $domTree = new DOMDocument(); $domTree->loadHTML($purified); // find all anchors (even good ones) $anchors = $domTree->getElementsByTagName('a'); // collect bad anchors (destroying them in this loop breaks the DOM) $destroyNodes = array(); for ($i = 0; ($i < $anchors->length); $i++) { $anchor = $anchors->item($i); $href = $anchor->attributes->getNamedItem('href'); // <a></a> if (is_null($href)) { $destroyNodes[] = $anchor; // <a href="http:/"></a> } else if ($href->nodeValue == 'http:/') { $destroyNodes[] = $anchor; } } // destroy the collected nodes foreach ($destroyNodes as $node) { // preserve content $retain = $node->childNodes; for ($i = 0; ($i < $retain->length); $i++) { $rnode = $retain->item($i); $node->parentNode->insertBefore($rnode, $node); } // actually destroy the node $node->parentNode->removeChild($node); } // strip out HTML out of DOM structure string $html = $domTree->saveHTML(); $begin = strpos($html, '<body>') + strlen('<body>'); $end = strpos($html, '</body>'); return substr($html, $begin, $end - $begin); } I'd still much rather have a good HTML Purifier solution to this, so, just as a heads-up, this answer won't end up self-accepted. But in case no better answer ends up coming around, at least it might help those with similar issues. :)
Q: Multiple JPanel not being printed in front of background I wanted to create a Calendar that creates itself dinamically depending on the month it is based of. At first, I created a background that will be used on any months, and its dimensions are 700x500 (700/7 for each day and 500/5 since every month but 28-days-February-starting-in-Monday has 5 rows of weeks). I did this with this sentences: public class Graph { private final int sizeX = 700; private final int sizeY = 500; private Calendar calendar; public Graph(Calendar calendar) { this.calendar = calendar; JFrame frame = new JFrame(); graph(frame); } public void graph(JFrame frame) { buildBackground(frame); } private void buildBackground(JFrame frame) { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setSize(sizeX, sizeY); JPanel panel = new Background(sizeX, sizeY); frame.add(panel); frame.validate(); frame.repaint(); } } public class Background extends JPanel { private int sizeX; private int sizeY; public Background(int sizeX, int sizeY) { this.sizeX = sizeX; this.sizeY = sizeY; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.DARK_GRAY); g.fillRect(0, 0, sizeX, sizeY); } } And that works correctly, a dark gray background is created correctly. The problem appears when I try to create small rectangles that represents the days; I designed a class which I want to represent those rectangles on a certain coordinates: public class DayRectangle extends JPanel { private int posX; private int posY; private int day; public DayRectangle(int posX, int posY, int day) { this.posX = posX; this.posY = posY; this.day = day; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.fillRect(posX, posY, 60, 60); } public Dimension getPreferredSize() { return new Dimension (60, 60); } @Override public String toString() { return String.format("(%d,%d):%d", posX, posY, day); } } Rectangles' coordinates are created correctly, since this are the content of the ArrayList of DayRectangle: [(20,20):1, (120,20):2, (220,20):3, (320,20):4, (420,20):5, (520,20):6, (620,20):7, (20,120):8, (120,120):9, (220,120):10, (320,120):11, (420,120):12, (520,120):13, (620,120):14, (20,220):15, (120,220):16, (220,220):17, (320,220):18, (420,220):19, (520,220):20, (620,220):21, (20,320):22, (120,320):23, (220,320):24, (320,320):25, (420,320):26, (520,320):27, (620,320):28, (20,420):29, (120,420):30, (220,420):31] They start on (20, 20) because I wanted to let some gaps between those rectangles. The main problem is that no rectangle is printed when I execute this code: public void graph(JFrame frame) { buildBackground(frame); frame.getGraphics().setColor(Color.WHITE); JPanel panel; for (DayRectangle d : arraylist) { panel = d; frame.add(panel); frame.repaint(); } } What am I doing wrong? Why is nothing being printed? Thanks. A: You appear to be forgetting that a JFrame uses a BorderLayout for its layout manager. Rather you should likely add your Day JPanels into another JPanel that uses GridLayout, and also remember that the Day JPanels will draw relative to their own local coordinate system, and so each Day JPanel should probably draw its rectangle at the same location, starting near 0, 0, not relative to the containing Container. If you want one JPanel to be a background JPanel, then that should be added to the JFrame in the BorderLayout.CENTER position. Give it a GridLayout, and add your Day JPanels to it, and any JLabels needed (empty if you need empty squares). Also Day may need to be non-opaque if you want background images or colors to show through. e.g., public class DayRectangle extends JPanel { private static Color RECT_COLOR = Color.LIGHT_GRAY; private static final int PREF_W = 60; private static final int GAP = 4; private int posX; private int posY; private int day; public DayRectangle(int posX, int posY, int day) { this.posX = posX; // not sure that you need this this.posY = posY; // ditto this.day = day; // if you desire a background to show throw // setOpaque(false); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(RECT_COLOR); g.fillRect(GAP, GAP, PREF_W - 2 * GAP, PREF_W - 2 * GAP); } public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_W); } @Override public String toString() { return String.format("(%d,%d):%d", posX, posY, day); } } For a simple example: import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.GridBagLayout; import java.awt.GridLayout; import javax.swing.*; @SuppressWarnings("serial") public class ExampleGrid extends JPanel { public ExampleGrid() { JPanel mainGrid = new JPanel(); mainGrid.setLayout(new GridLayout(0, 7)); // just to show a little off-set of the days mainGrid.add(new JLabel()); mainGrid.add(new JLabel()); mainGrid.add(new JLabel()); // now fill the calendar for (int i = 0; i < 30; i++) { mainGrid.add(new DayRectangle(i + 1)); } JLabel monthLabel = new JLabel("JULY", SwingConstants.CENTER); monthLabel.setFont(monthLabel.getFont().deriveFont(Font.BOLD, 36f)); // label the days of the week at the top String[] daysOfWk = { "Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat" }; JPanel daysOfWkPanel = new JPanel(new GridLayout(1, 7)); for (String dayOfWk : daysOfWk) { daysOfWkPanel.add(new JLabel(dayOfWk, SwingConstants.CENTER)); } JPanel topPanel = new JPanel(new BorderLayout()); topPanel.add(monthLabel, BorderLayout.PAGE_START); topPanel.add(daysOfWkPanel, BorderLayout.CENTER); setLayout(new BorderLayout()); add(topPanel, BorderLayout.PAGE_START); add(mainGrid, BorderLayout.CENTER); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // not sure what you want to do here } private static void createAndShowGui() { ExampleGrid mainPanel = new ExampleGrid(); JFrame frame = new JFrame("Example Grid"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> createAndShowGui()); } } @SuppressWarnings("serial") class DayRectangle extends JPanel { private static Color RECT_COLOR = Color.LIGHT_GRAY; private static final int PREF_W = 60; private static final int GAP = 4; private static final float FNT_SZ = 20f; private int day; public DayRectangle(int day) { this.day = day; setLayout(new GridBagLayout()); JLabel label = new JLabel("" + day); label.setFont(label.getFont().deriveFont(Font.BOLD, FNT_SZ)); add(label); // if you desire a background to show throw // setOpaque(false); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(RECT_COLOR); g.fillRect(GAP, GAP, PREF_W - 2 * GAP, PREF_W - 2 * GAP); } public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_W); } public int getDay() { return day; } }
Q: Python wget bypass checkbox before download So I am trying to download a file from a website namely the jdk to automate a workstation setup. When downloading from the oracle website you are forced to accept the TOS. My question is, How exactly do you accept the TOS from python wget? import wget import ssl ssl._create_default_https_context = ssl._create_unverified_context url = "https://download.oracle.com/otn-pub/java/jdk/11.0.1+13/90cf5d8f270a4347a95050320eef3fb7/jdk-11.0.1_windows-x64_bin.exe" wget.download(url, 'java11.exe') A: With the wget module you cannot set cookies, which the Oracle website uses to accept the TOS. Instead, you can use the requests module to set cookies, download, and save the file. import requests url = 'https://download.oracle.com/otn-pub/java/jdk/11.0.1+13/90cf5d8f270a4347a95050320eef3fb7/jdk-11.0.1_windows-x64_bin.exe' cookie = { 'oraclelicense': 'accept-securebackup-cookie' } r = requests.get(url, cookies=cookie) if r.status_code == 200: with open("jdk-11.0.1_windows-x64_bin.exe", 'wb') as file: file.write(r.content) EDIT: I see you're also connecting through unverified SSL, to do this with requests, you can set verify to False: r = requests.get(url, cookies=cookie, verify=False)
Q: Point Cloud Visualization I am trying to load and visualize a point cloud data by "addPointCloud" instruction. //*********** pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>); if (pcl::io::loadPCDFile<pcl::PointXYZRGBA> ("f.pcd", *cloud) == -1) { PCL_ERROR ("Couldn't read the pcd file \n"); return (-1); } pcl::visualization::PCLVisualizer viewer ("Simple Cloud Viewer"); viewer.setBackgroundColor (0, 0, 0); viewer.addPointCloud(cloud, "sample cloud"); //*********** But instead of seeing my point cloud in a black background, only see a white backbround whithout any point cloud. Can any one tell me kindly where is my problem? A: add the following to your code pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>); // do stuff pcl::visualization::PointCloudColorHandlerRGB<pcl::PointXYZRGB> rgb(cloud); viewer.addPointCloud <pcl:PointXYZRGB> (cloud,rgb,"cloud1"); Depending on the viewpoint you have to zoom out. Hope this helps A: pcl::visualization::PCLVisualizer viewer window object has been created and you're currently looking at just the window... You would need to add .spin() viewer.spin();
Q: Regex: Stop when it finds the first ocurrence of a character So I want a regex that finds for example a sequence of letters and non-digits and stops when it founds a hyphen. Here's my regex: \D+(?=-) For example: HELLO I'M LOOKING FOR HELP- Would be: HELLO I'M LOOKING FOR HELP And my regex works fine for 1 hyphen but if I write 2 hyphens like this for example: HELLO I'M LOOKING FOR HELP-- It takes the first hyphen as a match, so the result after the regex is applied is: HELLO I'M LOOKING FOR HELP- Which is not what I want, any ideas of what I did wrong?
Q: Скорость загрузки классов Java Использую в проекте Spring и Hibernate, разные ServiceDAO, осуществляющие доступ к данным, имеют уже порядка 30 методов, мне стало интересно, стоит ли их разбивать ради повышения производительности, или кол-во методов в классе не влияет на его скорость загрузки? A: Не влияет. На скорость влияет код в методах, а не количество их в классе, т.к. код выполняется многократно, а классы загружаются один раз. Скорость загрузки байт-кода так высока что какие бы то ни было различия будут неощутимы. Выигрыша, даже незначительного, не будет в любом случае т.к. вместо одного класса с 30-ю методами будет загружено три по 10 в каждом. Более общая мысль: если решили всерьез заняться оптимизацией, то первым делом нужно измерить скорость выполнения кода, найти самые медленные места и сосредоточиться на них. Навряд ли самой медленной частью будет работа загрузчика классов. Вызовы методов, загрузка классов, JIT-компиляция, как правило, работают быстро. Запрос к БД либо обращение к сервисам займут в тысячи раз больше времени. Запуск сборщика мусора и загрузка сущности из кэша работают в сотни раз медленнее. Экономить на наносекундах можно, но в этом мало смысла когда секунды тратятся впустую. стоит ли их разбивать ради повышения производительности Не стоит. Разбивать классы стоит для организация логики и повышения удобочитаемости. P.S. «Преждевременная оптимизация — корень всех зол.» Дональд Кнут A: "Разбивать классы" следует в соответствии с архитектурными принципами, а не руководствуясь скоростью их загрузки. Если у вас 30 методов в одно классе, то вы явно нарушаете принцип единственной ответственности, как минимум.
Q: Unbound with forward zones In my network, I have a Unbound instance which works well for the global DNS. But all local requests are to be forwarded to another server (Dnsmasq) which holds the reverse and local addresses. It quite often bugs. First of all, I am not sure the status of the Dnsmasq : it is not a forward DNS : for its job, it knows the answers. But yet, it looks like unbound only accepts to work when Dnsmasq is declared as "forward". And then I think I have misconfigurated the local zones. Here is the piece of Unbound's configuration to look at : unblock-lan-zones: yes insecure-lan-zones: yes local-zone: "22decembre.eu." nodefault local-zone: "22december.dk." transparent local-zone: "10.in-addr.arpa." transparent local-zone: "d.f.ip6.arpa." transparent local-zone: "2.2.0.0.6.1.0.2.0.0.d.f.ip6.arpa." transparent private-domain: 22decembre.eu private-domain: 22december.dk domain-insecure: 22decembre.eu domain-insecure: 22december.dk domain-insecure: "10.in-addr.arpa." domain-insecure: "2.2.0.0.6.1.0.2.0.0.d.f.ip6.arpa." forward-zone: name: "10.in-addr.arpa." forward-addr: fd00:2016:22:dec::1 forward-zone: name: "22decembre.eu." forward-addr: fd00:2016:22:dec::1 forward-zone: name: "22december.dk." forward-addr: fd00:2016:22:dec::1 forward-zone: name: "2.2.0.0.6.1.0.2.0.0.d.f.ip6.arpa." forward-addr: fd00:2016:22:dec::1 When verifying conf', I get this : [1506975455] unbound-checkconf[89619:0] warning: duplicate local-zone
Q: Deleting an untyped shared_ptr I am working on wrapping a C++ library into a C bridge. All objects, I'd like to maintain with shared_ptrs on the heap like: void* makeFoo() { return new shared_ptr<void>(shared_ptr::make_shared<Foo>()); } Can I use a generic destroy like this: void destroy(void* p) { delete static_cast<shared_ptr<void>*> p; } Or is there a cleaner way? A: The type of the argument to delete must match the actual type of the thing you're deleting (otherwise how would the right destructor be invoked, for example?), or at least be a base type in a polymorphic hierarchy so the destructor can be found virtually ([expr.delete]/3). So, no, you can't do that. A: No. There is no such "generic delete". Alternative solution: You can insert the std::shared_ptr<void> into a map, using the address of the dynamic object as key. The deallocation function can erase the shared pointer from the map. A: There are a two things at play here: * *When you call new SomeType() ... then you need to call delete pointer where pointer has type SomeType * and points to the object allocated by that new expression. There are extensions to this rule with regards to base classes, but inheritance is not involved here, so we'll leave it at that. *shared_ptr<Foo> manages not only the Foo object, but also a "deleter" which knows how to destruct the Foo object. When you construct one shared_ptr from another, then that deleter gets passed on. This allows for "type erasure": shared_ptr<Foo> typed = make_shared<Foo>(); shared_ptr<void> erased = typed; Here, erased does no longer have compile time information about the type of the object it points to (that information was "erased"), but still has runtime information (the deleter) about the type of the object. So to make this work, you need to make sure that you don't violate point 1 above; you need to delete the same type which you allocated with new: a shared_ptr<void>. This shared_ptr<void> needs to be constructed from a shared_ptr<Foo> because then it has a deleter which knows how to destruct a Foo: void* makeFoo() { shared_ptr<Foo> with_type = make_shared<Foo>(); shared_ptr<void> type_erased = with_type; // Just for illustration, merge with line below! return new shared_ptr<void>(type_erased); } void destroy(void * ptr) { shared_ptr<void> * original_ptr = ptr; delete original_ptr; } makeFoo returns a pointer to a shared_ptr<void>. Just with the type info stripped, i.e. as void *. destroy assumes it is passed such a pointer. Its delete calls the destructor of shared_ptr<void>. Because the shared_ptr<void> has the deleter of the original shared_ptr<Foo>, it knows how to actually destruct the object (Foo). Side note: OP's code changed quite a few times, but still has basic syntax errors. This is not valid C++!! delete <shared_ptr<void>*> p;
Q: Can't see the headers set by Interceptors in request calls in devtools In my Angular 5 application, I'm using interceptors to set header. But when I see the HTTP request calls in devtools I can't see the header I set. Interceptor Class: export class InterceptorService implements HttpInterceptor{ intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const duplicate = req.clone({ setHeaders: { Authorization: `Bearer Lalinda` } }); return next.handle(duplicate); } constructor() { } } Capture of Devtools request : Update: app.module.ts providers: [ { provide: PERFECT_SCROLLBAR_CONFIG, useValue: DEFAULT_PERFECT_SCROLLBAR_CONFIG}, { provide: LocationStrategy, useClass: HashLocationStrategy}, AuthenticationService, LocalStorageService, { provide: HTTP_INTERCEPTORS, useClass: InterceptorService, multi: true } ], A: try this way it worked for me: const duplicate = req.clone({ headers: req.headers.set('Authorization', 'Bearer Lalinda') });
Q: .hover is causing repeated animation? I was browsing and I saw this site http://www.toybox.co.nz/ I liked the animation that happens when we hover over the image. Since it works only in chrome I decided to code it. Below is my code var len,i,hoverindex,flag=0; $(function(){ len = $(".clubsevent").length; $(".clubsevent").hoverIntent(function(){ if(flag==0){ flag=1; hoverindex= $(".clubsevent").index(this); $(".clubsevent").eq(hoverindex).css('z-index',2); for(i=0;i<len;i++){ if(i!=hoverindex){ var rand=Math.random(); var elemheight =rand*parseInt($(".clubsevent").eq(i).css('height')); var elemwidth =rand*parseInt($(".clubsevent").eq(i).css('width')); var elemleft = Math.random()*250; var elemtop = Math.random()*250; var elemopacity = Math.random()*.6; $(".clubsevent").eq(i).animate({ left:elemleft, top:elemtop, height:elemheight, width:elemwidth, opacity:elemopacity, },250); } } } },function(){ if(flag==1){ flag=0; for(i=0;i<len;i++){ var elemheight =50; var elemwidth =100; var elemleft = $(".clubsevent").eq(i).attr('left'); var elemtop = $(".clubsevent").eq(i).attr('top'); var elemopacity = 1; $(".clubsevent").eq(i).animate({ left:elemleft, top:elemtop, height:elemheight, width:elemwidth, opacity:elemopacity, },250); } } }); }) this is my css part .clubsevent{ height:50px; width: 100px; opacity:1; position: absolute; } #cepheid{ top:100px; left:100px; background: #6600FF; } #endeavour{ top:100px; left:210px; background: #FF0000; } #electronika{ top:100px; left:320px; background: #6600FF; } #e-cell{ top:100px; left:430px; background: #6600FF; } #infero{ top:160px; left:100px; background: #6600FF; } #informals{ top:160px; left:210px; background: #6600FF; } #kludge{ top:160px; left:320px; background: #6600FF; } #robotics{ top:160px; left:430px; background: #6600FF; } #torque{ top:220px; left:100px; background: #6600FF; } this is my html part <div class="clubsevent" left="100" top="100" id="cepheid"></div> <div class="clubsevent" left="210" top="100" id="endeavour"></div> <div class="clubsevent" left="320" top="100" id="electronika"></div> <div class="clubsevent" left="430" top="100" id="e-cell"></div> <div class="clubsevent" left="100" top="160" id="infero"></div> <div class="clubsevent" left="210" top="160" id="informals"></div> <div class="clubsevent" left="320" top="160" id="kludge"></div> <div class="clubsevent" left="430" top="160" id="robotics"></div> <div class="clubsevent" left="100" top="220" id="torque"></div> I am able to send all other images to random positions. But the problem is that sometimes when I hover over one element. The animation happens repeatedly.I thought that may be it happens because the other elements which were getting animated were triggering it. I added a flag, but it didn't work. A: var len,i,hoverindex,flag=0; $(function(){ len = $(".clubsevent").length; $(".clubsevent").hoverIntent(function(){ if(flag==0){ flag=1; hoverindex= $(".clubsevent").index(this); $(".clubsevent").eq(hoverindex).css('z-index',2); for(i=0;i<len;i++){ if(i!=hoverindex){ var rand=Math.random(); var elemheight =rand*parseInt($(".clubsevent").eq(i).css('height')); var elemwidth =rand*parseInt($(".clubsevent").eq(i).css('width')); var elemleft = Math.random()*250; var elemtop = Math.random()*250; var elemopacity = Math.random()*.6; $(".clubsevent").eq(i).animate({ left:elemleft, top:elemtop, height:elemheight, width:elemwidth, opacity:elemopacity, },250); } } } },function(){ if(flag==1){ flag=0; for(i=0;i<len;i++){ var elemheight =50; var elemwidth =100; var elemleft = $(".clubsevent").eq(i).attr('left'); var elemtop = $(".clubsevent").eq(i).attr('top'); var elemopacity = 1; $(".clubsevent").eq(i).stop().animate({ left:elemleft, top:elemtop, height:elemheight, width:elemwidth, opacity:elemopacity, },250); } } }); }) I've added .stop() before the animate function: http://api.jquery.com/stop/ A: Try like this, refer my answer here for same kind of question set timer/ set timeout delay in mouseenter function var flag = false; $('#ele').hover(function(){ flag = true; var that = $(this); window.setTimeout(function(){ if(flag) that.animate({...}, 500); }, 300); }, function(){ flag = false; });
Q: D3/React: Passing data to the Constructor? I am new to React and all the example code I have looked at so far shows constructor(props). I am trying to pass data ({data:{action:[action: "changed", timestamp: 12345678], ...} but I am confused because I have never seen that syntax with constructor before. class Graph extends Component { constructor({nodes}) { const times = d3.extent(nodes.action.map(action => {action.action})) const range = [50, 450] super({nodes}) this.state = {nodes, times, range} }
Q: Назначение цены для фич с приложения из ituness Я заканчиваю первый проект, настройл in-app purchase в приложений, но цены для фич нужно добавлять в iTunesConnect подскажите как реализовать данную хитрость
Q: Access webpack entry points in compiled code If I have multiple entry points defined like this entry: { home: "./home.js", about: "./about.js", contact: "./contact.js" } can I access the names of the entry points in my compiled code e.g. in home.js for generating a navigation? Or is it better in this case to generate the entry points with a function that shares the configuration with the code that will be compiled?
Q: How to push data from php to a multidimensional array I have an array variable and it will be used in a json. This is my code: $arr = array(); $data=mysql_query("SELECT * FROM t_location WHERE loca_id = '$id' ")or die(mysql_error()); while($a=mysql_fetch_array($data)){ array_push(); //what should i do { I want to push data from database to array like: $arr= array( array( "id" => "1", "name" => "London", ) ); Can anyone help me? A: $arr = array(); $data=mysql_query("SELECT * FROM t_location WHERE loca_id = '$id' ")or die(mysql_error()); while($a=mysql_fetch_array($data)){ array_push($arr,$a); {
Q: Android 10 Changing @ sign to @ when sending auth header through Ksoap2 I have a webservice that is starting to fail when calling from Android 10 because Android 10 appears to be changing the '@' to '&#64 ;' (the ascii code for the @ sign).. We have one user that has an '@' in their username, example: username@areaname On all other devices from Android 4.4 to Android 9.0, this comes through the SOAP envelope just fine, as 'username@areaname'. However, for some reason, all Android 10 devices are changing this to 'username&#64 ;areaname'. Does anyone have any idea why this is happening and how to avoid it? Here is some of the code, even though I don't think it'll help with anything.. I believe I've explained the anomaly the best that I can. request = new SoapObject(NAMESPACE, REQUEST); PropertyInfo pi = new PropertyInfo(); pi.setName("token"); pi.setValue(tokenvalue); request.addProperty(pi); envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); Element headers[] = new Element[1]; headers[0]= new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security"); headers[0].setAttribute(envelope.env, "mustUnderstand", "1"); Element security=headers[0]; Element token = new Element().createElement(security.getNamespace(), "UsernameToken"); token.setAttribute("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Id", "UsernameToken-13"); Element username = new Element().createElement(security.getNamespace(), "Username"); username.addChild(Node.TEXT, usernamevalue); token.addChild(Node.ELEMENT,username); Element password = new Element().createElement(security.getNamespace(), "Password"); password.setAttribute(null, "Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"); password.addChild(Node.TEXT, passwordvalue); token.addChild(Node.ELEMENT,password); headers[0].addChild(Node.ELEMENT, token); envelope.headerOut = headers; envelope.dotNet = false; envelope.implicitTypes = false; envelope.setOutputSoapObject(request); httpTransport = new HttpTransportSE(STALL_SOAP_URL); try{ httpTransport.call(STALL_SOAP_ACTION, envelope); }catch(Exception e){ e.printStackTrace(); }
Q: Doing NAT with multiple uplinks on Linux Currently, I have 3 NICs on a server, 1 connects to a adsl modem(eth0), another connects to a optical fiber(ppp0) and the other to a LAN(eth2). I've set up all the interfaces, routes and rules as described here (http://www.linux.org/PRIVOXY-FORCE/docs/ldp/howto/Adv-Routing-HOWTO/lartc.rpdb.multiple-links.html), and it works perfectly. I can connect externally to both hosts without any problems, but I'm facing another problem now... I can only do NAT on the host that I've set up as the default route on the main table. For example, if I use these rules: iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.2:8080 iptables -t nat -A PREROUTING -i ppp0 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.2:8080 It works depending on the default route. If the default route is via eth0, incoming connections from ppp0 do not get redirected to the LAN machine. Also, if the default route is via ppp0, connections from eth0 will not be redirected. I have a table for each provider with the gateway configured as default route, but it doesn't seem to work for NAT. Does anyone have an idea to fix this issue? A: The "default route" is meaningless if you have setup your routes with "ip route" correctly. The difficulty comes from the fact that both eth0 and ppp0 are likely to be setup by DHCP, which will overwrite whatever you had setup. You should give the output of "ip route show" for all the tables you have setup, as well as "ip rule show" and anything else you've done during setup. BTW, the link you posted did not work for me, this one does A: I have done this using CONNMARK, firewall marking, and multiple routing tables. Works great even for PPP and DHCP interfaces.
Q: Latest compiler versions and GLIBC_2.32 dependency * *When I compile my library with GCC 11 or Clang 12 I get a GLIBC_2.32 dependency. *When I compile the same library with the same arguments but with older version compilers (GCC 10, Clang 11) I don't get the GLIBC_2.32 dependency. Is there a way to get rid of this dependency on newer versions of compilers? readelf -s mylib.so | grep GLIBC 4: 00000000 0 FUNC WEAK DEFAULT UND [...]@GLIBC_2.1.3 (2) 5: 00000000 0 FUNC GLOBAL DEFAULT UND sn[...]@GLIBC_2.0 (3) 6: 00000000 0 FUNC GLOBAL DEFAULT UND strlen@GLIBC_2.0 (3) 7: 00000000 0 FUNC GLOBAL DEFAULT UND getcwd@GLIBC_2.0 (3) 8: 00000000 0 FUNC GLOBAL DEFAULT UND dlopen@GLIBC_2.1 (4) 9: 00000000 0 FUNC GLOBAL DEFAULT UND strcmp@GLIBC_2.0 (3) 10: 00000000 0 FUNC GLOBAL DEFAULT UND dlsym@GLIBC_2.0 (5) 11: 00000000 0 FUNC GLOBAL DEFAULT UND st[...]@GLIBC_2.0 (3) 12: 00000000 0 FUNC GLOBAL DEFAULT UND fopen@GLIBC_2.1 (6) 13: 00000000 0 FUNC GLOBAL DEFAULT UND fgets@GLIBC_2.0 (3) 14: 00000000 0 FUNC GLOBAL DEFAULT UND fclose@GLIBC_2.1 (6) 15: 00000000 0 FUNC GLOBAL DEFAULT UND isspace@GLIBC_2.0 (3) 16: 00000000 0 FUNC GLOBAL DEFAULT UND memchr@GLIBC_2.0 (3) 17: 00000000 0 FUNC GLOBAL DEFAULT UND printf@GLIBC_2.0 (3) 18: 00000000 0 FUNC GLOBAL DEFAULT UND puts@GLIBC_2.0 (3) 19: 00000000 0 FUNC GLOBAL DEFAULT UND bcmp@GLIBC_2.0 (3) 20: 00000000 0 FUNC GLOBAL DEFAULT UND __[...]@GLIBC_2.0 (3) 21: 00000000 0 FUNC GLOBAL DEFAULT UND strtol@GLIBC_2.0 (3) 22: 00000000 0 FUNC GLOBAL DEFAULT UND abort@GLIBC_2.0 (3) 23: 00000000 0 OBJECT GLOBAL DEFAULT UND _[...]@GLIBC_2.32 (7) << WHAT IS THIS? 24: 00000000 0 FUNC GLOBAL DEFAULT UND sprintf@GLIBC_2.0 (3) 25: 00000000 0 FUNC GLOBAL DEFAULT UND strncmp@GLIBC_2.0 (3) 26: 00000000 0 FUNC GLOBAL DEFAULT UND gettext@GLIBC_2.0 (3) 27: 00000000 0 FUNC GLOBAL DEFAULT UND __[...]@GLIBC_2.4 (8) 28: 00000000 0 FUNC WEAK DEFAULT UND pt[...]@GLIBC_2.0 (3) 29: 00000000 0 FUNC GLOBAL DEFAULT UND realloc@GLIBC_2.0 (3) 30: 00000000 0 FUNC GLOBAL DEFAULT UND memset@GLIBC_2.0 (3) 31: 00000000 0 FUNC GLOBAL DEFAULT UND read@GLIBC_2.0 (3) 32: 00000000 0 FUNC GLOBAL DEFAULT UND memcmp@GLIBC_2.0 (3) 34: 00000000 0 FUNC WEAK DEFAULT UND pt[...]@GLIBC_2.0 (3) 35: 00000000 0 FUNC GLOBAL DEFAULT UND fputc@GLIBC_2.0 (3) 36: 00000000 0 FUNC GLOBAL DEFAULT UND fputs@GLIBC_2.0 (3) 37: 00000000 0 FUNC GLOBAL DEFAULT UND memcpy@GLIBC_2.0 (3) 38: 00000000 0 FUNC GLOBAL DEFAULT UND malloc@GLIBC_2.0 (3) 39: 00000000 0 OBJECT GLOBAL DEFAULT UND stderr@GLIBC_2.0 (3) 40: 00000000 0 FUNC GLOBAL DEFAULT UND ioctl@GLIBC_2.0 (3) 41: 00000000 0 FUNC GLOBAL DEFAULT UND fwrite@GLIBC_2.0 (3) 42: 00000000 0 FUNC GLOBAL DEFAULT UND close@GLIBC_2.0 (3) 43: 00000000 0 FUNC GLOBAL DEFAULT UND open@GLIBC_2.0 (3) 44: 00000000 0 FUNC GLOBAL DEFAULT UND syscall@GLIBC_2.0 (3) 45: 00000000 0 FUNC GLOBAL DEFAULT UND memmove@GLIBC_2.0 (3) 46: 00000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.0 (3) 47: 00000000 0 FUNC GLOBAL DEFAULT UND _[...]@GLIBC_2.3 (10)
Q: How to read the header content of a webpage in Django? I created a search engine in Django and bs4 that scrapes search results from the Ask.com search engine. I would like when Django fetches search results from Ask, it checks the value of the X-Frame-Options header in order to give a value to my notAccept boolean depending on the result of the condition. I took inspiration from this page of the Django documentation and also from this other page and after testing a proposed answer, I modified my code like this: for result in result_listings: result_title = result.find(class_='PartialSearchResults-item-title').text result_url = result.find('a').get('href') result_desc = result.find(class_='PartialSearchResults-item-abstract').text res = requests.get(result_url) #for header in final_result[1]: response = res.headers['content-type':'X-Frame-Options'] #the error is generated here if response in ["DENY", "SAMEORIGIN"]: head = True notAccept = bool(head) But when I test, I get in the terminal the following errors: Internal Server Error: /search Traceback (most recent call last): File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\Documents\AAprojects\Whelpsgroups1\searchEngine\search\views.py", line 32, in search response = res.headers['content-type':'X-Frame-Options'] File "C:\Python310\lib\site-packages\requests\structures.py", line 54, in __getitem__ return self._store[key.lower()][1] AttributeError: 'slice' object has no attribute 'lower' [26/Sep/2022 22:57:24] "GET /search?csrfmiddlewaretoken=1m8mRf9JWoHvzps2AemMyA7Wlb76PVzQ5UzuEtfH1p3PzwmZfqLlBHTkCvIDlot6&search=moto HTTP/1.1" 500 93598 This error is related to the following line as specified in the code. response = res.headers['content-type':'X-Frame-Options'] #the error is generated here I modified this line like this: response = res.headers['X-Frame-Options'] but now I obtain the following errors: Traceback (most recent call last): File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\Documents\AAprojects\Whelpsgroups1\searchEngine\search\views.py", line 32, in search response = res.headers['X-Frame-Options'] #the error is generated here File "C:\Python310\lib\site-packages\requests\structures.py", line 54, in __getitem__ return self._store[key.lower()][1] KeyError: 'x-frame-options' I looked on this page to find a solution but I can't find much. I don't know how to solve this problem. I'm not very good with handling headers I must admit. Thank you! A: This is more of a Python Requests issue than Django.. from my limited knowledge I don't believe you can get header information of pages just by looking at the Links. You need to actually send a GET request because it's in the Header of the request: for l in links: response = requests.get(l) if response['X-Frame-Options'] in ["DENY", "SAMEORIGIN"]: head = True notAccept = bool(head) else: notAccept = bool(False) I was unable to find anything about CSP_FRAME_ANCESTORS tho.. Hopefully you can find some of this useful.. at the very least now you know to search python requests {x} on the topic Edit I'll explain the error that you've added, invalid Index: # Final Result is an Array Filled with Tuples # OR just think of it as an Array filled with Arrays # --- # This would be the result on the first loop: final_result = [ (result_title0, result_url0, result_desc0), # index 0 ] # You used: final_result[1] # => Undefined # Correct Way: # --- # Grab first item in Array: final_result[0] # => (result_title0, result_url0, result_desc0) # Grab first item in Array + and then 2nd item in list: final_result[0][1] # => result_url0 # Next Issue # --- # But you will run into this issue / always grabbing the first item final_result = [ (result_title0, result_url0, result_desc0), # index 0 (result_title1, result_url1, result_desc1), # index 1 ] final_result[0][1] # => result_url0 **Wrong!** # -1 should be used instead // (Last Item in list) final_result[-1][1] # => result_url1 **Correct!** # ^ Actual solution # --- But because you already have result_url as a variable in the loop you might has well use it in the GET instead of trying to fetch it from that Nested Array for result in result_listings: result_title = result.find(class_='PartialSearchResults-item-title').text result_url = result.find('a').get('href') result_desc = result.find(class_='PartialSearchResults-item-abstract').text final_result.append((result_title, result_url, result_desc)) # Ping URL found here: result.find('a').get('href') response = requests.get(result_url) # Check for header information in the response if response['X-Frame-Options'] in ["DENY", "SAMEORIGIN"]: # head = True notAccept = True else: notAccept = False and you might as well wait until the very end to add that tuple to the final_result list- maybe even use a dictonary Wait until end for result in result_listings: result_title = result.find(class_='PartialSearchResults-item-title').text result_url = result.find('a').get('href') result_desc = result.find(class_='PartialSearchResults-item-abstract').text # Ping URL found here: result.find('a').get('href') response = requests.get(result_url) # Check for header information in the response if response['X-Frame-Options'] in ["DENY", "SAMEORIGIN"]: # head = True notAccept = True else: notAccept = False # Add here! Last second. final_result.append((result_title, result_url, result_desc, notAccept)) Wait until end + Dict for result in result_listings: result_title = result.find(class_='PartialSearchResults-item-title').text result_url = result.find('a').get('href') result_desc = result.find(class_='PartialSearchResults-item-abstract').text # Ping URL found here: result.find('a').get('href') response = requests.get(result_url) # Check for header information in the response if response['X-Frame-Options'] in ["DENY", "SAMEORIGIN"]: # head = True notAccept = True else: notAccept = False # Dict makes Code a little more readable last on when you use this data final_result.append({ 'title':result_title, 'url': result_url, 'desc': result_desc, 'x-frame': notAccept }) Edit 2 So the error you are getting KeyError: 'x-frame-options' and that means x-frame-options isn't in the header. The res.header is a dictionary like: * *do print(res.header) and you can see it yourself. res.header = { 'content-encoding': 'gzip', 'transfer-encoding': 'chunked', 'connection': 'close', 'server': 'nginx/1.0.4', 'x-runtime': '148ms', 'etag': '"e1ca502697e5c9317743dc078f67693f"', 'content-type': 'application/json' } ## Your error, an explanation: print(res.header.keys()) # ['content-encoding' 'transfer-encoding', 'connection', 'server', 'x-runtime', 'etag', 'content-type',] print('x-frame-options' in re.header.keys()) # False res.header['x-frame-options'] # KeyError: Key doesn't exist! If you try to fetch a Key that isn't in the Dictionary, you'll get a KeyError Here's some Potential things you can do: (it depends on your end goal) 1, see if x-frame-options is in header (Return True or False) has_x_frame_options = ('x-frame-options' in res.header.keys()) print(type(has_x_frame_options), has_x_frame_options) # Bool, (True or False) 2, get Value of x-frame-options if it's in the header, else be false if 'x-frame-options' in res.header.keys(): x_frame_options = res.header['x-frame-options'] else: x_frame_options = False print(type(x_frame_options), x_frame_options) # will be: # String, '{some_string}' # Bool, False # Condensed like: x_frame_options = res.header['x-frame-options'] if 'x-frame-options' in res.header.keys() else False
Q: How can I compile fragment and AppCompatActivity in Java? I am a beginner in coding and I am making an app for a school project. I made a drawer menu using the Android fragment, but now I want to include features under AppCompatActivity in Java class. I cannot compile the fragment with the AppCompatActivity in the Java class. Please see the code below: public class ProfileFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_about, container, false); } public class about extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_about); } A: Hello @aviraj Welcome to the Stackoverflow. See basically, In order to compile any class which extends Fragment,AppCompatActivity you also need to map these core classes to Android SDK. If you will just going to put them out in simple text file, it will not going to get the implementation of Fragment,AppCompatActivity from JRE/JDK. Hence, it will not be compile. Suggest you to go through the basics of Android Development from developer.android.com and you will find step by step guidance about building process of Android App. Hope it will help.
Q: Getting Websocket Failure when trying to anonymously authenticate user using AngularFire I am trying to anonymously authenticate users using AngularFire. I want to authenticate a user only once (so, if the user has already been authenticated, a new uid won't be generated). When I use the code below, I get a previous_websocket_failure notification. I also get an error in the console that says TypeError: Cannot read property 'uid' of null. When the page is refreshed, everything works fine. Any thoughts on what I'm doing wrong here? app.factory('Ref', ['$window', 'fbURL', function($window, fbURL) { 'use strict'; return new Firebase(fbURL); }]); app.service('Auth', ['$q', '$firebaseAuth', 'Ref', function ($q, $firebaseAuth, Ref) { var auth = $firebaseAuth(Ref); var authData = Ref.getAuth(); console.log(authData); if (authData) { console.log('already logged in with ' + authData.uid); } else { auth.$authAnonymously({rememberMe: true}).then(function() { console.log('authenticated'); }).catch(function(error) { console.log('error'); }); } }]); app.factory('Projects', ['$firebaseArray', '$q', 'fbURL', 'Auth', 'Ref', function($firebaseArray, $q, fbURL, Auth, Ref) { var authData = Ref.getAuth(); var ref = new Firebase(fbURL + '/projects/' + authData.uid); console.log('authData.uid: ' + authData.uid); return $firebaseArray(ref); }]); A: In your Projects factory, you have assumed authData will not be null. There are no guarantees here, since your Projects factory is initialized as soon as you inject it into another provider. I also noticed that your Auth service doesn't actually return anything. This probably means that the caller has to know the internal workings and leads to quite a bit of coupling. A more SOLID structure would probably be as follows: app.factory('Projects', function(Ref, $firebaseArray) { // return a function which can be invoked once // auth is resolved return function(uid) { return $firebaseArray(Ref.child('projects').child(uid)); } }); app.factory('Auth', function(Ref, $firebaseAuth) { return $firebaseAuth(Ref); }); app.controller('Example', function($scope, Auth, Projects) { if( Auth.$getAuth() === null ) { auth.$authAnonymously({rememberMe: true}).then(init) .catch(function(error) { console.log('error'); }); } else { init(Auth.$getAuth()); } function init(authData) { // when auth resolves, add projects to the scope $scope.projects = Projects(authData.uid); } }); Note that dealing with auth in your controllers and services should generally be discouraged and dealing with this at the router level is a more elegant solution. I'd highly recommend investing in this approach. Check out angularFire-seed for some example code.
Q: Canvas highlight squares on mouse move I have a canvas with many grids on it and a text will be shown on it. I need to have user interaction with the canvas also. I want to highlight the corresponding squares when the user drags his mouse over the canvas or clicks on it. I am not able to select the grid which I am supposed to highlight using Javascript. Posting the entire code - fiddle-link I tried this, but it is not working. $('.canvasld').mousedown(function(e){ let x = e.clientX - $('.canvasld').offsetLeft, y = e.clientY - $('.canvasld').offsetTop, col = Math.floor(x /6), row = Math.floor(y /6); context.rect(x, y, 5, 5); //pixel['enabled'] = true; context.fillStyle = canvasConfig.options.enabledPixelColor; context.fill(); }); A: The jsfiddle you linked has several problems: First, your x and y values are NaN, since $('.canvasld').offsetLeft) is undefined. In JQuery, there is not offsetLeft property on a query. You can use the JQuery .offset() method, which returns an object that has the properties left and right. Second, your context and canvasConfig are both undefined. Here's a snippet of the code in question with those issues corrected. I used your defaults object in place of the canvasConfig, which didn't exist: // revised mousedown code $('.canvasld').mousedown(function(e) { // small square size let squareSize = (defaults.pixelSize / 2); // get the x and y of the mouse let x = e.clientX - $('.canvasld').offset().left; let y = e.clientY - $('.canvasld').offset().top; // get the grid coordinates let col = Math.floor(x / squareSize); let row = Math.floor(y / squareSize); // get the canvas context let context = $('.canvasld')[0].getContext('2d'); // check if the square falls into the smaller grid if(col > 0 && row > 0 && col % 2 > 0 && row % 2 > 0) { // draw the rectangle, converting the grid coordinates back // into pixel coordinates context.rect(col * squareSize, row * squareSize, squareSize, squareSize); context.fillStyle = defaults.enabledPixelColor; context.fill(); } }); Hope I could help! :-)
Q: Serial port does not work in rewritten Python code I have a Python program that reads some parameters from an Arduino and stores it in a database. The serial port is set up and used like this: ser = serial.Serial(port=port, baudrate=9600) ser.write('*') while 1 : ser.write('*') out = '' # Let's wait one second before reading output (let's give device time to answer). time.sleep(1) while ser.inWaiting() > 0: out += ser.read(1) if out != '': etc ... handling data (The Arduino is set up so when it receives a star, it sends back a data string.) I would like to rewrite this as a daemon, so I am using the python-daemon library. In the init-part, I just define the port name, and then: def run(self): self.ser = serial.Serial(port=self.port,baudrate=9600) while True: self.ser.write('*') out = '' # Let's wait one second before reading output (give device time to answer). time.sleep(1) while self.ser.inWaiting() > 0: out += self.ser.read(1) if out != '': etc ... Everything is equal, except that I am now doing the serial handling within an App-object. The first version runs fine, when I try to run the latter, I get File "storedaemon.py", line 89, in run while self.ser.inWaiting() > 0: File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 435, in inWaiting s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str) IOError: [Errno 9] Bad file descriptor I am not able to see what has changed - except that I have tossed the code inside a new object. I have tried both to do the initialisation in init and in run, but I end up with the same result. (The complete scripts are available at hhv3.sickel.net/b/storedata.py and hhv3.sickel.net/b/storedaemon.py.) A: During the daemonization of your app, all file handlers are closed except stdin, stderr and stdout. This includes the connection to /dev/log, which then fails with the fd error (so it looks like this has nothing to do with the serial fd, but instead with the handler's socket). You need either to add this FD to the exclusion list: class App(): def __init__(self): ... self.files_preserve = [handler.socket] ... Or alternatively, set up the handler after the daemon process forked: class App(): def run(self): handler = logging.handlers.SysLogHandler(address = '/dev/log') my_logger.addHandler(handler) my_logger.debug(appname+': Starting up storedata') ... Both version ran fine during my tests.
Q: Fated to earn money (simple algebra used but may require other things) I posted this on puzzling stack exchange before I flagged it to delete it because I think it may be a pure mathematics question (it might take awhile before it's closed on puzzling stack exchange though). I also think the people here may be more inclined to answer this question. https://puzzling.stackexchange.com/questions/87949/fated-to-earn-money Here is my problem: Joe has investments in Company A, Company B, and Company C. Joe is fated to earn $25.00 from Company A within 2 days from now. Joe is fated to earn $45.00 from Company B within 3 days from now. Joe is fated to earn $100.00 from Company C within 5 days from now. Joe is fated to earn no more than $26.00 from Company C and Company B on day 1 (1 day from now). Joe is fated to earn at least $14.00 from Company A and Company C on day 2 (2 days from now). Joe has to earn twice the amount of money on the first day than the second day from Companies A, B, and C and twice the amount of money on the second day than the third day from Companies A, B, and C. This can be expressed algebraically as Joe earning x money on day 3 (3 days from now), 2x money on day 2 (2 days from now), and 4x money on day 1 (1 day from now). Joe can earn whatever amount of money (that satisfies the other conditions) from Companies A, B, and C on day 4 and day 5 (4 and 5 days from now). What is the lowest amount of money Joe can earn on day 1 (1 day from now) from Companies A, B, and C? Explain your reasoning. P.S. How come there doesn't seem to be good formulas to use for this question? Edit: I do know the answer to this question, but I have no idea why. If you can explain your reasoning, that would be great! Hint: You won't have to calculate in cents for this question.
Q: Two versions of php in El Capitan. How do I get rid of one or upgrade the other? In terminal, php -v gives PHP 5.3.29 (cli) (built: Sep 28 2015 06:33:13) (with imagick installed) but, in the browser (using apache) phpinfo(); gives PHP Version 5.5.27 (with no imagick installed) How do I resolve this? I don't want to mess about with php.ini and httpd.conf when I'm not entirely sure what I'm doing! A: Solved it. I entered locate libphp5.so into terminal to find paths to the php installations. This outputted /usr/libexec/apache2/libphp5.so /usr/local/Cellar/php53/5.3.29_4/libexec/apache2/libphp5.so I then edited the apache configuration file sudo nano /private/etc/apache2/httpd.conf and changed LoadModule php5_module libexec/apache2/libphp5.so to LoadModule php5_module /usr/local/Cellar/php53/5.3.29_4/libexec/apache2/libphp5.so NOTE : This line will be different for your local installation, copy the value outputted from the locate command above I then restarted apache with: sudo apachectl graceful Credit to this solution for the command to find the php installations A: This may be a help to you : Upgrade to PHP 5.4 on MAC and remove version 5.3.10 I would suggest that you work in a virtual setup instead. like Vagrant: https://www.vagrantup.com/ Also take a look at Homestead: http://laravel.com/docs/4.2/homestead "Laravel Homestead is an official, pre-packaged Vagrant "box" that provides you a wonderful development environment without requiring you to install PHP, HHVM, a web server, and any other server software on your local machine. " It will also allow you to keep your configuration if you change machine and/or operating system.
Q: Check if element is contained on an unequal element of different length Im trying to find if part of a character vector overlaps part of another character vector x <- c("OCT/NOV/DEC", "JAN/DEC/AUG") y <- c("JAN/FEB/MAR", "APR/MAY/JUN", "JUL/AUG/SEP") # Months should be split into separate characters So I would use: list_x <- strsplit(x, '/') list_x #> [[1]] #> [1] "OCT" "NOV" "DEC" #> #> [[2]] #> [1] "JAN" "DEC" "AUG" list_y <- strsplit(y, '/') list_y #> [[1]] #> [1] "JAN" "FEB" "MAR" #> #> [[2]] #> [1] "APR" "MAY" "JUN" #> #> [[3]] #> [1] "JUL" "AUG" "SEP" As we can see, list_x[[1]] has no elements located in any of list_y, so a FALSE should return; list_x[[2]] has "JAN" and "AUG", which are located in list_y[[1]] and list_y[[3]], so a TRUE should return # The response should be c(FALSE, TRUE) # for each of x elements # I tried: detect <- function(x, y){ mapply(function(x, y) any(x %in% y), strsplit(x, '/'), strsplit(y, '/')) } detect(x,y) # Which gives a warning stating the lengths are not multiple and: #> [1] FALSE FALSE FALSE So how can I tell if there are x elements that are also in y elements? Edit: After Akrun's response, I tried a more complex approach envolving non-equi joins detect <- function(a,b){ sapply(str_split(a, '/'), function(x) any(sapply(str_split(b, '/'), function(y) any(x %in% y)))) } a <- tibble(a1 = c("A/B/C", "F/E/G"), b1 = c(1,2), c1 = c("OCT/NOV/DEC", "JAN/DEC/AUG")) b <- tibble(a2 = c("A/B/C", "D/E/F", "G/H/I"), b2 = c(1,2,3), c2 = c("JAN/FEB/MAR", "APR/MAY/JUN", "JUL/AUG/SEP")) fuzzyjoin::fuzzy_left_join(a, b, by = c("a1" = "a2", "b1" = "b2", "c1" = "c2"), match_fun = list(detect, `==`, detect)) ## Wrong Result: #> a1 b1 c1 a2 b2 c2 #> <chr> <int> <chr> <chr> <int> <chr> #> 1 A/B/C 1 OCT/NOV/DEC NA NA NA #> 2 F/E/G 2 JAN/DEC/AUG D/E/F 2 APR/MAY/JUN # Row 2: Although a1 and a2 have matching characters and b1 matches b2, c1 and c2 have no matching characters, so the join shouldn't be possible ## Expected: #> a1 b1 c1 a2 b2 c2 #> <chr> <int> <chr> <chr> <int> <chr> #> 1 A/B/C 1 OCT/NOV/DEC NA NA NA #> 2 F/E/G 2 JAN/DEC/AUG NA NA NA Maybe I'm misinterpreting something in this function? A: We could use a nested sapply with any sapply(list_x, function(x) any(sapply(list_y, function(y) any(x %in% y)))) #[1] FALSE TRUE For the updated data, if we change the any with all, it would give the expected output detect <- function(a,b){ sapply(str_split(a, '/'), function(x) all(sapply(str_split(b, '/'), function(y) any(x %in% y)))) } fuzzyjoin::fuzzy_left_join(a, b, by = c("a1" = "a2", "b1" = "b2", "c1" = "c2"), match_fun = list(detect, `==`, detect)) # A tibble: 2 x 6 # a1 b1 c1 a2 b2 c2 # <chr> <dbl> <chr> <chr> <dbl> <chr> #1 A/B/C 1 OCT/NOV/DEC <NA> NA <NA> #2 F/E/G 2 JAN/DEC/AUG <NA> NA <NA>
Q: Is the hypothesis of $G$ being a finite group necessary in this exercise? I've been trying to solve an exercise for my Algebra class and even found this question asked already: Suppose $H$ is the only subgroup of order $o(H)$ in the finite group $G$. Prove that $H$ is a normal subgroup of $G$. Although, is the finiteness hypothesis a must for this exercise? A: Suppose $H$ is the only subgroup of $G$ of order $|H|$. Fix an element $g \in G$ and let $K = gHg^{-1}$. Take $a,b \in K$. There exist $a' , b' \in H$ such that $a = ga'g^{-1}$ and $b = gb'g^{-1}$. Thus $$ ab = ga'g^{-1} gb' g^{-1} = ga'b'g^{-1} $$ which is an element of $K$ since $a'b' \in H$. Moreover, $e \in H$ since $H$ is a subgroup, so $$ e = geg^{-1} \in K $$ Thus, we have shown $K \leq G$. Now, consider the maps \begin{align} f &: H \to K \\ &h \mapsto ghg^{-1} \\ g &: K \to H\\ &k \mapsto g^{-1}k g \end{align} I leave it to you to check that $g = f^{-1}$, which shows that $|H| = |K|$. By assumption, this means $H = K = gHg^{-1}$. Since $g \in G$ was arbitrary, this proves that $H$ is a normal subgroup of $G$. Notice that nowhere did we need to assume that $G$ was finite.
Q: add blank attribute in magento backend and use php to calculate the value i have added a new atribute called frontend_price in magento's backend in the manage product selection. In the value of this attribute would like to get the product's price and multiply it with the Vat tax and the currency. Nothing fancy just to se the product's frontend price in the backend, but not stored into any table of the db. This attribute is for internal porpose only, so it does not have to be visible in the frontend. i was thinking of : Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_FRONTEND,Mage_Core_Model_App_Area::PART_EVENTS); $currencyrate = Mage::app()->getStore()->getCurrentCurrencyRate(); $price_normal = $_product->getPrice(); $_product->getResource()->getAttribute('frontend_price')->getFrontend()->getValue($_product) = $price_normal*$currencyrate*1.24; Unfortunatly i don't know where to implement this code to see it in the backend. Any ideea where to edit the page for the backend product selection page. Thank you.
Q: Tracking function instances OK so is there a way in php do track function calls such as function Tracker($name,$returnedValue,$file,$line) { echo $name . '() was called and returned a ' . typeof(returnedValue); } function test(){} test(); The reason for this is to send a custom framework data type back so another example would be $resource = fopen('php://stdin'); //This would return an instance of (Object)Resource. if($resource->type == 'fopen') { //Code } I have never seen anyway to do this but does anyone know if it is possible ? A: It's not possible to do this using just PHP, a debugger might help, however you could wrap the function: function wrapper() { $args=func_get_args(); $function=array_shift($args); $returned=call_user_func_array($function, $args); print "$function (" . var_export($args, true) . ") = " . var_export($returned, true) . "\n"; return $returned; } $value=wrapper('test_fn', 1 ,2 ,3, 'something'); $value=wrapper('mysql_connect'); I don't understand your explanation of what you are trying to achieve here. C. A: Not really. Xdebug is able to log function calls though: http://xdebug.org/docs/execution_trace A: Maybe you want something like Observer pattern? http://en.wikipedia.org/wiki/Observer_pattern
Q: Jquery form validation - telephone number I have setup jQuery validation on form, The validation currently tests that the telephone number field isn't empty and is a number, but I'd like it to be able to handle a user placing a space after the mobile/area code. Can anyone advise what i'd need to do to allow this? This is my current code - if((phone.length == 0) || (names == 'Please Enter Your Contact Number (no space)')){ var error = true; $('.error').fadeIn(500); $('.pStar').fadeIn(500); }else{ var value = $('#phone').val().replace(/^\s\s*/, '').replace(/\s\s*$/, ''); var intRegex = /^\d+$/; if(!intRegex.test(value)) { var error = true; $('.error').fadeIn(500); $('.pStar').fadeIn(500); } else{ $('.pStar').fadeOut(500); } } A: I would highly recommend using jQuery validate rather than re-inventing the wheel a quick google search for uk numbers with jquery validate turned this up filters that looks like this jQuery.validator.addMethod('phoneUK', function(phone_number, element) { return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(\(?(0|\+44)[1-9]{1}\d{1,4}?\)?\s?\d{3,4}\s?\d{3,4})$/); }, 'Please specify a valid phone number' ); A: Use this regex to validate phone numbers. var pattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/; if(!$('#phone').val().test(elementValue)){ //Invalid number } This regex will optionally accept starting ( or ending ) for area code and will optionally accept - after first 3 digits after area code.
Q: WPF Regex special character '&' incorrect syntax In my WPF application I want to validate email with this conditions. The local part can be up to 64 characters in length and consist of any combination of alphabetic characters, digits, or any of the following special characters: ! # $ % & ' * + – / = ? ^ _ ` . { | } ~. My Regex is [a-zA-Z0-9!#$%'*+–=?^_`.{|}~/&]{1,64}@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4} But when i use '&' character it shows the following error Expected the following token: ";". A: I have found my solution. I had to use & and My final Regex is [^.][a-zA-Z0-9!#$%'*+=?^_`.{|}~-/&]{1,64}@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}
Q: What is this battery connector called? We received a product with this high-current battery connector, but don't know where to get the matching other half for it. Does anyone know what this connector is called? A: That looks like an Amass connector, especially because it uses an "anti-spark" pin (black tipped pin), which is a feature exclusive to Amass. It's an extension of the "XT" type connector for high-current battery power in consumer products such as drones (such as the XT30, XT60, XT90). https://china-amass.en.china.cn/ https://china-amass.en.alibaba.com/productgrouplist-813801759/MR_series.html?spm=a2700.icbuShop.88.26.448513d1gsJGbs http://www.china-amass.com/product/index EDIT: Found it! AS150U http://www.china-amass.com/product/contain/iW154529aUC817m6
Q: how to pass parameters to implementation of HttpServer? I have implemented com.sun.net.httpserver.HttpServer: HttpServer server = HttpServer.create(new InetSocketAddress(8001), 0); server.createContext("/myserver", new myHttpHandler()); server.createContext("/myserver/get", new GetHttpHandler()); I want to pass parameters to /myserver/get with the following url: http://localhost:8000/myserver/get?deviceid=ABB00122 static class GetHttpHandler implements HttpHandler { public void handle(HttpExchange exchange) throws IOException { // how do I now access the deviceid? } } How do I access the parameter deviceid I sent with my url in the handle method? A: The HttpServer class is very simple. If you want to access parameters passed in the URL (using the GET method) then you need to provide a method to extract them. you get the full URL from: httpExchange.getRequestURI().getQuery() and then from this String you can get the details. see http://www.rgagnon.com/javadetails/java-get-url-parameters-using-jdk-http-server.html for additional information. A: I haven't used this type but it seems from the HttpExchange doc that attributes are not request parameters. The information is likely accessible via the getQueryString() method.
Q: Best Practice when trying to conditionally render a styled component inside or outside of wrapper based on screen width I have this code. I am trying to figure how best to have the code conditionally put inside our outside of the wrapper. But I am not sure what is the best practice for this. But that seems a little undry. Is there a better practice than this? Thanks! But that seems A: In render, store the JSX of the thing you need to move around in a variable and then use that in the same way you did in the last method you mentioned. const overlay = ( <CTAButton colorStyle={el.ctaColor === "green" ? "green" : "black"} href={el?.cta?.link} > {el?.cta?.text} </CTAButton> ); // ... return ( <> <Styled.OverlayWrapper> {el.headline && ( <Styled.HeroHeadline as="h4">{parse(el.headline)}</Styled.HeroHeadline> )} {screenWidth <= 600 && overlay} </Styled.OverlayWrapper> {screenWidth >= 601 && overlay} </> ); Though I should add, usually with this sort of thing, it can be solved with CSS breakpoints without DOM changes needed -- which is preferable. But that'd be an entirely different question. Notably it can't always be solved that way depending on the circumstances of the desired layout. The above could be fine in your use case.
Q: Running a loop on multiple xml files in one folder in R I am trying to run this script as a loop function as I have over 200 files in a folder and I am trying to produce one CSV file at the end listing all of the data that I need to extract. I have tried various ways of running this in a loop e.g. In R, how to extracting two values from XML file, looping over 5603 files and write to table Whenever I do try these different options I get errors like: Error: XML content does not seem to be XML or permission denied. However, when I run the code selecting just one file it runs fine. These errors only seems to occur when I try convert it into a loop function for multiple files in a single folder. Here is the original code used for a single file: doc<-xmlParse("//file/path/32460004.xml") xmldf <- xmlToDataFrame(nodes = getNodeSet(doc, "//BatRecord")) df1 <- data.frame(xmldf) df1 <- separate(df1, xmldf.DateTime, into = c("Date", "Time"), sep = " ") df1$Lat <- substr(xmldf$GPS,4,12) df1$Long <- substr(xmldf$GPS,13,25) df_final <- data.frame(df1$xmldf.Filename, df1$Date, df1$Time, df1$xmldf.Duration, df1$xmldf.Temperature, df1$Lat, df1$Long) colnames(df_final) <- c("Filename", "Date", "Time", "Call Duration", "Temperature", "Lat", "Long") write.csv(df_final, "//file/path/test_file.csv") Here is a link to some example files: https://drive.google.com/drive/folders/1ZvmOEWhzlWHRl2GxZrbYY9y7YSZ5j9Fj?usp=sharing Any help is appreciated. Here is my version details: platform x86_64-w64-mingw32 arch x86_64 os mingw32 system x86_64, mingw32 status major 3 minor 6.3 year 2020 month 02 day 29 svn rev 77875 language R version.string R version 3.6.3 (2020-02-29) nickname Holding the Windsock A: This should work using tidyverse and xml2. require(tidyverse) require(xml2) ### Put all your xml files in a vector my_files <- list.files("path/to/your/xml/files", full.names = TRUE) ### Read function to transform them to tibble (similar to data.frame) read_my_xml <- function(x, path = "//BatRecord") { tmp <- read_xml(x) # read the xml file tmp <- tmp %>% xml_find_first(path) %>% # select the //BatRecord node xml_children # select all children of that node # this extracts the text of all children # aka the text between the > TEXT </ Tags out <- tmp %>% xml_text # Takes the names of the tags <NAME> ... </NAME> names(out) <- tmp %>% xml_name # Turns out to tibble - see https://stackoverflow.com/q/40036207/3301344 bind_rows(out) } ### Read the files as data dat <- map_df(my_files, read_my_xml) # map_df is similar to a loop + binding it to one tibble ### To the transformation dat %>% separate(DateTime, into = c("Date", "Time"), sep = " ") %>% mutate(Lat = substr(GPS,4,12), Long = substr(GPS,13,25)) %>% write_csv("wherever/you/want/file.txt")
Q: (Java) User selection of JTable row I have a JTable that lists customer information returned from an SQL query. How do I set up the table so the user can select one row, by perhaps double clicking or ticking a check box, and then JTextField is filled in with the chosen customer name? A: Here a sample code to go fwd public class PersonTable { JTable table; public PersonTable() { final MyTableModel myTableModel = new MyTableModel(); myTableModel.fill(); table = new JTable(myTableModel); JFrame frame = new JFrame("Persons"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JPanel panel = new JPanel(); JPanel panel1 = new JPanel(); final JTextField t1 = new JTextField(10); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { int selectedRow = table.getSelectedRow(); Object valueAt = myTableModel.getValueAt(selectedRow, 0); t1.setText((String) valueAt); } }); panel1.add(new JLabel("Name"), BorderLayout.EAST); panel1.add(t1, BorderLayout.WEST); panel.add(new JScrollPane(table), BorderLayout.NORTH); panel.add(panel1, BorderLayout.SOUTH); frame.add(panel); frame.pack(); frame.setVisible(true); } public class MyTableModel extends AbstractTableModel { String[] columnName = new String[]{"Customer Name", "Phone Number", "Area"}; String[][] valueA = null; public void fill() { valueA = new String[3][columnName.length]; for (int i = 0; i < 3; i++) { valueA[i][0] = "Name" + i; valueA[i][1] = "989481125" + i; valueA[i][2] = "Area No" + i; } } @Override public int getRowCount() { return valueA.length; } @Override public String getColumnName(int column) { return columnName[column]; } @Override public int getColumnCount() { return columnName.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { return valueA[rowIndex][columnIndex]; } } public static void main(String[] args) { new PersonTable(); } } A: Try reading the Java Swing Tutorial on how to use JTables. Basically, you write an Listener for row selection: How to Use Tables
Q: Integrating $\int\frac{xe^{2x}}{(1+2x)^2} dx$ I need help in integrating $$\int \frac{x e^{2x}}{(1+2x)^2} dx$$ I used integration by parts to where $u=xe^{2x}$ and $dv=\frac{1}{(1+2x)^2}$ to obtain $$=\frac{-1}{2(1+2x)}\left[e^{2x}+2xe^{2x}\right] + \frac{1}{2}\int \frac{1}{(1+2x)}\left(2e^{2x}+\frac{d}{dx}\left(2xe^{2x}\right)\right)dx$$ Which is pretty long, which made me question whether I'm doing it correctly or not. Are there any other ways to properly evaluate the integral? Do note though that I already know the answer to this one since it was given in a textbook, I just don't know how to arrive at such an answer. $$\int \frac{xe^{2x}}{(1+2x)^2}dx = \frac{e^{2x}}{4+8x}$$ A: \begin{align} & \int \frac{x e^{2x}}{(1+2x)^2} dx \\ = & -\frac{1}{2}\int xe^{2x}d\left(\frac{1}{1 + 2x}\right) \\ = & -\frac{xe^{2x}}{2 + 4x} + \frac{1}{2}\int \frac{e^{2x} + 2xe^{2x}}{1 + 2x}dx \\ = & -\frac{xe^{2x}}{2 + 4x} + \frac{1}{2}\int e^{2x}dx \\ = & -\frac{xe^{2x}}{2 + 4x} + \frac{1}{4}e^{2x} \\ = & \frac{e^{2x}}{4 + 8x} \end{align} A: Notice, $$\int\frac{xe^{2x}}{(1+2x)^2}dx$$ Let $1+2x=t\implies 2dx=dt$ $$=\frac{1}{4}\int\frac{(t-1)e^{t-1}}{t^2}dt$$ $$=\frac{1}{4}\int e^{t-1}\left(\frac{1}{t}-\frac{1}{t^2}\right)dt$$ $$=\frac{1}{4}\left[\int \frac{e^{t-1}}{t}-\int \frac{e^{t-1}}{t^2}\right]$$ $$=\frac{1}{4}\left[\frac{e^{t-1}}{t} +\int \frac{e^{t-1}}{t^2}-\int \frac{e^{t-1}}{t^2}\right]$$ $$=\frac{1}{4}\frac{e^{t-1}}{t}$$$$=\frac{e^{2x}}{4(1+2x)}+c$$ A: HINT: $$2\frac{x e^{2x}}{(1+2x)^2}=\dfrac{d[e^{2x}]}{dx}\cdot\dfrac1{1+2x}+e^{2x}\cdot\dfrac{d\left[\dfrac1{1+2x}\right]}{dx}$$ Another way could be: Set $2x=y$ and write the numerator as $1+y-1$ and use $\dfrac{d\left[\dfrac1y\right]}{dy}=-\dfrac1{y^2}$ to match with $$\dfrac{d\{e^z\cdot f(z)\}}{dz}=e^z[f(z)+f'(z)]$$
Q: Geb testing: How to click the link of a controller action? I am working through a segment of a Geb test for a Grails app, and can't find this in the docs (though I might be overlooking something). How do you select and click on the link of a controller action? Here's the form element with that has a controller action link (I had to rename some things...) Is it the problem of the elementId or do I need to look elsewhere? Normally I can hit Ids with the # selector just fine. Had a hard time finding an example in the docs. Any help or direction is greatly appreciated. (Using Grails 2.4.3, Geb 9.3, and Firefox 37.0.2) Form item: <li id="formItemID"> <g:link elementId="linkId" controller="controller" action="linkAction">Link Text HERE</g:link> </li> Geb Test: def "test controller action link"(){ when: go linkURL here $('#linkId').click() // this won't hit then: $('.some kind of panel-heading').value('something value...') } A: Take a look at the rendered HTML in firebug (or chrome dev console, or whatever). What gets rendered? <li id="formItemID"> <a id="linkId" href="http://localhost:8080/controller/linkAction">Link Text HERE</g:link> </li> If it looks like this, then you should be able to click the link using the code snippet you've supplied. $('#linkId').click() Alternatively, you could try some of these: $("a", id: "linkId").click() $("li", id: "formItemID").find("a")[0].click() Normally, I create links like this: <a id="myId" href="${createLink(controller: 'myController', action: 'myAction')}">link text</a> So I'm more certain of what the rendered HTML output will be. EDIT: Some tips for creating geb tests * *Use the debugger in GGTS. Put a breakpoint in your test method and try out different ways to reference parts of the DOM using the Display View. *When you figure out how to interact with a particular UI component (like a JQGrid table, Select2 dropdown, etc), encapsulate this functionality in a utility method *For sequential flows like new user registration, password reset etc, again encapsulte these in utility methods. You'll really cut down on bloat in your tests, and if the registration (or whatever) process changes, you'll only need to change your tests in one place. *Try to avoid using Thread.sleep(), it's a one way ticket to the world of flaky tests. If you need to wait for some ajax to finish, create a utility method that waits for the loading spinner to disappear, and call this from your tests.
Q: Repeat Timer Event 10 times then end it? How would I make a Timer that when its ran runs most of its code 10 times then after then 10th time it runs Timer2.Stop() The code below makes the monster move right 5 pixels then stop, i want it to move one pixel 5 times then run the right.Stop() and Timer1.start() If someone could help me fix this that would be awesome :D Private Sub right_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles right.Tick Timer1.Stop() If Me.mob2.Location.X < 750 Then Me.mob2.Location = New Point(Me.mob2.Location.X + 5, Me.mob2.Location.Y) End If right.Stop() Timer1.Start() End Sub A: Try this: Private Sub right_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles right.Tick Timer1.Stop() Static moveCount as Integer = 1 If Me.mob2.Location.X < 750 Then Me.mob2.Location = New Point(Me.mob2.Location.X + 1, Me.mob2.Location.Y) End If moveCount += 1 ' edit this for how many times you want it to move If moveCount = 5 Then right.Stop() moveCount = 1 Timer1.Start() End If End Sub
Q: Bezier path doesn't update when going from portrait to landscape I have a custom UIView and a table view that are all created programmatically. My custom UIView involves a UIBezierPath to create it's shape. I add this UIView to the table view tableHeaderView and it has a dynamic height. When I rotate my app from portrait to landscape the curve doesn't update. Any help would be much appreciated. Here is all the code for the curved header view: class ExplanationCurvedHeaderView: UIView { public lazy var headerView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.autoresizesSubviews = true view.autoresizingMask = [.flexibleWidth, .flexibleHeight] //view.backgroundColor = .gray return view }() private lazy var headerLabel: UILabel = { let headerLabel = UILabel() headerLabel.translatesAutoresizingMaskIntoConstraints = false headerLabel.numberOfLines = 0 headerLabel.lineBreakMode = .byWordWrapping headerLabel.textAlignment = .center headerLabel.font = .systemFont(ofSize: 18, weight: .semibold) headerLabel.textColor = .black headerLabel.text = "Hello this is a test Hello this is a testHello this is a testHello this is a test Hello this is a test Hello this is a test Hello this is a test Hello this is a test Hello this is a test" return headerLabel }() public lazy var imageIcon: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit imageView.image = UIImage(systemName: "exclamationmark.triangle.fill") return imageView }() override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() createCurve() } func configure() { addSubview(headerView) headerView.addSubview(headerLabel) headerView.addSubview(imageIcon) NSLayoutConstraint.activate([ headerView.topAnchor.constraint(equalTo: topAnchor, constant: -44), headerView.leadingAnchor.constraint(equalTo: leadingAnchor), headerView.trailingAnchor.constraint(equalTo: trailingAnchor), headerView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -80), headerLabel.topAnchor.constraint(equalTo: headerView.topAnchor, constant: 75), headerLabel.leadingAnchor.constraint(equalTo: headerView.leadingAnchor, constant: 20), headerLabel.trailingAnchor.constraint(equalTo: headerView.trailingAnchor, constant: -20), headerLabel.bottomAnchor.constraint(equalTo: headerView.bottomAnchor, constant: -20), imageIcon.centerXAnchor.constraint(equalTo: centerXAnchor), imageIcon.topAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 10), imageIcon.heightAnchor.constraint(equalToConstant: 64), imageIcon.widthAnchor.constraint(equalToConstant: 64) ]) } func createCurve() { let shapeLayer = CAShapeLayer(layer: headerView.layer) shapeLayer.path = pathForCurvedView().cgPath //shapeLayer.frame = self.bounds shapeLayer.frame = headerView.bounds shapeLayer.fillColor = UIColor.lightGray.cgColor headerView.layer.mask = shapeLayer.mask headerView.layer.insertSublayer(shapeLayer, at: 0) } func pathForCurvedView() -> UIBezierPath { let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: 0)) path.addLine(to: CGPoint(x: UIScreen.main.bounds.maxX, y: 0)) path.addLine(to: CGPoint(x: UIScreen.main.bounds.maxX, y: headerView.frame.height + 30)) path.addQuadCurve(to: CGPoint(x: UIScreen.main.bounds.minX, y: headerView.frame.height + 30), controlPoint: CGPoint(x: UIScreen.main.bounds.midX, y: headerView.frame.height + 70)) print("header view height:", headerView.frame.height) print("header label systemLayou:", headerLabel.systemLayoutSizeFitting(UIView.layoutFittingExpandedSize)) path.close() return path } } Here is view controller code: import UIKit class ViewController: UIViewController { private lazy var headerView: ExplanationCurvedHeaderView = { let curvedView = ExplanationCurvedHeaderView(frame: .zero) return curvedView }() var arrayValues: [String] = [] private lazy var tableView: UITableView = { let tableView = UITableView() tableView.translatesAutoresizingMaskIntoConstraints = false tableView.delegate = self tableView.dataSource = self tableView.frame = view.safeAreaLayoutGuide.layoutFrame return tableView }() /* Tried few things in this override but no correct results override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in self.headerView.headerView.setNeedsLayout() self.headerView.createCurve() self.tableView.setNeedsLayout() self.tableView.setNeedsDisplay() }) } */ override func viewDidLoad() { for x in 1...6 { if x.isMultiple(of: 2) { arrayValues.append("Get To Invesin InvestinGet To Kn Get e o Kn Get eo Kn Get eo") } else { arrayValues.append("Get To Invesin InvestinGet To Kn Get e o Kn Get eo Kn Get eo Kn Get eo Kn Get eo Kn Get eo Kn Get eo Kn Get eo Kn Get e Get To Invesin InvestinGetGet To Invesin InvestinGetGet To Invesin InvestinGetGet To Invesin InvestinGetGet To Invesin InvestinGet nvestinGetGenvestinGetGenvestinGetGenvestinGetGenvestinGetGe") } } tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "cell") //tableView.tableHeaderView = headerView view.addSubview(tableView) NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor), ]) tableView.tableHeaderView = headerView } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let headerView = self.tableView.tableHeaderView { let headerViewFrame = headerView.frame let height = headerView.systemLayoutSizeFitting(headerViewFrame.size, withHorizontalFittingPriority: UILayoutPriority.defaultHigh, verticalFittingPriority: UILayoutPriority.defaultLow).height var headerFrame = headerView.frame if height != headerFrame.size.height { headerFrame.size.height = height headerView.frame = headerFrame self.tableView.tableHeaderView = headerView } } headerView.layoutIfNeeded() tableView.beginUpdates() tableView.endUpdates() } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayValues.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? CustomTableViewCell else { return UITableViewCell() } cell.setValue(value: arrayValues[indexPath.row]) return cell } func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude } } This also comes up in the console: 2021-04-19 22:35:19.292199-0400 HeaderViewCurve[62191:1769385] [LayoutConstraints] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. ( "<NSLayoutConstraint:0x6000022fac60 V:|-(75)-[UILabel:0x7fdce741ce10] (active, names: '|':UIView:0x7fdce741cca0 )>", "<NSLayoutConstraint:0x6000022fad50 UILabel:0x7fdce741ce10.bottom == UIView:0x7fdce741cca0.bottom - 20 (active)>", "<NSLayoutConstraint:0x6000022fab20 V:|-(-44)-[UIView:0x7fdce741cca0] (active, names: '|':HeaderViewCurve.ExplanationCurvedHeaderView:0x7fdce740cf60 )>", "<NSLayoutConstraint:0x6000022fac10 UIView:0x7fdce741cca0.bottom == HeaderViewCurve.ExplanationCurvedHeaderView:0x7fdce740cf60.bottom - 80 (active)>", "<NSLayoutConstraint:0x6000022f0460 'UIView-Encapsulated-Layout-Height' HeaderViewCurve.ExplanationCurvedHeaderView:0x7fdce740cf60.height == 0 (active)>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x6000022fad50 UILabel:0x7fdce741ce10.bottom == UIView:0x7fdce741cca0.bottom - 20 (active)> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful. 2021-04-19 22:35:19.293129-0400 HeaderViewCurve[62191:1769385] [LayoutConstraints] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. ( "<NSLayoutConstraint:0x6000022fab20 V:|-(-44)-[UIView:0x7fdce741cca0] (active, names: '|':HeaderViewCurve.ExplanationCurvedHeaderView:0x7fdce740cf60 )>", "<NSLayoutConstraint:0x6000022fac10 UIView:0x7fdce741cca0.bottom == HeaderViewCurve.ExplanationCurvedHeaderView:0x7fdce740cf60.bottom - 80 (active)>", "<NSLayoutConstraint:0x6000022f0460 'UIView-Encapsulated-Layout-Height' HeaderViewCurve.ExplanationCurvedHeaderView:0x7fdce740cf60.height == 0 (active)>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x6000022fac10 UIView:0x7fdce741cca0.bottom == HeaderViewCurve.ExplanationCurvedHeaderView:0x7fdce740cf60.bottom - 80 (active)> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful. A: Per DanielMarx suggestion I was able to solve my question by adding this in my view controller override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in self.headerView.layer.sublayers?.first?.removeFromSuperlayer() self.headerView = ExplanationCurvedHeaderView() self.tableView.tableHeaderView = self.headerView }) }
Q: maintain dictionary structure while reducing nested dictionary I have a list of pairs of nested dict dd and would like to maintain the structure to a list of dictionaries: dd = [ [{'id': 'bla', 'detail': [{'name': 'discard', 'amount': '123'}, {'name': 'KEEP_PAIR_1A', 'amount': '2'}]}, {'id': 'bla2', 'detail': [{'name': 'discard', 'amount': '123'}, {'name': 'KEEP_PAIR_1B', 'amount': '1'}]} ], [{'id': 'bla3', 'detail': [{'name': 'discard', 'amount': '123'}, {'name': 'KEEP_PAIR_2A', 'amount': '3'}]}, {'id': 'bla4', 'detail': [{'name': 'discard', 'amount': '123'}, {'name': 'KEEP_PAIR_2B', 'amount': '4'}]} ] ] I want to reduce this to a list of paired dictionaries while extracting only some detail. For example, an expected output may look like this: [{'name': ['KEEP_PAIR_1A', 'KEEP_PAIR_1B'], 'amount': [2, 1]}, {'name': ['KEEP_PAIR_2A', 'KEEP_PAIR_2B'], 'amount': [3, 4]}] I have run my code: pair=[] for all_pairs in dd: for output_pairs in all_pairs: for d in output_pairs.get('detail'): if d['name'] != 'discard': pair.append(d) output_pair = { k: [d.get(k) for d in pair] for k in set().union(*pair) } But it didn't maintain that structure : {'name': ['KEEP_PAIR_1A', 'KEEP_PAIR_1B', 'KEEP_PAIR_2A', 'KEEP_PAIR_2B'], 'amount': ['2', '1', '3', '4']} I assume I would need to use some list comprehension to solve this but where in the for loop should I do that to maintain the structure. A: Since you want to combine dictionaries in lists, one option is to use dict.setdefault: pair = [] for all_pairs in dd: dct = {} for output_pairs in all_pairs: for d in output_pairs.get('detail'): if d['name'] != 'discard': for k,v in d.items(): dct.setdefault(k, []).append(v) pair.append(dct) Output: [{'name': ['KEEP_PAIR_1A', 'KEEP_PAIR_1B'], 'amount': [2, 1]}, {'name': ['KEEP_PAIR_2A', 'KEEP_PAIR_2B'], 'amount': [3, 4]}]
Q: Android CalendarView issue In my android studio project where I am using CalendarView I want to display events on day button. So how can I highlight the day button so the user will know the particular date contain events? Expected output:- A: Use this API in your code.. It will help u to insert event, event with reminder and event with meeting can be enabled... This api works for platform 2.1 and above Those who uses less then 2.1 instead of content://com.android.calendar/events use content://calendar/events public static long pushAppointmentsToCalender(Activity curActivity, String title, String addInfo, String place, int status, long startDate, boolean needReminder, boolean needMailService) { /***************** Event: note(without alert) *******************/ String eventUriString = "content://com.android.calendar/events"; ContentValues eventValues = new ContentValues(); eventValues.put("calendar_id", 1); // id, We need to choose from // our mobile for primary // its 1 eventValues.put("title", title); eventValues.put("description", addInfo); eventValues.put("eventLocation", place); long endDate = startDate + 1000 * 60 * 60; // For next 1hr eventValues.put("dtstart", startDate); eventValues.put("dtend", endDate); // values.put("allDay", 1); //If it is bithday alarm or such // kind (which should remind me for whole day) 0 for false, 1 // for true eventValues.put("eventStatus", status); // This information is // sufficient for most // entries tentative (0), // confirmed (1) or canceled // (2): eventValues.put("eventTimezone", "UTC/GMT +2:00"); /*Comment below visibility and transparency column to avoid java.lang.IllegalArgumentException column visibility is invalid error */ /*eventValues.put("visibility", 3); // visibility to default (0), // confidential (1), private // (2), or public (3): eventValues.put("transparency", 0); // You can control whether // an event consumes time // opaque (0) or transparent // (1). */ eventValues.put("hasAlarm", 1); // 0 for false, 1 for true Uri eventUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(eventUriString), eventValues); long eventID = Long.parseLong(eventUri.getLastPathSegment()); if (needReminder) { /***************** Event: Reminder(with alert) Adding reminder to event *******************/ String reminderUriString = "content://com.android.calendar/reminders"; ContentValues reminderValues = new ContentValues(); reminderValues.put("event_id", eventID); reminderValues.put("minutes", 5); // Default value of the // system. Minutes is a // integer reminderValues.put("method", 1); // Alert Methods: Default(0), // Alert(1), Email(2), // SMS(3) Uri reminderUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(reminderUriString), reminderValues); } /***************** Event: Meeting(without alert) Adding Attendies to the meeting *******************/ if (needMailService) { String attendeuesesUriString = "content://com.android.calendar/attendees"; /******** * To add multiple attendees need to insert ContentValues multiple * times ***********/ ContentValues attendeesValues = new ContentValues(); attendeesValues.put("event_id", eventID); attendeesValues.put("attendeeName", "xxxxx"); // Attendees name attendeesValues.put("attendeeEmail", "[email protected]");// Attendee // E // mail // id attendeesValues.put("attendeeRelationship", 0); // Relationship_Attendee(1), // Relationship_None(0), // Organizer(2), // Performer(3), // Speaker(4) attendeesValues.put("attendeeType", 0); // None(0), Optional(1), // Required(2), Resource(3) attendeesValues.put("attendeeStatus", 0); // NOne(0), Accepted(1), // Decline(2), // Invited(3), // Tentative(4) Uri attendeuesesUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(attendeuesesUriString), attendeesValues); } return eventID; } Hope that helps you For further information you may refer below link How to add calendar events in Android?
Q: How to make two different Constructors in the same Class - Android i think that this can be done, but maybe im wrong (Im sure im wrong). I have this adapter that sometimes uses a List of Class1 and in other moments uses a list of Class2. So, can i do TWO differents constructors where un the first one i use List1 and in the other one i use the List2? public class SpinnerAdapter extends BaseAdapter { private List<String> listaDeTexto; private Activity activity; private LayoutInflater layoutInflater; private List<MetodoDePago> listaMetodosDePago; private List<Banco> listaDeBancos; public SpinnerAdapter(List<String> listaDeTexto, Activity activity, List<MetodoDePago> listaMetodosDePago) { this.listaDeTexto = listaDeTexto; this.activity = activity; this.layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.listaMetodosDePago = listaMetodosDePago; } public SpinnerAdapter(List<String> listaDeTexto, Activity activity, List<Banco> listaDeBancos) { this.listaDeTexto = listaDeTexto; this.activity = activity; this.layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.listaDeBancos = listaDeBancos; } @Override public int getCount() { return listaDeTexto.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (convertView == null){ view = layoutInflater.inflate(R.layout.spinner_custom,null); } TextView textView = view.findViewById(R.id.textViewSpinner); textView.setText(listaDeTexto.get(position)); ImageView imageView = view.findViewById(R.id.imgViewSpinner); Glide.with(view) .load(listaMetodosDePago.get(position).getThumbnail()) .into(imageView); return view; } } A: Due to type erasure in Java, you are basically declaring two constructors which look like, SpinnerAdapter(List l1, Activity a, List l2) { } to Java. A simple solution would be to create one constructor and add a type argument. So, something like, SpinnerAdapter(List l1, Activity a, List l2, int type) { }. You can then check the type value in the constructor and the getView(...) method to initialize your variables as needed.
Q: Script to get CPU Usage I am using this script to get CPU usage from multiple server $Output = 'C:\temp\Result.txt' $ServerList = Get-Content 'C:\temp\Serverlist.txt' $CPUPercent = @{ Label = 'CPUUsed' Expression = { $SecsUsed = (New-Timespan -Start $_.StartTime).TotalSeconds [Math]::Round($_.CPU * 10 / $SecsUsed) } } Foreach ($ServerNames in $ServerList) { Invoke-Command -ComputerName $ServerNames -ScriptBlock { Get-Process | Select-Object -Property Name, CPU, $CPUPercent, Description | Sort-Object -Property CPUUsed -Descending | Select-Object -First 15 | Format-Table -AutoSize | Out-File $Output -Append } } and I am getting error Cannot bind argument to parameter 'FilePath' because it is null. + CategoryInfo : InvalidData: (:) [Out-File], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.OutFileCommand + PSComputerName : ServerName Can you pls assist me in this...? A: The problem is that you use $Output in your script block which you invoke on the remote computer via Invoke-Command and therefore is not defined when the script block is executed in the remote session. To fix it you could pass it as parameter to the script block or define it within the script block but I guess you rather want to write the file on the initiating client rather than on the remote computer. So instead of using Out-File in the script block you may want to use it outside the script block like so $Output = 'C:\temp\Result.txt' $ServerList = Get-Content 'C:\temp\Serverlist.txt' $ScriptBlock = { $CPUPercent = @{ Label = 'CPUUsed' Expression = { $SecsUsed = (New-Timespan -Start $_.StartTime).TotalSeconds [Math]::Round($_.CPU * 10 / $SecsUsed) } } Get-Process | Select-Object -Property Name, CPU, $CPUPercent, Description | Sort-Object -Property CPUUsed -Descending | Select-Object -First 15 } foreach ($ServerNames in $ServerList) { Invoke-Command -ComputerName $ServerNames -ScriptBlock $ScriptBlock | Out-File $Output -Append } Please also notice that I moved the definition of $CPUPercent into the script block as this suffered from the same problem.
Q: Unicode characters emoticons in MySQL with 4 bytes I have to insert in Mysql Strings that may contain characters like '' . I tried this: ALTER TABLE `table_name` DEFAULT CHARACTER SET utf8mb4, MODIFY `colname` VARCHAR(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL; and when I insert ''; INSERT INTO `table_name` (`col_name`) VALUES (''); I get the following SELECT * FROM `table_name`; ???? How can I do to get the correct value in the select statements? Thanks a lot. A: You will need to set the connection encoding to utf8mb4 as well. It depends on how you connect to MySQL how to do this. SET NAMES utf8mb4 is the API-independent SQL query to do so. What MySQL calls utf8 is a dumbed down subset of actual UTF-8, covering only the BMP (characters 0000 through FFFF). utf8mb4 is actual UTF-8 which can encode all Unicode code points. If your connection encoding is utf8, then all data is squeezed though this subset of UTF-8 and you cannot send or receive characters above the BMP to or from MySQL.
Q: Linked List - Segmentation Fault This code is supposed to make a link list of ten names inputed by the user and it should print out that list. #include<stdio.h> #include<stdlib.h> struct NameList { char *name; struct NameList *nname; }; typedef struct NameList NL; int main() { int i; NL *first; NL *next; first = (NL*)malloc(sizeof(NL)); if (first ==NULL) printf("Memory not properly allocated\n"); NL *pNames; pNames = first; for(i = 0; i<10; i++) { printf("Enter a name: "); scanf("%s", &pNames->name); if(i == 9) next = NULL; else next = (NL*)malloc(sizeof(NL)); pNames->nname = next; pNames = pNames->nname; } Up to here there are no issues, I input the ten names but as soon as I enter the last name I get a segmentation fault. I'm guessing it's originating from here but I am not sure at all pNames = first; while(pNames != NULL) { printf("%s\n", pNames->name); pNames = pNames->nname; } } A: This line is the source: printf("Enter a name: "); scanf("%s", &pNames->name); Would be best to create a static buffer like this: char buf[20]; then printf("Enter a name: "); scanf("%s", buf); finally: pNames->name = strdup(buf); Edit: For sake of completeness, there is a risk of buffer overflow. where more than certain characters go past the end of the buffer inducing undefined behaviour. This can be mitigated as suggested by @ebyrob, in this fashion fgets(buf, 20, stdin); A: allocate space for "name", preferably use std::string you need to get "next" node. for(i = 0; i<10; i++) { printf("Enter a name: "); scanf("%s", &pNames->name); if(i == 9) next = NULL; else next = (NL*)malloc(sizeof(NL)); pNames->nname = next; pNames = next; } pNames = first; while(pNames != NULL) { printf("%s\n", pNames->name); pNames = pNames->next; } A: You have not allocated memory to hold the name field of your NameList objects. The name field is of type char * which has enough room for a pointer, not a string of characters. When you perform scanf(%s, &pNames->name); you are telling scanf to write the name into that memory location, but that will overwrite a lot more than the bytes needed to store a pointer. Instead you could have scanf load into a temporary array first, then malloc enough space to hold it char *tempbuff = malloc(128); // or some large enough buffer for (i = 0; i<10; ++i) { // load the input into tempbuff first scanf("%s", tempbuff); // now make room for the string in the current object pNames->name = malloc(strlen(tempbuff)+1); // leave room for trailing null // now copy it from the tempbuff to its new home strcpy(pNames->name,tempbuff); .... // rest of code
Q: Normalisation of a free particle with Gaussian wave packet The Gaussian wave packet where the $x$-dependence is given by the wave function $$\Phi(x) = N\exp\bigg(ikx - \frac{x^2}{2\Delta^2}\bigg)$$ $N$ is a normalisation constant. $k$ is the wave number. I need to find the case where: $$\int^{\infty}_{-\infty} |\Phi(x)|^2\,\mathrm{d}x = \int^{\infty}_{-\infty} \Phi^*(x)\Phi(x)\,\mathrm{d}x = 1$$ $\Phi^*(x)$ is the complex conjugate. I want to find the normalisation constant $N$. I have some integrals to use but I'm not sure how to do it: $$\int^{\infty}_{-\infty} e^{-\alpha x^2}\,\mathrm{d}x = \sqrt{\frac{\pi}{\alpha}},\quad \int^{\infty}_{-\infty} xe^{-\alpha x^2}\,\mathrm{d}x = 0,\quad \int^{\infty}_{-\infty} x^2e^{-\alpha x^2}\,\mathrm{d}x = \frac{1}{2}\sqrt{\frac{\pi}{\alpha^3}}$$ I have thought about rearranging the given wave function to get: $$\Phi(x) = N\exp(ikx)\exp\Big(-\frac{x^2}{2\Delta^2}\Big)$$ But I am also unsure what to make of the $\Delta$ part. A: Assume that $\Delta^2$ is real and positive and that $k$ is real. Then $$\Phi^*(x)\Phi(x)=N^2\mathrm{e}^{-x^2/\Delta^2}$$ can be integrated using your table. If $\Delta^2$ is complex and satisfies $\Re \Delta^2 >0$, then $$\Phi^*(x)\Phi(x)=N^2\mathrm{e}^{-x^2\Re \Delta^{-2}}$$ can be integrated using your table. A: With the assumption that $\Delta$ is just a variable, I have the following solution: \begin{align} \int^{\infty}_{\infty} |\Phi(x)|^2\,\mathrm{d}x &= \int^{\infty}_{\infty} N^2\exp\bigg(-\frac{2x^2}{2\Delta^2}\bigg)\cdot\frac{e^{ikx}}{e^{ikx}}\,\mathrm{d}x = N^2\int^{\infty}_{\infty} \exp\bigg(-\frac{x^2}{\Delta^2}\bigg)\,\mathrm{d}x\\ &= N^2\cdot \sqrt{\frac{\pi}{\frac{1}{\Delta^2}}} = N^2\sqrt{\pi}\Delta = 1 \Rightarrow N = \frac{1}{\sqrt[4]\pi \sqrt\Delta} \end{align} I don't know if Delta means something else in quantum mechanics so if it does then please share. If not then could someone check this please? EDIT: Yey! I have a confirmation email from my tutor that $\Delta$ is a constant in this case.
Q: Set 'Load in QGIS' of all batch processing rows to 'no'? I'm using 'Save Selected Features' algorithm from the Processing Toolbox. I'm batch processing thousands of GeoJSON files to tab files but the same would be true for any conversion. I've created a JSON input file to load in my thousands of records to convert, but QGIS opens each record created to the map view and therefore consumes all my system memory. Is there a way to set all the rows to no without manually changing each, row by row? A: Yes, it is possible. Just manually set the first No value and then double-click on the Load in QGIS field name: it will set all the other rows to No.
Q: onfocus and onblur not working for input color element when visibility: hidden; is set Onchange is working. But what is the way to make onfocus and onblur events to fire when working with input color element when visibility: hidden; is set? I was seeing the example on internet. And I am using it. But it does not work when i have next set in css. #colorDialogID { visibility: hidden; } On the end maybe there would be some better solution to register if color dialog was opened and closed without any change? function getColor2() { console.log("change"); } document.getElementById("colorDialogID").onchange = getColor2; function myFocusFunction() { console.log("open"); } function myBlurFunction() { console.log("close"); } document.getElementById("colorDialogID").onfocus = myFocusFunction; document.getElementById("colorDialogID").onblur = myBlurFunction; var statusName; function createStatusF(){ document.getElementById("colorDialogID").focus(); document.getElementById("colorDialogID").value = "#FFCC00"; document.getElementById("colorDialogID").click(); } document.getElementById("newStatuslabelID").onclick = createStatusF; A: You must have some duplicated id. I did this demo for you: HTML <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <select id="colorDialogID"> <option value="#df0000">Red <option value="#7b93d3">Blue <option value="#000000">Black </select> <hr> <span>Your selection</span> <p id="selectedColor"></p> </body> </html> JAVASCRIPT function getColor2() { var x = document.getElementById("colorDialogID").value; document.getElementById("selectedColor").innerHTML = "You selected: " + x; console.log("Selected color is:" + x); } document.getElementById("colorDialogID").onchange = getColor2; function myFocusFunction() { console.log("open"); } function myBlurFunction() { console.log("close"); } document.getElementById("colorDialogID").onfocus = myFocusFunction; document.getElementById("colorDialogID").onblur = myBlurFunction; Working Demo A: You can call function like this document.getElementById("colorDialogID").onfocus = function() {myFocusFunction()};
Q: Converting TensorFlow tensor into Numpy array Problem Description I am trying to write a custom loss function in TensorFlow 2.3.0. To calculate the loss, I need the y_pred parameter to be converted to a numpy array. However, I can't find a way to convert it from <class 'tensorflow.python.framework.ops.Tensor'> to numpy array, even though there seem to TensorFlow functions to do so. Code Example def custom_loss(y_true, y_pred): print(type(y_pred)) npa = y_pred.make_ndarray() ... if __name__ == '__main__': ... model.compile(loss=custom_loss, optimizer="adam") model.fit(x=train_data, y=train_data, epochs=10) gives the error message: AttributeError: 'Tensor' object has no attribute 'make_ndarray after printing the type of the y_pred parameter: <class 'tensorflow.python.framework.ops.Tensor'> What I have tried so far Looking for a solution I found this seems to be a common issue and there a couple of suggestions, but they did not work for me so far: 1. " ... so just call .numpy() on the Tensor object.": How can I convert a tensor into a numpy array in TensorFlow? so I tried: def custom_loss(y_true, y_pred): npa = y_pred.numpy() ... giving me AttributeError: 'Tensor' object has no attribute 'numpy' 2. "Use tensorflow.Tensor.eval() to convert a tensor to an array": How to convert a TensorFlow tensor to a NumPy array in Python so I tried: def custom_loss(y_true, y_pred): npa = y_pred.eval(session=tf.compat.v1.Session()) ... giving me one of the longest trace of error messages I ever have seen with the core being: InvalidArgumentError: 2 root error(s) found. (0) Invalid argument: You must feed a value for placeholder tensor 'functional_1/conv2d_2/BiasAdd/ReadVariableOp/resource' with dtype resource [[node functional_1/conv2d_2/BiasAdd/ReadVariableOp/resource (defined at main.py:303) ]] [[functional_1/cropping2d/strided_slice/_1]] (1) Invalid argument: You must feed a value for placeholder tensor 'functional_1/conv2d_2/BiasAdd/ReadVariableOp/resource' with dtype resource [[node functional_1/conv2d_2/BiasAdd/ReadVariableOp/resource (defined at main.py:303) ]] also having to call TensorFlow Compatibility Functions from Version 1.x does not feel very future-proof, so I do not like this approach too much anyhow. 3. Looking at the TensorFlow Docs there seemed to be the function I needed just waiting: tf.make_ndarray Create a numpy ndarray from a tensor. so I tried: def custom_loss(y_true, y_pred): npa = tf.make_ndarray(y_pred) ... giving me AttributeError: 'Tensor' object has no attribute 'tensor_shape' Looking at the example in the TF documentation they use this on a proto_tensor, so I tried converting to a proto first: def custom_loss(y_true, y_pred): proto_tensor = tf.make_tensor_proto(y_pred) npa = tf.make_ndarray(proto_tensor) ... but already the tf.make_tensor_proto(y_pred) raises the error: TypeError: Expected any non-tensor type, got a tensor instead. Also trying to make a const tensor first gives the same error: def custom_loss(y_true, y_pred): a = tf.constant(y_pred) proto_tensor = tf.make_tensor_proto(a) npa = tf.make_ndarray(proto_tensor) ... There are many more posts around this but it seems they are all coming back to these three basic ideas. Looking forward to your suggestions! A: y_pred.numpy() works in TF 2 but AttributeError: 'Tensor' object has no attribute 'make_ndarray indicates that there are parts of your code that you are not running in Eager mode as you would otherwise not have a Tensor object but an EagerTensor. To enable Eager Mode, put this at the beginning of your code before anything in the graph is built: tf.config.experimental_run_functions_eagerly(True) Second, when you compile your model, add this parameter: model.compile(..., run_eagerly=True, ...) Now you're executing in Eager Mode and all variables actually hold values that you can both print and work with. Be aware that switching to Eager mode might require additional adjustments to your code (see here for an overview).