INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Is there a way to suppress FindBugs from generating warnings on code generated by static weaving? I'm getting what I think are false positives from FindBugs (2.0.2) and Sonar (3.7.3) on code that is being generated via static weaving of EclipseLink (2.5.1) JPA entities. Specifically, I am seeing multiple occurrences of ES_COMPARING_PARAMETER_STRING_WITH_EQ Comparison of String parameter using == or != in com.test.domain.MyEntity._persistence_set(String, Object) and URV_INHERITED_METHOD_WITH_RELATED_TYPES Inherited method com.test.domain.MyEntity._persistence_get(String) returns more specific type of object than declared Is there a way to eliminate these warnings for the code generated by EclipseLink without having to globally disable the rules or exclude analysis on the entities entirely?
Very good question! Since your issues originate with FindBugs, you can use FindBugs exclusion filters to address this. Especially, take a look at the `<Method>` exclusion. You can specify a regex that matches the method names of your getters and setters in the entity classes, such as <Method name="~_persistence_[gs]et" /> Such a filter file can be used by all forms of FindBugs, including the Eclipse plugin and SonarQube. For example, using the SonarQube ant task, you can set the property `sonar.findbugs.excludesFilters` to the absolute path to the FindBugs exclusion file.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 5, "tags": "jpa, eclipselink, sonarqube, findbugs" }
What is the expiry date time of the access token? When we implement the Client Credentials grant - Protecting an API using Client Credentials how long is the access token usable for (e.g. whats is the expiry date) before the client needs to generate a new access token?
When you create a client you can define the lifetime of an access token var myClient = new Client { ClientId = "testClient", AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets = { new Secret("secret".Sha256()) }, AllowedScopes = { "api1" }, AccessTokenLifetime=3600 }; If you do not supply AccessTokenLifetime then it will default to 3600 which is an hour. This means it will expire one hour after it is created
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": ".net core, identityserver4, openid connect" }
Can you configure a Wordpress-based site for private use only? If I build a site using Wordpress, is there a straightforward way to restrict access to the whole site to only those who I specify? I've looked a few plugins that attempt to redirect unregistered users to the login page, but most seem old, fragile, or generally just hacks. I want to know if a standard Wordpress installation lets you do this, or otherwise if there's a decent and secure plugin to do it. I need a solution that doesn't involve changing the default wordpress PHP scripts as I don't have direct access to the server. It's quite important that the solution is secure. Any help or past experience would be appreciated. EDIT: Apologies if this is better suited to < wasn't aware this existed. Please move if necessary :-)
The new version of WP, I believe v 3.1.2, has this option for pages and posts under the quick edit. You can set a password per post / page or mark them as private.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "security, wordpress" }
Oracle: "grep" across multiple columns? I would like to perform a `like` or `regexp` across several columns. These columns contain tags, keywords, etc. Something that's the equivalent of: sqlplus scott/tiger @myquery.sql | grep somestring Right now I have something like select * from foo where c1 || c2 || c3 like '%somestring%' but I'm hoping I can get something a bit more general purpose and/or optimized. Any clues appreciated!
Have you thought about using the **Concatenated Datastore** feature of Oracle Text? Oracle Text lets you create full-text indexes on multiple columns in the same table. Or at least there's a process by which you can do this. There's a good example document on the Oracle site I've used before: < Oracle Text searches are ridiculously fast. I think I'd look at keeping separate context indexes on each individual column so that you could apply relevance and priority to each column match. Let me know if you'd like an example and I'll add something to the answer. Hope this helps.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "sql, oracle, grep" }
Vuejs: get parameters from url in js file? I have a url : ` In **page.vue** : * I use : `console.log(this.$route.query.id)` and get it successfully. And now I want to get that params in the file : **page.js** import addon from './addon' import user from './user' // I want to check if there is a new params id that has it export default if (this.$route.query.id) { export default [...addon, ...user] } * `console.log(this.$route.query.id)` ERROR: **Reason: TypeError: Cannot read properties of undefined (reading '$route')** Is there any way to get params in js file? Please give me some experience. Thank you.
You could export a function that takes the `$route` as parameter : import addon from './addon' import user from './user' export default function checkParams(route) { if(this.$route.query.id){ return [...addon, ...user] } } and in any component you could do : import checkParams from './page.js' ..... let data=checkParams(this.$route)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -1, "tags": "javascript, vue.js" }
Table partitioning in MYSQL Master Slave I have to Partition a MYSQL table using Range partitioning. Table is 200M rows big and I have Master/Slave replication. What I want to do is to stop replication on slave, partition the table on slave and start replication. My question for you guys is would this work despite the fact Master would have no partitioning on that table but slave would have roughly 50 partitions of that table? Would replication still work ?
The manual does not list a problem, but... Statement Based Replication should not have any problem since the Slave simply re-executes the DML statement without knowing or caring (up front) about whether the table is partitioned. Some rare statements are very likely to break replication: SELECT ... PARTITION pnnn -- 5.6.2 ALTER TABLE -- to change PARTITIONs Please comment on bug report if you find more issues.
stackexchange-dba
{ "answer_score": 1, "question_score": 1, "tags": "mysql, replication, partitioning, alter table" }
How to insert array items into PostgreSQL table Give an array like this: my_array = [2,3,5,23,4] and a table like this: column1 | column2 ---------+---------- 1 | 2 | 3 | 4 | 5 | How can I insert the array values into a table. Roughly I want to do something like this with SQL: for item in my_array: UPDATE my_table SET colum2 = item The updated table should be like this column1 | column2 ---------+---------- 1 | 2 2 | 3 3 | 5 4 | 23 5 | 4 UPDATE: I am using Python psycopg2 but I am wondering if there is a way with pure SQL.
You need to somehow generate an array "index" for each row in the table. _If_ the `column1` value **always** matches the array index, you can do it like this. update test set column2 = (array[2,3,5,23,4])[column1]; However if the value in `column1` does not reflect the array index, you need to generate the array index based on the sort order in the table. If that is the case you can do something like this: with numbered_data as ( select ctid, row_number() over (order by column1) as rn --<< this generates the array index values from test ) update test set column2 = (array[2,3,5,23,4])[nd.rn] from numbered_data nd where nd.ctid = test.ctid; If your table has a proper primary key, then you can use that instead of the `ctid` column.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 13, "tags": "sql, arrays, postgresql" }
Performance of gameserver I've made a gameserver using the TCP protocol. I'm using the KryoNet framework if that have anything to say. It's broadcasting players positions and names once every half second right now, however i'm not sure how low i could put this while still being reasonable. How often would it be recommended to have a gameserver broadcasting?
This depends totally on the kind of game you are making. For many games a periodical broadcast is stictly inferior to an on-change or query approach. But if you decide for the periodical broadcast you can determine the correct time very easily: Ask yourself how precise the player-positions are needed on the client (as opposed to how much the client can interpolate) and divide the location-difference by the maximum speed a player's position can change at.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, networking" }
Build elements in jQuery and add to dom I am trying to build a ul list in jQuery, however it seems to be only creating the ul element, and not the li?? var list = $('<ul></ul>').append($("<li/>").addClass('test').text('hello')); Seems simple enough, but not sure why it won't work??
var list = $('<ul></ul>').append($("<li/>").addClass('test').text('hello')); $('body').append(list); here is the fiddle <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jquery" }
List not showing up on my localhost, but shows on jsfiddle I'm trying to eventually make a sliding form with jQuery, but while testing out my html code I noticed the ul lists didn't show up on my apache localhost. Yet it shows up on the jsfiddle as one can see in the link--> < Why is that? My jquery library is updated and `$(document).ready(function() {` is in the beg of my code.
You could try the console.log to debug. First thing i would try is `console.log($('#navigation'));` and check your browser console to see if it returns the right object, and not 'undefined'. If that works the next step would be to inspect the code of your `#navigation` block and see wich styles get applied after the code has ran. Perhaps you have something like `display: none !important;` in your stylesheet, wich would not get overwritten by the inline styles jQuery apllies to show the content. Or perhaps the block is positioned somewhere off-screen. There is bound to be an isue somewhere else in your code, as the .show() function from jQuery is rather basic and has never caused me any problems. If you can not find the issue, feel free to post a link to the live page so we can have a look at it and try to help out.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, html" }
How to duplicate a branch and all the data in it? I am bit confused on how to create a duplicate new branch. I have a github branch called `abc` now I want to create a exact duplicate of that branch with a different name (i.e., lets say `def`), All the data in `def` should be exactly similar to `abc` branch the only difference should be the name of the branch. I have cloned the repo and checkout the branch using, git clone git checkout abc What else I have to do?
Just create a new branch from `abc`: git branch def If you want to also switch to that new branch while creating it, then use: git checkout -b def Note that a branch is really just a pointer to a commit. So, to create a "duplicate" of `abc` not very much has to move, just a new reference to the HEAD commit of `abc` needs to be created. To push the `def` branch to GitHub, you may use something like: git push origin def
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "git" }
Is it OK that entire table can relate only to certain items in a table? Assume that I have a table of toys with properties like amusability, price, breakage rate, date bought, place where bought. (Some rc cars, brain teasers, planes, some LEGO sets). But then I'm interested in pieces LEGO sets have. Is it perfectly OK, that I create another table "pieces of set" with keys(indices) to toys in the "toy" tables, but these keys will actually point only to toys with pointer to category ("category" is also table) "LEGO Sets"? So that an entire table "pieces of set" actually relates only to certain items in a table "toy"?
Yes. Now, answers on SO need to be longer than one word, so here are some Wikipedia articles you may want to have a go with: "Cardinality (data modeling))" and "Entity-attribute-value model"
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "database" }
Does an electrocardiography recorder put current/voltage on its electrodes? _(I do hope my question is not off-topic)_ Currently learning about ECG recorders (Our 7-months old daughter has to have one during her sleep), I wonder whether this is a pure "passive" measuring device (like a multimeter) or not. I do think I understood that it measures heart activity by comparing potential differences between 2 or more body-connected electrodes. But I did not understand whether this works purely by getting signals from the heart and processing them or whether the device actively sends some signals through the electrodes and measures what comes back. **So my question is:** Does an ECG recorder send signals trough the electrodes or not?
An ECG recorder works by recording electrical signals produced by the heart, and does not need to provide any active signal to do so. That said, most commercial ECG systems will actually use a driven ground arrangement, called a "driven right leg" to make the recordings better (feeding back the common mode signal through a reference electrode), and thus do "send signals through the electrodes" -- but those signals have nothing to do with the signals generated by the heart. From an electrical engineering point of view, this minimizes the effect of different impedances between the different electrodes and the skin, among other things. There's a reasonable review of the method at < As pointed out by Zayzoon there may also be a small current for detection of leads falling off. All these currents are not dangerous, and you can use the device without fear of injury.
stackexchange-electronics
{ "answer_score": 7, "question_score": 6, "tags": "voltage, current, sensor, biopotential" }
With $x_1^2+3x_2^2+2x_1x_2=32$, find max value of $|x_1-x_2|$ > With $x_1^2+3x_2^2+2x_1x_2=32$, find the maximum of $|x_1-x_2|$. * * * I have tried with AM-GM, but can't solve it. With $d = |x_1-x_2|$ and $d^2 = 2x_1^2 + 4x_2^2 - 32$, then I wonder how to do next. Thank a lot for helping! ![](
$(x_1+x_2)^2+2(x_2)^2=32.$ We are finding the value of $\max(|x_1-x_2|)=\max(|x_1+x_2-2x_2|)$. Let $x_1+x_2=X, x_2=Y.$ Then, we can rewrite the problem: > If $X^2+2Y^2=32$, Find the maximum of $|X-2Y|$. Let $\sin(A)=\dfrac{X}{4\sqrt{2}}.$ Then, $\cos(A)=\dfrac{Y}{4}.$ So, the problem changes: > Find the maximum of $|4\sqrt{2}\sin{A}-8\cos{A}|.$ Let $\sin(B)=-\dfrac{\sqrt{2}}{\sqrt{3}}, \cos(B)=\dfrac{1}{\sqrt{3}}$. Then, $|4\sqrt{2}\sin{A}-8\cos{A}| = |4\sqrt{6}(\cos{B}\sin{A}+\sin{B}\cos{A})| =|4\sqrt{6}\sin(A+B)| \leq 4\sqrt{6}.$ So, the answer will be $4\sqrt{6}.$
stackexchange-math
{ "answer_score": 5, "question_score": 4, "tags": "calculus, multivariable calculus, inequality, optimization" }
Contour Integral with Many Singularities How would one compute? $$ \oint_{|z|=1} \frac{dz}{\sin \frac{1}{z}} $$ Can one "generalize" the contour theorem and take the infinite series of the residues at each singularity?
Another method for this case: Think of the outside of the unit disk as your domain. Go around the contour in the opposite direction. Outside the unit disk, the function $$ \frac{1}{\sin\frac{1}{z}} $$ is meromorphic. It has only one singularity in that region: a pole with residue $-1/6$ at $\infty$. So the value of the integral is $$ (-2\pi i)\left(\frac{-1}{6}\right) = \frac{i\pi}{3} . $$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "complex analysis" }
Predict function tuning for random forest I have created a random forest object in R (using the `randomForest` package) with `ntree = N`. Now I would like to predict some new data on it using a subset of `N`, that is using only `n` trees for the prediction. Is this possible? For the random forest object the forest is located at `fit$forest`, but I don't know how to extract them (if possible).
Sounds like you want to set `predict.all = TRUE`. This will cause `predict.randomForest` to return a list containing a vector of the aggregate predictions and a matrix of the individual tree predictions. You can then ensemble the individual trees at your leisure. library("randomForest") data(mtcars) rf <- randomForest(mpg ~ ., data = mtcars, ntree = 10) preds <- predict(rf, newdata = mtcars, predict.all = TRUE) preds$aggregate # Aggregate predictions preds$individual # Invididual tree predictions Make sure you set `newdata = <something>` or this trigger fails for some reason.
stackexchange-stats
{ "answer_score": 2, "question_score": 2, "tags": "r, random forest" }
To Encrypt the IMEI number I have got the code to find the IMEI number of the device, But now I want to Encrypt that format, How can I encrypt that ?
Here give the sample for Encrypt Ad Descrypt for String using Cipher
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, imei" }
Can't delete files in VS 2015 Setup project I have a normal VS 2015 Setup project (installed the extension, so it looks like the Setup projects of VS 2010 and older). In the 'File System on Target Machine' section, I've added a folder "MyAppFolder" and then added the primary output of one of the projects of the solution. VS then added a bunch of dll's as well. However, when I try to delete the folder it says: > Cannot delete folder. Folder is not empty or it might contain excluded files, which are not shown. Well yes, it is not empty. If I right-click on a single dll file, the "Delete" option is disabled. I don't want this folder to be installed on the target machine. How do I get rid of this folder in my setup project?
The supported way to delete files from an installation that are no longer needed (for example, because they were used in a custom action) is to set the component id to null. < See remarks about Component Id. There is no support for this in Visual Studio setups, so it's typically done manually by editing the MSI file with a tool such as Orca. In general I think you always need to delete the individual files before deleting the folder.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "visual studio 2015, setup project" }
Which type of collection should I use for this Java problem? I would like to have a bi-dimensionnal array that contains only integers. The coordinates are integers as well. The problem is: * I don't know by advance how many cols/rows there will be. * I would like to fill it randomly. Example: Assuming the first number to be `2`, placed in `(3;2)`. I want to be able to add the `8` simply, for example like that: `array.add(8,2,1);` _ _ _ _ _ _ _ _ _ _ _ _ => _ _ 8 _ _ _ _ 2 => _ _ _ 2 I already found something that was actually working, but it is really heavy. It is Hashtable<Integer, Hashtable<Integer, Integer>> Does anyone see a more sophisticate way to do it? I'm not that good with Collections.
Maybe you could use Table from Guava This provides you table.put(R rowKey, C columnKey, V value) Guava Table
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, collections" }
How to get request string on .net core WebApi Help me to get request string when I receive request on web server Here my code: [Route("membersave/{name}/{username}/{email}/{token}")] public class MemberSave : Controller { public TokContext _context { get; set; } public MemberSave([FromServices] TokContext context) { _context = context; } [HttpGet] public bool Get_Member_Save(string name, string username, string email, string token) { return DataAccess.Member_Save(_context.Database.GetDbConnection().ConnectionString, name, username, email, token); } } I want to get string like this `myip/membersave/John&Wick/wick/[email protected]/603D3163-DCCA-4FC2-8F85-9A2F94F9A725` I need to save all requests to db
You can get request path like that: var path = HttpContext.Request.Path.Value;
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c#, asp.net web api, asp.net core, .net core" }
Significato e origine dell'espressione "soffiare nel fuoco" Nel romanzo _Bàrnabo delle montagne_ di Dino Buzzati ho letto questo paragrafo di un testo nel quale si parla dei lavori di costruzione di una strada di montagna: > «Uno dei lavoranti va, una notte, a rubare in una casa. Danno allora la colpa a Bettoni perché non sorveglia abbastanza gli operai. Un suo concorrente che aveva perduto l'appalto **_soffia nel fuoco_**. Minacciano di far saltare il deposito di esplosivi.» Mi potreste spiegare cosa significa l'espressione "soffiare nel fuoco"? Sarei inoltre curiosa di sapere da dove nasce questo modo di dire.
Di solito si dice _soffiare sul fuoco_ , ma non è diverso. Quando si accende un fuoco, occorre soffiarci sopra per aumentare la quantità di ossigeno a disposizione della fiamma e anche per eliminare il fumo che la potrebbe soffocare. Il soffio deve essere delicato per non spegnere la fiamma, naturalmente. Quindi _soffiare sul fuoco_ significa alimentare la fiamma e, in senso figurato, rendere la situazione più tesa, fomentare contrasti, risentimenti, passioni. Vedi <
stackexchange-italian
{ "answer_score": 7, "question_score": 3, "tags": "meaning, idioms, phrase origin" }
Unable to print python thread name I am trying to print the default thread name for the timer thread, but that is printing nothing, please let me know what is wrong I have done. from threading import current_thread, Timer,Thread def def1(): print "inside def1 method",current_thread() timer1 = Timer(0,def1, []) timer1.setDaemon(True) timer1.start() and output is inside def1 method why above code is not printing the thread name, please let me know. I am using python 2.7 Thanks in advance.
`timer1` is a daemon thread. The most likely cause is that it gets killed (by your process terminating) before it gets a chance to print the result of `current_thread()`. Try joining the thread to see if it makes a difference (it does for me): from threading import current_thread, Timer,Thread def def1(): print "inside def1 method",current_thread() timer1 = Timer(0,def1, []) timer1.setDaemon(True) timer1.start() timer1.join() # <====== ADD THIS
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "python, python 2.7" }
How to access web application with another subnet? My computer ip is 10.0.0.19 and my default gateway is 10.0.0.2 I need to access web application with ip 192.168.0.120 using default gateway 10.0.0.190. I'm not sure how to do that ?
On Windows you can start a `cmd.exe` as an administrator and there run route add 192.168.0.120 mask 255.255.255.255 10.0.0.190 to create a route only for this IP or route add 192.168.0.0 mask 255.255.255.0 10.0.0.190 to create a route for the complete 192.168.0.x network. Using Linux the commands would be (don't forget to replace eth0 with the right interface) ip route add 192.168.0.120 via 10.0.0.190 dev eth0 ip route add 192.168.0.0/24 via 10.0.0.190 dev eth0
stackexchange-superuser
{ "answer_score": 0, "question_score": -1, "tags": "networking, routing" }
how to choose libc6 or libc6-dbg Im bug checking a c program and would like to install valgrind, the system then tells me that I should also install libc6 with debug symbols libc6-dbg. Now my question is, when I in the future compile with gcc, which version of libc will be used? How do I choose which libc6 I'm compiling against? I'm not asking how to install this, I'm on ubuntu so apt-get install libc6-dbg will do the trick.
`libc6-dbg` is not a separate library from `libc6` — it's the debugging symbols for `libc6`, so that you can get accurate tracebacks within libc.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "c++, c, gcc, libc" }
How to get all xtype values from a window Let's say I have a window which are several combobox's and texfield's. What I want to do, getting all selected and filled values from this window to be able to post server side. I used to ComponentQuery but only getting specified type of field. Is there any solution to get any kind of xtype values, like combobox, checkbox, textfield etc?
The solution is to use an Ext.form.Panel, it contains functionality to manage groups of fields: var win = new Ext.window.Window({ layout: 'fit', items: { border: false, xtype: 'form', items: [] // your fields here } }); // Later console.log(win.down('form').getForm().getValues());
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "extjs, extjs4" }
A problem about the limit of a sequence having to do with the partial sums of another sequence Let us suppose that $\\{a_n\\}_{n \in \mathbb{N} \cup \\{0\\}}$ is a sequence of positive real numbers and that the sequence $s_{0}, s_{1}, s_{2}, \ldots$ is defined by $s_{k}=a_{0}+\ldots+a_{k}$ for every $k \in \mathbb{N}\cup \\{0\\}$. Let us suppose that $\lim_{k \to \infty} \ln \left(\frac{s_{k+1}}{s_{k-1}}\right)=0$ and that $\lim_{k \to \infty} \ln(s_{k+1}s_{k})=\ell$ for a certain real number $\ell$. Do the previous conditions are sufficient to guarantee that the sequence $\\{\ln (s_{k})\\}$ has a limit as $k \to \infty$? Thanks in advance for your comments and answers.
$(s_k)$ is an increasing sequence and so is $(\ln (s_k))$. So we only have to check if this sequence is bounded. Suppose $\ln (s_k) \to \infty$. Then $\ln (s_{k+1}s_k) =\ln (s_{k+1})+\ln (s_k) \to \infty$ contradicting the hypothesis. Hence $(\ln (s_k))$ is convergent.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "real analysis, sequences and series, limits, power series" }
Ruby Enterprise Edition giving Time.now in wrong format On my VPS (Ubuntu 10.04LTS), I have ree-1.8.7-2011.03 and ruby-1.9.2-p180 installed through RVM. My problem is that when I call Time.now in ree-1.8.7(irb), I get `Thu May 12 12:16:50 +0200 2011`, when I do the same in ruby-1.9.2(irb), I get `2011-05-12 12:17:44 +0200`. The problem is the ree version of the date is unusable in my rails queries (The SQL generated is just plain broken). Formatting the time using strftime in every single query is not an option at the moment, and neither is switching to 1.9.2, so I need your help to figure out why this is happening and fix it. Thanks for any help!
This is not a REE issue. Ruby 1.9.2 changes the default format for Time#to_s. $ rvm use 1.8.7 ruby-1.8.7-p334 :001 > Time.now # => Thu May 12 12:42:35 +0200 2011 $ rvm use 1.9.2 ruby-1.9.2-p180 :001 > Time.now # => 2011-05-12 12:42:44 +0200 It's a good practice to never rely on the default Time#to_s format but always use a custom helper or method to format a date output otherwise you have no control on how the information are displayed. > Formatting the time using strftime in every single query is not an option at the moment Not only it should be an option, it should have been your first choice. I strongly encourage you to fix the existing code to use a custom formatting method. A temporary workaround would be to override Ruby 1.8.7 Time#to_s method to use a custom format. However, making such this change might break other libraries.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 0, "tags": "ruby on rails, ruby, ruby on rails 3, locale, ruby enterprise edition" }
Error on compiling a grid view I'm having a strange issue with getting my GridView - RowDataBound method to compile. I've got a simple GridView with the following: <asp:GridView ID="gv_View_Documents" runat="server" AllowSorting="true" DataKeyNames="DocumentName,Description" AutoGenerateColumns="false" OnSorting="gv_View_Documents_Sorting" OnRowCancelingEdit="gv_View_Documents_RowCancelingEdit" OnRowDataBound="gv_View_Documents_RowDataBound" OnRowEditing="gv_View_Documents_RowEditing" OnRowUpdating="gv_View_Documents_RowUpdating"> When I compile, it shows an error shown below. > Compiler Error Message: CS0123: No overload for 'gv_View_Documents_RowDataBound' matches delegate 'System.Web.UI.WebControls.GridViewRowEventHandler' I have a similar setup for another grid view with no compile issues. Any ideas? I'm working with C# and ASP.NET
Most probably your event handler method signature does not match with GridViewRowEventHandler signature i.e. public delegate void GridViewRowEventHandler( Object sender, GridViewRowEventArgs e ) Most probably, you may have used EventArgs as a parameter in your event handler.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "asp.net, gridview" }
Looking for a free Morphing - Ageing program for Mac OS X.6 I'm looking for a free morphing and/or ageing software for Mac OS X.6, not too hard to use, with the kind of Mac "one click" function, if you know what I mean. Cheap programs are also welcome, I paid for a Photoshop license, so why not another software... My goal is to be able to modify faces, make them look older or younger, add some piercing or other, funny stuff. Thanks for your tipps.
If you already paid for Photoshop then your best use of time is to learn how to do age progressions with Photoshop. Any decent artist will tell you that you can't "one click" half of the stuff they do. It takes a good eye, some practice, and some time. Age progressions are particularly tricky to do.
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "mac, software rec, photos" }
How to www-forward to a WordPress site? I'm trying to setup a www-forward that points a domain name to a WordPress category. Example: www.myexample.com forwarded to www.mywordpress.com/category. This returns an "Internal Server Error" though, and my host says that this is due to WordPress not making physical file structures. Maybe this should be in ServerFault, but I'm asking here if there are some ways to fix this in the WordPress settings, or with a plugin or so?
If I understand you correctly. Try Create a forward to a php page that then forward to the wordpress category. eg. On the server forward to www.myexample.com/to-category.php Then in the to-category.php <?php header("location: ?> That will send the viewer to your category page.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, wordpress" }
read.csv read csv file with function, cell wrapped with ="{value}" I export my CSV file with python, numbers are wrapped as ="10000000000" in cells, for example: name,price "something expensive",="10000000000", in order to display the number correctly, I prefer to wrap the big number or string of numbers(so someone could open it directly without reformating the column), like order ID into this format. It's correct with excel or number, but when I import it with R by using read.csv, cells' values show as =10000000000. Is there any solution to this? Thank you
how about: yourcsv <- read.csv("yourcsv.csv") yourcsv <- gsub("=", "", yourcsv$price) Also, in my experience `read_csv()` from the `tidyverse` library reads data in much faster than `read.csv()` and I think also has more logic built into it for nonideal cases encountered, so maybe it's worth trying.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "r" }
CATiledLayer to CALayer I have a view with a CATiledLayer backing. I want to take the visible tiles from this CATiledLayer UIView and add it to another view as its CALayer backing, thus recreating the visible image in another UIView that doesnt use CATiledLayer. The reason I want to do this is I will use this second UIView to mask the effect of updating the CATiledLayer backed UIView - this currently produces a flicker as all tiles are re-loaded. The problem is, I'm not totally sure how i would do this. Any ideas?
> CATiledLayer is a subclass of CALayer providing a way to asynchronously provide tiles of the layer's content, potentially cached at multiple levels of detail. You can render the visible things in the layer into a CGContextRef with: - (void)renderInContext:(CGContextRef)ctx And then use this to update your other layer by settings its delegate and implementing the - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context ss shown here < But honestly I don't think this is efficient.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 9, "tags": "iphone, ios, cocoa, uiview, catiledlayer" }
Delete all lines except the one that matches a pattern and also keep 2 lines before the match Is it possible in vim to delete all the lines except for the ones that match a pattern and also keep a couple of lines before and after (like a context in grep).
Since you mentioned grep, the cleanest way is probably to simply invoke `grep` on the whole buffer. %!grep -2 pattern_to_match I will update if I find a pure-vim solution, but I doubt it will be cleaner than the above solution.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "vim" }
The coordinate of mouse? public class mouse extends JFrame { private int x, y; private JLabel label; public mouse() { JPanel panel = new JPanel(); addMouseMotionListener(new MouseMotion()); label = new JLabel(); panel.add(label); setPreferredSize(new Dimension(400, 200)); add(panel, BorderLayout.SOUTH); pack(); setVisible(true); } private class MouseMotion extends MouseMotionAdapter { public void mouseMoved(MouseEvent e) { x = e.getX(); y = e.getY(); label.setText("mouse coordinate " + "(" + x + "," + y + ")"); }} public static void main(String[]args) { mouse a = new mouse(); } } When I move mouse to border, it is not (0,0). Why? For example, I move mouse to top left corner, it shows (4,30) rather than (0,0).
Add the MouseListener or MouseMotionListener to the JFrame's contentPane, not the JFrame itself, else you have to worry about borders, menus, insets, and the like. For example: getContentPane().addMouseMotionListener(new MouseMotion()); Also, please format your code so we can read it.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "java, swing, mouse" }
Notepad++ Search and Replace with Tab Delimited File I have a file that is tab delimited. When exporting from Excel, if the cell has a comma in it, it will wrap the cell with double quotes. To find the first double quote, I can look for a tab then double quote ex: `\t"` The next double quote to remove is at the end of the line, so I would like to find double quote then newline ex: `\n"` but this is not working. Example of the file format: `text``TAB``text``TAB``"moretextwithquotes"``CRLF`
First, you're searching for `\n"` instead of `"\n`, if I well understand your problem. Secondly, you need to search for `\r\n` instead of `\n`, so your final result should be `"\r\n`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "regex, excel, notepad++" }
In an electric vehicle, do you need to come to a complete stop before switching to low gear? I recently got a 2016 Ford Focus Electric. Before that, I was driving a 1996 Toyota Camry Wagon. I've been told many times that one needs to come to a complete stop before changing gears or else risk damaging the transmission. However, electric cars have a one gear transmission, so I wasn't sure if this same concern applied to them. Broadly, do I need to come to a complete stop in an electric car before changing gears? Specifically, do I need to come to a complete stop in an electric car before switching to low gear from drive, or to drive from low gear?
The Ford Focus Electric doesn't have a transmission per se, the gear selector is actually a mode selector for the electric drivetrain. Switching from D to R changes the polarity of the electric motor, causing it to spin in the other direction. When you are in Drive the car is in "Auto Regeneration" mode, meaning that whenever you lift your foot off the pedal it will automatically slow you down by using regenerative braking (changes the motor into a generator and converts kinetic rolling energy back into electric power). Low mode engages more auto-regeneration, slowing you down much faster if you lift off the pedal, possibly useful if you want to go down a hill and don't want to ride the brake (which also engages regenerative braking). Low mode has no benefit for going up a hill as it doesn't change any sort of ratio. So, changing from D to L can be done at any speed without any sort of issues. There's a discussion of the benefits/drawbacks of D,L and N modes here.
stackexchange-mechanics
{ "answer_score": 4, "question_score": 5, "tags": "transmission, electric vehicle" }
Neural Network - convert model output to the predicted target class I am building a neural network from scratch in python. In the dataset I am using for testing, the features are all numeric (57 features) and the target variable is categorical (10 classes, already converted it to numeric from 0-9, but can use other encoding). Everything seems to be working, except that I am quite stuck on how to compare my model output with the y_true value to compute the error. So I have 10 classes for the target variable and what I get as output is an array of 10-elements for each observation, instead of a unique value/classification for each sample. Can someone give me a simple way to convert my output to a single y_predicted value that's comparable with the y_true? I am trying not to use any libraries except for Numpy and pandas, so using Keras SparseCategoricalCrossentropy() is not an option.
So neural networks don't return the class labels as we know it. They return probabilities of the input belonging to all the classes. Naturally, these probabilities sum up too 1. Suppose you have 4 classes: A, B, C and D. if the true label of an input is B, the NN output will not looks like this: output = [0, 1, 0, 0] It will look like this: output = [0.1, 0.6, 0.2, 0.1] Where the chance of input belonging to class A is 10%, class B is 60%, class C is 20% and class D is 10%. You can easily make sure that this array sums up to 1 by adding the array elements and dividing each element by the sum. Then, you can use numpy argmax to get the index of the highest probability. If you don't need the probabilities, then you can skip converting the output such that the sum is 1 and directly apply numpy argmax to get the index of the class with the highest probability.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, neural network" }
How to get the tuple which contains nearest tuple to a given tuple I have a list of tuples: x = [('abc', (7, 1, 8, 41), None), ('efg', (12, 2, 13, 42), None)] element = (13, 2, 14, 78) I need to fetch the tuple that has the tuple which is nearest to the 'element'. i.e I need to get the answer as **('efg', (12, 2, 13, 42), None)** for element = **(13,2,14,78)** How can I do this in python?
It's very simple. Let take step by step to clear your question. It is **count** the **matches** by 2 **tuple** and get the **max**. maxCount = 0 index = 0 for i,item in enumerate(x): count = 0 for a in element: if a in item[1]: count+=1 if maxCount < count: index = i print(x[i])
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, python 3.x" }
Different Prices per Customer Is it possible to have a different price to your customers? This is mainly for wholesale where retailers would have different pricing depending on several things. The idea is that once they login they would be able to see their price in the system.
It is possible, but it involves a few concessions on your part. Are you willing to split your inventory? Same SKU could cost N prices. So you have to split available inventory N ways. If it is simply a retail vs wholesale price, it is much easier. Tag the customer as wholesale, and then in your theme, when a customer is tagged wholesale, you'd show off wholesale priced products, likely from some wholesale collection. If they were retail, you'd show the retail collection of products. When you examine how Apps do customer specific pricing, you'll see other concessions you might have to make too.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "shopify" }
Conditional variables depending on whether Matlab or Octave is running the code I have written some code for Matlab/Octave. Basically, they have the same syntax and everything, but, for example, they have different functions for optimization (`linprog`/`glpk`,`quadprog`/`qp`). I want to run the same code in both Matlab and Octave and this code suffers from needing different functions in each environment. Until now, I have a variable that tells the programm whether it is running on Matlab or on Octave, but I always have to set this variable manually. Is there a way that a program can recognise in which environment it runs? So, I want a statement to set the variable `x=1`, if it is running on Octave and `x=0` if it is running on Matlab.
You could check whether Octave’s built-in variable `OCTAVE_VERSION` is set.
stackexchange-superuser
{ "answer_score": 2, "question_score": 3, "tags": "matlab, octave" }
How to set the filter for wordpress xmlrpc wp.getPosts while using node.js? (NOT PHP) I was wondering how to set the filter option for wp.getPosts. I want to get posts with a status of 'trash'. is currently blank, and returns all posts other than trash. I am using the xml-rpc wordpress api. Here is my current code: wpw.getPosts('<filter>', ['title','status'], function(err, data){ }); I am not sure what to put in the filter section, all the examples I could find are PHP examples and do not work in this context. Is it even possible to get the posts with a status of 'trash'?
It is possible to get posts filtered by status. For the filter I added: {status:'trash'} This worked well. To get multiple status filters I just used an array: {status: ['trash','publish']}
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "wordpress, node.js, filter, recycle bin" }
question about recognizing function and module in python My questions are about code with this format: name1.name2() Question1: I saw this format in python a lot. I want to make sure is it ture that every time I see this format name1 is a module and name2() is a function of this module? Question2: Is it possible to have name1.name2 (without () in front of name2)? and in this format is name2 a module or function?(My Thought on question2: name2 cant be function because it need "()" to be a function But I am not sure if it is a module or even we have this format.)
Answer 1: Actually you cant be sure at all since it's not necessary for the `name1` to be a module. It can be almost anything. And anyhing in Python is an Object :) The `name2`, as a result, is probably a method of that Object. So the `name1` can be an instance of a class, the class itself, a string, an integer, a module or a package, whatever ... Answer 2: Yes, it is possible to have that format. The `name2` in this case may again be a lot of things, it can be anything that is defined in the `name1` object. It can be a property, a function in the module, a module in a package, a method of the Object or anything else.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "python 3.x" }
Possible to generate an iPhone application automatically from another iPhone application? As title; is there any function that can achieve this?
Theoretically maybe, practically no. If you want to sell it in the App store double no.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "iphone, cocoa touch, code generation" }
Error Query failed: Cannot unnest type: row I'm running a query with a select bar_tbl.thing1 from foo cross join unnest(bar) as t(bar_tbl) And got the error `Error Query failed: Cannot unnest type: row` Why? The bar column looks like this `{thing1=abc, thing2=def}`
Turns out I was trying to expand a row, which doesn't make sense. I should have just done select bar.thing1 from foo
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 11, "tags": "presto" }
spark withcolumn create a column duplicating values from existining column I am having problem figuring this. Here is the problem statement lets say I have a dataframe, I want to select value for column c where column b value is foo and create a new column D and repeat the vale "3" for all rows +---+----+---+ | A| B| C| +---+----+---+ | 4|blah| 2| | 2| | 3| | 56| foo| 3| |100|null| 5| +---+----+---+ want it to become: +---+----+---+-----+ | A| B| C| D | +---+----+---+-----+ | 4|blah| 2| 3 | | 2| | 3| 3 | | 56| foo| 3| 3 | |100|null| 5| 3 | +---+----+---+-----+
You will have to extract the column `C` value i.e. `3` with `foo` in column `B` import org.apache.spark.sql.functions._ val value = df.filter(col("B") === "foo").select("C").first()(0) Then use that value using `withColumn` to create a new column `D` using `lit` function df.withColumn("D", lit(value)).show(false) You should get your desired output.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "scala, apache spark, dataframe, apache spark sql" }
SAS column input skipping lines I was looking at the SAS base exam questions and I came across this particular one: data test; input employee_name $ 1-4; if employee_name = ‘Ruth’ then input idnum 10-11; else input age 7-8; datalines; Ruth 39 11 Jose 32 22 Sue 30 33 John 40 44 ; run; At first I thought the IDNum when the employee name is "Ruth" would be 11, but it seems it skips the Ruth row and jumps down to the second row, and inputs 22 instead. And why is Sue's age 40 instead of 30? Can someone explain why this is? Thank you. Here is the result: Name IDnum Age Ruth 22 Sue 40
Without a trailing `@` or `@@` at the end of an input statement, any subsequent input statements in the same data step will skip the rest of the current line start reading from the beginning of the next line.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "testing, sas" }
Neumann KM 183 Stereo Pair Just wondering if anyone has had any experience of using these for recording outdoor atmos and quiet room tones? I would like a pair of omnis to record open outdoor spaces and from what I understand are also good for quiet room tones (or air) as omnis have low noise. Would like to know how these compare to the Schoeps CMC with omni capsule or the Sennheiser 8000 series omnis. Cheers.
Here's a quick room tone recording inside a playback/conference room I made just now with the KM183: < (this is the original 96 kHz 24bit wav file) (re-uploaded Feb. 25th) Neumann KM183 spaced omni pair, about 1m apart, into a Sound Devices 788t, 60 dB of gain. No filtering, no editing. The background SPL was 31.0 dBA (measured). The buzz you hear is a pair of Genelec subwoofers that is switched on. At the moment, I don't have any quiet outdoor atmos on hand. Maybe I'll get around to it later.
stackexchange-sound
{ "answer_score": 0, "question_score": 4, "tags": "neumann, omni, ambience, room, stereo" }
Getting form widget name in Symfony2/Twig So, what I need to do is to output current element's ID in each `field_row`. What I came to is overriding Symfony's default field_row block with the following code: {% block field_row %} {% spaceless %} <div class="clearfix" id="{{ form.get('name') }}-row"> {{ form_label(form) }} <div class="input"&gt; {{ form_widget(form) }} </div> </div> {% endspaceless %} {% endblock field_row %} However, the `{{ form.get('name') }}` construct seems pretty awkward to me and I'm sure there's a more civilised way of doing this. Anyone?
Do you mean the id generated by symfony? then it's just: {{ id }}
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "symfony, twig, symfony forms" }
Braking force required to allow bike to move down slope with an arbitrary constant velocity > _Find the braking force required to allow a bike to move down a frictionless slope, inclined at $\theta$ radians above horizontal, with a constant velocity of v m/s._ I'm confused because Newton's 2nd Law of motion implies that the sum of forces on the bike must be zero in order for velocity to be constant, meaning that the braking force required is simply the bike's weight, resolved long the direction of the slope, in the opposite direction. But this only makes sure that velocity is constant. How is it possible to apply a force to make the bike move with a constant velocity, of exactly v? My guess is that it has something to do with work, energy and power, but I haven't found a way yet.
You are right that in this theoretical problem the breaking force to achieve constant velocity is the same for all velocities. You either stipulate that the bike has the desired speed as a initial condition, or that it coasts with no breaking applied until the desired velocity is reached. In the real world, there will always be some friction or drag forces that are dependent on velocity, so for a real bike going down a real hill, there will be different breaking forces required to keep the bike at different speeds. Also there would be a human in the control loop adjusting the breaking pressure as needed to maintain the desired speed, probably without much conscious thought. These factors together make the answer to this problem seem unintuitive, but you have it right.
stackexchange-physics
{ "answer_score": 2, "question_score": 3, "tags": "homework and exercises, forces, energy" }
How do I remove the title attribute from images in Wordpress? My client is not too crazy about the tooltip you see when you hover on images in browsers like Safari. !enter image description here The tooltip displays the title attribute in the img tag, which Wordpress forces you to have. Removing the title value from the tag (easy to do with jQuery) still shows you a blank tooltip. So I don't need a solution that does this: <img title=" " src="foobar.png" /> I need a solution that does **this** : <img src="foobar.png" /> I have searched all over the Internet, and the answers that come close don't seem to work. I believe it can be done by overriding the Wordpress core function that generates the image tags.
If you want a straight JavaScript solution this should work: var imgs = document.getElementsByTagName('img'); for (var i = 0; i < imgs.length; i++) { imgs[i].removeAttribute('title'); }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php, javascript, wordpress" }
set width to float div I have a div that contains two other divs,, like this: ---------------------------- | | | | | | | div 1 | div 2 | | | | | | | | | | ---------------------------- div 1 has a fixed width and in same cases i need to remove it. div 2 is always shown. The container of the two div has a fixed width. My problem is how to define div2 width. If there is div1, div2 width has to be x but if the div1 is not shown, div2 width has to be the same of the container. Div1 and div2 have the following css: #div1{ width: 146px; height: 118px; float: left; } #div2{ height: 104px; padding: 12px 5px 2px 11px; float: left; } How can i do?
Write like this: **CSS** #div1{ width: 146px; height: 118px; float: left; background:red; } #div2{ height: 104px; padding: 12px 5px 2px 11px; overflow:hidden; background:green; } Check this <
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "css, html, width, css float" }
steps to deploy the BIRT reports in jboss AS7 for reports= BIRT server =JBOSS AS 7.1.1 front end =Richfaces i have created some reports using BIRT.But when i am calling the reports through my webpage it is showing error. how to deploy the reports in jboss and how to call the reports?
See Eclipse's BIRT Viewer Setup documentation here. From the 'Deploying to JBoss' section of the referenced link: > * Download the zip file with the BIRT report engine runtime. The file is named birt-runtime-version#.zip. > * Unzip the file in a staging area. > * Look under the birt-runtime- directory and locate the "WebViewerExample" directory. > * Copy the "WebViewerExample" directory to your JBoss installation, under the deploy directory for your configuration. (eg) C:\dev\jboss-as-7.1.1.Final\standalone\deployments. > * Rename the WebViewerExample directory to birt.war, so it will deploy in place. > * Start up JBoss and enter the URL to BIRT (ie < and run the test report. >
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jboss7.x, birt" }
How to concatenate multiple shell variables into one? I need to form a single variable from a for loop. My script: #! /bin/sh if [ "$#" -le 1 ]; then echo "Illegal number of parameters" exit 1 else # Form domains variable DOMAINS="" for i in "${@:2}"; do DOMAINS+="$i," done echo "${DOMAINS::-1}" fi When I execute it: sh script.sh command domain1 domain2 I get the following error: certbot.sh: line 10: DOMAINS+=mmand,: not found certbot.sh: line 10: DOMAINS+=domain1.com,: not found certbot.sh: line 10: DOMAINS+=domain2.com,: not found It seems as I used bash syntax since the following execution works: bash script.sh command domain1.com domain2.com I get: domain1.com,domain2.com I need it to work as sh not bash. I can't seem to find a solution.
Just: IFS=, echo "$*" Or you seem to want from a second argument. Then like: ( shift; IFS=,; echo "$*" )
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "linux, bash, shell" }
Pegar um objeto de uma lista por referência e não por posição Olá, gostaria de saber como posso criar uma lista de objetos em C#, mas ao invés de pegar eles por `posição ([0], [i])`, quero pegar por referência `[LacoAzul] [CorVermelha]`. Tem como criar uma lista assim? Desde já obrigado!
Existem algumas classes do Framework que funcionam assim. Você pode usar um dicionário.aspx). Em um dicionário não existe ordem. Você acessa os elementos por chaves. A chave pode ser de qualquer tipo - se for um tipo por referência, então você pode passar a referência de um objeto para obter o outro objeto do par **chave** - **valor**. ~~Talvez uma tabela hash (com a classeHashtable.aspx)) também resolva o seu problema. Assim como o dicionário ela também funciona com pares de **chave** - **valor** , mas é uma estrutura mais simples.~~ **edição:** a classe Hashtable agora é obsoleta. P.S.: se o objetivo é _apenas_ saber se o elemento se encontra na lista, a própria lista genérica (classe List.aspx)) possui o método `Contains`.aspx), que indica se um elemento se encontra ou não na lista a partir de sua referência.
stackexchange-pt_stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "c#" }
How to set CultureInfo.InvariantCulture default? When I have such piece of code in C#: double a = 0.003; Console.WriteLine(a); It prints "0,003". If I have another piece of code: double a = 0.003; Console.WriteLine(a.ToString(CultureInfo.InvariantCulture)); It prints "0.003". My problem is that I need a dot as decimal mark but C# makes a comma as default. Besides I don't want to type such a long line of code just for printing out a double variable.
You can set the culture of the current thread to any culture you want: Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; Note that changing the culture also affects things like string comparison and sorting, date formats and parsing of dates and numbers.
stackexchange-stackoverflow
{ "answer_score": 58, "question_score": 38, "tags": "c#, double" }
Can FreeForm Pro email a user-entered value? I have a situation where somebody will submit a form, then somebody else will come back and edit that form. Upon submitting the edit, an email address defined in an open text field in the form will be emailed a notification. Is this possible with FreeForm Pro? I'm using 4.2.5 with EE 2.7.3, but I'm open to upgrading if a newer release works.
There's currently no support for this with Freeform Classic (aka Freeform Pro 4/5/6), nor is there for the new Freeform (aka Freeform Next) editions. However, sometime in the future we might add this type of functionality to Freeform Pro (Next) for EE3/EE4. :)
stackexchange-expressionengine
{ "answer_score": 1, "question_score": 1, "tags": "solspace freeform" }
rsync fails and can't connect to host I am running a rsync script that is very simple: #!/bin/sh rsync -avz --delete <path> user@hostname:<dest path> I use it everyday and works fine, today it seems I can't run it and I am not sure why. Biggest change to my system I made is update Java. The behavior is it just looks like it hangs, and if i let it run long enough I get: rsync: connection unexpectedly closed (0 bytes received so far) [sender] rsync error: unexplained error (code 255) at /SourceCache/rsync/rsync-42/rsync/io.c(452) [sender=2.6.9] I am able to rsync from my host to my machine but not vice versa.
The problem lies in my .bash_profile. I removed it and it seemed to work. Odd thing is when I put it back it seems to still work
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "macos, rsync" }
How to initialize SystemUsage of ActiveMQ with spring-boot? I'm trying to initialize **embedded** `activemq` JMS using `spring-boot`. It works in general, but I want to also lower the memory usage. Therefore I'm trying to provide the `SystemUsage` as a bean. But the `SystemUsage` bean is not taken into account and the activemq embedded has still the default configuration of _1GB_ . What might be wrong? @EnableAutoConfiguration @EnableJms public class AppConfig { @Bean public SystemUsage systemUsage() { MemoryPropertyEditor editor = new MemoryPropertyEditor(); SystemUsage system = new SystemUsage(); MemoryUsage memory = new MemoryUsage(); editor.setAsText("20mb"); memory.setLimit((long) editor.getValue()); system.setMemoryUsage(memory); return system; } }
You have to inject that bean manually to the amq broker if you need to alter the default config. So I guess you are stuck with manually fire up the broker using spring xml or java somewhere to set that property.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, spring, activemq, spring boot" }
"Something that interests me" and "Something interesting me" I know that "something that interests me" and "something interesting me" are equivalent. But I would like to know if there is any further subtle difference between these two?
They're related, but they're not the same. "Something that interests me" is talking about the thing itself. "What are you staring at?" "I'm looking at that building. Architecture is something that interests me." "Something interesting me" refers to the process, not the thing. I'm struggling to come up with an example that does not sound awkward because it's not something a fluent English speaker would normally say. Maybe, "Why did you walk into the fence?" "I was distracted, my mind was occupied by something interesting me." But that's awkward.
stackexchange-ell
{ "answer_score": 1, "question_score": 4, "tags": "phrase usage" }
xampm phpmyadmin cannot edit, delete or add database I installed Xampp and I was able to start apach and mysql with `8080` port, but the problem is when I want to log in `phpmyadmin` using this link: ` I can't login unless I changed this line in `config.inc.php` from `['auth_type'] = 'cookie';` to `['auth_type'] = 'config';` and it let me login without username and password and I can't edit, delete or add new database. for example when I try to create new databse it stuck on this message: `(processing request)` any help will be appreciated. I am using windows 10
In `config.inc.php`, if you changed your DB username and password, make sure it's correct in these lines: $cfg['Servers'][$i]['user'] = '<user>'; $cfg['Servers'][$i]['password'] = '<password>'; Hope I helped! -CM
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, mysql, phpmyadmin" }
There are not available platforms Im using cocos2d-x version 12 and NDKrc12 and I have all the paths in my .bash_profile set. But when I build for android and type: cocos compile -p android It displays a message "There are not available platforms" which can't be because I have the android SDK installed in the correct path what is wrong?
On the latest version of cocos2d-x for some odd reason you need to use the '-s' option like this: cocos run -s /Users/me/myprojects/mygame -p android Otherwise without '-s' it displays "there are not available platforms" seems unnecessary when your in your project folder but I guess it is!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "android, cocos2d x" }
Google Video does not embed in IE This google video embedded code does not work in ie. Just blank space. <embed id=VideoPlayback src= style=width:400px;height:326px allowFullScreen=true allowScriptAccess=always type=application/x-shockwave-flash> </embed> Chrome and FF works fine. The question is: How can I create Alt picture for embedded video(For example if the video is not loaded correctly, the picture with a link to the video will be shown. Thanks
IMHO a simple link to the video link would solve. <embed id=VideoPlayback src= style=width:400px;height:326px allowFullScreen=true allowScriptAccess=always type=application/x-shockwave-flash> </embed> Video not loading correctly? Click <a href="videourl">HERE</a> By the way AFAIK Internet Explorer doesn't support embeddings.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "video" }
Evaluating Hall Effect Sensor - Practical Explanation of Bops / Brps? I am trying to choose between two types of hall effect diodes with internal pull-up resistors. What is the practical explanation when comparing the Bop and Brp of the types (red square): \- AH3781 and AH3782? Do the Bop and Brp of the hall effect sensor determine the sensitivity of the sensor? ![enter image description here](
Yes, these values show the sensitivity of your sensor. The B is your magnetic flux density strength (in Gauss) and Bop is your operating point, and Brp is your release point. By the + and - values, I would think this has something to do with it sensing from their North and South poles. Let's use the AH3781 as an example. Essentially, it looks like when the South pole reaches 25G, the sensor will switch on and go low (due to the internal pullup note, it is safe to assume that the output of this sensor is HIGH), then to switch it back OFF again, you will need 25G sensed on the North pole. **Confirmation** In fact, if you look at this DATASHEET, you will see I was correct. The important thing to note, is the _smaller_ the number is, the _more sensitive_ your sensor is. Also, be aware of the direction of magnetic flux. Different sensors will detect on different axis. The datasheet will usually tell you, then you can figure out the best orientation for your sensor or magnet.
stackexchange-electronics
{ "answer_score": 1, "question_score": 2, "tags": "hall effect" }
Assigning 2 values to radio button element and calling them in PHP I have radio inputs on a form I am trying to assign them two separate values. One shall be the name of the product, the other is the price of the product. Then in php I will be totaling the selections. <input type="radio" id="tile1" name="tile" value="Calcatta 12x 24 | 2.99" /> <input type="radio" id="tile2" name="tile" value="Subway 3x12 | 1.99" /> <input type="radio" id="tile3" name="tile" value="Marazza 12x24 | 2.99" /> <input type="radio" id="tile4" name="tile" value="Chicaro 12x12 | 3.99" /> For my confirmation email, I need to be able to call on the name of the product. For totaling cost, I need to be able to call on the price of the product. i have tried to search a solution, but I haven't been able to find a specific solution that works.
You should `explode()` the value of `tile` like: $tile = $_POST['tile']; // e.g. "Calcatta 12x 24 | 2.99" $details = explode(' | ', $tile); echo $details[0]; //Calcatta 12x 24 echo $details[1]; //2.99 Please note: never ever trust/use user-submitted data like in the example above. Avoid using `$_POST`/`$_GET` variables 'as is'.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "php, html, forms" }
how to use simple alert message using TempData with Escape single asp.net mvc I have the following string in french languages which contains single quotes between the characters and words. This message I want to show in alert. string Mlocal = "Ce porduit n'a pas encore été livré."; TempData["msg_Vide"] = "<script>alert('" + Mlocal + "');</script>"; the alert not showing **i use escape "`\'`" and "`&sbquo;`" and "`&#8218;`" and "`&#39;`" but not working** passing string value is ok, but passing alert message with the special characters no ok
Just pass the string to you view and let your view do the rest (and of course escape your single quote: public IActionResult Index() { TempData["msg_Vide"] = "Ce porduit n\\'a pas encore été livré."; return View(); } View: @if(TempData["msg_Vide"] != null) { <script> alert('@Html.Raw(TempData["msg_Vide"])') </script> } ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net mvc" }
Reflective subcategory, initial object Why is the reflection $R(a)$ of an intial object $a$ also initial object in the reflective subcategory ( **please explain in some detail** )? It is nearly obvious but not quite. $A \subseteq B$ is reflective in $B$ ifand only if there is a functor $R : B\to B$ with values in the subcategory $A$ and a bijection of sets $A(R b, a) \cong B(b, a)$ natural in $b\in B$ and $a \in A$. A reflection may be described in terms of universal arrows: $A \subseteq B$ is reflective if and only if to each $b\in B$ there is an object $R(b)$ of the subcategory $A$ and an arrow $\eta_b : b\to R(b)$ such that every arrow $g: b\to a \in A$ has the form $g = f\circ \eta_b$ for a unique arrow $f: R(b)\to a$ of $A$.
Let $I : A \to B$ be the inclusion functor, and let $R' : B \to A$ be the obvious functor induced by $R$. A more informative way to describe the natural bijection of sets is as giving an adjunction $R' \dashv I$; i.e. where $R'$ is left adjoint to $I$. It's a general theorem that left adjoints preserve all colimits that exist in the source category. In particular, initial objects are colimits of empty diagrams. The theorem is actually a one-liner, using the hom-set formulations of colimits and adjunctions: $$ \hom_A(R'(\mathrm{colim}_i b_i), a) \cong \hom_B(\mathrm{colim}_i b_i, Ia) \cong \mathrm{lim}_i \hom_B(b_i, Ia) \cong \mathrm{lim}_i \hom_A(R' (b_i), a) $$
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "category theory" }
Decode string with \x in PHP that has char encoded over 255 # My problem is about string decoding. Let's assume a string like: $str = "\xce\xbb\xc6\x9b\xc2\xac\xe2\x88\xa7\xe2\x9f\x91\xe2\x88\xa8\xe2\x9f\x87\xc3\xb7 \xe2\x82\xac\xc2\xbd\xe2\x88\x86\xc3\xb8\xe2\x86\x94\xc2\xa2\xe2\x8c\x90\xc3\xa6"; I want to decode it and to look like that: `λƛ¬∧∨÷ €½∆ø↔¢⌐æ` I tried to use utf8_encode(utf8_encode($str)); But it's not what was expected. In python something like that works: _str = b"\xce\xbb\xc6\x9b\xc2\xac\xe2\x88\xa7\xe2\x9f\x91\xe2\x88\xa8\xe2\x9f\x87\xc3\xb7 \xe2\x82\xac\xc2\xbd\xe2\x88\x86\xc3\xb8\xe2\x86\x94\xc2\xa2\xe2\x8c\x90\xc3\xa6" _str = _str.decode() print(_str)
You don't need to decode that. This is legal notation for strings in PHP. $str = "\xce\xbb\xc6\x9b\xc2\xac\xe2\x88\xa7\xe2\x9f\x91\xe2\x88\xa8\xe2\x9f\x87\xc3\xb7 \xe2\x82\xac\xc2\xbd\xe2\x88\x86\xc3\xb8\xe2\x86\x94\xc2\xa2\xe2\x8c\x90\xc3\xa6"; echo $str; //λƛ¬∧∨÷ €½∆ø↔¢⌐æ <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, utf 8, decode, encode" }
algebra odd numbers A question states, using algebra, prove that when the square of any odd number is divided by four, the remainder is $1$ I managed to go up to $4(n^{2}+n)+1$, from $(2n+1)^{2}$ but I dont know how to prove it. Please help!
You say you managed to go from $(2n+1)^2$ to $4(n^2+n)+1$, but aren't sure how to continue from here. The final step left ( _which depending on skill level of writer and reader can be omitted entirely_ ) is to cite the quotient-remainder theorem which paraphrased states that for any integer $a$ and positive integer $b$ there exists a unique pair of integers $\color{red}q,\color{blue}r$ with $0\leq \color{blue}r<b$ such that $a=b\color{red}q+\color{blue}r$. Here $\color{red}q$ is called the "quotient" and $\color{blue}r$ is called the "remainder" for the division So, we recognize that $(2n+1)^2 = 4\color{red}{(n^2+n)}+\color{blue}1$, so by the quotient-remainder theorem, since we could write $(2n+1)^2$ as above it follows from the uniqueness part of the theorem that $1$ is in fact _the_ remainder.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "linear algebra, numerical linear algebra" }
setup an ftp server with mamp pro I am currently using mamp pro on osx for local development and I want to mirror my mosso cloud setup as much as possible. has anyone setup an ftp server with their local installation of mamp pro using sites i.e. local.mydev.com through apache? hope everyone had a great holiday.
heres how to do it: < found the instructions on Mamps site
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "apache, macos, ftp, mamp" }
If $P_n(1)=1$ calculate $P'_n(1)$ in Legendre polynomials $P_n(x)$ is in $[-1,1]$ and $P_n(1)=1$ .The problem is getting $P'_n(1)$. On Wikipedia it says that it is $\frac{n(n+1)}2$. I derive the problem showed here How could I prove that $P_n (1)=1=-1$ for the Legendre polynomials? in order to get P'(n) but it didn't helped so much.
It follows by induction from the recurrence $$ (n+1) P_{n+1}(x) = (2n+1) x P_n(x) - n P_{n-1}(x) $$ Just differentiate both sides and use that $P_n(1)=1$.
stackexchange-math
{ "answer_score": 3, "question_score": 4, "tags": "orthogonal polynomials, legendre polynomials" }
Cocoa/Swift 3.0 replacement for NSNumberFormatter.isPartialStringValid In a Swift Cocoa app for macOS I inherited from NSNumberFormatter and have overridden isPartialStringValid. After migrating to Swift 3.0 I now have to subclass NumberFormatter and I get the error "Method does not override any method from its superclass". With what could I replace the method? override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<AutoreleasingUnsafeMutablePointer<NSString?>>?, errorDescription error: AutoreleasingUnsafeMutablePointer<AutoreleasingUnsafeMutablePointer<NSString?>>?) -> Bool { ... }
When I typed `isPartialS...` inside a subclass of `NumberFormatter`, Xcode suggested this: override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>?, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool { //... } Seems your method header has extraneous `AutoreleasingUnsafeMutablePointer`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "swift, cocoa, swift3" }
How to take Elasticsearch single index backup Can someone guide me to take single index backup in elasticsearch. When I search for this, I get all commands to take full snapshot.
By default a snapshot of all open and started indices in the cluster is created. This behavior can be changed by specifying the list of indices in the body of the snapshot request. PUT /_snapshot/my_backup/snapshot_2?wait_for_completion=true { "indices": "index_1,index_2", "ignore_unavailable": true, "include_global_state": false }
stackexchange-serverfault
{ "answer_score": 1, "question_score": 0, "tags": "linux, elasticsearch" }
How To Check If CustomSetting OrgDefault is empty? Documentation Custom Settings Methods says: > getOrgDefaults(): > > If no custom setting data is defined for the organization, this method returns an empty custom setting object. How to check if it is empty, because == null is not working here. XyCustomSettings__c customSettingObject = XyCustomSettings__c.getOrgDefaults(): Boolean checkboxSet = (customSettingObject == null)?true:customSettingObject.checkbox_Activated__c; I also tried if (customSettingObject.checkbox_Activated__c == null) didn't work.
For hierarchy settings, you can use: Settings__c.getOrgDefaults().Id == null If there was no data, there would be a null ID value; otherwise you would have a non-null ID value.
stackexchange-salesforce
{ "answer_score": 8, "question_score": 3, "tags": "customsetting" }
When is it a good idea to punch people? As a Heavy, I have in my posession what is arguably the most powerful close-range weapon in the game. One that can shred through an enemy in fractions of a second. I am also in posession of the biggest 'guns' in the game, them being my massive fists of doom. Which seems redundant, given the large number of boolits I can shoot with my mighty mighty gun. So when is it a better idea to spend the time switching to my fists for a good punchfest, over holding out my minigun and preparing for a mowdown?
As with almost every melee weapon, the answer is almost never. This is especially true with the heavy- you have the strongest short range weapon in the game as your primary weapon and you are far too slow to easily punch anyone. Even if you are out of ammo, punching someone is still a bad idea. A non-critical melee attack usually* deals 65 damage and takes almost a second between attacks. This gives your target plenty of time to back away and shoot you. At this point there is nothing you can do to your target- they're faster than you. If you're looking for a weapon that doesn't need spinning up, use one of the Heavy's shotguns. The real use for your fists is you can swap them for either the Gloves of Running Urgently, which cause you to run faster and take minicrits when wielded or the Fists of Steel, which reduce incoming ranged damage and increase incoming melee damage when wielded. *Scout, spy and certain unlockable melee weapons change this.
stackexchange-gaming
{ "answer_score": 17, "question_score": 30, "tags": "team fortress 2, tf2 heavy" }
Does `UPDATE SET WHERE` have concurrency issues? Consider the statement below UPDATE SET is_locked = 1 WHERE id = 1 and is_locked = 0; Does it have consistency problem under concurrent updates? Why? (MySQL 5.7, with transaction isolation level of REPEATABLE-READ)
No, it does not, since update requires an exclusive lock on the record being updated and innodb will not grant more than 1 exclusive lock on a record at a time.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mysql, concurrency, innodb" }
How to extract json data from a Promise.all in node.js **This works fine** esi_requests.fetch('character_info', {character_id: character_id}) .then( results => results.json() ) .then( results => { console.log(results) }) **But how do I get the same information from 2 promises with a Promise.all?** Promise.all([ esi_requests.fetch('character_info', {character_id: character_id}), esi_requests.fetch('character_info', {character_id: member_id}) ]) .then( results=> { // what do I do here to translate the response-body from both requests to json? }) .then( results => { console.log(results) })
You can do it before you have the results. Performance is actually quite a bit better if you do. You don't have to wait for all the requests to finish before you start .json'ing them. e.g.: Promise.all([ esi_requests.fetch('character_info', {character_id: character_id}).then(res => res.json()), esi_requests.fetch('character_info', {character_id: member_id}).then(res => res.json()) ]) .then( results => { console.log(results) }) What you probably actually want is a function that sets this up for you. const example = id => esi_requests.fetch('character_info', {character_id: id}).then(res => res.json()); Promise.all([character_id, member_id].map(example)) .then( results => { console.log(results); })
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "node.js, promise" }
Can OkHttp used in Java Projects without android We see many good reviews about rest client OKHTTP , but we are in dilemma that can we use it in normal java projects (ie: Spring batch, java batches) as we see it is primarily used in android applications Could some one throw some light on this ? Thanks,
OkHttp works great on non-Android Java projects. It’s used extensively in Square’s backends, where it carries tens of thousands of calls per second between services. It works well on its own, and also when paired with cloud mesh tech like Envoy and Istio.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, okhttp" }
Which is the correct way yo use in business mails in below sentences We **haven’t been** offloaded any items by last Thursday. Or We **didn’t** offload any items by last Thursday. Pls share the correct grammatical sentence to use in business mails
As Phylyp mentions, your two sentences have different meanings. In either case, though, the correct tense (in business mails or otherwise) is the past perfect: > We hadn't been offloaded any items by last Thursday. > We hadn't offloaded any items by last Thursday. You are speaking of something that happened before a time point in the past (by last Thursday), so you have to use the past perfect.
stackexchange-ell
{ "answer_score": 0, "question_score": 0, "tags": "grammar, prepositions, sentence construction, grammaticality, difference" }
How to use specific conditions in dataFrame.loc in pandas python? I have a pandas Dataframe and i only want to select the rows if the 'code' is available in my set. I am currently trying this: country_codes = set(set(dle['Code']) & set(dgdp['Code'])) dgdp.loc[dgdp['Code'].str in country_codes] or dgdp.loc[dgdp['Code'] in country_codes] On the second one I get the problem TypeError: 'Series' objects are mutable, thus they cannot be hashed and in the first one I get KeyError: False. How can I get the info for the codes that I want?
try: dgdp.loc[dgdp['Code'].isin(country_codes)]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, pandas, dataframe" }
Is readonly variable thread safe? > **Possible Duplicate:** > Is a readonly field in C# thread safe? A quite simple program private readonly string _data1; private readonly int _data2; private readonly MyAnotherClass _data3; public MyClass(string data1, int data2, MyAnotherClass data3) { _data1 = data1; _data2 = data2; _data3 = data3; } Are `_data1, _data2 and _data3` thread safe?
A read-only variable is guaranteed to be initialized before it is accessed. The initial value is assigned during construction of the object, before the object is fully allocated. > Variable initializers are transformed into assignment statements, and these assignment statements are executed before the invocation of the base class instance constructor. This ordering ensures that **all instance fields are initialized by their variable initializers before any statements that have access to that instance are executed**. Reference: C# Spec, 10.11.3 Constructor execution (emphasis mine) > Assignment to a readonly field can only occur as part of the field’s declaration or in a constructor in the same class Reference: C# Spec, 1.6.5 Fields For that reason, the value will be set before it is available to any thread, and will not change, so it is thread safe.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "c#, multithreading" }
How do I find the path of a data file in Dancer to use in Javascript? I have the following Javascript segment: function setLifts() { var $lifts = []; $.ajax({ url: 'data/lifts.csv', contentType: 'text/csv', async: false, success: function(text) { $lifts = text.split(/\n/); return; } }); return $lifts; } I get the following error when I load the page in Chrome: `GET 404 (Not Found)` I have a data directory in the root of my Dancer app. What is the correct path to the csv files? Thanks!
You need to define a route handler to deal with those and have Dancer send the file to the client. See the Dancer doc. > Lets the current route handler send a file to the client. Note that the path of the file must be relative to the public directory unless you use the system_path option (see below). > > > get '/download/:file' => sub { > return send_file(params->{file}); > } > The directory `data` is not included in a standard Dancer installation. You should move the data to public out of security concerns (the doc talks of `return send_file('/etc/passwd', system_path => 1);`). Of course stuff in `public` can be downloaded without a route handler. The CSS, JS and `dispatch.fcgi` are in there for starters.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "javascript, perl, dancer" }
How can I convert a char vector to a char array? I'm reading the bytes of a file (an image) to then convert into base64. The bytes get written into a char vector called buffer, since I haven't found working examples for writing the bytes from the file into a char array I do the char vector like such: ifstream infile("image.png", ios_base::binary); infile.seekg(0, ios_base::end); size_t length = infile.tellg(); infile.seekg(0, ios_base::beg); vector<char> buffer; buffer.reserve(length); copy(istreambuf_iterator<char>(infile), istreambuf_iterator<char>(), back_inserter(buffer)); infile.read(&buffer[0], length); The base64 encoding function is: int base64_encode(unsigned char *source, size_t sourcelen, char *target, size_t targetlen); I need to send the base64 encoded text to a website, so that it can be displayed on a page for example.
In c++, vectors are dynamically allocated arrays. Whenever you call the `.push_back()` method, the array is reallocated with the new data appended at the end of the array. If you really need to transfer the data from the vector into a regular array you could use a for loop to assign the data to the array like this: for (int i = 0; i < vec.size() && i < arrLen; i++) { arr[i] = vec[i]; } Although a much better method considering vectors are just dynamically allocated arrays would be to transfer a raw pointer of the vector's first element to the function. foo(&vec[0]); OR foo(vec.begin());
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c++, arrays, vector, type conversion" }
ProgressValue in onPostExecute() in AsyncTask class How the `ProgressValue` (passing in the onPostExecute() in `AsyncTask` ) represents. it's value depends on what ?
When you create your AsyncTask class, you may specify types of the parameters, progress and result: private class MyTask extends AsyncTask<ParamType, ProgressType, ResultType> { ... } If you want to use progress values to update the progress bar, I'd recommend to use Integer, so your class declaration will look like this: private class MyTask extends AsyncTask<ParamType, Integer, ResultType> { ... } the following call should be made somewhere from `doInBackground()`: publishProgress(progress_value); // progress_valus is integer and your `onProgressUpdate()` member will look like this: protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); dialog.setProgress(values[0]); // dialog is the ProgressDialog }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, android asynctask, progress" }
/django.db.utils.IntegrityError: NOT NULL constraint failed/ after python manage.py migrate app zero I had some mess with migrations in production and localy. Finally the situation was that in production there were only initial migration and localy there were 8 migrations or something. So I decided to use python manage.py migrate app zero both in production and localy(django 1.8.7). In prodcution it worked but locally it raised error which didn't appear before after `makemigrations` or `migrate` command. django.db.utils.IntegrityError: NOT NULL constraint failed: app_userprofile__new.phone_number after few attempts to try different things, the error began to appear after migrate commands too. The model itself : class UserProfile(models.Model): user = models.OneToOneField(User) phone_number = models.IntegerField(null=True, blank=True, default=None)
Check your local database. This error usually happens when one or more records do not meet the NOT NULL requirement UserProfile.objects.filter(phone_number=None) You can resolve this by filling the phone_number field of the objects found Or deleting objects that do not have filled phone_number **UPDATE** Manage database changes with `database migrations` can prevent this type of situation
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, django, django models, migration, django migrations" }
JSON handling clientside? Is it possible to handle data from a JSON file without having it served via http:// or https:// ? Basically like you reference a JS file or CSS file in the HTML page?
Basically - nope. First of all, also when you reference a JS or CSS file, it is always served over http:// or the browser will load everything you give him with the http-protocol, the only one he knows.. if you don't believe me, have a look in your network tab of the developer tools and you will see there every single file loaded over the network.. the only other way to load local files is the file:// protocol, which is not recommended because your browser falls in a sandbox-mode where not everything is possible to do. But storing JSON data locally.. that's kind a new stuff which is possible to achieve with localStorage of HTML5 ;-)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "javascript, html, json" }
InterlockedExchange Visual Studio 2010 Intrinsic I have intrinsics enabled in the optimization settings for the compiler, however, the resulting code for InterlockedExchange is generating calls into kernel32.dll rather than producing inline assembly. This is especially problematic because the function is not available on versions of windows prior to Vista. The MSDN documentation states " _This function is implemented using a compiler intrinsic where possible_ ". Is it possible to get the compiler to use actual intrinsic code for InterlockedExchange?
the interlocked intrinsics require an underscore prefix (or `#pragma intrinsic`), so you want to use `_InterlockedExchange`, you will also need to include `intrin.h` also, you you read your quote fully, it says this: > This function is implemented using a compiler intrinsic where possible. For more information, see the Winbase.h header file and **_InterlockedExchange**.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c++, visual studio 2010, atomic, intrinsics, interlocked" }
Switching between states during DNS propagation I recently purchased a domain name from namecheap.com and played around with it a little. I got it to do a URL redirect to Wikipedia.org. A few hours later, I got a free hosting account with 000webhost.com and pointed my nameservers toward 000webhost. I built a sample website using 000webhost's tools. It's been more than 24 hours, and when I try to access my website, I'd get Wikipedia some of the time and my sample site the rest of the time. From what I understand about DNS propagation, I should be getting one or the other. What's going on? Is my understanding of DNS propagation incorrect?
It can change depending on which nameservers are updated. Check your TTL -- if it's 24 hours, it means servers are allowed to cache at least that long. But, some cache longer anyway, and it can be staggered, which means it can easily be 3x the TTL to actually move. If you know you're going to be switching DNS, set your TTLs low so the switch can happen more quickly (for most DNS servers).
stackexchange-serverfault
{ "answer_score": 3, "question_score": 2, "tags": "domain name system" }
How to get cell reference from range object in Excel using VB.net? I have : Dim cell As Excel.Range = sheet.Range("A2") Console.WriteLine("Cell references to = " + ????? ) **What should I replace ????? with to get A2 printed in its place ?** Please help !!
With `cell.Address(false, false)`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": ".net, vb.net, excel, vba" }
How to make UIView with AVCaptureVideoPreviewLayer look better? I'm trying to build a subclass of UIView to quickly take one snapshot by using AVFoundation. It's working great but I would really like to make the corners round or add a little shadow. How can I achieve this using Core Graphics etc.? GitHub: < **Update:** This is what the result looks like: <
Use QuartzCore #import <QuartzCore/QuartzCore.h> then you can modify the layer off your the view: someView.layer.cornerRadius = 8; someView.layer.shadowOffset = CGSizeMake(-15, 20); someView.layer.shadowRadius = 5; someView.layer.shadowOpacity = 0.5; or something like that
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ios, objective c, uiview, avfoundation, calayer" }
Raycasting center of camera is not working: why? In my game i'm using Unity First Person controller. I check every second what I am looking with the following code: cam = Camera.main; RaycastHit hit; Vector3 CameraCenter = cam.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, cam.nearClipPlane)); if (Physics.Raycast(CameraCenter, transform.forward, out hit, 5)) { WhatIamLookinTag = hit.transform.tag; } The problem is that isn't working if move Up and down player "view" (so i move up and down mouse..) I need the object that is in screen center (based on what am i looking). Why ?
This solved my problem: cam.transform.forward instead transform.forward cam = Camera.main; RaycastHit hit; Vector3 CameraCenter = cam.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, cam.nearClipPlane)); if (Physics.Raycast(CameraCenter, cam.transform.forward, out hit, 5)) { WhatIamLookinTag = hit.transform.tag; } Thanks to DMGregory.
stackexchange-gamedev
{ "answer_score": 0, "question_score": 0, "tags": "unity, raycasting" }
SQL query return column null if not found This query will return all orgs if it finds a camera of that org, else it wont return a row. SELECT org.id as organization_id, cam.id as device_id, org.slug as organization_slug FROM accounts_organization org INNER JOIN devices_camera cam on org.id=cam.owner_id WHERE org.slug IN ('org1','org2') and cam.unique_identifier = '123' How can I change this so it will return all the queried orgs, but if there is no such related camera, then that column field will be null but the row will still be displayed?
change `inner join` to left join and change `cam.unique_identifier = '123'` to the `on` clause SELECT org.id as organization_id, cam.id as device_id, org.slug as organization_slug FROM accounts_organization org left JOIN devices_camera cam on org.id=cam.owner_id and cam.unique_identifier = '123' WHERE org.slug IN ('org1','org2')
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "sql, postgresql" }
Can some advise me on how to solve this system of equations? I have the following system of 3 equations and 3 unknowns: $$c_{0} = \frac{x_0}{x_0 + x_1},\ \ c_{1} = \frac{x_1}{x_1 + x_2},\ \ \ c_{2} = \frac{x_2}{x_2 + x_0},$$ where all $c_i\\!\in\\!(0,1)$ are known and all $x_i > 0$ are unknown. Am I right in that the solution of this system is the nullspace of the following matrix? $$\mathbf{A}=\left[\begin{matrix}(c_0-1)& c_0 & 0 \\\ 0 & (c_1-1) & c_1 \\\ c_2 & 0 & (c_2-1) \end{matrix}\right].$$ If so, I want to find the non-trivial solution, i.e. the basis for $null(\mathbf{A})$. p.s. I have attempted to simplify $\mathbf{A}$ to its reduced row echelon form $rref(\mathbf{A})$. I know that $null(\mathbf{A}) = null(rref(\mathbf{A}))$, but I get a diagonal matrix for $rref(\mathbf{A})$. So does this mean that $null(\mathbf{A}) = \mathbf{0}$, and therefore, there are no solutions to the system?
We rewrite the equations as a system of linear equations $Ax=0$ with $$ A=\begin{pmatrix} c_0-1 & c_0 & 0 \\\ 0 & c_1-1 & c_1 \\\ c_2 & 0 & c_2-1& \end{pmatrix} $$ and $x=(x_0,x_1,x_2)^t$. The nullspace of $A$ is non-trivial if and only if $\det(A)=0$. We have $$ \det(A)=2c_0c_1c_2 - c_0c_1 - c_0c_2 + c_0 - c_1c_2 + c_1 + c_2 - 1. $$ The trivial solution $x=0$, i.e., $x_0=x_1=x_2=0$ is forbidden by you. So let us suppose that $\det(A)=0$ and $2c_0c_1 - c_0 - c_1 + 1\neq 0$. Then we can express $c_2$ by $c_0$ and $c_1$ and then $\ker(A)$ is spanned by $$ \begin{pmatrix} c_1-1\\\ -c_0 \\\\- 2c_0c_1 + c_0 + c_1 - 1 \end{pmatrix}.$$ Similarly for the other cases.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "linear algebra, matrices, vector spaces, matrix equations, homogeneous equation" }
Is there a shortcut key to duplicate a tab in Google Chrome? Is there a keyboard shortcut to duplicate a tab in Google Chrome? I've read through all the replies in the Google Chrome Forum thread, but there's no hope there. The only hope I get from that page is: > Next update for Chrome should definitely include a duplicate shortcut.
There is not currently a keyboard shortcut to duplicate a tab in Google Chrome (see a list of keyboard shortcuts). However, it looks like Chrome may soon enable support for extensions to duplicate tabs, which means you might soon be able to find a Chrome extension that can duplicate a tab through a keyboard shortcut. Currently, all of the extensions that show up in the store don't preserve history. Non-keyboard-wise, there are two ways you can duplicate a tab: either middle-click on the refresh button, or right-click on a tab and choose "Duplicate" from the menu: !Chrome screenshot
stackexchange-superuser
{ "answer_score": 55, "question_score": 107, "tags": "google chrome, keyboard shortcuts" }
Random number generation I need a random number generation algorithm that generates a random number for a specific input. But it will generate the same number every time it gets the same input. If this kind of algorithm available in the internet or i have to build one. If exists and any one knows that please let me know. (c, c++ , java, c# or any pseudo code will help much) Thanks in advance.
Usually the standard implementation of random number generator depends on seed value. You can use standard random with seed value set to some hash function of your input. C# example: string input = "Foo"; Random rnd = new Random(input.GetHashCode()); int random = rnd.Next();
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "algorithm" }
AutoHotKey: How does the WinTitle work? I just started playing around with AutoHotKey today but got stuck at moving/resizing windows... `WinMove` needs a `WinTitle` but I can't figure out how the `WinTitle` works. When I try the following code: #SingleInstance force #y:: run, notepad Sleep, 1000 WinGetTitle, window,, A MsgBox, Active window: %window% Sleep, 1000 WinMove, window,, 0, 0 MsgBox, %window% moved. return Notepad dosn't get moved to the top left corner, but why? I have also tried storing the ID as a string: `program := window` `WinMove, program,, 0, 0` but that didn't work either.
In your example "window" is a variable and "WinMove" is a command. **Commands** always use "traditional syntax". Meaning: when you use a variable in a command, you have to enclose the variable in percent signs: WinMove, %window%,, 0, 0 **EDIT:** Btw. WinGetTitle, window,, A has to be WinGetTitle, window, A **EDIT2:** #SingleInstance force #y:: run, notepad WinWait, Untitled - Notepad ; title - Use Window Spy to find the exact title of this window ; IfWinNotActive, Untitled - Notepad, ,WinActivate, Untitled - Notepad ; WinWaitActive, Untitled - Notepad Sleep, 200 WinMove, Untitled - Notepad,, 0, 0 return
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "windows, autohotkey" }
VB6: what is the likely cause of Error 3078 " ... Jet database engine cannot find the input table or query ... " VB6: what is the likely cause of Error 3078 " ... Jet database engine cannot find the input table or query ... "
Try checking the connection and checking the database for corruption, that is, back up and then compact and repair. You might also like to `read this article on corruption`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "vb6, jet" }
Upgrading Dell R5400 from Windows Server 2003 32Bit to Windows Server 2008 R2 This is a newbie question... I have a client with a Dell R5400 machine. They are seeking additional services from us to upgrade their machine from Windows 2003 to Windows Server 2008R2 and also increasing RAM from 4 GB to 20 GB. Is is possible to do this? How long do you think this process will take? Thanks
The machine can fit up to 32 GB in 4 DIMMs, so yes, you can upgrade the RAM. That should take you about 5 minutes, once you have the new RAM in-hand. It looks like that's an x64 machine, so the OS install will work. Installing Windows 2008 R2 should take <1-2 hours, depending on disk speed and install media (LAN vs DVD.) You can't do an in-place upgrade from Win2k3-> Win2k8, so you'll have to add in the time to back any data up and reinstall any applications after the OS is laid down.
stackexchange-serverfault
{ "answer_score": 2, "question_score": -2, "tags": "dell, memory" }
Array search problem $comedy = 'comedy, drama, thriller, action'; $array = array('action', 'fantasy', 'war', 'comedy', 'romance', 'drama', 'thriller'); I need to find the key words from each variable `$comedy`. I need: 3 5 6 0 Thank you!
What about the following portion of code : $comedy = 'comedy, drama, thriller, action'; $array = array('action', 'fantasy', 'war', 'comedy', 'romance', 'drama', 'thriller'); foreach (explode(', ', $comedy) as $word) { $index = array_search($word, $array); var_dump($index); } Which gives me the following output : int 3 int 5 int 6 int 0 Basically : * As your words in the `$comedy` variables are always separated by the same pattern `', '`, you can use **`explode()`** to get an array that contains those words. * Then, iterating over those words, you just have to call **`array_search()`** to get their position in your `$array` array.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php, arrays, search, key" }
Angular 6 - How to read angular specific attributes I have a component on which I specify the angular i18in attribute like this: <app-text i18n="meaning|description"> DeveloperText</app-text> I want to be able to read this property. I have tried using ElementRef and accessing nativeElement but the attribute i18n is not a part of the DOM element when I view the source. When my app is launched the DOM looks like this: <app-text _ngcontent-c0=""> DeveloperText</app-text> So can I somehow read properties like this using the Angular Framework?
In your HTML: <app-text #something i18n="meaning|description">DeveloperText</app-text> In your controller: @ViewChild('something') fred; You now have a handle on the element. If you log it like this: console.log(this.fred); console.log(this.fred.nativeElement); You should find the value of the property you are interested in.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, html, angular, typescript" }
How can I use D3DXLoadMeshFromX with Direct3D 11? I'm trying to write some class for loading meshes from X files. But I can't use the function `D3DXLoadMeshFromX` because its third parameter is `LPDirect3DDevice9`. In my D3D initialization code I don't have variable of this type. Did I initialize D3D incorrectly? How can I call this function?
D3DXLoadMeshFromX is not supported in DirectX 11. You will have to create your own model importer for a file format. Something simple like .obj would be a good place to start.
stackexchange-gamedev
{ "answer_score": 2, "question_score": 1, "tags": "c++, directx" }