INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
solve the differential equation by integrating directly
I am trying to solve a differential equation and I don't know how to solve it when it comes to integrating directly. I'd like to know how to do this so I can start doing other problems. Thanks in advance.
Solve the differential equation by integrating directly
$${{\rm d}y \over {\rm d} t} = {4t + 4 \over \left(t + 1\right)^{2}}$$ | $$y'(t)=4t+\frac4{(t+1)^2}\implies y(t)=2t^2+\frac{4t}{t+1}+y(0)$$ $$y'(t)=\frac{4t+4}{(t+1)^2}\implies y'(t)=\frac{4}{t+1}\implies y(t)=4\log(t+1)+y(0)$$ The solution of the second version on the interval $(-\infty,-1)$ would be $$ y(t)=4\log|t+1|+y(-2). $$ | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "ordinary differential equations"
} |
List the time zones for a Country
I am looking for the code that displays list of countries/regions in ruby on rails when selecting a specific country/region, it displays the time zone of it. For example when i choose “United Kingdom" as country/region then it should displays “(GMT +00:00)London" as Time Zone. My application runs on Rails 3.2.11. I am displaying all the countries using **countries** gem and all the time zones using **ActiveSupport::TimeZone**. I want to know if Ruby on Rails provide this functionality by default or if there is any other possible way to achieve this. | You can use TimeZone class. You can get all timezones list by:
zones_hash = ActiveSupport::TimeZone::MAPPING
And you can get time zone of any country as the following:
country_zone = ActiveSupport::TimeZone.new("Europe/Skopje")
country_zone.formatted_offset
The output: `+01:00` for the above example. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "ruby on rails, ruby"
} |
Mating patterns and genetic superiority
In peacocks and peahens, the peahens prefer mating with peacocks having a large and bright tail. But how is having a large tail an indicator of genetic "fitness" (in survival terms) ? If having a large and bright tail is not related with genetic superiority, then what is the point of having the mating ritual? | Darwin thought quite a bit about this. He even said "The sight of a peacock makes me sick". < He added to his ideas about natural selection to include sexual selection. Traits selected by females, even when they are non-adaptive for males, will increase the males fitness (as defined by his number of offspring). There is also the idea that perhaps possessing such an outrageous and non-adaptive tail proves that you a good mate, the same way we would think that a guy who could win a sprint while carrying barbells must be superior. | stackexchange-biology | {
"answer_score": 3,
"question_score": 0,
"tags": "genetics, evolution"
} |
How can I upload a picture to a device while running appium script on AWS' device farm
String imagePath = this.getClass().getResource("/files/images.jpg").getPath();
driver.pushFile("/data/local/tmp/image.jpg", new File(imagePath));
This code works fine on emulators & real device but doesn't work on device farm of AWS | Device farm uses physical devices and is recommend using /sdcard/ directory to pushFile. While on emulators you can use directories like /data/. This solution for work for your use case. Let us know if you see this issue again | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "appium, aws device farm"
} |
Работа с XML в MS SQL
Есть XML вида:
<root>
<node>
<node2>
<node3></node3>
</node2>
</node>
<node>
</node>
<node>
<node2>
</node2>
<node2>
<node3></node3>
<node3></node3>
<node3></node3>
</node2>
<node2>
<node3></node3>
</node2>
</node>
<node>
<node2>
<node3></node3>
<node3></node3>
</node2>
</node>
</root>
Как я могу получить в MS SQL через запрос значения, которые находятся в node3? | Можно так:
select
x.c.value('text()[1]', 'varchar(100)') node3
from
[table] t
cross apply t.xmlColumn.nodes('//node3') x(c)
Если полностью указать путь до узла node3, то план запроса должен построиться чуть более оптимальный
select
x.c.value('text()[1]', 'varchar(100)') node3
from
[table] t
cross apply t.xmlColumn.nodes('/root[1]/node/node2/node3') x(c) | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "sql, база данных, xml, sql server, веб программирование"
} |
Youtube API returns zero results if setting orderby
Using Youtube API v2 to retrieve uploads in specific channel. When setting the parameter "orderby" to "published" the API returns zero results. This worked previously, stopped working today (2014-08-28).
E.g. works: <
doesn't work: <
I'm aware the v2 protocol is deprecated, but it's been promised to be around up until April 2015. Can anyone shed light into this issue? | Looks like it was shortage in service of the API: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "youtube api, youtube data api, youtube channels"
} |
Java 8 getOrDefault method on HashMap not working as expected
I cannot figure out why this hashmap routine is not adding up counts on my characters as expected. I suspect it has something to do with the cast between Character and char, but I'm not certain. The count is always 1 for every character.
String s = "loveleetcode";
Map<Character, Integer> hm = new HashMap<Character, Integer>();
for (int x = 0; x < s.length(); x++) {
hm.put(s.charAt(x), hm.getOrDefault(hm.get(s.charAt(x)), 0) +1);
} | I think you want to change the line;
hm.put(s.charAt(x), hm.getOrDefault(hm.get(s.charAt(x)), 0) +1);
to
hm.put(s.charAt(x), hm.getOrDefault(s.charAt(x), 0) +1);
In the original code `hm.get(s.charAt(x))` will return `null`, and that key will not be present. Although the `null` is typed as an `Integer`, `Map.getOrDefault` (or indeed `get`) accepts `Object` for that argument, as that makes the `Map` interface work better with Java's bounded generics.
`char` can be autoboxed to `Character` just fine. `Character` can autounbox to `char` so long as it is not `null`. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "java, hashmap"
} |
Android - Signing an apk
I have written a little program, by default, it is signed with debug certificate. I checked the documentation at Android developer site, I don't know how to get the certificate and key, could someone advice me? | 1. Right click your project:
Android Tools -> Export Signed Application Package
1. Give the project name which you want to sign. Click next.
2. If you want to create a new keystore, select "Create New Keystore".
3. Give the location where to save it. The name of the keystore should end with `.keystore` and give a password for it. Click next.
4. Give the details and click finish. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "android"
} |
Easiest/best back end layer to tie MS SQL database and ExtJS front end
We currently have a big project that consists of the following layers:
* MS SQL Server database
* Microsoft RIA WCF Service layer
* IIS and
* ExtJS web application
Everything works more or less. The only my concern is I think second layer is a bit over kill and over complicated for what we have on the front end - the whole task for it is to generate JSON messages with the data from the database. This structure was chosen because originally we were planning to use Silverlight as a front end (thank God! we decide to drop it in the favor of ExtJs btw).
Now I have couple other web projects on the horizon and I'm wondering if dropping this second layer (RIA WCF) is the right choice. What are my other options if I decide to stick with MSSQL/IIS/ExtJs? If somebody had experience with something else I would appreciate any feedback. Any links would be very helpful too. | You should look at Entity Framework and MVC. Entity Framework is useful for mapping your SQL Database into business objects that can be handled via MVC and displayed using ExtJs and the Razor view engine. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "sql server, wcf, iis, extjs, ria"
} |
mysql_query return TRUE on empty table
> $rs = mysql_query("SELECT user, userid FROM House WHERE userid='$userid'");
This return `Resource id #37` The table House is empty, shouldn't it return FALSE? According to the manual <
I have always gotten FALSE on error, but not this time. Can someone explain, thanks! | If there is nothing wrong with your query, then `mysql_query()` will not return `false`. An empty result set is not an error.
Calling any of the fetch functions against that result _will_ return `false`. `mysql_num_rows()` will return `0`. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 1,
"tags": "php, mysql"
} |
Differential Equations question
Here's my problem:
> If $y' = y^2$ and $y(0) = 3$, then find $y(-1)$.
I'm not quite sure what to do with it. What I've watched on Khan Academy doesn't seem to be in the same format as this question. | We have $$\dfrac{dy}{dx} = y^2 \implies \dfrac{dy}{y^2} = dx \implies d \left(-\dfrac1y\right) = dx \implies -\dfrac1{y(x)} = x +\text{constant}$$ We are given $y(0) = 3$. This gives us $$-\dfrac13 = \text{constant}$$ Hence, we have $$-\dfrac1{y(x)} = x - \dfrac13 \implies \dfrac1{y(x)} = \dfrac{1-3x}3 \implies y(x) = \dfrac3{1-3x}$$ | stackexchange-math | {
"answer_score": 2,
"question_score": 3,
"tags": "ordinary differential equations"
} |
iOS "search" key on keyboard does not do anything
I have an HTML website with a input field for users to do searches. However, after typing in a query on iOS or Android and hitting "Search" from the soft keyboard, nothing happens.
I'm having trouble finding discrepancies of mobile Safari and webkit. Any leads please? Thanks
!enter image description here | Just thought i'd let anyone know the resolution:
I notice that hitting the "Return" button on my physical keyboard also did not work, so i added a Javascript listener to handle the keyup event 13. This leads to the last piece:
Make sure your input type = "search" (i had mine as "text"). Now you're ready to go!
$('search_field').observe('keyup',function(e){
if(e.keyCode === 13){
NAME.search($('search_field'));
}
});
Cheers | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "html, ios, input, keyboard"
} |
size of slide numbers reveal js
I've added slide numbers to my reveal js presentation with
Reveal.configure({ slideNumber: true });
Reveal.configure({ slideNumber: 'c/t' });
But the slide numbers are very small. I'm not familiar with javascript. Can someone please tell me how to make them bigger? | adding
.reveal .slide-number {
font-size: 24pt;
color: #ffffff; }
To the css did the trick | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 4,
"tags": "reveal.js"
} |
regsvcs-registered .NET class and dllhost
Suppose there is defined ClassA which is
1\. COM visible ,
2\. registered as COM+ out-of-process (using regsvcs)
There is also .NET code like
void f()
{
ClassA a = new ClassA();
}
Is it right that when constructor of ClassA called , dllhost process started? | You are instantiating the class through .NET, not COM+, so the COM+ hosting process will not be involved. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": ".net, com interop, com+"
} |
R: C++ Optimization flag when using the inline package
In R when using the cxxfunction from the inline package, how does one change the optimization flag for the cpp compiler?
By default, on my machine, it compiles with `-g -O2`. But I would like to use the `-O3` optimization to gain speed. I use the `Rcpp` plugin if that makes any difference.
I have tried creating my own plugin, and I have tried to set the different arguments of the cxxfunction but nothing worked.
I guess one option would be to compile it using `R CMD SHLIB` instead of using `cxxfunction`. But Rcpp recommends the use of `inline` because most of their test cases are using it.
thanks for your help, let me know if you need any clarification | There are a couple of options:
1. The best solution is to modify this **for all usage by R** so create _e.g._ a file `~/.R/Makevars` and set CFLAGS, CXXFLAGS, ... there. This will affect all use by `R CMD INSTALL ...`, `R CMD SHLIB ...` etc pp and as `cxxfunction()` from inline uses it, it works here too.
2. Specific to inline and Rcpp: modify the plugin, that's why it is a plugin system. See `Rcpp:::Rcpp.plugin.maker()`.
3. Switch back from `cxxfunction()` to `cfunction()`, hence do not use a plugin and set all arguments manually.
Needless to say, I like option 1 and use it myself.
_Edit:_ A fourth (and crude !!) method I used to use in the past is to edit `$R_HOME/Makeconf` and/or `Makeconf.site`. | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 21,
"tags": "c++, r, inline, rcpp"
} |
Git directory not found
I've been working on a project and using git for version control for a couple of weeks now, and everything was fine untill this morning. Suddenly, git bash doesn't recognize my folder as a repository anymore.
Here be the folder contents:
: .git
I have another project in git, and that's still working fine. The only difference between them is that the working one has a .gitignore, and this one doesn't.
Any ideas on this? I'd love to get this back up in stead of having to make a new repository. | Peek inside the `.git` directory. It should have a file named `HEAD` (all caps, although on Windows or OS X case-insensitive file systems the case of the file name does not matter). If that file is missing, Git decrees that the repository is not a repository. Of course, if that file has gone missing, perhaps others have as well, but it can be worth trying restoring that file and see if the rest of the repository is still sensible.
The `HEAD` file normally contains the name of a branch, e.g., `ref: refs/heads/master` (followed by a newline, not a CR-LF pair; also be sure that any editor you use to create it makes a regular, 8-bit text file, not any fancy Unicode or rich-text). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "git, bash"
} |
Best practice when constructing if statement based on datatype?
I am constructing a basic function with an if statement based on datatype. I am wondering whether there is any problem with using:
if type(number) == int:
in something like:
def distance_from_zero(number):
"""Takes input 'number', checks datatype. If integer or floating point, returns absolute value. If other, returns 'Nope'"""
if type(number) == int:
return abs(number)
elif type(number) == float:
return abs(number)
else:
return "Nope"
distance_from_zero(45)
Is there a cleaner/better way to use datatypes in if statements? | Why even check?
try:
return abs(number)
except TypeError:
return 'Nope' | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "python, if statement, types"
} |
How to use UMLFS?
I'm trying to mount what is inside UML session as FUSE filesystem on host.
There's "uml_mount" program which looks like a thing for this purpose, but it fails.
What is UMLFS (I haven't found any documentation at all) and how to mount it?
`uml_mount` mounts FUSE filesystem and starts `uml_mconsole <umid> umlfs <file descriptor>` which tries to send this file descriptor to UML kernel (to deal with further FUSE things), but sending fails. Also I haven't found any signs of FUSE inside a kernel.
Do I need some special patch for this? | Modify mountlo-0.6 for the task. At least I can now mount NFS over FUSE using this approach. | stackexchange-superuser | {
"answer_score": 0,
"question_score": 0,
"tags": "fuse"
} |
Contacts doesn't show up under account sync
I can't get my contacts to sync. In the contacts app (both google and default phone app) it shows "1 account" (won't tell me what, presumably the 'on device' since it still shows that if I remove my Gmail). If I try to add my Gmail account it tells me the account is "already on the device". If I go to settings>accounts>my Gmail>sync there's a few switches, but contacts is not one of them. I can click my account instead of the sync menu and scroll over to People and Sharing and it tells me I have 480 contacts, and will open contacts.google.com and show them, but I can't get them on my phone.
I've tried deleting and re-adding my Gmail, clearing contacts app data, looked for a google contacts sync app (didn't have one). Contacts apps have all permissions granted. | I went under settings>apps ticked show system apps, and searched for 'google'. Found my google contacts sync there. Went through a bunch of relevant sounding system apps that didn't all have the contacts permission, and granted contact permissions. It was to several apps, so no telling which one actually made it work. | stackexchange-android | {
"answer_score": 0,
"question_score": 1,
"tags": "contacts, sync, google account, android 10, oneplus 5"
} |
bootstrap input-group-addon need to use with button
Check the bootstrap code bellow. The is attached with input text field which looks like button however should be a button to submit form data. Please tell me how can i implement button to submit from data also it will display just beside input like now?
<div class="col-md-6 col-md-offset-3">
<div class="input-group input-group-lg">
<input type="text" class="form-control" placeholder="eg: restaurant templates">
<span class="input-group-addon btn btn-primary">Search</span>
</div>
</div> | <div class="col-md-6 col-md-offset-3">
<div class="input-group input-group-lg">
<input type="text" class="form-control" placeholder="eg: restaurant templates">
<input type="submit" value="Search" class="input-group-addon btn btn-primary">
</div>
</div>
Not that hard. It's a matter of playing the values
For reference: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "twitter bootstrap"
} |
Embedded Linux Stability
I'm developing an embedded Linux (it is almost over now). What I'm struggling with is the system goes unstable by cutting power source frequently and it does not boot anymore. It even does not perform `fsck`.
The system just has a XFCE with a fixed Qt App autoloaded to display some charts.
My question is that how commercial embedded Linux distros (like Wifi AP's management Linux, ...) avoid this problem?
Do you have any idea? | Most do one of two things:
They either run the main filesystem read-only and have a separate area for storage of data that is mounted read-write,
or
They have the main filesystem compressed in a file which gets expanded into a ramdisk at bootup time.
This means that the filesystem is always in the same state whatever happens. There is only the small configuration storage area to worry about, and that can have a filesystem that doesn't worry too much about power loss.
Another tip is to disable all caching on the storage partition so all changes are immediately written to disk. | stackexchange-superuser | {
"answer_score": 3,
"question_score": 2,
"tags": "linux, embedded"
} |
.Net alternative for OpenCV's camera capture
I am processing video from a camera using OpenCV.Net's camera Capture. Initially I was using more functionality of OpenCV, but because of bugs and performance problems I have rewritten nearly all functionality that I need in C#.
Currently I am still only using OpenCV's Capture to get the video frames from the camera. For this the use of OpenCV seems like overkill.
Is there an alternative in .Net to read frames from a camera? | I am now using AForge, it seems to work well. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": ".net, camera, video capture"
} |
remove text after two spaces in a java string
I need to remove the string after two or more consecutive spaces. I have tried:
String.replaceAll(".+$.+$","");
But its not working. I need something like below:
String = "hi there how are you?"
output:
String = "hi there".
Please suggest a simple regex for the above.Thanks in advance. | You can leverage non-greediness with a positive lookahead to make sure the matched portion is followed by two or more whitespaces:
^.*?(?=\\s{2,})
Demo | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "java, regex"
} |
Rounding binding expressions appmaker
I'm trying to format the output of an expression as a percentage to be shown in a table. With a normal cell, appmaker lets you select the dropdown to #formatNumber. I can't figure out how to do this with a longer expression:
@datasource.item.ROI_Percent * (365/(@datasource.item.Sale_Date - @datasource.item.PO_Date))
I've tried throwing the whole thing in parens and adding #formatNumber but that doesn't seem to work. Is there another function I'm missing? I want this to be a rounded percentage (704%)
Thanks | Once you break away from a single bound output, App Maker can no longer determine the result type and thus doesn't allow you to use their helper functions. You'll have to use plain old javascript.
Here's one way to format as a percentage:
(@datasource.item.ROI_Percent * (365/(@datasource.item.Sale_Date - @datasource.item.PO_Date))).toLocaleString("en", {style: "percent"}) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "google app maker"
} |
Creating a row with onClick properties in JavaScript
I'm using this code snippet from W3Schools to create a new row in my table:
// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
After creating it, all the rows in the table have their onClick functions except the one I just created, so my question is, how can I specify an onClick function for that row? | you can also use
document.getElementById("myTable").innerHTML+="<tr onClick='myFunc();'></tr>"
* * *
or by your way you can use
row.onClick="myFunc();"
or
row.setAttribute( "onClick", "javascript: myFunc();" ) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript, onclick, buttonclick"
} |
How can a portal that connects two planets affect the environment?
In my world there are two planets within the same solar system, which are connected approximately every seven cycles through a portal that opens for a few days.
* The planets are very similar.
* The atmospheres are breathable.
* Both people and animals can move from one planet to another without problems.
* Gravity is the same (don't touch this).
* The fauna is different; different kinds of plants, flowers and animals exist on both sides.
Is it possible that these openings affect the flora and fauna, taking into account that they only remain open for a short period of time? | # Yes.
* Look at the concept of invasive species. Just a few pregnant rats or rabbits, a few seeds can start the process which imbalances an ecosystem, especially if their natural predators don't come along immediately.
* Look at the concept of virgin field or virgin soil epidemics. When a plague hits a population without immune defenses, the results can be devastating, as in the contact between Europe and America.
* Farmers (or their rulers) might deliberately bring crops because they taste better, or simply to add variety to the dinner table. | stackexchange-worldbuilding | {
"answer_score": 44,
"question_score": 20,
"tags": "biology, planets, environment, earth like"
} |
Missing View in Inspector Area in Xcode Version 13.3
I have Xcode version 13.3. After downloading Xcode 13, I can set the corner radius from the storyboard. This feature is given by Xcode it is not a custom function or IBinspectable. My old view with the features.
 they use `<b></b>`. Damned shame they're not encouraging semantics.
Anyone know something that gets people off on the right foot? | Exactly, I personally started off on HTMLGoodies, also. I think tizag.com is more updated. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 10,
"tags": "html, css, semantics"
} |
Append two individual lists to list of lists
Let's say I have:
a=[1,2,3]
b=[4,5,6]
Now I want to create a list of list from a and b, I would do it like this:
c=[a,b]=[[1,2,3],[4,5,6]]
As `a.append(b)` would result in: `[1,2,3,b]=[1,2,3,[4,5,6]]`
Now let's say there exists anew list which I want to append to c:
d=[7,8,9]
I now have to do `c.append(d)` to get `[[1,2,3],[4,5,6],[7,8,9]]`
Because
e=[c,d]=[[[1,2,3],[4,5,6]],[7,8,9]]
How can I get a list of list from individual lists without know how my lists are structured? | The two actions you are describing are distinctly different. The first is creating the outer list (a.k.a. `c`) and the second is appending to it.
To make the process more uniform you can just start off with an outer list and append all the child lists to it.
c = []
a=[1,2,3]
b=[4,5,6]
d=[7,8,9]
c.append(a)
c.append(b)
c.append(d)
c is now
[[[1,2,3],[4,5,6]],[7,8,9]] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 4,
"tags": "python, list, nested lists"
} |
Get today -2 (skipping weekend)
How can I get the Today -2 days (the last 2 working days from now)? but skipping the weekend?
> Example #1: Today is February 25, I want February 21
>
> Example #2: Today is February 26, I want February 24
PS: Date format is DD/MM/YYYY
I have this, but the result is going forward, should I use datediff or what?:
<%
Dim d
d = DateAdd("m", 1, Now)
d = "01/" & Month(d) & "/" & Year(d)
d = DateAdd("d", -1, d)
If Weekday(d) = 7 Then
d = DateAdd("d", -1, d)
ElseIf Weekday(d) = 1 Then
d = DateAdd("d", -2, d)
End If
Response.Write "Day: " & d
%> | To get your desired result you need to subtract 3 days on Saturdays, 4 days on Sundays and Mondays, and 2 days on all other days. This can be achieved with something like this:
today = Now
num = Weekday(today, vbWednesday)
d = today - (2 + num\5 + num\6)
response.write "Two working days back: " & d
The `Weekday` function returns a numeric value for each weekday. By basing the week on Wednesday you can calculate the additional number of days you need to subtract from the current date with integer divisions:
* `num\5` returns 1 for Saturday, Sunday and Monday, and 0 otherwise.
* `num\6` returns 1 for Sunday and Monday, and 0 otherwise.
Thus the term `2 + num\5 + num\6` becomes 3 for Saturdays, 4 for Sundays and Mondays, and 2 for all other days. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "date, vbscript"
} |
Can we identify the main source of new law in the UK?
IIUC the primary sources of law in the UK are:
* statute (acts of Parliament)
* delegated legislation (statutory instruments)
* case law
* EU law
But can we pick one of those as being the main source of new laws? | By volume, it's almost certainly Statutory Instruments (SIs).
From the relevant page on legislation.gov.uk, we can see that the number since 2010 has ranged from 1241 to 3485 per year. Compare that to, say, Acts of Parliament (23 to 41 per year in that period).
The EUR-Lex page has some numbers relating to EU law. For example, in 2018, there were a total of 430 "legislative acts", and 1496 "non-legislative acts". Note that while EU Regulations become law directly in member states, EU Directives have to be implemented by domestic legislation. In the UK, this is normally done with SIs, which contribute to the numbers in the previous paragraph. | stackexchange-law | {
"answer_score": 4,
"question_score": -1,
"tags": "united kingdom"
} |
exclude an asset regex
I need to write a regex that will capture everything in a directory except one asset. Ex. I want to exclude `/test1/test2/new.jpg` and capture everything else in `/test1/test2/`
I tried the negative lookahead but doesn't seem to work.
`/test1/test2/^(?!new.jpg).*` | You don't need `^` in between:
/test1/test2/(?!new.jpg).*
See this: < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "regex greedy"
} |
Check that click isn't on grid elements
I have a grid, there are: stackpanel, button and ~50% empty space.
I need to handle click only if it is not on button,stackpanel, only on empty space of grid.
How I can do this? | Here is example based on default template, with Grid named `LayoutRoot`.
private void LayoutRoot_Tap(object sender, GestureEventArgs e)
{
if (e.OriginalSource == LayoutRoot)
MessageBox.Show("You clicked on LayoutRoot!");
else
MessageBox.Show("You clicked on somewhere else!");
}
XAML
<Grid x:Name="LayoutRoot" ... Tap="LayoutRoot_Tap"> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, windows phone 7"
} |
Does/Will Entity Framework 6 support the new Sql Azure & Azure Active Directory Authentication
Does EF 6 support this method for authentication and if so what is the installation process and nuget packages to make it work?
< | It looks like EF6 will support this without any changes, as it "only" requires .Net 4.6, the Microsoft Active Directory Authentication Library for Microsoft SQL Server and a special connection string key, either:
Authentication=Active Directory Integrated;
Or
Authentication=Active Directory Password; | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "entity framework, azure, azure sql database, azure active directory"
} |
O programa não está reconhecendo número inteiro como tal
a = int (input ("insira um número :"))
if a != int :
print ("isto não é um numero inteiro")
else :
print ("seu número foi :"+ str(a))
Estou tentando fazer um programa em que o usuário coloque um valor e o programa diga qual foi o valor que ele inseriu, mas se inserisse uma letra, desse tela de erro.
Acontece que quando ele insere um número o programa não reconhece como tal. | Python, as suas funções padrões, detecta conversões impossíveis através de um mecanismo de exceção, então tem que capturar a exceção para identificar que houve erro, assim:
try:
a = int(input("insira um número: "))
print ("seu número foi: " + str(a))
except ValueError:
print ("isto não é um numero inteiro")
Veja funcionando no **ideone**. E no **repl.it**. Também coloquei no **GitHub** para referência futura. | stackexchange-pt_stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "python, python 3.x, validação, tipagem"
} |
Is there are a way to read images into a prediction engine without saving to file first?
All the of the Microsoft tutorials on ML.NET involve reading images from a file and referencing them only using their file location. I'm trying to implement a prediction engine into piece of code which is taking photos as it is being run. Currently I'm saving all my images to file and then reading them to make a prediction but I'm wondering if there's a better way? | This was enabled in MAdded support for in-memory ‘image type’ in IDataview was enabled in ML.NET 1.1. Please read this blog post for more details < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, .net, ml.net"
} |
Redirect all active users to specific page without they send any request
If you are using two steps authentication on facebook and tried to login, facebook will ask you for a code from you phone. At the same time before you receive the code, if you are logged in another device you will see a message asking you if you was trying to login
If you press "yes it was me" facebook redirect you from "enter code" page to your account immediately without doing any thing
Now i want to make something similar in laravel
I want if admin pressed "redirect all user to .... Page" button Server redirect all users **immediately** to this page | There are 3 options for this:
1. Long pulling
2. Server Sent Events (SSE)
3. Websocket
You can search about these methods and pros and cons but if you are using laravel, I suggest you to use socket.io and implement this feature with that. There are many tutorials about laravel with socket.io | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "php, laravel"
} |
Setting window size on desktop for a Windows 10 UWP app
I've just started learning UWP app development on Windows 10 Pro using Visual Studio 2015 Community Edition. I tried to modify the C# version of the official "Hello, World!" sample by setting the `Width` and `Height` attributes of the Page tag in MainPage.xaml.
Interestingly, when I start the app, its size will be different. Moreover, if I resize its window and then restart it, the app seems to remember its previous window size.
Is it possible to force a UWP app to have a predefined window size, at least on desktop PCs? | Try setting `PreferredLaunchViewSize` in your `MainPage`'s _constructor_ like this:
public MainPage()
{
this.InitializeComponent();
ApplicationView.PreferredLaunchViewSize = new Size(480, 800);
ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
}
As @kol also pointed out, if you want any size smaller than the default _500x320_ , you will need to manually reset it:
ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(200, 100)); | stackexchange-stackoverflow | {
"answer_score": 79,
"question_score": 36,
"tags": "c#, window, win universal app, windows 10, uwp"
} |
PSQL database creation from script
I have an issue with automatic database creation. I have created create_database.sql file with following code:
BEGIN;
\i schema.sql
\i domains.sql
\i sequences.sql
\i tables.sql
\i dane/insert_users.sql
\i dane/insert_default_expenses.sql
\i dane/insert_default_incomes.sql
\i dane/insert_default_payments.sql
\i dane/insert_user_incomes.sql
\i dane/insert_user_expenses.sql
\i dane/insert_user_payments.sql
\i dane/insert_expenses.sql
\i dane/insert_incomes.sql
\i procedures.sql
\i views.sql
COMMIT;
I would like to automatically create database using that transaction. So I am typing inside SQL SHELL:
psql budget < 'C:\Users\xxx\Desktop\yyy\create_database.sql'
There is no error returned but also DB is not being updated. Any ideas why ? | For running a SQL file you need to provide the file by using the following command
./psql -U postgres -d postgres -p 5432 -f 'C:\Users\xxx\Desktop\yyy\create_database.sql'
Also in create_database.sql you need to provide full path for all sql files that you are executing from inside the tracnsaction block e.g
\i C:\Users\xxx\Desktop\yyy\schema.sql | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "scripting, transactions, psql"
} |
Mathematical formulation for equation in a loop
How can somebody write in a mathematical framework for a recursively defined function, for example:
$ f = f(t,x,g(t,x)) $ and $ g = g(t,x) $
for i = 1:t_end
$ f^{(i)} = \alpha \cdot f^{(i-1)} + \beta \cdot g^{(i)} $ where, $ g^{(i)} = \int_{i-1}^{i} g \cdot dt $
end | You might want to check the indices, but it should turn out to be something like
\begin{align} f_i &= \alpha f_{i-1} + \beta g_i = \alpha ( \alpha f_{i-2}+\beta g_{i-1})+\beta g_i = ...\\\ &= \alpha^i f_0 +\beta \sum_{k=1}^i \alpha^{i-k} g_k. \end{align}
Now to evaluate $f_{t_{end}}$, just use $i=t_{end}$ in the above formula, that is \begin{align} f_{t_{end}} &= \alpha^{t_{end}} f_0 +\beta \sum_{k=1}^{t_{end}} \alpha^{t_{end}-k} g_k. \end{align} | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "functions"
} |
Angular 2 - Preprocessor directives like #if
Is there a way to define preprocessor directives on typescript, something like #define #if etc of c#, specially in angular 2?
I´m developing a project that is multiplatform, and I want to use the same code for mobile and web. The problem is when I use a technology that is not supported for one platform. | > There is a way to define preprocessor directives on typescript, something like #define #if etc of c#, specially in angular 2
No. However the angular team uses webpack and it has the option to define enviroment variables and does dead code elimination on those.
# More
< | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "angular, typescript"
} |
Substitution into integral
I have to do a substitution (`u = pi/2-x`) into an definite integral, which I have defined as `f[u]`. When I evaluate my code, no result is produced.
The code I have written is
substitute[Integrate[f[u], x], {x, 0, Pi/2}], u -> pi/2-x]
Is there something I am missing in my code that I am unaware of?
My `f[u]`is `((Sin[x])^n/(Cos[x])^n + (Sin[x])^n)`. and I am trying to substitute `u = u = pi/2-x` into` it. | You have to solve for x with respect to u then name it y then substitute with it because your original function f[x] depend on x there's only x
f[x_] := ((Sin[x])^(n)/(Cos[x])^(n)) + (Sin[x]^n)
y = x /. Solve[u == (pi/2) - x, x] /. Rule -> Equal
final = Integrate[f[x], x, {x, 0, Pi/2}] /. x -> y
 {
var p = Raphael(10, 10, 400, 400);
p.circle(100, 100, 45);
}
</script>
</head>
<body>
</body>
</html>
All help is greatly appreciated! Thanks! | I think that the circle is present on the page, but it is white, with white stroke on white background. Have you try to set a color
// Sets the fill attribute of the circle to red (#f00)
circle.attr("fill", "#f00");
or
// Sets the stroke attribute of the circle to white
circle.attr("stroke", "#fff"); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, raphael"
} |
How to register an nsIModule DLL on Windows
I've created a Windows library with an implementation of nsIModule (and nsIProtocolHandler) a while ago. I've only recently got round to debugging it some more, but FireFox doesn't run my library any more. I've tried to register my module again, with `regxpcom` and deleting `xpti.dat` and `compreg.dat`, but my contract-id doesn't get listed. If I try debugging firefox or regxpcom, it appears like my DLL doesn't get loaded (where they used to call `NSGetModule` of my DLL).
Has something changed to the registration process? Do I need to provide a `.xpt` file? It wasn't required before, and I don't need/use any interfaces of my own, so if I do it would be an empty type library anyway...
< | I've done a bit more searching, and found out what I need is to create an XPI file. < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "windows, delphi, firefox, mozilla, xpcom"
} |
Find the domain of combined functions
I have a question asking to find the domain of $g(f(x))$ given $f(x)=2x^2+x$, and $g(x)=x^2+1$. I can easily do these questions in reverse when you have to find $f(g(x))$, but when having to find $g(f(x))$ I get a little mixed up. Here is how I started:
$g(f(x))$
$=x(2x^2+x)^2+1$
$=2x^2+x(2x^2+x)+1$
But I am not sure if I have set this up properly.
If someone could help me through this, I'd really appreciate it. | You have the right idea, but you just have to do one thing at a time. Here,
$g(f(x))$
$= g(2x^2 + x)$
$= (2x^2 + x)^2 + 1$
Just think of $g$ as a machine that takes its input, and outputs the input squared plus one.
Now, assuming that the domains of $f$ and $g$ are both $\mathbb{R}$, see if there are any real numbers $x$ for which the above expression creates a problem. If there are, those values are not part of the domain. If there are no such values, then the domain is all of $\mathbb{R}$. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "algebra precalculus, functions, graphing functions"
} |
Anti-Debugging technique in Os-monitor
Im trying to bypass some trial functionnalities in os-monitor, the point is, after running it through ollydbg, a notification appears to tell that executable segment is encrypted with exe-packing algorithm.
!enter image description here
I ignored that, and continue to execute it, then another notification said that program halted because a debugger is detected.
!enter image description here
Can anyone enlighten me of what type of antidebugging technique is used in this software? | > Can anyone enlighten me of what type of antidebugging technique is used in this software?
Yes, that `Protection Error` message is from ASProtect's unpacking stub.
From < it features the following antidebugging techniques:
> * compression of the application
> * encryption of the application
> * counteraction to dumping application memory using tools like ProcDump
> * application integrity check
> * counteraction to debuggers and disassemblers
> * counteraction to memory patching
> * API for interaction between application and protection routines
> * creation and verification of registration keys using public keys encryption algorithms
> * keeping of the database and checkup of "stolen" (illegal) registration keys
> * possibility to create evaluation (trial) versions, that limit application functions based on evaluation time and the number of runs left
> * expose nag-screens
> * generating of registration keys, based on the specific computer system.
> | stackexchange-reverseengineering | {
"answer_score": 3,
"question_score": 1,
"tags": "ollydbg"
} |
mysql insert fails for innodb
i have a simple mysql table with innodb as engine and there are only three columns and the server load is also very minimum always under 1 but i can see that there are only 4000 rows inserted but the the autoincrement number of id shows 21000 so i am not clear what does it mean. does it mean that there are 17000 insert failures my table structure is
id data1 remarks
1 this is text 1
2 another tedt 0
like that table grows but the autoincrement number is creating confusion for me.
i am using mysqli insert
mysqli_query ($con,"INSERT INTO tablea (data1) VALUES ('$data1')");
please suggest/guide in clearing my doubt at a time maximum 30/40 rows are getting inserted maximum | i think i have solved the issue.if your column is unique and mysql tries to insert the data but the data could not be inserted as column is unique but the autoincrement number increases as it tried to insert the data but failed due to unique coulmn propoerties | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "php, mysql, sql, mysqli"
} |
Autohotkey script to send space when tapped and shift when held. It is affecting other mappings
I wrote this script to make my space-bar button act as a space-bar when tapped and a shift button when held. However, it affects mappings such as
> ::btw::by the way
## Scenario:
when I tapped space-bar after typing "btw" to convert "btw" into "by the way ", the conversion did not take place.
* * *
* * *
Is there anyway that I can change my script below to ensure that conversion in the above scenario happens?
$Space::
now := A_TickCount
while GetKeyState("Space", "P") ; to find out whether space-bar is held
if (A_TickCount-now > 180) ; this time is tested on asker's computer
{
SendInput {Shift Down}
KeyWait, Space
SendInput {Shift Up}
return
}
SendInput {Space} ; if key detected to be tapped, send space as per normal
return
Thanks :) | Hotstrings ignore events generate by Autothotkey if their send level is equal or lower than the send level of the event.
This means that the send level of `Space`, must be set to a higher level than the level of hostrings you wish to trigger with it:
#InputLevel, 10 ;set send level for the following code to 10
$Space::
#InputLevel ;set it back to default value of 0 for any remaining code
now := A_TickCount
while GetKeyState("Space", "P") ; to find out whether space-bar is held
if (A_TickCount-now > 180) ; this time is tested on asker's computer
{
SendInput {Shift Down}
KeyWait, Space
SendInput {Shift Up}
return
}
SendInput {Space} ; if key detected to be tapped, send space as per normal
return | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "autohotkey"
} |
I can't seem to divide NSUInteger by 2
The snippet of code:
NSUInteger *lengthOfLine =100;
NSUInteger *half = lengthOfLine/2;
The compile error for line 2:
Invalid operands to binary expression ('NSUInteger *' (aka 'unsigned long *') and 'int') | you should use `NSUInteger`, not `NSUInteger *`. `NSUInteger` is a primitive type, not a subclass of `NSObject`. Now you're dealing with a pointer to `NSUInteger` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios, objective c, nsuinteger"
} |
Overlapping a line plot to a horizontal bar plot in pandas
I'm trying to overlap a line plot to a horizontal bar plot in pandas.
Having a dataframe like this
data = pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=list('ABCD'))
I can overlap a plot to a bar plot, like this:
ax = data[['A','B','C']].plot(kind='bar', stacked=True)
data['D'].plot(color='k',ax=ax)
with this result
Plot on a bar plot
But when I try to use a horizontal barplot
ax = data['D'].plot(color='k')
data[['A','B','C']].plot(kind='barh', stacked=True, ax=ax)
I have this result
Plot on a barh plot
How can I flip the line plot so to have it coherent with the barh plot=
Thank you for any hint! | You can reset the index and plot as follows. Here I am using the values of `D` column as x-values and the `index` (range of values) as the y-values. By using `reset_index()` you add a column of index which makes using `y='index'` straightforward for your plotting purpose.
import pandas as pd
data = pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=list('ABCD')).reset_index()
ax = data.plot(x='D', y='index', color='k', legend=False)
data[['A','B','C']].plot(kind='barh', stacked=True, ax=ax)
**Output**
 is run at the same time across other sessions / connections. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql server, stored procedures, transactions, execution"
} |
How to get X509Certificate from an arbitrary HTTPS URL?
I'm using `HttpWebRequest` to pull a page from an arbitrary HTTPS URL. In addition to the actual page result, I want to get an `X509Certificate2` instance for the remote server I just talked to. I'm sure the public certificate is on the computer somewhere because its chain had to be validated as part of the request. How can I get access to it?
Also, how can I make sure that the ciphersuite used in the SSL channel isn't simply the null ciphersuite? I need to make sure that decent encryption is actually occurring. | Oh! (duh)
HttpWebRequest.ServicePoint.Certificate
But this doesn't answer the ciphersuite part of the question, so that's still open if anyone can answer it. :) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": ".net, x509certificate2"
} |
SharePoint - KQL - Department property contains value
Requirement: I do have "People search" webpart and I need to return ONLY users with a value associated to Department property.
Additional comments: If in the SharePoint User Profile, the department property does not hold any value, I don't need to return this specific user.
I expected to have this one (below) working but it still returns users with no values associated to the Department property
{searchboxquery}* Department<>""
Thanks | Can't filter based on empty value directly, you could check the 'workaround' here.
Department:a*
Department:b*
Department:c*
Department:d*
Department:e*
Department:f*
Department:g*
Department:h*
Department:i*
Department:h*
Department:k*
Department:l*
Department:m*
Department:n*
Department:o*
Department:p*
Department:q*
Department:r*
Department:s*
Department:t*
Department:u*
Department:v*
Department:w*
Department:x*
Department:y*
Department:z* | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "sharepoint"
} |
Laravel custom db driver
i know there is a nice way of defining connections via `app/config/database.php` . But i don't think there is a driver for me available.
Imagine my db is read from file, like a txt. (Yeah! that's my client db, sort of).
So in that file, before I
'connections' =>
'filedb' => array(
'driver' => 'what-should-i-put-here'
i need a real driver!
Currently it uses a txt base db but in a future we will be migrating to mysql, so current eloquent implementation will filt excelent for me. But right now i would like to implement a driver for my txt db so i can fully use eloquent now.
Does laravel provides a way to implement your own driver ? In both cases (true or false) , do you have suggestions about it ? | **Laravel doesn't offer a driver like that**.
Laravel's database component uses **PDO** internally, which means it can only work with the databases that PDO supports.
You could build a driver that would support the text files you use, but honestly the effort seems bigger than migrating your project to MySQL, regardless its size :)
If you need an example, have a look at here: < Laravel doesn't offer MongoDB support, but it can be added with this library. Browse the code - this should help visualise the amount of work that would be needed. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 3,
"tags": "php, database, laravel, laravel 5, eloquent"
} |
Compute cosines and sines of a sequence of angles
I should create a program which computes the cosines and sines of a sequence of angles k*α, where k is a growing natural number (i.e., 0, 1, 2,...) and α is a constant angle which lies between 0 and π. I would like to make this program as fast as possibile.
Hence, I want to compute first the cosine of each angle, and then the related sine with `sqrt(1-cos(k*α)^2)`. The problem is the sign of the sine, which should be determined by the position of the angle k*α on the real line.
I would like to know how I could implement this dynamic comparison as fast as possibile, or if the fastest way to proceed is to compute directly the sine, too. | After some time, I thought again about this problem and I found a really simple solution:
n = floor(k*alpha/pi);
if (n % 2 == 0)
sin_alpha = +sqrt(1-pow(cos(k*alpha,2)));
else
sin_alpha = -sqrt(1-pow(cos(k*alpha,2)));
Problem solved. :) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "performance, comparison, trigonometry"
} |
Jmeter - JSON Extractor - Large numbers erroring
Hope someone can help me :)
I have the response json below :
"endValue":{"amount":12515920.97,"currencyCode":"EUR"}
and I'm using the JSON extractor to retrieve the "amount" number and is working fine for any numbers that have up till 6 characters before the decimal point, but for large numbers like this one, is actually saving "1.251592097E7" on my variable. Is this a limitation or is there any other way that I can have the full number extracted?
Thanks in advance! | All the digits of the number are there, it is just that it is being _displayed_ in scientific notation.
You can format the number when the program needs to display it, for example using DecimalFormat:
import java.text.DecimalFormat;
public class Example{
public static void main(String []args){
double x = 12515920.97;
DecimalFormat df = new DecimalFormat("#,###,###,##0.00");
String result = df.format(x);
System.out.println(result);
}
}
Outputs:
> 12,515,920.97 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "json, jmeter, extractor"
} |
Shebang in windows
Since Windows doesn't support shebang like Unix-like operating systems where you can specify the interpreter in the beginning of the script:
Is putting it in the scripts and running them on Windows going to cause a problem?
I tried it for PHP and it seems to be fine. Is it possible that other interpreters see it as a syntactic error or it's gonna be fine no matter what? | Most language runtimes that run across platforms know about the shebang and ignore it, regardless of platform, or (as in the case of Perl), known about it and do the right thing with it (by invoking the desired program). So if you're using a language like PHP which runs across a variety of OSes, then you should have no problems.
In addition, many of these languages ignore the shebang because in that language the hash mark (`#`) starts a comment, so even if they lack special handling for it, they'll ignore it nevertheless.
The only time you might ever see a problem with a script is if you have a language where `#` is not a comment and it runs only on Windows, but I know of very few languages where that's the case. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "linux, unix, scripting, shebang"
} |
Complex inner product space.

I proved that **_a_** and **_d_** must be real positive, and **_b_** is the conjugate of **_c_**. The solution indicates that **_a.d-b.c_** must also be positive, but i can't figure that out.
thanks for your help. | Hint 1: $f(u,v) = u \begin{pmatrix}a & b \\\ c & d \end{pmatrix} \overline{v}^T$.
Hint 2:
> What happens to $f(u,u)$ if the determinant of that matrix is negative? | stackexchange-math | {
"answer_score": 1,
"question_score": -2,
"tags": "linear algebra"
} |
how to maintain database integrity for write operations in a website
* A website to change add records delete etc
* website is not connected architecture, so i cant expect sql to refuse writes to a table being edit by some one else also. As data is only written when its sent back to server by the grid..
so is there a way using c# and asp.net, some code , by which i cant explicitly tell the sql server to lock the table, so that viewing is allowed but writing to it gives error like
"sorry another user is using the writting function for this table please wait". | No. SQL does not support "lock nowait" semantics with normal transaction modes; only Oracle does. See < for more information on Oracle. Yes, the code will just hang until the table is released.
There is an option of lowering your transaction mode, but then you get more like "free for all" semantics, which you probably also don't want. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c#, database, sql server 2005, locking"
} |
SQL Server - Missing precision on calculating percentage of total using values stored as money
I am currently trying to calculate a percentage of total dollars using values stored as `money`. I am having issues with the precision of the decimal value being rounded, and sometimes to zero. I am casting the value to `decimal(23,22)`, shown here:
CAST(Dollars / (SELECT SUM(Dollars) FROM #TempTable) AS DECIMAL(23, 22)) AS DollarShare
An example would be a record having a total sales of $7.00 out of a total spend of $645503.98. The value returned is 0.0000150000000000000000 when it should be 1.084423987594933e-5.
Someone please help! | Money / Money will return Money.
Convert at least the numerator or denominator (or both) to either a float or decimal
**Example**
Declare @num money = 7
Declare @den money = 645503.98
Select AsMoney = @num/@den
,AsFloat = (@num+0.0)/@den
,AsDecimal = convert(decimal(23,22),@num)/@den
**Returns**
AsMoney AsFloat AsDecimal
0.00 0.000010844239875949 0.000010844239875949331869340294385 | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "sql, sql server"
} |
trim() not working while applying to a string from a backbone model
I'm getting a string `"hi\nbye\ngoodluck\n\n{{optout}}"` from a backbone model. But i need to trim() the string. But it's not working.
When i'm using the same string with trim() in browser, it's working fine : `"hi\nbye\ngoodluck\n\n{{optout}}".trim()`
Expected output :
hi
bye
goodluck
{{optout}} | your string has `multiple-new-lines(\n)`,and `trim()` remove single new-lines. That's why issue occur
You need to use `.replace()` with a `pattern`
Working snippet:-
console.log("hi\nbye\ngoodluck\n\n{{optout}}".replace(/[\r\n]+/g, '\n')); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript, jquery, backbone.js"
} |
How does a browser get a website's logo?
How does an internet browser get the logo/favicon of a website? I run a website and it'll be useful if I know how exactly this happens.
For example, an HTTP request to somewhere might return the value but I'm interested in knowing how this happens in details.
Like how it gets the image, how it implements it. How can I manipulate it? | I believe the 'technical' term for it is a favicon
It's traditionally an .ico file that's 16x16 pixels, and placed at the root of your website directory
With modern browsers. PNGs and GIFs are very widely supported and there's other formats supported too. You can also embed these as tags. | stackexchange-superuser | {
"answer_score": 1,
"question_score": -2,
"tags": "browser"
} |
Find first occurrence of non-integer in a specific column of a dataframe
I have a dataframe with a bunch of integers in a column; at some point in the column, a string or letter will appear. I need to find this string or letter or non integer, then remove all data that comes after it.
How would I go about this? | That should do the trick:
In [20]: df = pd.DataFrame({'x': [1, 2, 'a', 1, 2]})
In [21]: df
Out[21]:
x
0 1
1 2
2 a
3 1
4 2
In [22]: df.loc[(~df.x.apply(np.isreal)).cumsum() == 0, :]
Out[22]:
x
0 1
1 2 | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "python, string, pandas, find"
} |
SKTexture: Error loading image resource
This seems to work perfectly fine:
!enter image description here
and when I created a new project with exactly the same thing, just new images, it doesn't work:
!enter image description here
I even tried
var mainChartxt = SKTexture(imageNamed: "mainC.png")
and it still gives me the same error:
SKTexture: Error loading image resource: "img/mainC.png"
I tried cleaning the project and deleting the derived data folder and still no luck as the image doesn't show up on the app!
Thanks. | Where / How did you add the image in your project ?
The second syntax (without the _path_ ) should be ok. You don't even have to specify _.png_ if that's the file format (but you need to if it something else : _.jpg_ , _.jpeg_ , ...
You might want to check that your asset is "checked" for the target membership. On the right side (Utilities) > File Inspector > Target Membership : _check_ your target (not the tests one if you don't have any tests). | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 5,
"tags": "ios, swift"
} |
ffmpeg encoding sample wanted?
I found this tutorial about ffmpeg the thing i do not get is how to encode video.
can any one, please provide a tutorial.. with explanations for that? (not that i dont get this official one but i'd love to see more comments) | FFmpeg's developers guide refers to an api sample featuring encoding and decoding of both audio and video. This answer links to it as well. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 8,
"tags": "c++, c, video, encoding, ffmpeg"
} |
Where does the Chasam Sofer z”l state that the Megillah is holier than the Torah?
I once heard a lecture from Rav Moshe Wolfson shlita, where he said in the name of the Chasam Sofer that the Megillah has more kedushah (holiness) than Toras Moshe. Does anyone know the source for this?
Also I found this trying to look it up quoting the same in his name, but still without source.
< | The statement you are looking for is in his Derashos I p. 164 column 2 s.v. אמר חז׳ל פ׳ק
> כיון דקבלת תורה בימי מרע׳ה היה באונס והדר קבלוהו בימי אחשורש, על כן אור קדוש הכלול במגילה הוא ממש יותר גדול נכבד מתורתינו הקדושה בעצמה. | stackexchange-judaism | {
"answer_score": 6,
"question_score": 6,
"tags": "megillat esther, kedusha holiness"
} |
Nebula - Convert a grid into a NatTable
I'm looking to convert a nebula grid into a NatTable. My goal is to be able to generate an excel file automatically using this code :
final ExportCommand cmd = new ExportCommand(natTable.getConfigRegistry(), natTable.getShell());
natTable.doCommand(cmd);
Do you know if it is possible?
Thanks | There is no simple way to convert from an SWT Table, JFace TableViewer or Nebula Grid to a NatTable. They have completely different architectures and designs. The mentioned three implementations use the native OS table, or at least simulate the same, while NatTable is completely custom painted. Another fact is that those three implementations are created column by column, while NatTable uses an `IDataProvider` that is two-dimensional by design, so there is no column-by-column approach.
I explained this also in our Getting Started Tutorial.
So no, there is no simple way to convert. You need to create it from scratch. But that should be no big deal when checking our examples. Well, of course that depends on the features you want to use. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, nattable, nebula"
} |
Save function argument as character
I want to save the argument of a function as a variable in r. I've tried deparse, but on a dataframe it returns the wrong thing. Below is what I want.
dataframe <- data.frame(a=c(1, 2, 3), b=c(3, 6, 8))
afunction <- function(arg1, arg2) {
arg1_character <- deparse(arg1)
arg2_character <- deparse(arg2)
}
afunction(a ~ b, dataframe)
Based on this simple example I'd want the following output:
arg1_character <- "a~b"
arg2_character <- "dataframe" | Try `deparse(substitute())`.
afunction <- function(arg1, arg2) {
arg1_character <- deparse(substitute(arg1))
arg2_character <- deparse(substitute(arg2))
c(arg1_character, arg2_character)
}
afunction(a ~ b, dataframe)
# [1] "a ~ b" "dataframe"
Or try `match.call()`
afunction2 <- function(arg1, arg2) {
cat('Call:\n')
match.call()
}
afunction2(a ~ b, dataframe)
# Call:
# afunction2(arg1 = a ~ b, arg2 = dataframe) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "r, dataframe, character"
} |
How many accessories can a mouse equip in Mice and Mystics
The accessory cards do not show a usage slot (head, body, paws). Does that mean there is no limit to how many a single mouse can equip? Or are they limited to one? | This BGG thread contains confirmation from the game's designer that you can equip as many accessories at once as you want. | stackexchange-boardgames | {
"answer_score": 5,
"question_score": 4,
"tags": "mice and mystics"
} |
Why does this line tell me a float can not be used as integer
I have this one line that my script is getting caught up on:
for d in range(len(r)/2)
I am not sure what value is what value it thinks in a float. I try casting the length of r/2 as an int but still I get this error. I am really new to Python and really lost. | In Python 3.x, the `/` division operator _always_ gives a float value. To use integer division, use `//`:
for d in range(len(r) // 2):
I suspect you tried `range(int(len(r))/2)` but that doesn't change how the division works. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 3,
"tags": "python, python 3.x"
} |
How many connections to maintain in RabbitMQ?
I am using the RabbitMQ java client. My app has multiple exchanges and queues. Adopting something similar to the Pub/Sub model.
What is the best practice regarding connections? Shall I have one connection per app?
I understand the channel model, and the thread (un)safety model. Just not sure if I should have multiple connections or not. | One connection per app is correct.
Within that connection, you will have many channels - where the actual work is done.
You can have hundreds or thousands of message producers and consumers (each on their on channel) inside a single connection.
If you start to see slowdown in your RMQ setup because you're dong too much work, look at clustering RMQ and/or standing up multiple instances of your app.
But you would still maintain 1 connection per app instance. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "java, rabbitmq, amqp"
} |
How to get all the dates within a date range in ionic 3?
I currently have a start date (2019-11-30) and a end date (2019-12-7). How do I list out all the dates in between and put them into an array?
I want to store it in this format in the array:
["2019-11-30", "2019-11-31", "2019-12-1", "2019-12-2", "2019-12-3", "2019-12-4", "2019-11-5"]; | This is a simple example that maybe work for you:
var startDate = new Date("2019-11-30"); //YYYY-MM-DD
var endDate = new Date("2019-12-07"); //YYYY-MM-DD
function formatDate(date) {
var day = date.getDate();
var month = date.getMonth()+1;
var year = date.getFullYear();
return day + '-' + month + '-' + year;
}
var getDateArray = function(start, end) {
var arr = new Array();
var dt = new Date(start);
while (dt <= end) {
arr.push(formatDate(new Date(dt)));
dt.setDate(dt.getDate() + 1);
}
return arr;
}
var dateArr = getDateArray(startDate, endDate);
console.log(dateArr)
I hope this will help you | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "angular, ionic framework, ionic3"
} |
Error while initializing MongoDB
I'm trying to initialize MongoDB from a tutorial and I had to write the following code:
`mongod --directoryperdb --dbpath C:\mongodb\data\db --logpath C:\mongodb\log\mongo.db --logappend --install`
After I type it, it gives me the following error:
2018-02-27T21:11:20.978-0800 F CONTROL [main] Failed global initialization: FileNotOpen: Failed to open "C:\mongodb\log\mongo.db"
I don't have the directory "log" but nor does the guy in the tutorial, so I'm a little confused what might be the problem. | The problem was that I didn't have the files "log" and "data", and inside of data the file "db". You have to create those files manually in order for it to work. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "database, mongodb, initialization"
} |
What does a negative value mean for a liability on the London Stock Exchange Fundamentals page?
Take this page :
<
Under non-current liabilities
What does a negative value mean for borrowings?
Does that mean they started paying it back? or is it what they borrowed? | That's what's owed.
You can follow the math by looking at current assets, current liabilities and net current assets.
Current Assets 1.47
Current Liabilities -0.54
------
Net Current Assets 0.94
Obviously there's a little rounding error when you're only given 3 digits of a 7 digit number, but you get the picture. | stackexchange-money | {
"answer_score": 1,
"question_score": 0,
"tags": "stock analysis"
} |
How can I use a quote " or ' character within a string?
am working on selenium webdriver using JAVA !
am trying to pass a string dynamically using the variable exp
String exp=",,,4'-TETRA; P-CHLORIDE";
d.findElement(By.xpath("a[contains(text(),\""+exp+"\")]//ancestor::table//parent::div")).sendKeys(Keys.ARROW_DOWN);
but its giving me an error :
Unable to locate element: {"method":"xpath","selector":
"a[contains(text(),\",,,4'-TETRA; P-CHLORIDE\")]//ancestor::table//parent::div"
} | Use `'"+exp+"'` instead of `\""+exp+"\"` :
d.findElement(By.xpath("a[contains(text(),'"+exp+"')]//ancestor::table//parent::div")).sendKeys(Keys.ARROW_DOWN);
**Update**
d.findElement(By.xpath('a[contains(text(),"'+exp+'")]//ancestor::table//parent::div')).sendKeys(Keys.ARROW_DOWN); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "java, string, xpath, selenium webdriver"
} |
How to get substring after next ':' after a slice?
I have a string that looks like this:
var string = 'foo:bar:1234:something:4321';
I want to return the section after `bar:` up until the next `:`. In this case I want "1234". The size can vary.
Here's what I have started, but am unsure how to specify the ending.
var newString = string.slice('bar:'.indexOf(), <HOW TO SPECIFY THE END?>);
**EDIT**
The string could also contain more values and colons so these are possible too:
var string = 'fu:bu:foo:bar:1234:something:4321';
var string = 'bar:1234:something:4321'; | function getBarValue(str) {
var splitString = str.split('bar:'); // make this `:bar:` if foobar: is an issue
if (splitString.length < 2) {
return null; // "bar:" does not exist in string
}
return splitString[1].substring(0, splitString[1].indexOf(':'));
}
var barVal = getBarValue('foo:bar:1234:something:4321');
console.log(barVal); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript"
} |
Query CMSPlugin model for draft or live objects
I've got a CMSPlugin & a request to display it's items in another app.
Obviously for every plugin you create there is a live and draft version, so doing `audio = Audio.objects.all()` brings you duplicate instances.
How would you go about creating a query which only returns the plugin objects from public pages?
My plugin;
class Audio(CMSPlugin):
"""
Model for storing audio clips.
"""
caption = models.CharField(
_("Title"),
max_length=255,
blank=True
)
audio_track = models.FileField()
description = models.CharField(
_("Description"),
max_length=255,
blank=True,
null=True
) | How about something like this:
Audio.objects.filter(placeholder__page__publisher_is_draft=False)
This assumes all `Audio` plugins belongs to a CMS page. CMSPlugins are not guaranteed to have a page associated with them! Unless you set `page_only` option to `True`:
page_only = True
Docs: < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "django cms"
} |
Is there a way to programmatically insert formulas into a csv file using vb.net?
I need to add formulas to a CSV file that already exists. Is this possible to do this using VB.Net?
The idea is I already have a CSV file and I need one column to be populated in each cell with a custom formula. This has to be done programmatically because these files are being created dynamically.
Does anyone know how to do this? Thanks. | While I stand by that my original answer is technically correct, I have been getting a lot of downvotes on this. Apparently popular spreadsheet software such as Microsoft Excel, Open Office, Libre Office Calc will calculate formulas that are entered into a CSV file. However, I would still not recommend relying in this capability.
**Original answer:**
The CSV format does not support formulas. It is a plain text only format. | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 18,
"tags": "vb.net, csv"
} |
Is it possible to skip column in CASE WHEN postgres
I have a query :
SELECT o.version, o.text, o.id
case when language=1
then o.language else [SKIP LANGUAGE COLUMN] end as language
FROM books AS o
Is it possible to skip column `language` if `language!=1`? so if language=1 I'd like to get: version|textt|id|language
otherwise: version|textt|id| (without language column) | "Is it possible to skip column in CASE WHEN postgres?"
If by "Skip" you mean have the query project different number of columns in the result set, like @a_horse_with_no_name commented, NO.
You can assign null (or other value) in your else expression.
case when language=1 then o.language else null end as language
Or just leave the else out if you want nulls
case when language=1 then o.language end as language
If you must have different number of columns projected, you will need to execute two separate queries. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "sql, postgresql, postgresql 9.6"
} |
All the cases for Image and Kernel
$$\pmatrix{ \alpha & 1 & 1 & -1 \\\ 2 & -\alpha & 0 & -2 \\\ -\alpha & 2 & 1 & 1 }$$
here alpha is a real variable, and I need to find the kernel and image for all values for alpha.
**Attempt:** I can't seem to figure out all the cases which I need to evaluate, as the last two columns are non-parallel - I've tried using this but to no avail. If someone could tell me the different cases to consider why that would be great, I'm sure I can from there work out the image and kernel. Thanks. | The last two columns are linearly independent. The first, third and fourth columns are linearly independent unless $\alpha = 1$. Thus for $\alpha \ne 1$ the rank is $3$, the image is $\mathbb R^3$ and the kernel is one-dimensional. For $\alpha = 1$ the rank turns out to be $2$, the image is two-dimensional, and the kernel is two-dimensional. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "linear algebra, matrices"
} |
direct (non-tcp) connection to redis from nodejs
hello all
I looked at the at the redis-node-client source (relevant part is shown bellow) and I see that it connects to redis via the 'net' package, which is TCP based.
line 370
exports.createClient = function (port, host, options) {
var port = port || exports.DEFAULT_PORT;
var host = host || exports.DEFAULT_HOST;
var client = new Client(net.createConnection(port, host), options);
client.port = port;
client.host = host;
return client;
};
I was wondering if there's a more direct client for redis, preferably via domain-sockets or something of that sort. Im using redis localy, as cache, without going over the wire so its unnecessary to encode/decode messages with TCP headers...
thank you | Unix Domain Socket support appears to have landed in Redis as of Nov 4th.
<
To connect to a Unix Domain Socket, you need to supply the pathname to net.createConnection. Maybe something like this in redis-node-client:
exports.createSocketClient = function (path, options) {
var client = new Client(net.createConnection(path), options);
client.path = path;
return client;
}; | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "node.js, redis"
} |
Using list comprehension. with nested if
Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filename. Using list comprehension#
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
newfilenames = [filename[:len(filename) - 3] + "h" for filename in filenames if filename.endswith("p")]
print(newfilenames)
output came `["stdio.h", "sample.h", "math.h"]` Should be `["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]` | I think you need
filenames = [i[:-3]+"h" if i.split(".")[-1]=="hpp" else i for i in filenames]
print(filenames) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "python, for loop, list comprehension, nested if"
} |
SSMS 2008 converts control characters to spaces when using 'Results to Grid'
I have a table in which one column (type ntext) has data that includes carriage return and linefeeds. (CHAR(13) and CHAR(10)).
If I right click the table in SSMS 2008 and choose 'Select Top 1000 rows' and the display mode is set to "Result to Grid" it seems that control characters (like TAB and CRLF) are converted to spaces for display in the grid!!
Yet if I right click the table and choose 'Edit Top 200 rows', the control character data is shown in the resulting grid (as two small squares).
Is there any way to keep SSMS from stripping out the control characters and changing them to spaces? At first I thought that it was just a display issue but if I right click one cell and choose copy and then paste into notepad, only spaces are pasted.
I don't understand why they would do that. | When you switch to "Results to Text" or "Results to file", special characters would be preserved. In grid, they are lost, unfortunately.
It wouldn't be hard to fix it, but someone has to open bug on < Then there is a chance SSMS team will react and fix it.
Since I'm no longer on that team, that's the only thing I can suggest. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ssms, spaces, sql server 2008"
} |
How can I stop Windows Indexing from running?
!enter image description hereXP Pro, SP3.
I now use "Everything" for search. How can I stop Windows Indexing from running? | > 1. In the "Start" menu, choose "Run."
>
> 2. Type "services.msc" and press Enter.
>
> 3. Scroll-down to "Indexing Service" and double-click it.
>
> 4. If the service status is "Running", then stop it by pressing the "Stop" button.
>
> 5. To make sure this service doesn't run again, under "Startup Type:", choose "Disabled."
>
>
— Lifehacker - Turn off indexing and speed up Windows XP | stackexchange-superuser | {
"answer_score": 4,
"question_score": 3,
"tags": "windows xp, search"
} |
Multiple regular expressions in PHP
Is there a better to handle running multiple regular expressions in PHP (or in general)?
I have the code below to replace non alphanumeric characters with dashes, once the replacement has happened I want to remove the instances of multiple dashes.
$slug = preg_replace('/[^A-Za-z0-9]/i', '-', $slug);
$slug = preg_replace('/\-{2,}/i', '-', $slug);
Is there a neater way to do this? ie, setup the regex pattern to replace one pattern and then the other?
(I'm like a kid with a fork in a socket when it comes to regex) | You can eliminate the second `preg_replace` by saying what you really mean in the first one:
$slug = preg_replace('/[^a-z0-9]+/i', '-', $slug);
What you really mean is "replace all sequences of one or more non-alphanumeric characters with a single hyphen" and that's what `/[^a-z0-9]+/i` does. Also, you don't need to include the upper and lower case letters when you specify a case insensitive regex so I took that out. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "php, regex"
} |
Changing the color in MathJax or MathML
If I have an equation like ax+b and I want to be able to display these with the coefficients highlighted, I could write
MathJax:
\(\color{blue}{m}x+\color{red}{c}\)
MathML:
<math>
<mi style="color: blue">m</mi>
<mi>x</mi>
<mo>+</mo>
<mi style="color: red">c</mi>
</math>
If I want to change the colors of the MathML-code I can simply use class-tags for the coefficients
<mi class="mColor">m</mi>
and I can use a simple jQuery script (.css()) to change the colour of this class. Is there a similar tool for MathJax? Something like
\color{$mColor}{m}
Which I can change with a jQuery script?
tldr:
Is there a script in JS/jQuery which lets me change the colour of a MathJax symbol? | Use `\(\class{mColor}{m}x+\class{cColor}{c}\)`. This will produce
<math xmlns="
<mi class="mColor">m</mi>
<mi>x</mi>
<mo>+</mo>
<mi class="cColor">c</mi>
</math>
so that you can change the styling of those two classes as you normally would. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "mathjax, mathml"
} |
Evaluate $\lim_{x\to45} \frac{\sqrt{x+4}-7}{x-45}$
Evaluate $\lim_{x\to45} \frac{\sqrt{x+4}-7}{x-45}$
So far I multiply both sides by $x+45$, but I don't know how to finish it.
Please Help!! | Try multiplying top and bottom by the quantity $\sqrt{x + 4} + 7$. This leads to
$$\frac{\sqrt{x + 4} - 7}{x - 45} = \frac{(\sqrt{x + 4} - 7)(\sqrt{x + 4} + 7)}{(x - 45)(\sqrt{x + 4} + 7)}$$
The numerator can be simplified to get $x - 45$. | stackexchange-math | {
"answer_score": 6,
"question_score": 0,
"tags": "calculus, limits"
} |
Provide a prompt answer during some script execution
I have these three sh scripts which are doing some sql scripts in oracle database. After some initial updates the scrip ask a question which needs to be answered by pressing J . But now i have to provide this answer manually whenever it stops. Does anyone have an idea about how should i provide this answer so that all the script will be finished without my intervention??
./1.sh A B && \
./2.sh A B && \
./2.sh A B | Yeah you can do this. Redirect stdin so that it takes its input from a file.
ie
/1.sh A B 0<ip1.txt && \
./2.sh A B 0<ip2.txt && \
./2.sh A B 0<ip3.txt
where ip1.txt, ip2.txt, ip3.txt etc contains your reply for each of the scripts respectively. It is restricted in that only one reply can be used per script.
You could tweak this ipi.txt files to redirect script responds to stdout. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "bash"
} |
Python cannot create subfolder by set folder name as input
I want to create folder name 1 in folder abc. This is the code.
id=input("enter user id : ")
path = "/abc/" + str(id)
try:
os.mkdir(path)
except OSError:
print ("Creation of the directory %s failed" % path)
else:
print ("Successfully created the directory %s " % path)
I enter 1 for create folder name 1 but it show error like this. How to fix it?
enter user id : 1
Creation of the directory /abc/1 failed | Try using:
id = input("enter user id : ")
path = "abc/{}".format(id)
try:
file = open(path)
except Exception:
if not os.path.exists(path):
os.makedirs(path) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python, directory"
} |
what options are there for dateFormat in as.xts() in R
When transforming a matrix/dataframe etc into a xts object I often use the function `as.xts()`. If my initial object has an index containing plain Dates like "2020-06-20", the output of `as.xts()` will have a timezone added like "2020-06-20 CEST".
I know there is an buildin option `dateFormat`, but I don't what values I can pass into that. Is there a list of possible inputs somewhere? I can't find any in the documentation the only one I know is "POSIXct"
new_xts_object <- as.xts(my_matrix, dateFormat="POSIXct")
So what else `dateFormat`'s are there? And is there one just like `as.Date()`, a plain date format? | You find such a list in `help("index.xts")`:
> The specified value for `tclass<-` must be a character string containing one of the following: `Date`, `POSIXct`, `chron`, `yearmon`, `yearqtr` or `timeDate`.
Trying it:
library(xts)
library(timeSeries)
x <- timeSeries(1:10, 1:10)
as.xts(x, dateFormat = "POSIXct")
as.xts(x, dateFormat = "POSIXlt")
as.xts(x, dateFormat = "Date")
library(chron)
as.xts(x, dateFormat = "chron")
library(timeDate)
as.xts(x, dateFormat = "yearmon")
as.xts(x, dateFormat = "yearqtr")
as.xts(x, dateFormat = "timeDate") | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "r, date, xts, date formatting"
} |
Python3 solution to create all parent directories and file from a relative path [Windows]
I am trying to create all non-existing directories and the file from a relative path but am unable to do so.
Example:
import os
path = os.path.join("folder1", "folder2", "folder3", "file.txt")
os.makedirs(path) # this creates a directory called 'file.txt' instead of a file.
I would like to have the following: `folder1` > `folder2` > `folder3` > `file.txt`
**Note** : Would be great if anyone has any one-liner solutions for this. | As far as I know that doesn't exist, but using this function, it can become a one liner:
def create_file_in_folders(p):
folders = p.rsplit("\\", maxsplit= 1)[0]
os.makedirs(folders)
with open(p, "w") as f: f.write("")
p = os.path.join("folder2", "folder2", "text.txt")
create_file_in_folders(p)
>>> # now you should find an empty txt file in the newly created folders | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, windows"
} |
Por que o logback usa tanto logback-test.xml como logback.xml como nome do arquivo de configuração?
Lendo o manual do logback, na seção de configuração, ele fala que procura pelos seguintes arquivos de configuração, em ordem:
1. logback-test.xml
2. logback.groovy
3. logback.xml
Qual o motivo de haver o sufixo `-test`? Pra mim só havendo logback.xml faz sentido. Pra que enlongar o nome do arquivo? | Testes de unidade normalmente incluem o projeto inteiro no classpath, inclusive arquivos de configuração, dentre eles o `logback.xml`.
Ocorre que as configurações de log dos testes de unidade normalmente são diferentes da configuração de log do projeto para produção. Uma forma simples de se resolver isso é colocar o arquivo `logback-test.xml` no classpath dos testes de unidade. Assim, o Logback saberá quando escolher o arquivo de configuração correto e o nome deixará claro se você está usando o de produção (`logback.xml`) ou o de teste (`logback-test.xml`). | stackexchange-pt_stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "java, logback"
} |
Force new line for isotope
I use isotope javascript on my website. I make nice design and in one page I want to force a new line for the items. How can I do that? I don't want to fit that two elements to be on the same line.
!enter image description here | You can do this two ways:
1) Make the isotope container the same width as the items. This can be done by CSS. This way you force every isotope item to be on each line as there are not enough space for two items on one line.
2) Set width of isotope item to 100%. This way it will fill the entire width of the container they are inside.
Both options should work. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, css, jquery isotope"
} |
"railroad flat" meaning in context
From The Godfather:
> He left the club an caught a cab to his furnished room on Tenth Avenue. He boarded with an Italian family to which he was distantly related. His two room was separated from the rest of their _railroad_ _flat_ by a special door.
So, I'm confused by the "railroad flat" phrase. Is railroad the same as railway here? | Same term as "railroad apartment" ("flat" is another term for "apartment", nowadays more often used in Britain), so called because of the similarity of the layout to a railroad car. See this. | stackexchange-ell | {
"answer_score": 4,
"question_score": 2,
"tags": "phrases"
} |
How to estimate optimal gamma parameter for gamma correction?
Is it possible to estimate optimal gamma parameter for gamma correction by algorithm using some image statistics? By 'optimal' I mean that image should 'look good' for human on average after correction. | If your image pixels are scaled on the range 0..255, you could use:
gamma = log(mean)/log(128)
where `mean` is the mean of your image pixels. If they are scaled on the range 0..1:
gamma = log(mean)/log(0.5)
Note that this is the technique that **ImageMagick** uses, documentation here, and you can test it yourself on the command line with:
magick input.jpg -auto-gamma result.jpg
Nothing is perfect though and that may not look good if there are heavy shadows or bright areas in your images. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "opencv, image processing, computer vision"
} |
import scalaz monad syntax outside of function
Is there a way I can avoid importing monad syntax in the body of all my functions? Here's what I'm stuck writing:
object Example {
def doMonadThings[M[_]: Monad, A](ma: M[A]): M[A] = {
val monadSyntax = implicitly[MonadSyntax[M]]
import monadSyntax._
ma.flatMap { x => point(x) }
}
}
`scalaz 7.2`
EDIT:
Here's what I ended up with:
object Example {
import scalaz.syntax.monad._
def doMonadThings[M[_], A](ma: M[A])(implicit m: Monad[M]): M[A] =
ma.flatMap { x => m.point(x) }
} | Try
import scalaz.syntax.monad._
def doMonadThings[M[_]: Monad, A](ma: M[A]): M[A] = {
ma.flatMap[A] { x => x.point }
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "scala, scalaz"
} |
Storing component into a variable and reuse it
Ok i got components imported as
import Payment from './pages/payment';
import Chat from './pages/chat';
Now I am using `Drawer` component and using it together with `Navigator` my renderScene become something like this
if( route.id == 'payment'){
return <Drawer xx={} yy={} and a lot more >
<Payment navigator={navigator} />
</Drawer>
}
if(route.id == 'chat'){
return <Drawer xx={} yy={} and a lot more >
<Chat navigator={navigator} />
</Drawer>
}
Those lengthy `Drawer` code are being used again and again. I want to store that `<Payment navigator={navigator} >` or the other into a variable and then return that with `Drawer` only once.
How can i store it and return it with Drawer?
Thanks | Not sure if you are asking this but what about something like:
const routes = {
payment: Payment,
chat: Chat
...
}
And then, just:
const Scene = routes[route.id];
return (
<Drawer>
<Scene navigator={navigator}/>
</Drawer>
) | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 11,
"tags": "reactjs, react native"
} |
Will the mail client elementary OS 6 include contact syncing?
I tried Beta 2 of elementary OS 6 and I admit to being very impressed. If contact syncing is going to be added prior to release, you can count on me as a convert. I'd love to move away from Thunderbird but so far, I have not seen an adequate replacement. | It appears that contact syncing has _not_ been written into the current, stable version of `pantheon-mail` for elementaryOS 6.0. I guess I'll be waiting for 7.0... | stackexchange-elementaryos | {
"answer_score": 2,
"question_score": 1,
"tags": "pantheon mail"
} |
Where do we see Targets in Xcode 4.2
Where do we see "Targets" in Xcode 4.2.
I want to see the headers, compiled files & libraries that are part of my project. I can see that in Xcode 3.2.6.
Any idea? | Click on the project file in the Project Navigator. You should see your Project and Targets list on the left pane. Click on the Build Phases tabs. Here, you can see your libraries (under "Link Binary with Libraries") and source files (under "Compile Sources"). | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "iphone, ios, xcode, xcode4.2"
} |
Subsets and Splits