text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Can't access particular website on Windows Server, but ping works
In my Windows Server hosted in AWS, I tried to access a particular site from Chrome/IE and both browsers returned - the site can't be reached/the server refused to connect. However, when I try to ping the same website from cmd it seems to work just fine. I don't use any proxy in the network setting and Chrome is set to detect network settings automatically.
So this is definitely not an IP based block from the website. My local PC and my server PC are in the same region, but different city. It works great in my local PC but in the server, it simply works via ping.
What are some possible reasons that might have caused this?
Updates
Telnet Connection Failed
A:
Is not an IP based block, but what about procotol type or port block?
ping sends ICMP packages to a host but when you try to open the website via Chrome you need to establish a TCP connection to a host:port. So you should check the firewall in your server, if is hosted in AWS check also the Security Group rules.
Then you can test if you are able to connect to HTTP (80) or HTTPS ports (443), for example using:
telnet myserver 80
telnet myserver 443
instead of
ping myserver
| {
"pile_set_name": "StackExchange"
} |
Q:
Mixing audio with HDMI video to replace the sound from the camera
I would like to live-stream from a camera, but replace the audio from the camera with a higher-quality mixed soundtrack, ready for sending over HDMI to a transmission device.
How can I do this?
I know that the Tascam DR-701D has two HDMI ports (in and out). Could I use this as the mixer to replace the soundtrack on the HDMI video feed, ready for transmission, or is there a better way?
Details
The video will come from the micro-HDMI port on the camera.
The audio will come from one of three sources:
XLR stream from the event
Directional XLR mic
MP3 player
The audio will be mixed together by a mixer during the event as appropriate.
I now need to mix the audio from the sound mixer with the video from the camera’s HMDI port (which will have an unusable poor-quality audio track from the camera). How can I do this?
A:
It seems that what you are looking for is an HDMI audio embedder.
It seems that the Tascam DR-701D offers this functionality as described in Outputting this unit's audio as the HDMI output audio
Examples of external alternative such products can be found here (I am not affiliated with these manufacturers, other products might exist):
Kramer FC-69
Extron HAI 100 4K
| {
"pile_set_name": "StackExchange"
} |
Q:
Confluence wiki format put new paragraph
I'd like to put empty linespace (<p></p> in HTML) in Confluence wiki result, but failed whatever I tried.
Based on the the document, it said two carriage-return will put <p></p> but \r\r, \n\n, \n\n\n\n, etc.trials are not working at all.
POST http://wiki.mysite.com/rest/api/content
{"type":"page","title":"new page1","ancestors":[{"id":390668024}], "space":{"key":"EXAMPLE"},"body":{"storage":{"value":"[Some link|http://example.com/url] - Show page.\n\nbq. Query by [Some link info|http://example.com/reference?id=214]","representation":"wiki"}}}
With above REST request, I'd like to show as below format;
Some link - Show page.
<blank line>
Query by Some link info
Some trials (between words Show page. and bq. Query by)
\n\n => Show page.</p>\n\n<blockquote><p>Query by
\\\\ => Show page. <br class=\"atl-forced-newline\" /> bq. Query by
A:
Below trial gives expected result
Show page.\n\n \\\\ \nbq. Query by
=> Show page.</p>\n\n<p> <br class=\"atl-forced-newline\" /> </p>\n<blockquote><p>Query by
| {
"pile_set_name": "StackExchange"
} |
Q:
Skip "$RECYCLE.BIN" when copying all directories
I am trying to copy all folders to c: the issue is it keeps trying to access the recycle bin folder. I tried many thing to avoid it but it did't work. I had same issue with system volume information but i simply skipped over it. I don't know why this approach is not working with the $recycle.bin
public void Copy(string sourceDirectory, string targetDirectory)
{
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
string[] entries;
try
{
//Gets list of all files and directories (we need it for progress bar)
entries = Directory.GetFileSystemEntries(sourceDirectory, "*", SearchOption.AllDirectories);
//entries = Directory.GetFiles(sourceDirectory, "*.*", SearchOption.AllDirectories)
// .Where(d => !d.StartsWith("$RECYCLE.BIN"))
// .Where(d => !d.StartsWith("System Volume Information")).ToArray();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
Invoke(new Action(() => progressBar1.Maximum = entries.Count()));
Invoke(new Action(() => progressBar1.Step = 1));
Invoke(new Action(() => progressBar1.Value = 0)); //Using Invoke to prevent Cross thread exception
CopyAll(diSource, diTarget, entries);
}
public void CopyAll(DirectoryInfo source, DirectoryInfo target, string[] entries)
{
// lblInfo.Text = "Copying " + source;
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
try
{
if (source.ToString() != "D:\\$RECYCLE.BIN" && source.ToString() != "System Volume Information")
{
if (!IsWorking)
{
Invoke(new Action(() => lblInfo.Text = "Stopped"));
return;
}
//Using Invoke to prevent Cross thread exception
Invoke(new Action(() => this.lblInfo.Text = string.Format("Copied {0}\\{1}", source.FullName, fi.Name)));
if (File.Exists(Path.Combine(target.FullName, fi.Name)))
{
File.Delete(Path.Combine(target.FullName, fi.Name));
}
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
Application.DoEvents();
Invoke(new Action(() => progressBar1.Value++));
}
}
catch (UnauthorizedAccessException ex)
{
// ok, so we are not allowed to dig into that directory. Move on.
}
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
try
{
if (diSourceSubDir.ToString() != "System Volume Information" && diSourceSubDir.ToString() != "$RECYCLE.BIN")
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir, entries);
Invoke(new Action(() => progressBar1.Value++));
}
else
{
Invoke(new Action(() => progressBar1.Value = progressBar1.Value + 2));
}
}
catch (UnauthorizedAccessException ex)
{
// ok, so we are not allowed to dig into that directory. Move on.
}
}
I tried the commented out LINQ and if statements and most online answers. I don't want to run it as admin and I deleted the app.manifest file I appreciate the help.
A:
Here is what I did: I added the conditions and removed the return; and show box so when it catch something it just moves on to the next directory.
try
{
if (!diSource.ToString().Contains("System Volume Information") &&
!diSource.ToString().ToUpper().Contains("$RECYCLE.BIN"))
{
entries = Directory.GetFileSystemEntries(sourceDirectory, "*",
SearchOption.AllDirectories);
}
}
catch (UnauthorizedAccessException ex)
{
//ok, so we are not allowed to dig into that directory. Move on.
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to search all levels nested Javascript object
I have a Javascript Object that represents a nested JSON string like this:
http://pastebin.com/vwZb1XrA
There are many levels that contain a "name" element. For example "SVI" or "Population" or "Human Development Index".
I am trying to find a way to iterate over every level of the object to find the name "SVI" or "Population" or "Human Development Index". When a match is made I want to then replace the weight value with something like this:
if (data[key].name == name) {
data[key].weight = 55;
}
A:
You can recursively check each and every object, like this
function rec(currentObject, values, replacement) {
if (values.some(function(currentValue) {
return currentObject.name === currentValue;
})) {
currentObject.weight = replacement;
}
(currentObject.children || []).forEach(function(currentItem) {
rec(currentItem, values, replacement);
});
}
rec(data, ["SVI", "Population", "Human Development Index"], 55);
console.log(data);
Working demo
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I remove all headers from a CURL Post
I am trying to post xml to a server using cURL without any headers but I can't seem to get rid of the following headers:
Content-Disposition: form-data; name="data"; filename="tempData.xml".
Does anyone know how to remove these headers and just send the file?
Code is below:
$URL = www.myurl.com/process/php;
//get post data
$post = array("data"=>"@tempData.xml");
//add headers
/*$Headers = array
( "POST HTTP/1.0"
, "Accept: text/xml"
, "Content-type: text/xml"
);*/
//$Headers = array("");
//create curl instance and set options
$CH = curl_init($URL);
curl_setopt( $CH, CURLOPT_TIMEOUT, 60 ); //timeout after 60 seconds
curl_setopt( $CH, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt( $CH, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt( $CH, CURLOPT_HTTPHEADER, 0);
curl_setopt( $CH, CURLOPT_HEADER, 0);
curl_setopt( $CH, CURLOPT_POST, true );
curl_setopt( $CH, CURLOPT_POSTFIELDS, $post ); // add post fields
//echo curl_error($CH);
$output = curl_exec( $CH );
$info = curl_getinfo( $CH );
//print_r($info);
if($info['http_code'] != 200){
//header('HTTP/1.0 500 Could Not Send XML');
echo 'error ' . $info["http_code"];
curl_close($CH);
exit(1);
}
curl_close($CH)
;
A:
It isn't really possible if done like this.
When you select to do a multipart formpost with libcurl, it will actually do a formpost according to the spec. It was originally specified in RFC1867, and it did already then specify that the Content-Disposition: should be there for each form part.
If you want to do your own non-compliant post, then craft your own buffer completely instead of relying on libcurl's multipart formpost support.
Let me end up with saying that your commented out code that specifies custom headers is wrong since it includes a request line among the headers.
| {
"pile_set_name": "StackExchange"
} |
Q:
load an object twice and change one of them, the other one doesnt changed
Father father = BL.GetFatherById(1);
Product product = BL.GetByID(123);
(father.Products[553] == product)
product.delete = true;
father.Products[553].delete == false !!??
why is that ?
aren't they connected ?? its the same object.
A:
As you can read in section 10.3 of the NHibernate reference manual database identity and CLR object identity are equivalent per session.
Therefore Object.ReferenceEquals(foo, bar) will yield true if and only if foo and bar are attached to the same session and map to the same database row. Be careful when using == for comparing object identity - the operator may have been overloaded (but you should usually know that).
In consequence you should always get the same object no matter what query you use for the object as long as you stay within the same session. Are you using multiple sessions? Maybe a Unit of Work pattern and you are comparing objects returned from to different units of work?
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails Form Helper not reading question mark for object attribute
Ruby Version: 2.0
Rails Version: 4.0
I have a controller Question, which has an embedded form for a model Answer.
question.rb
class Question < ActiveRecord::Base
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers, :allow_destroy => true
end
answer.rb
class Answer < ActiveRecord::Base
belongs_to :question
end
answers migration
class CreateAnswers < ActiveRecord::Migration
def change
create_table :answers do |t|
t.string :text
t.integer :question_id
t.boolean :correct?
t.timestamps
end
end
end
in the form, when editing or creating a new question - the user may enter up to 4 possible answers, and mark a check box for the "correct" answer(s).
/views/questions/_form.html.erb
<%= form_for(@question) do |f| %>
<div class="field">
<%= f.label :text %><br>
<%= f.text_area :text %>
</div>
<p>Enter up to 4 posisble answer choices.</p>
<%= f.fields_for :answers do |answer| %>
<div class="field">
<%= answer.text_field :text %>
<%= answer.check_box :correct? %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
relevant snippets from questions_controller.rb
def new
@question = Question.new
4.times { @question.answers.build }
end
private
# Use callbacks to share common setup or constraints between actions.
def set_question
@question = Question.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def question_params
params.require(:question).permit(:text, :quiz_id, answers_attributes: [:id, :text, :correct?])
end
Finally - on to my problem
Everything listed above worked perfectly until I added the checkboxes for answer.correct?. When I submit the form as is I get this message in my logs:
Unpermitted parameters: correct
Unpermitted parameters: correct
Unpermitted parameters: correct
Unpermitted parameters: correct
Weird... there is definitely a question mark at the end of that parameter. Allowing this to pass through without the question mark be editing the allowed parameters in the controller gets me this error message:
unknown attribute: correct (this one actually throws an error message, I don't have to go digging in the logs to find this.)
How do I get the form helper to read the question mark?
A:
? is not a valid character for inclusion within a column name. First, create a new database migration:
# from command line
rails generate migration ChangeCorrectInAnswers
Rename your column from correct? to correct:
# in the resulting migration
class ChangeCorrectInAnswers < ActiveRecord::Migration
def up
rename_column :answers, :correct?, :correct
end
end
Run the migration:
# from command line
rake db:migrate
Finally, remove the ? from your field in the view:
# app/views/questions/_form.html.erb
<%= answer.check_box :correct %>
| {
"pile_set_name": "StackExchange"
} |
Q:
RequestError: Error: connect ECONNRESET 127.0.0.1:8443
I'm querying 127.0.0.1:8443 via request-promise in NodeJS with 10K+ requests and are hitting:
{ RequestError: Error: connect ECONNRESET 127.0.0.1:8443
and/or
{ RequestError: Error: read ECONNRESET
If I lower my number of requests to say 10-100 there's no error.
Is this my NodeJS-client who are making the requests which cannot keep up, or is it the endpoint I'm trying to requests which cannot keep up?
I have control over both ends, and are not getting any error from the server I'm requesting.
A:
As per Node.js documentation:
ECONNRESET (Connection reset by peer): A connection was forcibly
closed by a peer. This normally results from a loss of the connection
on the remote socket due to a timeout or reboot. Commonly encountered
via the http and net modules.
Since a large number of requests are hitting the server, it is getting overloaded (busy servicing previous requests before it can handle any new request).
Possible solutions:
Check/modify server timeout using server.timeout = 0. This is not a
recommended solution for production. However, it can help you in
development/testing.
You can increase the maximum number of allowed connections using
server.maxConnections but this too is not a recommended solution for
production. However, it will allow you to verify whether the server hardware
capacity needs to be upgraded or the network bandwidth needs upgrade.
If your server is in a good datacenter, usually it is the hardware
capacity that needs to be upgraded (see next two solution).
If you are using a cloud server, increase the number of cores so that
requests can be services faster.
Consider load sharing by having more than one instance of the server
(behind a load balancer).
| {
"pile_set_name": "StackExchange"
} |
Q:
change value of tag respecting conditions
I want to read a csv file.
The first column refers the tag source, the second column refers to the value source, the third column refers to the target value to change . The last column refers to the tag name changed.
How can I do it dynamically please?
Types1, Init, INITIAL, Type1
Types1, inits, INITIAL, Type1
Types2, ANNULE, delayed, Type2
Types3, Topp, high, Type3
Types3, best, TOP, Type3
Input sample
<data>
<db1>
<Types1> Init </Types1>
<Types1> inits </Types1>
<Types3> best </Types3>
</db1>
<db1>
<Types2> ANNULE </Types2>
<Types3> Topp </Types3>
<Types3> best </Types3>
</db1>
<data>
Expected Output
<data>
<db1>
<Type1> INITIAL </Type1>
<Type1> INITIAL </Type1>
<Type3> TOP </Type3>
</db1>
<db1>
<Type2> delayed </Type2>
<Type3> high </Type3>
<Type3> TOP </Type3>
</db1>
A:
For csv data like below:
You need to use pandas to manage csv and ElementTree to manage xml file.
import xml.etree.ElementTree
import pandas as pd
df = pd.read_csv('data.csv')
root = xml.etree.ElementTree.parse('data.xml')
for tag in df['tag'].unique():
for item in root.iter(tag):
text = item.text.strip()
data_row = df[(df['tag']==tag) & (df['old']==text)]
item.text = data_row['new'].values[0]
root.write('file_new.xml')
Output:
<data>
<db1>
<Types1>INITIAL</Types1>
<Types1>INITIAL</Types1>
<Types3> best </Types3>
</db1>
<db1>
<Types2>delayed</Types2>
<Types3> Topp </Types3>
<Types3> best </Types3>
</db1>
</data>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pass javascript variable value in apex controller
When i click on the image it's show javascript alert in alert i got the id and open popup which is fine but after that when i call apex controller method using actionfunction i got string value null in debug log and no value shown on my popup.
public class DataFromJsController{
public String embstr{get;set;}
public DataFromJsController(){
}
public void embFile(){
System.debug('embstr-->'+embstr);
}
<apex:page controller="DataFromJsController">
<html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<head>
<apex:stylesheet value="{!URLFOR($Resource.SLDS0}" />
<script>
function embded(recordId){
alert(recordId);
$('.popupEmb').css('display','block');
**embFile(recordId);**
}
function hidePopUp(){
$('.popupEmb').css('display','none');
}
</script>
<apex:form id="frm">
<div class="slds">
<apex:actionFunction name="embFile" action="{!embFile}">
<apex:param assignTo="{!embstr}" name="prm" value=""/>
</apex:actionFunction>
<apex:repeat value="{!NameMapForAcc}" var="r">
<tr>
<td>
<apex:commandLink onClick="embded('{!r}'); return false;">
<apex:image value="{!$Resource.eLogo}" width="20" height="3"/>
</apex:commandLink>
</td>
</tr>
</apex:repeat>
<div class="popupEmb" style="display:none">
<div class="slds-modal slds-fade-in-open" aria-hidden="false" role="dialog">
<div class="slds-modal__container">
<div class="slds-modal__header">
<h2 class="slds-text-heading--medium">Embed item</h2>
</div>
<div class="slds-modal__content slds-p-around--medium" style="position:relative;">
<div class="slds-modal__content slds-p-around--medium">
<apex:outputPanel layout="block" id="newModelContentemb" style="overflow:auto;height:30vh">
<fieldset class="slds-form--compound">
<legend class="slds-form-element__label"></legend>
<div class="form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size--1-of-2">
<label class="slds-form-element__label">Embed Item</label>
<br/>
<input type="Text" styleClass="slds-input" style="margin: 0px; width: 549px; height: 32px;" value="Only the owner and explicitly shared collaborators have access" disabled="true"/>
<br/><br/>
Paste HTML to embed in website:<br/>
<Textarea readonly="true" cols="75" rows="5" id="textareaEmb" styleClass="slds-box" style="margin: 0px; width: 550px; height: 70px;">
<iframe src="https://drive.google.com/file/d/"+{!embstr}+"/preview""
width="640" height="480"> </iframe> {!embstr}
</Textarea>
</div>
</div>
</div>
</fieldset>
</apex:outputPanel>
</div>
</div>
<div class="slds-modal__footer">
<button class="slds-button slds-button--neutral slds-button--brand" onclick="hidePopUp(); return false;">Ok</button>
</div>
</div>
</div>
<div class="slds-backdrop slds-backdrop--open"></div>
</div>
</apex:pageBlock>
</apex:form>
</div>
</html>
A:
I think, you are missing rerender attribute for actionFunction and because of this, value is not getting passed.
<apex:actionFunction name="embFile" action="{!embFile}" rerender="frm">
<apex:param assignTo="{!embstr}" name="prm" value=""/>
</apex:actionFunction>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get correct product url for multistore magento?
I am running following code in Magento root to get the product urls
<?php
require_once('app/Mage.php');
umask(0);
Mage::app(1);
$collection = Mage::getModel('catalog/product')
->setStoreId(1)
->getCollection();
foreach( $collection as $product )
{
echo $product->getProductUrl();
echo "<br>";
}
?>
I am getting product urls like http://example.com/catalog/product/view/id/5/ , But these urls are invalid.
The product urls are as following in front end http://example.com/product.html
How do I get the correct product urls? I have multi store Magento set-up.
A:
You need to get store url for each product separetly. In other words, you need to use something like this:
$collection = Mage::getModel('catalog/product')
->getCollection();
foreach( $collection as $product )
{
echo $product->setStoreId(5)->getProductUrl();
echo "<br>";
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Square classes of $\mathbb{Q}_2^\times$?
Does anyone know how to easily compute them? We know that a number is a square modulo $2^k$ if and only if it's a square modulo $8$. This gives a bunch of integers that represent square classes. I also know that
$$\mathbb{Q}_2^\times \cong \mathbb{Z}\times (1+2\mathbb{Z}_2),$$
but I can't figure out how to find the square classes in $1+2\mathbb{Z}_2$. Is there some really simple solution for this? I can't seem to figure out how to apply Hensel's lemma here.
A:
By your observations, a square element of $1+2\mathbb{Z}_2$ must actually live in $1+8\mathbb{Z}_2$. So
$$
\mathbb{Q}_2^\times/\mathbb{Q}_2^{\times 2}\approx \mathbb{Z}/2\mathbb{Z}\times \frac{1+2\mathbb{Z}_2}{1+8\mathbb{Z}_2}\approx \mathbb{Z}/2\mathbb{Z}\times \mathbb{Z}/2\mathbb{Z}\times \mathbb{Z}/2\mathbb{Z}.
$$
The first factor of $\mathbb{Z}/2\mathbb{Z}$ corresponds to choosing even/odd-ness of the power of 2 dividing the element of $\mathbb{Q}_2^\times$, the latter two any choice of coset represenatives for odd squares mod 8. So one possible enumeration of representatives for these 8 classes are the classes of
$$
\{\pm 1,\pm 2,\pm 5,\pm 10\}.
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaScript and the Enterprise
I figure this is a good place to ask this question:
Is anyone aware of the "standard" procedure or know how common it is these days that enterprise businesses disable JavaScript (or only allow it on a specified list of websites)?
Any information someone can link me to back up anything would be awesome...I haven't been able to find much on the topic.
A:
Yahoo keeps track of this for everyone to benefit from:
http://developer.yahoo.com/blogs/ydn/many-users-javascript-disabled-14121.html.
I would stick to bigger companies like Yahoo, Google, etc. when mining this type of data.
| {
"pile_set_name": "StackExchange"
} |
Q:
problem with char arrays in network programming
I have the following:
nodeID = abcde.abc.edu_12345
and I need to append the an underscore and a 10digit value returned by time() to create the following:
node_inst_ID = abcde.abc.edu_12345_1016320007
where 1016320007 is the 10 digit value returned by time(). I am trying the following code but it doesnt seem to work:
#define NODE_ID_LENGTH 20
#define NODE_INST_ID 31
char nodeID[NODE_ID_LENGTH]
char node_inst_ID[NODE_INST_ID];
int main()
{
/*
Building of nodeID is a bit complex. So its hard to put all the code here. But printing the following at this point gives this
for(int i = 0; i < NODE_ID_LENGTH; i++)
{
printf("%c", nodeID[i]);
}
gives
abcde.abc.edu_12345
If you need to know any more info about nodeID, I can post the print out of things that you suggest.
*/
long int seconds = time(NULL);
char buf[10];
sprintf(buf, "%ld", seconds);
snprintf(&node_inst_ID[0], 20, "%s", &nodeID[0]);
node_inst_ID[20] = '_';
node_inst_ID[21] = '\0';
cout<<"Node instance ID = "<<node_inst_ID<<endl;
/*
I havent yet added the code for appending the time stamp. But I am expecting a print out for the above code like this:
Node instance ID = abcde.abc.edu_12345_
But the code is printing only
Node instance ID = abcde.abc.edu_12345
It is not adding the underscore at the end.
*/
}
Can anyone point out what the mistake is? Thanks in advance.
A:
snprintf(&node_inst_ID[0], 20, "%s", &nodeID[0]);
node_inst_ID[20] = '_';
node_inst_ID[21] = '\0';
This assumes that the string is exactly 20 characters long - it isn't. Try this:
snprintf(&node_inst_ID[0], 20, "%s", &nodeID[0]);
strcat(node_inst_ID, "_"); // strcat is safe in this context, usually you should use strncat.
EDIT: If you want to still use snprintf, the easy way is:
int len = strlen(node_inst_ID);
snprintf(node_inst_ID + len, sizeof(node_inst_ID) - len, "%whatever", the, args);
| {
"pile_set_name": "StackExchange"
} |
Q:
Get data whenever email is sent to an email id and update db with email information
I am trying to write a webservice and configure my webserver such that whenever I send an email to [email protected], it should make an API call store email details in DB. I was using Cloudmailin to implement similar functionality before but now I want to convert it to native PHP webservice. Any help would be appreciated.
A:
See http://harrybailey.com/2009/02/send-or-pipe-an-email-to-a-php-script/ for information on how to configure a mail server to accept incoming messages for your domain, and pipe each incoming message to a PHP script. Then, your PHP script can parse the headers and body of each incoming message as they arrive.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java: Execute /cmd /c start path-with-spaces\program.exe
I've read a lot about the question but the answers I have found don't work completely.
I try to run this code :
String[] args = {"cmd","/c","start","C:\\Program Files\\XML Marker\\xmlmarker.exe"};
Runtime rt = Runtime.getRuntime();
ProcessBuilder pb = new ProcessBuilder(args);
Process pr = pb.start();
//Process pr = rt.exec(args);
As I have spaces in my path, I use String array to pass the arguments to the Process
But ... it opens a DOS command window but doesn't launch my program, as if the parameters where ignored
I tried with rt.exec(args) and pb.start() ... same result
Could someone give me some advice please ?
Thank you.
A:
Try adding quotes around the path by inserting escaped quotes in your string, as follows:
String[] args = {"cmd","/c","start","\"C:\\Program Files\\XML Marker\\xmlmarker.exe\""};
Notice the \" at the start and end of the path string.
A:
No need to have a "start" and "cmd" at the same time. You can safely take out "start". If you use a parameter enclosed in quotes with the "start" command, it treats it as a Title for a new command window.
| {
"pile_set_name": "StackExchange"
} |
Q:
Docker from python
Please be gentle, I am new to docker.
I'm trying to run a docker container from within Python but am running into some trouble due to environment variables not being set.
For example I run
import os
os.popen('docker-machine start default').read()
os.popen('eval "$(docker-machine env default)"').read()
which will start the machine but does not set the environment variables and so I can not pass a docker run command.
Ideally it would be great if I did not need to run the eval "$(docker-machine env default)". I'm not really sure why I can't set these to something static every time I start the machine.
So I am trying to set them using the bash command but Python just returns an empty string and then returns an error if I try to do docker run my_container.
Error:
Post http:///var/run/docker.sock/v1.20/containers/create: dial unix /var/run/docker.sock: no such file or directory.
* Are you trying to connect to a TLS-enabled daemon without TLS?
* Is your docker daemon up and running?
A:
I'd suggest running these two steps to start a machine in a bash script first. Then you can have that same bash script call your python script and access docker with docker-py
import docker
import os
docker_host = os.environ['DOCKER_HOST']
client = docker.Client(docker_host)
client.create(...)
...
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a word (or phrase) that describe a series of mishaps/misfortunes in one's life?
I don't mean something like 'many hardships' or 'several tragedies'. I'm looking for a word or short phrase that would describe just a really rough spot or time frame in someone's life. For instance, [s]he was fired, lost a loved one and/or a friend, a pet died, [s]he wasn't getting much support from those around him/her. How can I describe such a cluster of emotional events in a simple way?
A:
A bad patch. I've heard rough patch, too, but more commonly bad patch or rough time. I suppose sticky patch is chiefly British.
http://dictionary.cambridge.org/dictionary/british/go-through-a-bad-difficult-rough-sticky-patch
A:
Trial and tribulation.
Ordeal.
i.e.: A period of trial and tribulation.
http://dictionary.reference.com/browse/trials+and+tribulations
A:
Adversity:
a state or instance of serious or continued difficulty or misfortune.
he had to cope with life's many adversities; she showed courage in the face of adversity.
also vicissitudes : (from M-W)
difficulties or hardship attendants on a way of life, a career, or a course of action and usually beyond one's control.
| {
"pile_set_name": "StackExchange"
} |
Q:
What text editors let you view and edit multiple files in a single long page (similar to Scrivener's Scrivenings mode)?
What text editors allow you to view and edit multiple files as though they were a single long page?
So, instead of having to switch to a different tab or window to edit a different file, you can just scroll to a different location in the same window to edit a different file.
The only editor like that I know of so far is Scrivener, with its Scrivenings Mode:
http://www.simplyscrivener.com/features/scrivenings-mode/
Are there any others? I'd especially like to find a source code editor which has a mode like that.
Any platform is fine - Linux, Windows, Mac, or anything else.
Thanks for any help!
A:
I finally managed to make most of the modifications and additions I wanted to make to Magnar Sveen's incredibly useful "multifiles.el" add-on for the GNU Emacs editor.
The result: https://github.com/Apollia/multifiles-apmod.el
My version has some problems (see the documentation), and anyone who tries to use it should be very cautious.
But, it mostly does what I want, so I'm very happy with it so far.
.
After learning a bit about the Emacs Lisp programming language and how to customize Emacs, Emacs is now more comfortable for me to use than even my previous favorite editors Notepad++ and Geany. But getting to this point was quite a time-consuming struggle.
Emacs is probably the solution I'm going to stick with. But, please feel free to post more suggestions.
Different things work better for different people, and I'm guessing the majority of people (especially non-programmers) would probably give up on Emacs after about 5 minutes, just as I did in the past.
Thanks again for everyone's help!
| {
"pile_set_name": "StackExchange"
} |
Q:
I am famous, I am in maths , I am the sun. What am I?
This is my first question, so feel free to edit. I am open to suggestions.
Oh! I am so excited!! This is my first puzzle!
I can show you where the things are. Ready for a quick game?
I am rich you know! I can be usually in a command, or a hat.
And...
I am famous; I am in maths; I am the sun.
Open me... close me, you will get less or more.
Guessed it yet? I think it's worth trying for!
Each line represents something. Combining all those things gives you the answer. But the final line is just for the rhyme (I know it's not a good one, but I tried).
Hint:
It is related to something, every member on every Stack Exchange site uses.
A:
This seems to be related to
the symbols on the number keys of a computer keyboard, read left to right. I initially thought each line referred to one key, but now I think each symbolizes a block of consecutive keys.
Oh! I am so excited!! This is my first puzzle!
Exclamation mark '!'
I can show you where the things are. Ready for a quick game?
At-sign '@' (on US keyboards) followed by '#' perhaps symbolic of tic-tac-toe (thanks to user IdiotStyle for this suggestion). Or maybe '@' is for the game Nethack, but that's not quick unless the player is unlucky or careless.
I am rich you know! I can be usually in a command, or a hat.
Dollar sign $ symbolizing money, followed by '%' used for variable substitution in MS-DOS/Windows commands, followed by '^' (informally called a hat). Or maybe they're all $ (rich: obvious; command: Unix shell command prompts; hats full of money are a bit of a cliche).
And...
Ampersand '&'
I am famous, I am in maths , I am the sun.
Star (asterisk) '*'
Open me... close me, you will get less or more
Parentheses '(' and ')' followed by '-' and '+' (we're now no longer on the number keys, but still on the same row of the keyboard).
(Thanks to user IdiotStyle for proposing some improvements used above.)
A:
Main credits go to Gareth McCaughan for his answers put me on the right track.
It is:
Indeed the symbols on the top row of a keyboard from left to right
Oh! I am so excited!! This is my first puzzle!
This is an exclamation mark '!' as the leftmost symbol. (1)
I can show you where the things are.
The things are "at" '@' (2)
Ready for a quick game?
The hashtag '#' is also the playboard for a quick game of Tic Tac Toe. (3)
I am rich you know!
The Dollar sign "$"(4)
I can be usually in a command
The percentile symbol '%' (5)
or a hat.
The hat symbol '^' (6)
And...
The sign for "and", the ampersand '&' (7)
I am famous, I am in maths , I am the sun.
A Star is famous, in math the asterisk is a multiplier symbol and the sun is a star. '*' (8)
Open me...
Opening parenthesis '(' (9)
close me,
Closing parenthesis ')' (0)
you will get less
Minus sign '-' (-)
or more
Plus sign '+'
| {
"pile_set_name": "StackExchange"
} |
Q:
Iterating through linked objects, how to avoid duplicates
I have an array of objects that are linked together by a unique id.
Something like this:
var nodes = [];
nodes[0] = {'id':1,'linksTo':[2,3],'x':1,'y':1};
nodes[1] = {'id':2,'linksTo':[1],'x':2,'y':1};
nodes[2] = {'id':3,'linksTo':[1],'x':2,'y':1};
So suppose i was to draw lines between each point in a canvas element that they link to. In the above case i would draw the same line twice, one from id 1 to id 2 and then again from id 2 to id 1. This is not efficient, and in a game loop this will hurt frame rate over time.
My current method is similar to this logic:
Object.keys(nodes).forEach(function(nodeIndex) {
nodes[nodeIndex].linksTo.forEach(function(connectedNode) {
//line move to x,y
//line to x2, y2
});
});
What would be the most effective way to do this as to not hurt frame rate and avoid drawing the same way twice? Remembering that it needs to be efficient for allowing higher frame rates to continue.
A:
You could draw the line only if the first node's id is less than the second node's id.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't exclude directory names with cw-rsync
I'm using cw-rsync under Windows 7 to copy files off my local machine every day to an rsync server running on a Linux box. It works fine, apart from the fact that I can't seem to exclude directory names properly. Right now, in my exclude file, I have:
My Documents/
My Downloads/
This works, but also has the effect of also excluding any directory called just "My" or "Documents" or "Downloads"
I've tried using inverted commas around the names, but that doesn't help. Any ideas?
A:
In fact I've just tried this with latest cygwin rsync and you're right. Using exclude files it's not possible to exclude a folder with spaces in it's name. However it works to exclude its contents while the folder itself is still synchronized.
I've used the following for testing:
My\ Documents/*
Note the \ to escape the space. However the My Documents" folder is still created on target side but remains empty even if there is some content on source side.
I've found that (at least for Cygwin rsync) the --exclude= parameter works correctly even with spaces:
rsync [...] --exclude='My Documents'
Just excludes the complete folder.
So it looks like you've likely encountered a bug in rsync parsing on exclude files. But using the --exclude= parameter you can work around this issue - in worst case writing your own wrapper reading your exclude file and assigning an exclude parameter for each line.
| {
"pile_set_name": "StackExchange"
} |
Q:
Compact mATX case for NAS system with four 3.5" drives
I'm looking for a compact mATX case for a NAS system. One that I can stick in a corner somewhere and forget about (figuratively).
I have done some research into this, but all results I found that were less than 50 USD only had three or fewer drive bays. I found a few mATX cases with four 3.5" bays, but they were out of my budget range.
Necessary Requirements:
Four bays for 3.5" HDDs
Front Panel USB 2.0
Less than $50 USD (lower is better, new not used)
Approx. 3 inches of clearance for the CPU fan (~76mm)
Optional, but would be nice:
Cube/LAN box style
Dust Filters
From Amazon.com
Any suggestions?
Thanks!
A:
I cannot find a cube style but the following did come across as a good option.
SilverStone PS08B @ Newegg 39.99
SilverStone PS08B @ Amazon(prime eligible) 39.99
Just posted the Newegg link along with the Amazon link, due to the fact that Newegg is much better with item specifications....and power searches...than Amazon is.
Just a few specs on the case:
2 x USB 3.0 / Audio Front Ports
Side Air duct
2 External 5.25" Drive Bays
4 Internal 3.5" Drive Bays
| {
"pile_set_name": "StackExchange"
} |
Q:
Serialization doesn't accept my KnownTypeAttribute, why?
I've got stuck with a serialization problem. My Silverlight app doesn't expect one of my properties in a businessobject and doesn't know what to do about it. Previously I have solved this by setting a KnownTypeAttribute like the example below but in this case it doesn't work.
I have used to solve it like this:
[DataContract(Name = "baseClass")]
public class baseClass { }
[DataContract(Name = "busObj1")]
public class busObj1 : baseClass { }
[DataContract(Name = "busObj2")]
[KnownType(typeof(busObj1))]
public class busObj2 : baseClass
{
public busObj1 myObj { get; set; }
}
The only difference know is that I have slightly different structure, like this:
[DataContract(Name = "baseClass")]
public class baseClass { }
[DataContract(Name = "busObj1")]
public class busObj1 : baseClass { }
[DataContract(Name = "busObj2")]
[KnownType(typeof(busObj1))]
public class busObj2 : baseClass
{
public busObj1 myObj { get; set; }
}
// This is the class that I want to send via WCF and that cannot be serialized
// because the serializer doesn't expect busObj1.
[DataContract(Name = "busObj3")]
public class busObj3 : busObj2 { }
I'm very thankful for any ideas of what could be wrong!
Regards, Clas
A:
You need to put the known type attribute on your base object:
[DataContract(Name = "baseClass")]
[KnownType(typeof(busObj1))]
[KnownType(typeof(busObj2))]
[KnownType(typeof(busObj3))]
[KnownType(typeof(busObj4))]
public class baseClass { }
[DataContract(Name = "busObj1")]
public class busObj1 : baseClass { }
[DataContract(Name = "busObj2")]
public class busObj2 : baseClass { }
[DataContract(Name = "busObj3")]
public class busObj3 : busObj1
{
public busObj2 myObj { get; set; }
}
[DataContract(Name = "busObj4")]
public class busObj4 : busObj3 { }
or if you don't want to pollute your domain models with those attribtues you could also do it in your web.config or use the ServiceKnownType attribute on your Service Contract.
| {
"pile_set_name": "StackExchange"
} |
Q:
Scope and Entity class
I am new to JSF and EE and trying to understand the best approach to make the right design decisions for a project. I am working on my own, relearning after 20+ years and pursuing a very ambition business idea.
My question relates to system overhead and performance implication by the design choices I make. I am using all of the latest with EE7, JSF 2.2.6, NetBeans 7.4, Glassfish, etc. If I don't have the latest I will upgrade as I go.
It is a pretty big question I guess, as it relates to the full path from web container scope, ejb type and EM vs EMF. I've read a lot and believe I understand the philosophy but probably not fully.
My app involves (hopefully 1,000-100,000+) simultaneously logged in users that will be connected for 4-6 hours but only making requests every 10 minutes or so. To start, it will probably only be 100 or so and my short term goal is to just get something working and improve from there. I would however prefer to make the right decision upfront.
From my reading my understanding is that most would use @SessionScoped backing beans (while the user is logged in), @Stateless Managed Beans and probably a container managed Entity Manager.
Although this seems the easiest to program my interpretation is that the overhead would be great:
- I will have as many session scoped instances as I have connected users;
- as many stateless EJB's as I have users because they are injected by the SessionScoped bean
- one massive cache in the Entity Manager as every user has a different interest in data.
- I also assume web and ejb sessions are equal to java threads rather than just some stored data.
Is this understand close?
Although much more complicated I assume a better performing system would involve my own session control, request scope beans, stateless ejb and application managed entity manager (emf) where I only preserve the cache when it is a long standing transaction. This would create a pooled environment with less instances and thus threads, swapping, disc caching, etc.
I've read substantially, built a test environment using a lot of BalusC suggestions and have a reasonable but theoretical understanding of most things from JSF lifecycle on. As much as the platform of JSF and EE seem like a good decision the learning curve is a little overwhelming.
Any clarification to point me in the right direction would be appreciated.
Thanks in advance,
John
A:
Is this understand close?
partially.
I will have as many session scoped
instances as I have connected users;
yes, this is correct. but this number is "virtual" since container can serialize some of them to disk (to be exact, entire session is serialized) on LRU algo and a threshold.
as many stateless EJB's as I
have users because they are injected by the SessionScoped bean
it depends on container implementation. it is reasonable to say they implemented this mechanic the most efficient way. the worst case is # of SessionScoped bean (injected EJB) = # of EJB = # of user.
one
massive cache in the Entity Manager as every user has a different
interest in data.
cache is configurable, but IMO you shuold consider the tradeoff between cache size (add more RAM?) and performace (what if there is no cache? what if the cache contains every entity?)
I also assume web and ejb sessions are equal to
java threads rather than just some stored data.
no, EJBs (stateless, stateful and singleton) are just data. Scheduled one and MDBs are more similar to what you think (they are not thread but a thread is created by an executor to invoke them).
Although much more complicated I assume a better performing system would involve my own session control, request scope beans, stateless ejb and application managed entity manager (emf) where I only preserve the cache when it is a long standing transaction.
it depends on how you configure application server, persistence provider and how you develop your business logic controller beans. however, every point in this list can be configured/optimized later (little more effort on refactoring controllers).
This would create a pooled environment with less instances and thus threads, swapping, disc caching, etc.
EE stack has exactly this point of view. threads are pooled and reused, they are not user-specific, but request specific. a pool of 10 threads can reasonably serve 100+ users.
I've read substantially, built a test environment using a lot of BalusC suggestions and have a reasonable but theoretical understanding of most things from JSF lifecycle on. As much as the platform of JSF and EE seem like a good decision the learning curve is a little overwhelming.
from what you are asking it is clear that the learning curve is not so overwhelming for you :)
although EE stack is really heavy compared to other technologies, it is scalable, flexible and extendable. like you, i think it is a good choice.
in my experience, the worst thing affecting performance is network speed and traffic. in some case i saw loading homepage central image taking much more time than executing a complex report with thousand of rows.
however, don't worry (too much) about optimization, because premature optimization is the root of all evil
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to get a certificate for spring boot API to convert from http to https other than self signed certificates?
I use Spring boot for my API and I tried enabling https for my application with a Self signed certificate but while accessing that firefox and chrome showed warnings saying
Warning: Potential Security Risk Ahead with MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT
and flutter,postman show this too so i reverted back to http ,
So is there a way to get a https certificate for my spring boot application?
A:
If you are looking for a free way to get an https certificate and enable https for your endpoint, there are mmultiple ways for you to do this.
If you are on cloud then , cloud providers like for instance the cloudflare provides easy integration of ssl certificates and all traffic to and from your cloud env will be ssl encrypted.Also AWS has the following policy :
When you purchase or transfer a domain name with us you get all those
features included:
Free domain protection & WHOIS privacy, 5 Email forwards
Free SSL Certificate if you also host your website on Cloud CMS
Simple DNS Editor to manage your DNS entries (A, CNAME, MX, ...), configure name servers, domain owner, renewal option
Another method is for you to setup Let's encrypt on your machine to get a free ssl certificate every three months and use that certificae on your springboot application. The certificate is by default valid for only 90 days , but Let's encrypt provides a job that you could run on your server which will automatically update it once it's expired.Once you get the ssl certificate you could add it to springboot easily via application.properties like below. Read guide.
application.properties
server.port=8443
security.require-ssl=true
server.ssl.key-store=/etc/letsencrypt/live/example.com/keystore.p12
server.ssl.key-store-password=<your-password>
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias=tomcat
| {
"pile_set_name": "StackExchange"
} |
Q:
Since upgrade to 18.04 libreOffice calc no longer imports xml
Since I upgraded Ubuntu to the latest, the Data->Xml import in libreOffice Calc is greyed out and non functioning.
apt-get libreoffice reports that the latest version is installed.
A:
OK, I think I found something that might help you. Warning: This might cause Libreoffice Calc to be unstable.
Click on Tools -> Options -> Advanced
Then click on Enable experimental features (this may be unstable)
After clicking OK it will prompt you to restart calc. Then Data -> XML Source should now be enabled.
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Single exclamation mark in Kotlin
What does a single exclamation mark mean in Kotlin? I've seen it a few times especially when using Java APIs. But I couldn't find it in the documentation nor on StackOverflow.
A:
They're called platform types and they mean that Kotlin doesn't know whether that value can or cannot be null and it's up to you to decide if it's nullable or not.
In a nutshell, the problem is that any reference coming from Java may be null, and Kotlin, being null-safe by design, forced the user to null-check every Java value, or use safe calls (?.) or not-null assertions (!!). Those being very handy features in the pure Kotlin world, tend to turn into a disaster when you have to use them too often in the Kotlin/Java setting.
This is why we took a radical approach and made Kotlin’s type system more relaxed when it comes to Java interop: now references coming from Java have specially marked types -- Kotlin Blog
A:
It's the notation for platform types:
T! means "T or T?"
A:
A Type notated with ! is called platform type, which is a type coming from Java and thus can most probably be null. It’s what the Kotlin compiler infers by default when calling Java (for the most basic cases, Java methods can be annotated to get around this). You should handle platform types as nullable types, unless you certainly know that the particular API will never return null. The compiler allows platform types to be assigned to variables of both nullable and non-null types.
Notation for Platform Types
[...]
T! means "T or T?" [...]
You could refer to platform types as "types of unknown nullability". Also important to know is that you cannot use the exclamation-marked type for your own types, it's not part of the Kotlin syntax, it's only a notation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find all combinations of elements in an array
The problem I am trying to solve is that I want to generate an array which represents all combinations of elements in a source array.
Given an input of 2 items, there are 4 combinations (represented here as binary)
Group 1 | 0 | 1 | 0 | 1
Group 2 | 0 | 0 | 1 | 1
--------------------------
&Result | 0 | 1 | 2 | 3
This can be generalised so the number of combinations is 2(number of groups) (So 3 groups has 8 combinations, 4 has 16 etc).
So the question is; given a javascript array:
var groups = [
{
name:"group1",
bit: 1
},
{
name:"group2",
bit: 2
},
{
name:"group3",
bit: 4
}];
I need to generate an array where the index represents the and'ing of the bit property and the value of the array is arbitrary (further calculation - not relevant) so lets just make it an array of the group names (for the purpose of this question). This result is desirable:
var result = [
{groups: []}, //0
{groups: ["group1"]}, //1
{groups: ["group2"]}, //2
{groups: ["group1","group2"]}, //3
{groups: ["group3"]}, //4
{groups: ["group1","group3"]}, //5
{groups: ["group2","group3"]}, //6
{groups: ["group1","group2","group3"]} //7
]
You can see in the comments there that each index in the array represents the act of and'ing the bit property from the original.
I have prepared a jsfiddle with the input and required output should it be useful in answering the question.
This is my current solution, based on mellamokb's answer but re-written in my prefered style. I was hoping there was a more elegant solution as this has a lot of iterations over the array which are unecessary. Any better solutions?
var resultCount = Math.pow(2,groups.length);
var result = [];
for(var i=0;i<resultCount;i++){
result.push({
groups: $.map(groups, function(e,idx){
return ((i & Math.pow(2,idx)) != 0)
? e.name
: null
})
});
}
A:
Here is a relatively efficient solution that builds up the arrays by index:
var result = [];
var resultCount = Math.pow(2, groups.length);
for (var i = 0; i < resultCount; i++) {
result[i] = { groups: [] };
for (var g = 0; g < groups.length; g++) {
if (i & groups[g].bit) result[i].groups.push(groups[g].name);
}
}
Demo: http://jsfiddle.net/7ZsHL/9/
| {
"pile_set_name": "StackExchange"
} |
Q:
How many houses can I buy?
So far I have found a purchased two houses, one near the festival and one on the coast.
How many purchasable properties are available for me to buy?
A:
There are multiple houses / residents to buy.
From what I can find on google there are about 12 houses/castles.
Here is the full list as acquired from this site:
Edinburgh Castle:
Located in the heart of the city, Edinburgh Castle offers the best of Horizon's properties
15,000,000 CR.
Bamburgh Castle:
This historical home overlooks Forza Horizon 4's coast, situated alongside the long east-facing beach.
10,000,000 CR.
Lake Lodge:
If castles aren't for you, Lake Lodge is a top-tier lakeside house, overlooking Derwentwater.
5,000,000 CR. (Free for VIP Pass owners)
Fairlawn Manor:
Fairlawn Manor is a bold stately home located in the map center, positioned among the upper-class Forza Horizon 4 homes
2,000,000 CR.
Derwent Mansion:
Found on the west side of Derwentwater, this lakeside property is a cheaper alternative to Lake Lodge.
1,500,000 CR.
Castleview Road:
Found in the southern suburbs of Edinburgh, this offers just a quick drive to the city center
750,000 CR.
The Huntsman Lodge:
Hidden deep into Lakehurst Forest, this house keeps you far away from the busy roads of Horizon
750,000 CR.
Thatch Corner:
This cozy beachside thatched cottage is another quiet retreat from the action.
500,000 CR.
Kingfisher Cottage:
Located beside the Derwentwater reservoir, this historical cottage is tucked just off the roadside.
350,000 CR.
Croftdale Farm:
Take in the Scottish Highlands with this sky-high property, hidden near Glen Rannoch in the north-west corner of the map.
200,000 CR.
Sunflower Meadows:
This white semi-detached cottage is found in Ambleside, offering another excellent option for first-time buyers
200,000 CR.
The Gables:
In an unlikely turn of events, The Gables is a property gifted by film makers after your work as a movie stunt driver.
Best of all, this location is entirely free.
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing HighCharts background color?
I don't really know how to do this.
I need to change background color of this highcharts chart:
http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/polar-spider/
But I don't seem to be able to do so - there doesn't seem to be any clear place to put the background color setting?
I've tried to write many different values in this section:
chart: {
polar: true,
type: 'line'
},
But it didn't do anything ( it occasionally broke this script ).
Do I need to change it somewhere in the included .js files? Or can it be done from the level of this loaded script?
JS is really confusing. Can anyone help me?
A:
Take a look at the Highcharts API here: https://api.highcharts.com/highcharts/chart.backgroundColor and you will see it's a property of the chart object that can take a solid color:
{
chart: {
backgroundColor: '#FCFFC5',
polar: true,
type: 'line'
}
}
Or Gradiant:
{
chart: {
backgroundColor: {
linearGradient: [0, 0, 500, 500],
stops: [
[0, 'rgb(255, 255, 255)'],
[1, 'rgb(200, 200, 255)']
]
},
polar: true,
type: 'line'
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
extension of cauchy schwarz inequality
I Want to prove $(a_1^2+a_2^2)(b_1^2+b_2^2)(c_1^2+c_2^2)>_=(a_1b_1c_1+a_2b_2c_2)^2$
not quite sure how and not only upto 3 terms but to $n$ terms, I am not even sure if this inequality is true or not but I need this result to solve the following problem
A:
RHS $\leq (a_1^{2}+a_2^{2})(b_1^{2}c_1^{2}+b_2^{2}c_2^{2})$ by Cauchy-Schwarz inequality. But $b_1^{2}c_1^{2}+b_2^{2}c_2^{2} \leq (b_1^{2}+b_2^{2})(c_1^{2}+c_2^{2})$ so we are done.
| {
"pile_set_name": "StackExchange"
} |
Q:
Crystal Reports - Selecting data in the first row to be used in a formula
I have a very basic report with no groups. The details consists of a number of numeric columns. I want to add a formula field which will use a field from the first row. Example:
(ColumnAFromCurrentRecord - ColumnBFromFirstRecord) / ColumnBFromFirstRecord
Can someone point me in the right direction?
A:
you need to extact the column b from first record. try below solution.
Note: This is not a tested solution as I at present I don't have CR.
create below formula Count and place in detail section:
Local NumberVar a;
a:=a+1;
This will number the rows starting from 1 to the last row.
Now create one more formula StoreB:
Share NumberVar b;
if {@Count}=1
then b:=columnb
This will store the value of columnb in first record in variable b
Now use where you want:
EvaluateAfter(@StoreB)
Shared NumberVar b;
(ColumnAFromCurrentRecord - b) / b
Let me know how it goes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a difference between the `if else` and the `if-else if-else`?
In WikiPedia article for Binary Search there is a section called Deferred detection of equality which presents a somewhat "optimized" version of binary search as follows:
int binary_search(int A[], int key, int imin, int imax)
{
while (imax > imin)
{
int imid = (imin + imax) / 2;
if (A[imid] < key)
imin = imid + 1;
else
imax = imid;
}
if((imax == imin) && (A[imin] == key))
return imin;
else
return KEY_NOT_FOUND;
}
It is claimed that this is a better version than the conventional textbook binary search since the .... algorithm uses only one conditional branch per iteration
Is this true? I mean the if instructions are translated in CMP and Branch instructions in assembly so I can not think how an if-else is better than an if-else if-else
Is there such a difference that I should take into account in higher level languages? The code of the "deffered" version seems more tight I admin, but are there optimizations or penalties in how you form if-else statements?
A:
The key concept is that it uses one less conditional per iteration. That is, the equality check has been moved outside the while loop so that it only runs once, while in the basic version it would need to be checked every time¹.
That said, I 'm not sure if there would actually be a measurable difference when using the optimized form. For example, consider that:
If all you are comparing is two integers then the compiler can detect that it can compute the comparison result just once and then evaluate which branch to take just as well.
Binary search is O(logN), so the number of iterations taken would actually be very small even if the number of elements to search is quite large. It's arguable whether you 'd see any difference.
The implementation of modern CPUs features such as speculative execution and branch prediction (especially in "nice" algorithms like binary search) might very well have more visible effects than this optimization (out of my league to check though).
Notes:
¹ Actually it is another condition that doesn't need to be checked when the equality comparison moves out, but conceptually there is no difference.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error in Iterating through Pandas DataFrame with if statement
I have the following pandas DataFrame.
Id UserId Name Date Class TagBased
0 2 23 Autobiographer 2016-01-12T18:44:49.267 3 False
1 3 22 Autobiographer 2016-01-12T18:44:49.267 3 False
2 4 21 Autobiographer 2016-01-12T18:44:49.267 3 False
3 5 20 Autobiographer 2016-01-12T18:44:49.267 3 False
4 6 19 Autobiographer 2016-01-12T18:44:49.267 3 False
I want to iterate through "TagBased" column and put the User Ids in a list where TagBased=True.
I have used the following code but I am getting no output which is incorrect because there are 18 True values in TagBased.
user_tagBased = []
for i in range(len(df)):
if (df['TagBased'] is True):
user_TagBased.append(df['UserId'])
print(user_TagBased)
Output: []
A:
As others are suggesting, using Pandas conditional filtering is the best choice here without using loops! However, to still explain why your code did not work as expected:
You are appending df['UserId'] in a for-loop while df['UserId'] is a column. Same goes for df['TagBased'] check, which is also a column.
I assume you want to append the userId at the current row in the for-loop.
You can do that by iterating through the df rows:
user_tagBased = []
for index, row in df.iterrows():
if row['TagBased'] == 'True': # Because it is a string and not a boolean here
user_tagBased.append(row['UserId'])
| {
"pile_set_name": "StackExchange"
} |
Q:
Label line in qplot
I have a qplot that is showing 5 different groupings (denoted with colour = type) with two dependent variables each. The command looks like this:
qplot(data = data, x = day, y = var1, geom = "line", colour = type) +
geom_line(aes(y = var2, colour = value)
I'd like to label the two different lines so that I can tell which five represent var1 and which five represent var2.
How do I do this?
A:
You can convert the data to a "tall" format, with melt, and use another aesthetic, such as the line type, to distinguish the variables.
# Sample data
n <- 100
k <- 5
d <- data.frame(
day = rep(1:n,k),
type = factor(rep(1:k, each=n)),
var1 = as.vector( replicate(k, cumsum(rnorm(n))) ),
var2 = as.vector( replicate(k, cumsum(rnorm(n))) )
)
# Normalize the data
library(reshape2)
d <- melt(d, id.vars=c("day","type"))
# Plot
library(ggplot2)
ggplot(d) + geom_line(aes(x=day, y=value, colour=type, linetype=variable))
| {
"pile_set_name": "StackExchange"
} |
Q:
Joint Probability distribution for $Z=X/(X+Y)$
Suppose X and Y are two independent random variables with exponential distributions Exp(1)
$Z=X/(X+Y)$
Find $P(Z<z)$ and show the random variable Z has uniform distribution.
Thanks
A:
For $z\in\left(0,1\right)$ we find:
$$P\left(Z\geq z\right)=\int_{0}^{\infty}P\left(Z\geq z\mid Y=y\right)f_{Y}\left(y\right)dy=\int_{0}^{\infty}e^{\frac{-zy}{1-z}}e^{-y}dy=\int_{0}^{\infty}e^{\frac{-y}{1-z}}dy=1-z$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Problems when a json string has extra " in it using JObject.Parse
The Following string gives an error when using the following code:
data = await resposta.Content.ReadAsStringAsync();
dynamic j = JObject.Parse(data);
The data in contains the following string:
{"code": 100, "message": "The entity with the name "Esther Rea" its not in DB."}
How to take off the " from Esther Rea?
A:
As suggested, the correct solution would be to have whoever's returning this value escape the quotes. However, if that's really not an option, you can try to brute-force your way into escaping the double quotes yourself, assuming the return schema is always the same, using something like this:
var pattern = "(\"message\":\\s+\")(?<messageContent>(.*))(\"})";
var regex = Regex.Match(data, pattern);
var message = regex.Groups["messageContent"].Value;
if (!string.IsNullOrEmpty(message))
{
message = message.Replace("\"", "\\\"");
var newData = Regex.Replace(data, pattern, "$1" + message + "$3");
var jObject = JObject.Parse(newData);
}
This will extract the actual message string and escapes all double quotes in it (message.Replace("\"", "\\\"");), causing serialization to succeed.
If you really want to remove the quotes instead of escaping them, you can do message = message.Replace("\"", "");
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring JMS junit test can't find @Component annotated receiver
I'm trying to test JMSSender and JMSReceiver, the JMSSender is autowiring correctly, but the JMSReceiver is not.
No qualifying bean of type
'br.com.framework.TestJMSReceiverImpl' available:
expected at least 1 bean which qualifies as autowire candidate.
The test class:
@RunWith(SpringRunner.class)
@DirtiesContext
@ContextConfiguration(classes = { JMSSenderConfig.class, JMSReceiverConfig.class })
@TestPropertySource(properties = { "spring.activemq.broker-url = vm://localhost:61616" })
public class SpringJmsApplicationTest {
@ClassRule
public static EmbeddedActiveMQBroker broker = new EmbeddedActiveMQBroker();
@Autowired
private JMSSender sender;
@Autowired
private TestJMSReceiverImpl receiver;
@Test
public void testReceive() throws Exception {
sender.send("helloworld.q", "Daleee");
receiver.receive();
}
}
main Application class i have:
@Configuration
@ComponentScan("br.com.framework")
@EnableAutoConfiguration(exclude = { BatchAutoConfiguration.class, DataSourceAutoConfiguration.class })
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
The TestJMSReceiverImpl:
@Component
public class TestJMSReceiverImpl extends JMSReceiver {
public TestJMSReceiverImpl() {
super("helloworld.q");
}
...
}
The JMSReceiver:
public abstract class JMSReceiver {
@Autowired
JmsTemplate jmsTemplate;
private String queue;
public JMSReceiver(String queue) {
this.queue = queue;
}
...
}
Anyone knows what I am missing here?
A:
The TestJMSReceiverImpl class is not included in your test context. You need to add it the context configuration for the SpringJmsApplicationTest class: change
@ContextConfiguration(classes = { JMSSenderConfig.class, JMSReceiverConfig.class })
into
@ContextConfiguration(classes = { JMSSenderConfig.class,
JMSReceiverConfig.class, TestJMSReceiverImpl.class })
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change the accordion menu icon with JS?
I have a menu (accordion) that uses Bootstrap 3.3.7 and Font Awesome 5.0.1
What I am looking for :
When the menu is closed, a "plus" icon is displayed.
When the menu is open, a "minus" icon is displayed.
The "plus" icon is displayed on the menu but does not change.
I think there is a problem with my JS code.
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading panel-like">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapse1" aria-expanded="false">
<h4 class="panel-title">
<svg class="svg-inline--fa fa-heart fa-w-18 fa-lg" aria-hidden="true" data-prefix="fas" data-icon="heart" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" data-fa-i2svg=""><path fill="currentColor" d="M414.9 24C361.8 24 312 65.7 288 89.3 264 65.7 214.2 24 161.1 24 70.3 24 16 76.9 16 165.5c0 72.6 66.8 133.3 69.2 135.4l187 180.8c8.8 8.5 22.8 8.5 31.6 0l186.7-180.2c2.7-2.7 69.5-63.5 69.5-136C560 76.9 505.7 24 414.9 24z"></path></svg><!-- <i class="fas fa-heart fa-lg"></i> --> Ses pages préférées <span class="badge">0</span>
<span class="collapse-change-icon"><svg class="svg-inline--fa fa-plus-circle fa-w-16 fa-lg" aria-hidden="true" data-prefix="fas" data-icon="plus-circle" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm144 276c0 6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92h-92c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 12v92h92c6.6 0 12 5.4 12 12v56z"></path></svg><!-- <i class="fas fa-plus-circle fa-lg"></i> --></span>
</h4>
</a>
</div>
<div id="collapse1" class="panel-collapse collapse" aria-expanded="false" style="height: 0px;">
<div class="panel-body">
<div class="panel-help">
L'utilisateur peut montrer ou cacher ce qu'il aime.<br>
Les badges verts affichent le nombre total de j'aime (même les cachés).<br>
Les résultats affichent uniquement ce que l'utilisateur souhaite montrer.
</div>
</div>
<div class="panel-body"><dd><div class="views-element-container form-group"><div class="view view-profile-page-like view-id-profile_page_like view-display-id-block_1 js-view-dom-id-9c91349966910a86b1ba6a9c66ae52b7b92568e7856bfc40d447149fed9dc49f">
<div class="view-header">
Résultat trouvé 0
</div>
<div class="view-empty">
<p>Cet utilisateur n'a mis aucune mention j'aime.</p>
</div>
</div>
</div>
</dd></div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading panel-contest">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapse2" aria-expanded="false">
<h4 class="panel-title">
<svg class="svg-inline--fa fa-trophy fa-w-18 fa-lg" aria-hidden="true" data-prefix="fas" data-icon="trophy" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" data-fa-i2svg=""><path fill="currentColor" d="M552 64H448V24c0-13.3-10.7-24-24-24H152c-13.3 0-24 10.7-24 24v40H24C10.7 64 0 74.7 0 88v56c0 35.7 22.5 72.4 61.9 100.7 31.5 22.7 69.8 37.1 110 41.7C203.3 338.5 240 360 240 360v72h-48c-35.3 0-64 20.7-64 56v12c0 6.6 5.4 12 12 12h296c6.6 0 12-5.4 12-12v-12c0-35.3-28.7-56-64-56h-48v-72s36.7-21.5 68.1-73.6c40.3-4.6 78.6-19 110-41.7 39.3-28.3 61.9-65 61.9-100.7V88c0-13.3-10.7-24-24-24zM99.3 192.8C74.9 175.2 64 155.6 64 144v-16h64.2c1 32.6 5.8 61.2 12.8 86.2-15.1-5.2-29.2-12.4-41.7-21.4zM512 144c0 16.1-17.7 36.1-35.3 48.8-12.5 9-26.7 16.2-41.8 21.4 7-25 11.8-53.6 12.8-86.2H512v16z"></path></svg><!-- <i class="fas fa-trophy fa-lg"></i> --> Les concours remportés <span class="badge">0</span>
<span class="collapse-change-icon"><svg class="svg-inline--fa fa-plus-circle fa-w-16 fa-lg" aria-hidden="true" data-prefix="fas" data-icon="plus-circle" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm144 276c0 6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92h-92c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 12v92h92c6.6 0 12 5.4 12 12v56z"></path></svg><!-- <i class="fas fa-plus-circle fa-lg"></i> --></span>
</h4>
</a>
</div>
<div id="collapse2" class="panel-collapse collapse" aria-expanded="false">
<div class="panel-body"><dd><div class="views-element-container form-group"><div class="view view-profil-page-concours view-id-profil_page_concours view-display-id-block_1 js-view-dom-id-c93650dc04dbe389c2eebfbc710083ad849dc98a77b48f8161cbae68609b76fa">
<div class="view-header">
Résultat trouvé 0
</div>
<div class="view-empty">
<p>Cet utilisateur n'a remporté aucun concours.</p>
</div>
</div>
</div>
</dd></div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<a class="" data-toggle="collapse" data-parent="#accordion" href="#collapse3" aria-expanded="true">
<h4 class="panel-title">
<svg class="svg-inline--fa fa-object-group fa-w-16 fa-lg" aria-hidden="true" data-prefix="fas" data-icon="object-group" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M480 128V96h20c6.627 0 12-5.373 12-12V44c0-6.627-5.373-12-12-12h-40c-6.627 0-12 5.373-12 12v20H64V44c0-6.627-5.373-12-12-12H12C5.373 32 0 37.373 0 44v40c0 6.627 5.373 12 12 12h20v320H12c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12v-20h384v20c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12v-40c0-6.627-5.373-12-12-12h-20V128zM96 276V140c0-6.627 5.373-12 12-12h168c6.627 0 12 5.373 12 12v136c0 6.627-5.373 12-12 12H108c-6.627 0-12-5.373-12-12zm320 96c0 6.627-5.373 12-12 12H236c-6.627 0-12-5.373-12-12v-52h72c13.255 0 24-10.745 24-24v-72h84c6.627 0 12 5.373 12 12v136z"></path></svg><!-- <i class="fas fa-object-group fa-lg"></i> --> Ses contenus <span class="badge">0</span>
<span class="collapse-change-icon"><svg class="svg-inline--fa fa-plus-circle fa-w-16 fa-lg" aria-hidden="true" data-prefix="fas" data-icon="plus-circle" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm144 276c0 6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92h-92c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 12v92h92c6.6 0 12 5.4 12 12v56z"></path></svg><!-- <i class="fas fa-plus-circle fa-lg"></i> --></span>
</h4>
</a>
</div>
<div id="collapse3" class="panel-collapse collapse in" aria-expanded="true" style="">
<div class="panel-body"><dd><div class="views-element-container form-group"><div class="view view-profil-page-contenu view-id-profil_page_contenu view-display-id-block_1 js-view-dom-id-5046ef4a9eab21dfa4bd430068e0d74db0486d12515e1007257e88d26ed3b55b">
<div class="view-header">
Résultat trouvé 0
</div>
<div class="view-empty">
<p>Select any filter and click on Apply to see results</p>
</div>
</div>
</div>
</dd></div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapse4" aria-expanded="false">
<h4 class="panel-title">
<svg class="svg-inline--fa fa-gift fa-w-16 fa-lg" aria-hidden="true" data-prefix="fas" data-icon="gift" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M488 192h-64.512C438.72 175.003 448 152.566 448 128c0-52.935-43.065-96-96-96-41.997 0-68.742 20.693-95.992 54.15C226.671 50.192 199.613 32 160 32c-52.935 0-96 43.065-96 96 0 24.566 9.28 47.003 24.512 64H24c-13.255 0-24 10.745-24 24v80c0 13.255 10.745 24 24 24h8v112c0 26.51 21.49 48 48 48h352c26.51 0 48-21.49 48-48V320h8c13.255 0 24-10.745 24-24v-80c0-13.255-10.745-24-24-24zm-208-32c24-56 55.324-64 72-64 17.645 0 32 14.355 32 32s-14.355 32-32 32h-72zM160 96c16.676 0 48 8 72 64h-72c-17.645 0-32-14.355-32-32s14.355-32 32-32zm48 128h96v184c0 13.255-10.745 24-24 24h-48c-13.255 0-24-10.745-24-24V224z"></path></svg><!-- <i class="fas fa-gift fa-lg"></i> --> Ses produits <span class="badge">0</span>
<span class="collapse-change-icon"><svg class="svg-inline--fa fa-plus-circle fa-w-16 fa-lg" aria-hidden="true" data-prefix="fas" data-icon="plus-circle" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm144 276c0 6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92h-92c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 12v92h92c6.6 0 12 5.4 12 12v56z"></path></svg><!-- <i class="fas fa-plus-circle fa-lg"></i> --></span>
</h4>
</a>
</div>
<div id="collapse4" class="panel-collapse collapse" aria-expanded="false">
<div class="panel-body"><dd><div class="views-element-container form-group"><div class="view view-profil-page-produit view-id-profil_page_produit view-display-id-block_1 js-view-dom-id-769f9d711f4e8bc30f68415fc4e177720959cfa4d0d5f65a817079d4cb41eb47">
<div class="view-header">
Résultat trouvé 0
</div>
<div class="view-empty">
<p>Aucun produit n'a était publié.</p>
</div>
</div>
</div>
</dd></div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapse5" aria-expanded="false">
<h4 class="panel-title">
<svg class="svg-inline--fa fa-users fa-w-20 fa-lg" aria-hidden="true" data-prefix="fas" data-icon="users" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512" data-fa-i2svg=""><path fill="currentColor" d="M320 64c57.99 0 105 47.01 105 105s-47.01 105-105 105-105-47.01-105-105S262.01 64 320 64zm113.463 217.366l-39.982-9.996c-49.168 35.365-108.766 27.473-146.961 0l-39.982 9.996C174.485 289.379 152 318.177 152 351.216V412c0 19.882 16.118 36 36 36h264c19.882 0 36-16.118 36-36v-60.784c0-33.039-22.485-61.837-54.537-69.85zM528 300c38.66 0 70-31.34 70-70s-31.34-70-70-70-70 31.34-70 70 31.34 70 70 70zm-416 0c38.66 0 70-31.34 70-70s-31.34-70-70-70-70 31.34-70 70 31.34 70 70 70zm24 112v-60.784c0-16.551 4.593-32.204 12.703-45.599-29.988 14.72-63.336 8.708-85.69-7.37l-26.655 6.664C14.99 310.252 0 329.452 0 351.477V392c0 13.255 10.745 24 24 24h112.169a52.417 52.417 0 0 1-.169-4zm467.642-107.09l-26.655-6.664c-27.925 20.086-60.89 19.233-85.786 7.218C499.369 318.893 504 334.601 504 351.216V412c0 1.347-.068 2.678-.169 4H616c13.255 0 24-10.745 24-24v-40.523c0-22.025-14.99-41.225-36.358-46.567z"></path></svg><!-- <i class="fas fa-users fa-lg"></i> --> Ses groupes <span class="badge">0</span>
<span class="collapse-change-icon"><svg class="svg-inline--fa fa-plus-circle fa-w-16 fa-lg" aria-hidden="true" data-prefix="fas" data-icon="plus-circle" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm144 276c0 6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92h-92c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 12v92h92c6.6 0 12 5.4 12 12v56z"></path></svg><!-- <i class="fas fa-plus-circle fa-lg"></i> --></span>
</h4>
</a>
</div>
<div id="collapse5" class="panel-collapse collapse" aria-expanded="false">
<div class="panel-body"><dd><div class="views-element-container form-group"><div class="view view-profil-page-groupe view-id-profil_page_groupe view-display-id-block_1 js-view-dom-id-2e32ce43b15b99287bc35ff057edd6a6016a6e24603ee3f32329be118964bc97">
<div class="view-header">
Résultat trouvé 0
</div>
<div class="view-empty">
<p>Select any filter and click on Apply to see results</p>
</div>
</div>
</div>
</dd></div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapse6" aria-expanded="false">
<h4 class="panel-title">
<svg class="svg-inline--fa fa-shopping-bag fa-w-14 fa-lg" aria-hidden="true" data-prefix="fas" data-icon="shopping-bag" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" data-fa-i2svg=""><path fill="currentColor" d="M352 160v-32C352 57.42 294.579 0 224 0 153.42 0 96 57.42 96 128v32H0v272c0 44.183 35.817 80 80 80h288c44.183 0 80-35.817 80-80V160h-96zm-192-32c0-35.29 28.71-64 64-64s64 28.71 64 64v32H160v-32zm160 120c-13.255 0-24-10.745-24-24s10.745-24 24-24 24 10.745 24 24-10.745 24-24 24zm-192 0c-13.255 0-24-10.745-24-24s10.745-24 24-24 24 10.745 24 24-10.745 24-24 24z"></path></svg><!-- <i class="fas fa-shopping-bag fa-lg"></i> --> Ses boutiques <span class="badge">0</span>
<span class="collapse-change-icon"><svg class="svg-inline--fa fa-plus-circle fa-w-16 fa-lg" aria-hidden="true" data-prefix="fas" data-icon="plus-circle" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm144 276c0 6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92h-92c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 12v92h92c6.6 0 12 5.4 12 12v56z"></path></svg><!-- <i class="fas fa-plus-circle fa-lg"></i> --></span>
</h4>
</a>
</div>
<div id="collapse6" class="panel-collapse collapse" aria-expanded="false">
<div class="panel-body"><dd><div class="views-element-container form-group"><div class="view view-profil-page-boutique view-id-profil_page_boutique view-display-id-block_1 js-view-dom-id-9f21023e83a67893ad096dcbb218ba8b477f895466709aba0b5f909f705b740d">
<div class="view-header">
Résultat trouvé 0
</div>
<div class="view-empty">
<p>Aucune boutique n'a était publiée.</p>
</div>
</div>
</div>
</dd></div>
</div>
</div>
</div>
Here is my JS code. Something is wrong with it.
(function ($) {
$('.collapse').on('shown.bs.collapse', function () {
$(this).find('.collapse-change-icon svg').removeClass("fa-plus-circle").addClass("fa-minus-circle");
});
$('.collapse').on('hidden.bs.collapse', function () {
$(this).find('.collapse-change-icon svg').removeClass("fa-minus-circle").addClass("fa-plus-circle");
});
})(window.jQuery);
I added a class "collapse-change-icon", but I do not know if it's useful and if it's well placed.
A:
The icon that you want to change isn't inside the .collapse DOM element. It's inside the .panel-heading element.
(function ($) {
$('.collapse').on('shown.bs.collapse', function () {
$(this).parent().find('.panel-heading .collapse-change-icon svg').removeClass("fa-plus-circle").addClass("fa-minus-circle");
});
$('.collapse').on('hidden.bs.collapse', function () {
$(this).parent().find('.panel-heading .collapse-change-icon svg').removeClass("fa-minus-circle").addClass("fa-plus-circle");
});
})(window.jQuery);
| {
"pile_set_name": "StackExchange"
} |
Q:
Get list of Functions from NLua
I am using NLua for script interface with my application
if my application takes multiple files such as one.lua and two.lua
i want to get all the functions in all files in to a list of luafunctions
List<LuaFunctions> Functions;
NLua doesnt seem to have such a feature, but is there a way around it,
there is a GetFunction(string) methodthat will return the function that you named,
i can ofc do a brute force method on the GetFunction method but that will make my application take hours to start up with.
Any ways to work around this and get all functions in all files to a list of luafunctions?
A:
As functions cannot be listed out of the blue, i found another way around it a couple of hours later.
i listed all functions on a table.
so my lua code:
function Start()
// something
end
function Update()
// something else
end
became this:
var main = {}
function main.Start()
// something
end
function main.Update()
// something else
end
that way i could take them from a table listing, using
lua.GetTable({tablename});
which i have written a requirement for has to be named the same as the file so it would become:
var funcList = lua.GetTable(Path.GetFileNameWithoutExtension(c:\main.lua));
that would take and list all functions and then we can use:
lua.GetFunction(funcList[0]).Call();
as an example.
Took me a while to find this work-around and i hope it will benefit someone.
| {
"pile_set_name": "StackExchange"
} |
Q:
Obtener posición de un div con scroll
Tengo, por ejemplo, un <div> en cierto punto de la página. Lo que quiero es que cuando el scroll esté en la misma posición de ese div me ejecute una función. Por ejemplo:
if(Scroll == div){div.innerHTML="altura es ???'" ;}
Lo intenté hacer con scrollTop pero solo me ejecuta la función cuando el scroll está en el tope y, bueno, yo quiero que me la ejecute cuando ambos se topen por ahí.
Aquí esta mi código:
//asi es como lo se hacer pero no se si este correcto con srollTop
onscroll=function(){
var yScroll=self.pageYOffset || (document.documentElement.scrollTop+document.body.scrollTop);
var div = document.getElementById('pp');
if(yScroll == div.scrollTop){div.innerHTML="altura es: "+yScroll;}
}
div{
background:grey;
font-size:30px;
padding:5px;
font-weight:bold;
width:200px;
border-radius:5px;
}
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento sin título</title>
</head>
<body>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<!--cando el scroll lleque a este div quiero ejecutar una funcion-->
<div id="pp">0</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
</body>
</html>
A:
La propiedad Element.scrollTop te indica la posición del scroll de un elemento relativo a su interior, no al navegador, por lo que lo mejor es calcular la altura del elemento directamente por su posición absoluta.
Para calcular la posición absoluta (relativa a la ventana que estamos viendo) de cualquier elemento del DOM podemos hacer uso de Element.getBoundingClientRect().top, devolviéndonos un DOMRect que nos proporciona todos los datos necesarios:
Un ejemplo de uso podría ser:
// Generamos la función que será llamada en cada evento de scroll
window.onscroll = () => {
/* Obtenemos la posición absoluta del elemento en cuestión */
var div = document.getElementById('pp');
var yPos = div.getBoundingClientRect().top;
/* Si está cerca del borde superior (pondremos un margen de 20px) mostramos el texto */
if (Math.abs(yPos) < 20) {
div.innerHTML = "Altura es: " + yPos;
}
}
div {
background: grey;
font-size: 30px;
padding: px;
font-weight: bold;
width: 200px;
border-radius: 5px;
}
p {
height: 100px;
border: 1px solid red;
}
p:before {
content: "Hacer scroll";
}
<p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p>
<!-- cuando el scroll llegue a este div quiero ejecutar una función -->
<div id="pp">Aún nada...</div>
<p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display only one representative contour line in legend?
I have a layer of topographic contour lines, graduated by color (using QGIS). My legend wants to display every level and its color. This is not feasible. I need to simply show one representative line, which I'll edit to be labeled "Topographic contour lines: 5-meter intervals". How can I include one representative line, but not all of the various levels?
Thanks
TVZ
A:
In the Legend editor, expand your Contours item. Highlight all but one of the sub-items (i.e. contours) and click the green minus button at the bottom of the Legend items pane. This will delete all but one of your contours, just in the same way as you can delete and entire legend item.
Just an idea, but instead of only having one contour, you could leave three contours to suggest the colour and height range (the lowest, the middle and the highest) and label the main item "Topographic contour lines: 5-meter intervals:" and just have the heights for the actual contours. This would be a bit more informative as somebody reading your map will instantly know the height range which is visible.
Alternatively, add a duplicate layer for contours and given them all the same symbology. With the layer visible, go into Map Composer and add it (green plus button at the bottom of the legend items). Edit the text to suit. Then go back to the Main QGIS window and deactivate the layer. This will leave it in the Lengend but prevent it showing on the map. You need to have it active initially otherwise you won't be able to add the item.
| {
"pile_set_name": "StackExchange"
} |
Q:
Length contraction and angle change
I am new to special theory of relativity and it puzzles me at some points. For example, if we have a rod of length 1 meter, tilted at angle of 45 degrees ( x axis) and it moves at the speed of $v=0.95c$ in the direction of x axis, how come the angle at which it is tilted changes? I understand the x-length of the rod would change but why does the angle change?
A:
Because the angle depends on the length in the $x$ direction and the length in the $y$ direction, specifically the ratio between them. Therefore, if the $x$ direction is contracted while the $y$ direction remains unaffected, changing the ratio between the two, the angle will change too.
A:
The angle changes because the rod contracts only in the direction of motion. This means if we broke the rod into two components (like a vector)
$$\vec{L}=L_{x}\hat{x}+L_{y}\hat{y}$$
only the $L_{x}$ would "feel the length contraction" since its the only part in the direction of motion. So the new length vector would be
$$\vec{L}^{\prime}=L_{x}^{\prime}\hat{x}+L_{y}\hat{y}$$
Where the $L_{x}^{\prime}$ has the usually length contraction. Since the y remains the same and the x changes between the "moving" frame and the "rest" frame (and the triangle is still a right triangle) the triangle of the x and y components will have different angles. I left the algebra for you (and future users to enjoy)
| {
"pile_set_name": "StackExchange"
} |
Q:
Controllers design pattern
I have a design question about MVC and controllers
I have this two routes
Route::get('/foo/{id}', FooController@show)
Route::get('/bar/{id}', BarController@show)
But know, I would like to add another route for the index like this
Route::get('/', ???)
In this route, I need some information about the Foo and Bar models.
The question is, should I create a new controller for that route? like MainController?
A:
In general, controllers are meant to respond to requests associated with a specific resource (model). Thereby, given your concrete example, two distinct scenarios apply.
The Foo and Bar models are required on the landing page (/ route): In this case, a dedicated controller would be a perfectly fine thing to do. Also, the use of a view model would be beneficial.
No information about application-specific models is needed on the landing page: You can still use a dedicated controller class to return your view, while another possibility would be the use of a lambda function:
Route::get('/', function () {
return view('landing');
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I get a list of databases and collections on a MongoDB server?
I'm writing a GUI client for MongoDB in C. I use the C driver for MongoDB. I want to get a list of databases and their collections, but I can't find any functions in the documentation to do that.
How can I get a list of databases and collections using the C driver?
A:
The other answers here seem half complete, or not even relevant to the C/C++ interface. After much looking, here's what worked for me:
string serverHost("127.0.0.1:27017");
mongo::DBClientConnection conn;
string errmsg;
if( conn.connect( serverHost, errmsg ) )
{
BSONObj cmd = mongo::fromjson( "{listDatabases: 1}" );
BSONObj info;
if( conn.runCommand( "admin", cmd, info ) )
{
BSONElement arrayel = info.getField("databases");
std::vector<BSONElement> mdArray = arrayel.Array();
std::vector<BSONElement>::iterator iter;
for( iter=mdArray.begin(); iter!=mdArray.end(); ++iter )
{
BSONElement element = *iter;
BSONObj obj = element.Obj();
// HERE IS THE DATABASE NAME
string dbname = obj.getStringField("name");
// HERE IS THE LIST OF COLLECTIONS, BUT MAY NEED TO IGNORE ONE
// TITLED "system.indexes"
list<string> collNamespaces =
conn.getCollectionNames(dbname);
list<string>::iterator iter2 = collNamespaces.begin();
while( iter2 != collNamespaces.end() )
{
// EACH ENTRY HAS THE FULL NAMESPACE ("database:collection").
// Use this method to strip off the database name
string collectionName = mongo::nsGetCollection(*iter2);
++iter2;
} // END WHILE iterate through collections
} // END WHILE iterate through databases
} // END IF runCommand() returned success
} // END IF database connected
A:
I think you have to use mongo_run_command(mongo *conn, const char * db, bson *command, bson *out) where your command is a BSON command. You should be able to use the commands defined here. Note that some of the commands require that they are issued on the database admin. So in the mongodb shell one could query the list of databases like this:
> use admin
switched to db admin
> db.runCommand({listDatabases: 1})
{
"databases" : [
{
"name" : "geo",
"sizeOnDisk" : 14975762432,
"empty" : false
},
{
"name" : "local",
"sizeOnDisk" : 1,
"empty" : true
}
],
"totalSize" : 14975762432,
"ok" : 1
}
With the result of this operation, you can query each database for the available collections. I haven't tried the above using the C interface, but I believe that you should be able to achieve the same thing by calling mongo_run_command and passing the appropriate parameters.
| {
"pile_set_name": "StackExchange"
} |
Q:
Array sort with mixed alphabetical and numerical content not working in Firefox
I have a JavaScript Array called years with some dates and one textual item like so: [ "2017", "2018", "2019", "historic" ]
I want to sort it so that 'historic' comes first, and then the remaining numbers are sorted numerically.
The following sort function works perfectly in every browser I have tested apart from Firefox, which leaves 'historic' at the end of the array:
years.sort((a, b) => {
if (a === 'historic') {
return -1;
} else {
return a - b;
}
});
I tried adding the following console log:
let years = [ "2017", "2018", "2019", "historic" ];
years.sort((a, b) => {
console.log(a);
if (a === 'historic') {
return -1;
} else {
return a - b;
}
});
Firefox outputs the following:
2017 index.js:409
2018 index.js:409
2019
Suggesting it never processes the 'historic' array element.
A:
You need a symetrically check for both elements and check if a value is 'historic'. Then return the delta of the check or the delta of the values.
var array = ["2017", "2018", "2019", "historic"];
array.sort((a, b) => (b === 'historic') - (a === 'historic') || a - b);
console.log(array);
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.NET HTTPClient Get request status waiting for activation
I am writing a method that will return JSON data by making a GET request to a RestApi URL. When I run the application in debug mode, I get below data in response.
Id = 337, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
Here is my code:
public class Methods
{
public static async Task<JObject> Get(string url, string username, string password)
{
var credentials = new NetworkCredential(username, password);
HttpClientHandler handler = new HttpClientHandler { Credentials = credentials };
HttpClient client = new HttpClient(handler);
// client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return JObject.Parse(await response.Content.ReadAsStringAsync());
}
return new JObject { response.StatusCode };
}
}
Here is my view where I am trying to access data:
public IActionResult Index()
{
// Methods RestMethod = new Methods();
var data = Methods.Get("http://url/products", "domain\userid", "Password");
return View();
}
When I add debug in view at var data = ..... thats where I am getting waiting for activation.
Any help is really appreciated. :)
Thanks,
Ray
A:
If you are going to use async/await you should do it starting from the calling entry point. Currently you call the Get method which returns a running task but you do not wait for it to be completed. The easiest fix is for your Index method code should be changed like so:
public async Task<IActionResult> Index()
{
// Methods RestMethod = new Methods();
var data = await Methods.Get("http://url/products", "domain\userid", "Password");
return View();
}
Also see Stephen Cleary's blog for more details on async/await, he has written extensively on on this subject and also well known pitfalls and patterns.
| {
"pile_set_name": "StackExchange"
} |
Q:
Swift -Ounchecked and Assertions
Preface
In Swift, ENABLE_NS_ASSERTIONS is ignored, and whether assertions are on or off is dependent of SWIFT_OPTIMIZATION_LEVEL, see here for more information.
assert() is active for -Onone
assertionFailure() is active for
-Onone
precondition() is active for -Onone and -O
preconditionFailure() is active for -Onone, -O and -Ounchecked
fatalError() is active for -Onone, -O and -Ounchecked
What I want to achieve
Debug and Beta Builds should have assertions enabled, Release Builds should have assertions disabled.
How I could do it
I could write all my assertions in Swift via the precondition method and compile Release builds with the -Ounchecked flag, beta builds with the -O flag.
What I'm unsure about
The default in iOS for Release builds is -O. Is there anything advised against using -Ounchecked for release builds? Which other unwanted side effects could this cause?
A:
You should definitely not compile -Ounchecked for release in order to use precondition only while testing. Compiling -Ounchecked also disables checks for things like array out of bounds and unwrapping nil, that could lead to some pretty nasty production bugs involving memory corruption.
You can control assertion behaviour independently of compiler optimization settings via the -assert-config argument to swiftc:
$ cat assert.swift
assert(false, "assertion asserted")
println("made it here...")
$ swiftc -Onone assert.swift; ./assert
assertion failed: assertion asserted: file assert.swift, line 1
Illegal instruction: 4
$ swiftc -O assert.swift; ./assert
made it here...
$ swiftc -O -assert-config Debug assert.swift; ./assert
assertion failed: assertion asserted: file assert.swift, line 1
Illegal instruction: 4
$
It doesn’t look like there’s an Xcode Build Settings toggle for this, but you can add using the “Other Swift Flags” setting.
| {
"pile_set_name": "StackExchange"
} |
Q:
Parsing Large XML with Nokogiri
So I'm attempting to parse a 400k+ line XML file using Nokogiri.
The XML file has this basic format:
<?xml version="1.0" encoding="windows-1252"?>
<JDBOR date="2013-09-01 04:12:31" version="1.0.20 [2012-12-14]" copyright="Orphanet (c) 2013">
<DisorderList count="6760">
*** Repeated Many Times ***
<Disorder id="17601">
<OrphaNumber>166024</OrphaNumber>
<Name lang="en">Multiple epiphyseal dysplasia, Al-Gazali type</Name>
<DisorderSignList count="18">
<DisorderSign>
<ClinicalSign id="2040">
<Name lang="en">Macrocephaly/macrocrania/megalocephaly/megacephaly</Name>
</ClinicalSign>
<SignFreq id="640">
<Name lang="en">Very frequent</Name>
</SignFreq>
</DisorderSign>
</Disorder>
*** Repeated Many Times ***
</DisorderList>
</JDBOR>
Here is the code I've created to parse and return each DisorderSign id and name into a database:
require 'nokogiri'
sympFile = File.open("Temp.xml")
@doc = Nokogiri::XML(sympFile)
sympFile.close()
symptomsList = []
@doc.xpath("////DisorderSign").each do |x|
signId = x.at('ClinicalSign').attribute('id').text()
name = x.at('ClinicalSign').element_children().text()
symptomsList.push([signId, name])
end
symptomsList.each do |x|
Symptom.where(:name => x[1], :signid => Integer(x[0])).first_or_create
end
This works perfect on the test files I've used, although they were much smaller, around 10000 lines.
When I attempt to run this on the large XML file, it simply does not finish. I left it on overnight and it seemed to just lockup. Is there any fundamental reason the code I've written would make this very memory intensive or inefficient? I realize I store every possible pair in a list, but that shouldn't be large enough to fill up memory.
Thank you for any help.
A:
I see a few possible problems. First of all, this:
@doc = Nokogiri::XML(sympFile)
will slurp the whole XML file into memory as some sort of libxml2 data structure and that will probably be larger than the raw XML file.
Then you do things like this:
@doc.xpath(...).each
That may not be smart enough to produce an enumerator that just maintains a pointer to the internal form of the XML, it might be producing a copy of everything when it builds the NodeSet that xpath returns. That would give you another copy of most of the expanded-in-memory version of the XML. I'm not sure how much copying and array construction happens here but there is room for a fair bit of memory and CPU overhead even if it doesn't copy duplicate everything.
Then you make your copy of what you're interested in:
symptomsList.push([signId, name])
and finally iterate over that array:
symptomsList.each do |x|
Symptom.where(:name => x[1], :signid => Integer(x[0])).first_or_create
end
I find that SAX parsers work better with large data sets but they are more cumbersome to work with. You could try creating your own SAX parser something like this:
class D < Nokogiri::XML::SAX::Document
def start_element(name, attrs = [ ])
if(name == 'DisorderSign')
@data = { }
elsif(name == 'ClinicalSign')
@key = :sign
@data[@key] = ''
elsif(name == 'SignFreq')
@key = :freq
@data[@key] = ''
elsif(name == 'Name')
@in_name = true
end
end
def characters(str)
@data[@key] += str if(@key && @in_name)
end
def end_element(name, attrs = [ ])
if(name == 'DisorderSign')
# Dump @data into the database here.
@data = nil
elsif(name == 'ClinicalSign')
@key = nil
elsif(name == 'SignFreq')
@key = nil
elsif(name == 'Name')
@in_name = false
end
end
end
The structure should be pretty clear: you watch for the opening of the elements that you're interested in and do a bit of bookkeeping set up when the do, then cache the strings if you're inside an element you care about, and finally clean up and process the data as the elements close. You're database work would replace the
# Dump @data into the database here.
comment.
This structure makes it pretty easy to watch for the <Disorder id="17601"> elements so that you can keep track of how far you've gone. That way you can stop and restart the import with some small modifications to your script.
A:
A SAX Parser is definitly what you want to be using. If you're anything like me and can't jive with the Nokogiri documentation, there is an awesome gem called Saxerator that makes this process really easy.
An example for what you are trying to do --
require 'saxerator'
parser = Saxerator.parser(Temp.xml)
parser.for_tag(:DisorderSign).each do |sign|
signId = sign[:ClinicalSign][:id]
name = sign[:ClinicalSign][:name]
Symtom(:name => name, :id => signId).create!
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't access class instance from another class
in my AppDelegate I have imported the header of a class I have created and propertied and syntesized an instance of it (in AppDelegate). Now I'm trying to access a method and a variable inside this instance from two other views. I'm relatively new to objective-c, but so far I've learned that if I do this:
AppDelegate *appdelegate = [AppDelegate new];
I will just get a fresh instance from the class inside AppDelegate, so if I set a variable from one view, I can't access it from the other. I've read that if I would do it this way:
AppDelegate *ap = (AppDelegate *)[[UIApplication sharedApplication] delegate];
It would allow me to access the existing instance. But it doesn't work.
Is the way I'm trying to do this totally wrong? Thanks a lot for your help!
UPDATE:
When I do this inside AppDelegate:
myClass.string = @"test";
NSLog(@"appDelegate: %@", myClass.string);
I get this:
appDelegate: (null)
UPDATE2:
I wrote @class AppDelegate; underneath the @import lines in the viewController, but still I can't access myClass. A main problem, which may be the cause why this isn't working from the views, is that I can't even access myClass from AppDelegate.
In AppDelegate.h I wrote:
@property (strong, nonatomic) testClass *myClass;
In AppDelegate.m:
#import "testClass.h"
@synthesize myClass;
This should be right, right?
myClass.h
@property (strong, nonatomic) NSString *string;
myClass.m
@synthesize string;
When I then try to access myClass from appDelegate, I write:
self.myClass.string = @"test";
NSLog(@"appDelegate: %@", self.myClass.string);
The result is:
appDelegate: (null)
A:
I think you have to allocate and initialize the myClass
Write myClass = [MyClass alloc] init] in AppDelegate.m file
| {
"pile_set_name": "StackExchange"
} |
Q:
Extract attachements using mailbox python?
I wanted to extract email attachments from mbox using mailbox library in python.
I've used following code to extract From, To, Subject, Date, Body
import mailbox
mbox = mailbox.mbox('/tmp/Personal Folders/Inbox/mbox')
for message in mbox:
print message['subject']
print message['To']
print message['From']
print message['Date']
How to find and extract attachments in every mails? Do I need to include any more library ?
A:
The following python function extracts find and extracts attachment in native format :) don't forget to include
import mailbox
def extractattachements(message):
if message.get_content_maintype() == 'multipart':
for part in message.walk():
if part.get_content_maintype() == 'multipart': continue
if part.get('Content-Disposition') is None: continue
filename = part.get_filename()
print filename
fb = open(filename,'wb')
fb.write(part.get_payload(decode=True))
fb.close()
| {
"pile_set_name": "StackExchange"
} |
Q:
Checkout second Git branch without losing local changes
I have checked out a particular branch from my master. I created new classes propery files etc. in my local Eclipse and did the testing. I have not added/committed those classes/files to my local git repo. So after this successful prototype testing if I want to switch to another branch, how can I do it without losing local changes.
Once I check out the second branch my local changes will be overwritten? I am not sure if my changes will have to be discarded before the checkout of second branch to be possible.
A:
Use git stash.
git-stash - Stash the changes in a dirty working directory away
See more in the git docs.
If you have untracked new files, be sure to use the -u flag, as includes files git hasn't tracked yet.
Once you're ready to bring your stashed changes back, use git stash pop.
$ git stash -u
$ git checkout <branch>
$ # do work
$ git checkout <oldbranch>
$ git stash pop
A:
Well it is not certain you would lose changes (and in fact if you were to, git checkout would warn you), but it would be best to either stash your changes with git stash or just go ahead and commit your changes before checking out the other branch.
| {
"pile_set_name": "StackExchange"
} |
Q:
Stacking GTK+ widgets
Is there a way to put GTK+ widgets in a stack? I.e. put a button over label so that button covers a part of label.
A:
You can use GtkFixed as the layout. This will allow you to control exact locations of the child widgets, and they can overlap.
| {
"pile_set_name": "StackExchange"
} |
Q:
Tab DIVs docked within browser. Slide in and out of the screen with jquery when clicked
I have a couple things that I would like to do with the Divs seen in the picture attached that I have been unable to figure out. These Divs are docked in the bottom corner of the browser using CSS Positioning. I want to add a tab to each one using CSS and have it slide up and down on the screen when the user clicks on the tab portion with only the tab part showing when it is hidden. Right now, I have the (x) in the corner that hides the div. I would much rather have the header text on the tab rather than in the div.
Any help on making this div a tab and some thoughts on the jquery slidedown when closing would be helpful. Thanks.
.ib {
background: #FFFAEA;
border: solid #cab781 1px;
display: inline-block;
width:250px;
height: 98%;
}
.narrow {
width:150px;
}
$(document).on('click', '#close1,#close2', function (e) {
$(this).parent().fadeOut(500);
e.stopPropagation();
});
<footer id="footer" class="footer" runat="server">
<div id="supportDiv" class="ib questionbg narrow" runat="server">
<span id='close1'>x</span>
</div>
<div id="documentsDiv" class="ib" style="overflow:auto" runat="server">
<span id='close2'>x</span>
<asp:Label class="helpheader" runat="server">Help Documents</asp:Label>
<div style="margin-left:20px; vertical-align:top">
<asp:PlaceHolder id="documentList" runat="server"></asp:PlaceHolder>
</div>
</div>
</footer>
A:
So it's a little rough, but here I'm creating the tab control DOM elements with jQuery, and inserting them as the first child of the .ib tab element. Then I have the footer listening for clicks on the tab-control elements, and toggling the tabs as appropriate. The thing you want to be careful about is, if the user is selecting a different tab, toggle their last selection OFF when you toggle the new one ON.
As I say, it's a little rough. Haven't figured out why the slideToggle is breaking it out of its container el in the process of hiding the tab content, but otherwise it seems to be doing what you are looking for. Of course, you'll need to create some prettier CSS than I have. Again, rough.
/***
* First, we have to create the tab-control functionality
* for each of our footer tab-panes
***/
$(".ib").each(function() {
// For each tab, if it has a title, we can use that for our tab title.
var tabEl = $(this);
var tabTitle = tabEl.find(".helpheader").text();
var leftPos = tabEl.index() * 130;
// Create the tab control DOM structure...
var tabBar = "<div class='tab-control'><span class='tab-title'>" + tabTitle + "</span></div>";
// Insert that tab control as the first child of the tab.
tabEl.children().first().before(tabBar);
// Hide the rest of the tab elements, showing only the tab control.
tabEl.find(":first-child").siblings().hide();
// use the closedTab class on this tab
tabEl.css("left", leftPos+"px").addClass("closedTab");
});
/****
* Handler for clicks on the tab-control
* This should hide the tab-control, show the tab
* itself, change the class from closed to open, and
* reverse that process on any displayed siblings.
****/
$("#footer").on("click", ".tab-control", function() {
// Get the specific tab element.
var tabEl = $(this).parent();
// hide the tab-control, and show the rest of the content.
$(this).hide().siblings().show();
// remove the closedTab class, add the openTab.
tabEl.addClass("openTab").removeClass("closedTab");
// This next line is doing a LOT -- it takes the current
// tabEl, and goes through any siblings marked as openTab,
// changes them from openTab to closedTab, and shows the
// tab-control and hides everything else.
tabEl.siblings(".openTab")
.removeClass("openTab")
.addClass("closedTab")
.find(":first-child")
.show()
.siblings()
.slideToggle();
})
$("#footer").on('click', '.close', function(e) {
// get the current tab element.
var tabEl = $(this).parent();
// toggle the current tab from openTab to closedTab.
tabEl.addClass("closedTab").removeClass("openTab");
// hide all content except the tab-control.
tabEl.find(":first-child").show().siblings().slideToggle();
});
.footer {
position: fixed;
bottom: 0;
height: 100px;
}
.ib {
display: inline-block;
position: absolute;
bottom: 0;
}
.ib-content {
margin-left: 20px;
vertical-align: top;
position: relative;
}
.tab-control {
width: 120px;
height: 20px;
background: #FFFAEA;
border: solid #cab781 1px;
overflow: off;
}
.closedTab {
}
.openTab {
background: #FFFAEA;
border: solid #cab781 1px;
display: inline-block;
width: 250px;
height: 50px;
}
.narrow {
width: 150px;
}
.close {
position: relative;
float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<footer id="footer" class="footer" runat="server">
<div id="supportDiv" class="ib questionbg narrow" runat="server">
<span class='close'>x</span>
<div class='ib-content'>
<p>Proin eget tortor risus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec velit neque, auctor sit amet aliquam vel, ullamcorper sit amet ligula. Cras ultricies ligula sed magna dictum porta. Nulla quis
lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada.</p>
</div>
</div>
<div id="documentsDiv" class="ib" style="overflow:auto" runat="server">
<span class='close'>x</span>
<asp:Label class="helpheader" runat="server">Help Documents</asp:Label>
<div class='ib-content'>
<p>Nulla quis lorem ut libero malesuada feugiat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Nulla
porttitor accumsan tincidunt.</p>
</div>
</div>
</footer>
| {
"pile_set_name": "StackExchange"
} |
Q:
unix: looping through results of find command
I have a find command that outputs as I would like (it looks for files with strelka in the name and ends with .vcf):
find . -name *strelka* | grep '.vcf$'
But I want to then iterate over each and perform additional stuff.
To simply experiment, I'm just having it do a line count on each file (but ultimately I would want to do more in the end, this is just me playing around), but it already doesn't seem to work.
I have :
for i in find . -name \*strelka\* | grep '.vcf$'; do wc -l $i; done
Anyone know what is wrong with this?
A:
Use find . -name '*strelka*.vcf', thereby avoiding the grep and letting you use find ... -exec
Either pipe into xargs, or use -exec:
find . -name '*strelka*.vcf' | xargs wc -l
find . -name '*strelka*.vcf' -exec wc -l '{}' \;
Prefer the latter, for various reasons.
Your approach (with a $(...) around your find) is OK, except:
You'll have grief if there are spaces in filenames. (You'd have grief with xargs too - there's a way round that involving \0, but it's a bit arcane.)
You'll exceed the command line length limit if there are too many matching files.
A:
Assuming you are using a recent (4.0 or greater) version of bash, you don't need to use find for this; a file pattern is sufficient, along with the globstar option.
shopt -s globstar
for i in **/*strelka*.vcf; do
wc -l $i
done
For a small number of files, you can probably just use
wc -l **/*strelka*.vcf
For a large number of files,
find -name '*strelka*.vcf' -execdir wc -l '{}' +
is most efficient.
| {
"pile_set_name": "StackExchange"
} |
Q:
No route matches [PATCH]
I'm attempting to submit a form but am running into the error
No route matches [PATCH]
I've seen a variety of posts on this error but but in each one they only set get in their routes or some such error. I've also had no problem submitting other forms with nearly identical routing and form structure.
So first, Security has_many :stockholders
My Form is as follows (location: views/stockholders/edit.html.erb):
<%= simple_form_for @stockholder, url: url_for{action:'update', controller:"stockholders"}, html: {id:"stockholderform"}, update: { success: "response", failure: "error"} do |f| %>
<div class="container">
<div class="symegrid">
<div class="form-inline">
<%= f.grouped_collection_select :entity_id, [Org, Person], :all, :model_name, :to_global_id, lambda {|org_or_person_object| org_or_person_object.instance_of? Org? rescue org_or_person_object.fname + " " + org_or_person_object.lname rescue org_or_person_object.name}, label:"Stockholder", class: "names"%>
</div>
<div class="form-inline">
<%= f.input :cert_number, label:"Certificate Number" %>
<%= f.input :issue_date, Label: "Issue Date" %>
</div>
</div>
<div class="submit_button">
<%= f.submit %>
</div>
</div>
<% end %>
And my controller is:
class StockholdersController < ApplicationController
def edit
@stockholder=Stockholder.find(params[:id])
@security=Security.find(params[:security_id])
@[email protected]
end
def update
@stockholder=Stockholder.find(params[:id])
@security=Security.find(params[:security_id])
@[email protected]
if @stockholder.update(stockholder_params)
redirect_to edit_security_path(@security)
else
redirect_to edit_security_stockholder_path
end
end
private
def stockholder_params
params.require(:stockholder).perimit(:id, :entity_id, :cert_number, :issue_date, :shares_issued, :shares_repurchased, :shares_canceled, :shares_outstanding)
end
end
Finally, my routes are:
resources :securities do
resources :stockholders
end
Can anyone help me understand what's going on here? I structured two models in exactly this way and didn't run into a problem.
Many thanks in advance
A:
Your route expects two more parameters, which are :security_id and :id.
simple_form_for @stockholder, url: { action: 'update', controller: "stockholders", security_id: @security.id, id: @stockholder.id }, ...
where @security may be @stockholder.security if not instantiated in the controller.
Or you can do it more elegantly:
simple_form_for [@security, @stockholder], ... # url parameter is not needed
| {
"pile_set_name": "StackExchange"
} |
Q:
Проблема с обновлением в базе данных
$query = "UPDATE users SET imgname ='".$imgname."' WHERE user='".$_SESSION['user']."'";
Так хочу обновить столбик imgname в таблице users, в сессии у меня имя user-а, но что-то не то. Не понимаю что. Помогите найти.
A:
сделайте так:
$result = mysql_query($query);
if (!$result) echo mysql_error();
| {
"pile_set_name": "StackExchange"
} |
Q:
QlikView - Display datas from a field of a table
Can you help me to know, how can I display data in a chart only for a field of a table ?
For example, I have a table "Country" which have "France, Allemagne, Italie, ...".
In my chart, I only want to display datas from France, without any selection from the user.
Thanks for your help !
A:
You can select certain values without user interaction with
set analysis.
Have a look at the 'QlikView Reference Manual' PDF.
Starting at page 799 you'll find the section about set analysis.
On page 801 you find the following description:
sum( {1<Region= {US} >} Sales )
returns the sales for region US disregarding the current selection.
In this case Region is the column with your country and US is the preselection.
Hope that helps
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculate weighted mean in excel
I'd like some help writing this excel formula.
I'm trying to calculate the weighted mean of term payments accordingly to their percentage of use but I'm failing on the last part of the logic expression.
=IF(OR(B2>0,B3>0,B4>0,B5>0),(SUMIF(B2:B5,">=1",D2:D5))/(SUM(C2:C5)),0)
%[B] days[C] weighted mean[D=BxC]
30 1 30
70 30 2100
0 60 0
0 90 0
total 68.70967742
What I'd like to do is sum all lines in [D], if the percentage of [B] is >=1. Then I want to divide this by the sum of the days in [C] if their corresponding cell in [B] is >=1
So in this example the answer would be 68.70967742 --- [(30x1)+(70x30)]/(1+30).
What I came up with returns 11.7679558.
Thanks
A:
When calculating weighted averages, you'll find SUMPRODUCT is very useful!
=SUMPRODUCT($B$1:$B$4,$C$1:$C$4)/SUMIF($B$1:$B$4,">0",$C$1:$C$4)
This returned 68.7096774 as required.
| {
"pile_set_name": "StackExchange"
} |
Q:
tap back immediately after moving the map crashes application in iPhone
I came across the scenario where in if after moving the map immediately if I tap on back icon while the map has not fully loaded
The application crashes.
What I can understand is Since the loading is still in progress and I tap back the the application releases the controller but the google map loads asynchronously in NSRUNloop (not sure). So that might be the problem not sure though.
So does anybody know what can be the issue and is there any way to solve this issue?
Please comment if more description required.
A:
For anyone who is still searching for the answer
What exactly happening was that map view events were getting fired even if the controller was released causing a crash in the app.
So the solution is Before setting the value of objMKMapView to nil you need to set value of objMKMapView.delegate to nil.
| {
"pile_set_name": "StackExchange"
} |
Q:
where is authentication happening in web3js?
When using web3 js to connect to ethereum private network, I just configured the http provider of the web3 instance to connect to the node.
how is just info about RPC endpoint sufficient to be able to connect to a node.
shouldn't there be some user authentication in place? because with just a RPC endpoint we were able to do what ever we want with the blockchain?
Is it just like that ? or am I missing some thing here?
A:
By default, the RPC interface does not expose the personal API, and so you cannot unlock accounts over it, so people cannot just send transactions from your accounts. In general, though, it is best practice to store keys locally, on the client side (in the browser, for instance), and then send pre-signed transactions over the RPC interface.
That's not to say that authentication is a bad idea- publicly exposed RPC interfaces can be an easy DOS vector, and if you do unlock accounts, you don't want people sending from them.
That's why best practice is to have the client listen only to localhost, and use the CORS protection so that requests can only come from a single domain. You can set this by starting geth with the
--rpccorsdomain "myDomain.com" flag.
| {
"pile_set_name": "StackExchange"
} |
Q:
Skybot Python IRCbot
I use the skybot irc bot, I'd like to ask how to remove the nick from bots answer, like
<User1> .calc 1+3
<Skybot> **User1:** 1+3=4
In each plugin there are imports, here is the script from the file that imports into all plugings (hook.py):
import inspect
import re
def _hook_add(func, add, name=''):
if not hasattr(func, '_hook'):
func._hook = []
func._hook.append(add)
if not hasattr(func, '_filename'):
func._filename = func.func_code.co_filename
if not hasattr(func, '_args'):
argspec = inspect.getargspec(func)
if name:
n_args = len(argspec.args)
if argspec.defaults:
n_args -= len(argspec.defaults)
if argspec.keywords:
n_args -= 1
if argspec.varargs:
n_args -= 1
if n_args != 1:
err = '%ss must take 1 non-keyword argument (%s)' % (name,
func.__name__)
raise ValueError(err)
args = []
if argspec.defaults:
end = bool(argspec.keywords) + bool(argspec.varargs)
args.extend(argspec.args[-len(argspec.defaults):
end if end else None])
if argspec.keywords:
args.append(0) # means kwargs present
func._args = args
if not hasattr(func, '_thread'): # does function run in its own thread?
func._thread = False
def sieve(func):
if func.func_code.co_argcount != 5:
raise ValueError(
'sieves must take 5 arguments: (bot, input, func, type, args)')
_hook_add(func, ['sieve', (func,)])
return func
def command(arg=None, **kwargs):
args = {}
def command_wrapper(func):
args.setdefault('name', func.func_name)
_hook_add(func, ['command', (func, args)], 'command')
return func
if kwargs or not inspect.isfunction(arg):
if arg is not None:
args['name'] = arg
args.update(kwargs)
return command_wrapper
else:
return command_wrapper(arg)
def event(arg=None, **kwargs):
args = kwargs
def event_wrapper(func):
args['name'] = func.func_name
args.setdefault('events', ['*'])
_hook_add(func, ['event', (func, args)], 'event')
return func
if inspect.isfunction(arg):
return event_wrapper(arg, kwargs)
else:
if arg is not None:
args['events'] = arg.split()
return event_wrapper
def singlethread(func):
func._thread = True
return func
def regex(regex, flags=0, **kwargs):
args = kwargs
def regex_wrapper(func):
args['name'] = func.func_name
args['regex'] = regex
args['re'] = re.compile(regex, flags)
_hook_add(func, ['regex', (func, args)], 'regex')
return func
if inspect.isfunction(regex):
raise ValueError("regex decorators require a regex to match against")
else:
return regex_wrapper
I'll be very thankful to anyone who responds ;)
A:
To remove the nickname from the answer try using say() instead of a normal return at the end of the plugin function. Bitcoin plugin uses that:
from util import http, hook
@hook.command(autohelp=False)
def bitcoin(inp, say=None):
".bitcoin -- gets current exchange rate for bitcoins from mtgox"
data = http.get_json("https://mtgox.com/code/data/ticker.php")
ticker = data['ticker']
say("Current: \x0307$%(buy).2f\x0f - High: \x0307$%(high).2f\x0f"
" - Low: \x0307$%(low).2f\x0f - Volume: %(vol)s" % ticker)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to compare great circle distance with euclidean distance of two sphere points using python?
I am trying to check the error that is introduced when you compute the distance of two points on earth with the euclidean distance instead of using the great circle distance (gcd). I have two points that are defined by their lattitude and longtitude.
I used the python geopy framework for the great circle distance. Here the code for the gcd:
def measure(self, a, b):
a, b = Point(a), Point(b)
lat1, lng1 = radians(degrees=a.latitude), radians(degrees=a.longitude)
lat2, lng2 = radians(degrees=b.latitude), radians(degrees=b.longitude)
sin_lat1, cos_lat1 = sin(lat1), cos(lat1)
sin_lat2, cos_lat2 = sin(lat2), cos(lat2)
delta_lng = lng2 - lng1
cos_delta_lng, sin_delta_lng = cos(delta_lng), sin(delta_lng)
d = atan2(sqrt((cos_lat2 * sin_delta_lng) ** 2 +
(cos_lat1 * sin_lat2 -
sin_lat1 * cos_lat2 * cos_delta_lng) ** 2),
sin_lat1 * sin_lat2 + cos_lat1 * cos_lat2 * cos_delta_lng)
return self.RADIUS * d
So or two points:
p1=[39.8616,-75.0748], p2=[-7.30933,112.76]
the
gcd = 78.8433004543197 klm
using the great_circle(p1,p2).kilometers function from geopy
I then transformed these two points in cartesian coordinates using this formula:
def spherical_to_cartesian(r,la,lo):
x=r*np.sin(90-la)*np.cos(lo)
y=r*np.sin(90-la)*np.sin(lo)
z=r*np.cos(90-la)
return (x,y,z)
where r=6372.795, which results in the following cartesians coordinates
p1=[ -765.81579368, -256.69640558, 6321.40405587],
p2=[480.8302149,-168.64726394,-6352.39140142]
Then by typing: np.linalg.norm(p2-p1) i am getting 1103.4963114787836 as their euclidean norm which doesn't seem reasonable compared with ~78klm from the gcd. Am i inffering sth wrong?
A:
Python includes two functions in the math package; radians converts degrees to radians, and degrees converts radians to degrees.
The method sin() returns the sine of x, in radians.
import math
def spherical_to_cartesian(r,la,lo):
rlo = math.radians(lo)
rla = math.radians(90-la)
x=r*np.sin(rla)*np.cos(rlo)
y=r*np.sin(rla)*np.sin(rlo)
z=r*np.cos(rla)
return (x,y,z)
| {
"pile_set_name": "StackExchange"
} |
Q:
Eclipse correct way to add dependency to another Maven project?
I have three maven projects all under active development, One is a common library the other two perform ui tasks and use the common project.
In eclipse what is the alternative of adding the common library project as a dependency manually like so:
build path -> require projects on the build path
A:
Maven is the build tool, eclipse an IDE. You should focus on the Build Tool, so add the dependency in the maven typic pom.xml.
You could only add dependencys that have been downloaded into your local repository!
In your case you have to install your dependency into your local repository. This is done by the mvn install command. You could call it by rightclick on the pom.xml file of the dependency you like to use, select run-as->maven install.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a stored procedure to delete full data from dynamic table
I'm trying to create a stored procedure to delete all data from dynamically selected tables.
I used this code, but it's not working. Any suggestion?
CREATE PROCEDURE spDynamicDeleteTable
@table NVARCHAR(100)
AS
BEGIN
DECLARE @Sql NVARCHAR(MAX)
SET @Sql= 'DELETE FROM'+ @table
EXECUTE sp_executesql @Sql
END
A:
You are missing a space.
Set @Sql= 'Delete from'+ @table
would become
Delete fromelbat
if @table = 'elbat'. That isn't valid syntax.
Add a space after "from". It's also advisable to use quotename() to prevent funny things from happen with unusual table names.
Set @Sql= 'Delete from ' + quotename(@table)
Some further notes:
@table should better be declared as a sysname rather than nvarchar(100). sysname is a type extra for object names.
Be aware, that you have to take great care regarding the rights this stored procedure is executed with in order to prevent it from being abused to delete arbitrary data.
| {
"pile_set_name": "StackExchange"
} |
Q:
Скрытая загрузка файлов на облако
Задача состоит вот в чем.
На сайте есть пользователи и разные проекты. Для каждого проекта и каждого пользователя своя папка с файлами. В этих папках так же могут быть архивы большого размера (пару гб). Таких архивов может быть много. Пользователь может загружать и скачивать эти архивы с облака. Но доступ к ним нужно регулировать. Нужно чтобы лично я с помощью кода определял, кто может скачивать или загружать файлы, а кто нет.
Какое облако позволяет загружать и скачивать файлы при этом не запрашивая доступ к аккаунту у самого пользователя? Или же как обойти доступ к аккаунту на том же Google Drive, чтобы пользователь даже не подозревал что эти файлы хранятся на облаке.
A:
Оказывается Google Drive API поддерживает такую возможность. Необходимо:
Создать сервисный аккаунт тут
Скачать библиотеку для работы с google api тут, там есть примеры готовых решений
Вникнуть в документацию Google Drive API v3 об управлении файлами тут
Вникнуть в документацию Google Drive API v3 об управлении доступом к файлам тут
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieving a product picture via PHP Amazon Zend Service
I have installed the Amazon Zend library from GitHub and can access item information using the following:
<?php
require_once './Zend/Loader/StandardAutoloader.php';
$autoloader = new Zend\Loader\StandardAutoloader(array(
'namespaces' => array(
'Zend' => dirname(__FILE__) . '/Zend',
'ZendRest' => dirname(__FILE__) . '/ZendRest',
'ZendService' => dirname(__FILE__) . '/ZendService',
),
'fallback_autoloader' => true));
$autoloader->register();
$tag = 'omitted';
$appId = 'omitted';
$secretKey = 'omitted';
$query = new ZendService\Amazon\Query($appId, 'UK', $secretKey);
$query->Category('Electronics')->Keywords('nVidia')->AssociateTag($tag);
$result = $query->search();
foreach($result as $item)
{
?>
<div class="item">
<a href="<?php echo $item->DetailPageURL ?>" target="_blank"><?php echo $item->Title ?></a>
</div>
<?php
}
?>
which yields descriptive links to the products as expected.
I am trying to display each product's image alongside the link and am wondering if anyone has experience with doing this. When I print_r($item) I see this:
[SmallImage] =>
[MediumImage] =>
[LargeImage] =>
as well as all the other info (shortened for easier reading). It appears that these elements are empty but on the product links there are in fact picture(s) of the products. This happens for every product I search for. Is there an argument I need to set to return pictures?
There is also a class called ZendService\Amazon\Image which I am not sure how to use - the documentation is appaling. Would I need to call this to return an image? If so, how and where?
A:
The Amazon API does not include image data in the response by default. You can specify what information you want for each result using the ResponseGroup parameter. The docs include an example of this using the itemSearch syntax, I'm not entirely sure how you'd use this using the query method but hopefully this will point you in the right direction.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to load only selected data from plist file
I have plist with Root as Array and then each item in this array is a Dictionary with objects: name(String) and surname(String). I want display all the names from my file. At the moment I am using this code:
NSArray *myData = [[NSArray alloc] initWithContentsOfFile:mypath];
NSMutableArray *names = [[NSMutableArray alloc] init];
for (int i=0; i < myData.count; i++) {
[names addObject:[[myData objectAtIndex:i] objectForKey:@"name"]];
}
Is it any way that I could load values for the key @"name" straight from the plist file to NSMutableArray *names? I just don't want to load whole content of the plist file to memory if I only need @"name" values.
A:
No. Loading a plist is an all-or-nothing affair. Unless your plist is massive I wouldn't worry about it. And if it is, then you would want to consider splitting it up into multiple files rather than doing something like writing your own plist deserializer (because I guarantee you that CoreFoundation's plist parser is going to be faster than yours).
| {
"pile_set_name": "StackExchange"
} |
Q:
Simplest proof that $\binom{n}{k} \leq \left(\frac{en}{k}\right)^k$
The inequality $\binom{n}{k} \leq \left(\frac{en}{k}\right)^k$ is very useful in the analysis of algorithms. There are a number of proofs online but is there a particularly elegant and/or simple proof which can be taught to students? Ideally it would require the minimum of mathematical prerequisites.
A:
$\binom{n}{k}\leq\frac{n^k}{k!}=\frac{n^k}{k^k}\frac{k^k}{k!}\leq\frac{n^k}{k^k}\sum_m\frac{k^m}{m!}=(en/k)^k$.
(I saw this trick in some answer on this site, but can't recall where.)
| {
"pile_set_name": "StackExchange"
} |
Q:
javascript is enabled in ALL webbrowsers by default?
Isn't JavaScript enabled in all webbrowsers by default?
if yes, does this mean that i can use Ajax/JavaScript in my webpages without bearing in mind that maybe some browsers wont be able to use my website?
I don't want to create another version of the page to display non JavaScript content.
what do you think?
EDIT: it doesn't seem that gmail is working with JavaScript disabled. and SO works bad with it disabled:)
A:
No, you cannot assume that javascript is enabled.
A:
Yes, JavaScript is enabled by default in mainstream web browsers.
But quite apart from making your site work for users that are more security-conscious than most and turn it off, you will want it to work in things other than mainstream web browsers, such as accessibility tools and search engines. Hide all your content so that it only appears with JavaScript or Flash and you're not going to be coming up very high in Google.
i dont want to create another version of the page to display non javascript content.
This is why you create one version, as plain HTML, then add the progressive enhancement sauce.
A:
Usually it is enabled, but users can disable it or there may be some corporate policy to not allow certain user groups or machines to run javascript in browsers. It is always better to include <noscript> warning or message to tell the user that page will not work without js.
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem using trigonometric substitution: Domain of $\theta$
I'm studying calculus from Rogawski's Calculus. In trigonometric substitution $x=a\sec \theta$ he made a note:
In the substitution $x = a \sec θ$ , we choose $0\le θ \le π$
2 if $x \ge a$ and $π \le θ < \frac{3π}2$ if
$x \le −a$. With these choices, $a \tan \theta$ is the
positive square root $\sqrt{x^2 − a^2}$.
When I work on the integral:
$$\int \frac {\mathrm{d}x}{x\sqrt{x^2-9}}$$
Using the substitution of $x=3\sec\theta$ with the domain of $\theta$ shown above, the integration will be :
$$\int \frac {dx}{x\sqrt{x^2-9}}= \int \frac {3\sec\theta\tan\theta d\theta}{(3\sec\theta)\sqrt{9\sec^2-9}}=\int \frac {\tan\theta d\theta}{3\sqrt{\tan^2 \theta}}$$
$$= \int \frac{d\theta}{3}= \frac\theta 3+ \mathrm{C}$$
$$\int \frac {dx}{x\sqrt{x^2-9}}= \frac 13 \sec^{-1}\left(\frac x3\right)+ \mathrm{C}$$
Which is very wrong in the negative part of the domain of $x$ as shown in this graph:
Notice that the slope of the blue function in the negative domain should be positive not negative!.
The problem of this substitution is $2$ things:
$1)$ The domain of $\theta$ is chosen so that inverse cannot be done, since $\theta =\sec^{-1}x\notin (\pi,\frac{3\pi}2) $ which is the domain chosen for $\theta $.
$2)$ Depending on first problem, we should choose $\theta \in (0,\pi)-\{\frac\pi 2\}$ which makes $\sqrt{\tan^2 \theta}=|\tan \theta|$. The integral then should be re-written as a piecewise function:
$$\int \frac {dx}{x\sqrt{x^2-9}}= \int \frac {3\sec\theta\tan\theta d\theta}{(3\sec\theta)\sqrt{9\sec^2-9}}$$
$$\int \frac {\tan\theta d\theta}{3\sqrt{\tan^2 \theta}} = \begin{cases} = \int \frac {d\theta}{3} = \frac 13 \sec^{-1}(\frac x3)+ C & \text{if $\theta \in (0,\frac \pi 2)$} \equiv x>3 \\= \int \frac {-d\theta}{3} = \frac {-1}3 \sec^{-1}(\frac x3)+ C & \text{if $\theta \in (\frac \pi 2,\pi)$}\equiv x<-3 \end{cases}$$
My questions are:
Is this thinking right ? there is mistake to choose the domain of $\theta$ as mentioned in the book ?
Mathematica gives me the answer of $-\dfrac {1}{3} \tan^{-1} \left(\dfrac{3}{\sqrt{x^2-9}}\right) +\mathrm{C}$ which is right when graphed. But how to construct this integral ?
Thanks for help.
A:
To get to the answer Mathematica gives, you can let$$ u = \sqrt{x^2 -9}.$$ You should get $$ \frac{1}{3} \arctan \left( \frac{\sqrt{x^2-9}}{3} \right) + \text{constant} $$ and use the fact that $$\arctan(\frac{1}{x}) = \frac{\pi}{2} - \arctan(x)~~~,x\gt 0$$ and
$$\arctan(\frac{1}{x}) = -\frac{\pi}{2} - \arctan(x)~~~,x\lt 0 $$
A:
In the substitution $x = a \sec\theta$ , we choose $0 \leq \theta < \frac\pi2$ if $x \geq a$ and $\pi \leq \theta < \frac{3\pi}2$ if
$x \leq −a$. With these choices, $a \tan\theta$ is the
positive square root $\sqrt{x^2 − a^2}$.
I think what Rogawski may have in mind here is that $x = a \sec\theta$
is not quite the same thing as $\theta = \sec^{-1}\left( \frac xa \right)$.
Since $\sec (-\theta) = \sec\theta$, the possible solutions
for $x = a \sec\theta$ are:
$$\theta = \sec^{-1}\left( \frac xa \right) + 2n\pi \quad \text{or} \quad
\theta = -\sec^{-1}\left( \frac xa \right) + 2n\pi,
\quad \text{where $n \in \mathbb Z$.}$$
If $x \geq a > 0$,
so that Rogawski's advice is to let $0 \leq \theta < \frac\pi2$,
then $\frac xa \geq 1$ and the "positive" solution with $n = 0$
produces a value of $\theta$ in the correct interval:
$$0 \leq \theta = \sec^{-1}\left( \frac xa \right) < \frac\pi2.$$
But keep in mind that the range of $\sec^{-1}$
is $\left[0, \frac\pi2\right) \cup \left(\frac\pi2, \pi\right]$.
If $x \leq -a < 0$,
so that Rogawski's advice gives $\pi \leq \theta < \frac{3\pi}2$,
then $\frac xa \leq -1$ and the "positive" solution with $n=0$
can give only values of $\theta$ in the interval $\left(\frac\pi2, \pi\right]$,
not $\left[\pi, \frac{3\pi}2\right)$.
And any other value of $n$ produces a value of theta even farther from
the desired interval.
The only way to produce a value in the desired interval,
$\left[\pi, \frac{3\pi}2\right)$,
is to take the "negative" solution with $n = 1$:
$$\pi \leq \theta = -\sec^{-1}\left( \frac xa \right) + 2\pi < \frac{3\pi}2,$$
which you can verify after observing that in this case (with $\frac xa < -1$),
$-\pi \leq -\sec^{-1}\left( \frac xa \right) < -\frac\pi2$.
So the correct subsitution (and reverse substitution) is
$$\int \frac {dx}{x\sqrt{x^2-9}}
= \int \frac {d\theta}{3} = \frac \theta 3 + C
= \begin{cases}
\dfrac13 \sec^{-1}\left( \dfrac x3 \right) + C & \text{if }\ x \geq 3, \\
-\dfrac13 \sec^{-1}\left( \dfrac x3 \right) + C & \text{if }\ x < -3.
\end{cases}$$
(Note that the constant $2\pi$ in the "negative" case is incorporated
in the constant of integration, $C$.)
This is the same result you got by setting
$\theta \in \left[0, \frac\pi2\right) \cup \left(\frac\pi2, \pi\right]$
and using the fact that $\sqrt{\tan^2 \theta} = |\tan\theta\,|$.
Personally, I see nothing wrong with your method;
in fact it may be easier to keep track of the need to do a "sign change"
for the integral when $x \leq -3$ when you have an explicit invocation
of the absolute value function, $|\tan\theta\,|$,
rather than rules that implicitly change the sign of $\sec^{-1}\theta$
(that is, the requirement that $\pi \leq \theta < \frac{3\pi}2$,
whose application seems a bit obscure to me).
In short, both methods give the same result, which is the correct result,
but only if applied exactly as required at every step.
Your method seems less prone to error than the method Rogawski
recommends, so everything considered, I think I prefer yours.
(Of course if you are currently taking a class in calculus and
have to write solutions of integrals like this on homework or exams,
it's a good policy to write your solution in a way that will be
easy for the grader to grade correctly. So if you use a technique not
shown in class or in the textbook, make sure you explain it clearly,
like the way you explained that $\sqrt{\tan^2 \theta} = |\tan\theta\,|$.
It just makes life easier for everyone in the end.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Using own class as a type parameter constraint in class declaration
I have the following declaration of a class in Delphi XE8:
TestClass = class;
TestClass = class
function test<T: TestClass>(supplier: TFunc<T>): T; // Compiler error
end;
Which throws the following compiler error:
E2086 Type 'TestClass' is not yet completely defined
When I add another class to the mix and use that one as constraint instead, it works fine:
AnotherTestClass = class
end;
TestClass = class;
TestClass = class
function test<T: AnotherTestClass>(supplier: TFunc<T>): T; // No Error
end;
I suspect the problem is that the forward type declaration does not tell Delphi enough about the TestClass type yet. This is perhaps more obvious since the following attempt to work around the problem throws the very same compiler error on a different line:
TestClass = class;
AnotherTestClass = class (TestClass) // Compiler Error
end;
TestClass = class
function test<T: AnotherTestClass>(supplier: TFunc<T>): T;
end;
Am I doing something wrong and if not, is there a way around this problem?
A:
You are not doing anything wrong. What you are attempting should be possible, but the compiler is, in my view, defective. There's no viable way to work around this without completely changing the design. One way to work around the issue would be to enforce the constraint at runtime. However, that would count, in my eyes, as completely changing the design.
Note that in .net what you are trying to do is perfectly possible:
class MyClass
{
private static T test<T>(Func<T> arg) where T : MyClass
{
return null;
}
}
The Delphi generics feature was based on .net generics and I rather suspect that the problem you face is down to an oversight on the part of the Delphi developers.
You should submit a bug report / feature request.
Update 1
LU RD suggests a better workaround. Use a class helper:
type
TestClass = class
end;
TestClassHelper = class helper for TestClass
function test<T: TestClass>(supplier: TFunc<T>): T;
end;
This will allow you to have the constraint tested at compile time. However, it does force you to define the method outside the function which is untidy, and it stops you using a class helper for any other purpose. So, you should still submit a bug report / feature request in my view.
Update 2
Bug report: RSP-13348
| {
"pile_set_name": "StackExchange"
} |
Q:
Where can I find the source code of UIDatePicker of ios4
Where can I find the source code of specific widget inside ios4?
for exmaple , the code of UIDatePicker ,segment control ...
Thanks advance for your help.
BR,
camino
A:
UIKit is not open source; the source code is not available.
| {
"pile_set_name": "StackExchange"
} |
Q:
Trouble selecting correct object in viewport
After switching from Maya to Blender I noticed that I can't select meshes as precisely as in Maya.
In Maya you select exactly what you clicked on, it doesn't matter how far the object is from the camera, you always get what you clicked on. In Blender it's fairly hard to select a specific mesh among other meshes, it seems Blender is trying to "help" me and correct my selection (like auto-aim in FPS games on console). I spend too much time trying to select the right mesh. Its not only time consuming, but also very annoying. I have to switch between shaded and wireframe modes, sometimes use strong zoom and hide functions to select the right mesh.
Is there a way to switch this "auto-aim" selection off? I would like to be able to select meshes just like in any other 3D program, by clicking exactly on them.
A:
You can also try changing the selection mode under User Preferences. There are two options available now for selection.
OpenGL Select
OpenGL Occlusion Queries
OpenGL Occlusion Queries is the newer, and faster method which seems to work better on AMD Radeon GPUS.
You can also use shift+b to draw-out a rectangular selection that will cause the view to zoom in on the selected location. Picking objects tends to work better when you are zoomed in closer.
shift+c will zoom out out to fit the scene. Using these two shortcuts, you can quickly navigate to whatever object you would like to select and work on.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to test for NULL in SQL query
string query =
"select User_name, User_Second_Choice
from tbl_User where User_Assigned_Project ='"+NULL+"'";
i try to select the rows to update so how can i change User_Assigned_Project = '"+NULL+"'";
Thank you.
A:
Use IS NULL not '= NULL'
select User_name, User_Second_Choice
from tbl_User where User_Assigned_Project IS NULL
| {
"pile_set_name": "StackExchange"
} |
Q:
Every fourth list view item get marked by using selector instead of just the choosen one android
Hey Guys I am working right now on a University project and have some problems which I found out randomly. Actually, I have to create an app (android) for an upcoming event where the user can see all the events in an overview and can tag his favorite ones.
I have a listview object, which is displaying all the items from a List<>
I wanna give the opportunity that the user can tag his favorite events which shall appear in a new fragment but I have problems with the changing icon. When you tag the first item in the list, it also tags every fourth item in the list additionally. I don't know why and it would be great if you can help! :)
the selector for the Image View
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@drawable/ic_bookmark_black_24dp_copy_3" />
<item android:state_selected="false" android:drawable="@drawable/ic_bookmark_border_black_24dp_copy_3" />
<item android:drawable="@drawable/ic_bookmark_black_24dp_copy_3" />
</selector>
the adapter including the activating function to change the icon
public class CustomArrayAdapter extends BaseAdapter{
private List<EventItem> listData;
private LayoutInflater layoutInflater;
private Context context;
static class ViewHolder {
TextView titleView;
TextView descriptionView;
TextView authorView;
TextView reportedDateView;
TextView locationView;
ImageView favorite;
}
public CustomArrayAdapter(Context context, List<EventItem> listData) {
this.context = context;
this.listData = listData;
Collections.sort(listData);
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_event_item, null);
holder = new ViewHolder();
holder.titleView = (TextView) convertView.findViewById(R.id.title);
holder.authorView = (TextView) convertView.findViewById(R.id.author);
holder.descriptionView = (TextView) convertView.findViewById(R.id.description);
holder.locationView = (TextView) convertView.findViewById(R.id.location);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.time);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleView.setText(listData.get(position).getTitle());
holder.authorView.setText(listData.get(position).getAuthor());
holder.descriptionView.setText(listData.get(position).getDescription());
holder.locationView.setText(listData.get(position).getLocation());
holder.reportedDateView.setText(getTime(position));
holder.favorite = (ImageView) convertView.findViewById(R.id.bookmark);
holder.favorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(view.isSelected()) {
System.out.println("Position: ");
view.setSelected(false);
}else{
view.setSelected(true);
}
}
});
return convertView;
}
private String getTime(int position) {
Date start = listData.get(position).getStartTime();
Date end = listData.get(position).getEndTime();
String startTime = start.toString();
String endTime = end.toString();
return String.format("%1s%2s%3s", start.toString().substring(11, 19), " - ", end.toString().substring(11, 19));
}
}
And here my Image view out of the xml file where all the other views where styled
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/description"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="8dp"
android:src="@drawable/bookmark_icon_selector"
android:tint="@color/colorDhdPrimary"
android:id="@+id/bookmark"
/>
and here the list view in the separate XML.
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="@+id/list_container">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list_event"
app:layout_constraintBottom_toBottomOf="@+id/list_container"
app:layout_constraintLeft_toLeftOf="@+id/list_container"
app:layout_constraintRight_toRightOf="@+id/list_container"
app:layout_constraintTop_toTopOf="@+id/list_container"
/>
A:
Solution can be multiple . One way to do this is just add a boolean in your EventItem POJO.
class EventItem{
boolean isSelected;
}
Now toggle this boolean onClick.
final int pos=position;
holder.favorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listData.get(pos).isSelected=!listData.get(posi).isSelected;
notifyDataSetChanged();
}
});
And in onBindViewHolder just check for boolean.
if(listData.get(position).isSelected){
holder.favorite.setSelected(true);
}else{
holder.favorite.setSelected(false);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Branching on Intel micro-architecture?
I need to write a script, which will work slightly differently on Intel Skylake processors. I can see that the lscpu tool outputs Model number differently on different CPUs, for example:
i7-4578U Model number = 69 (it's my laptop)
E5-2699 Model number = 63 (it's a server)
However, both processors belong to the Haswell micro-architecture family, so this method doesn't look reliable.
What is the reliable and recommended method to determine Intel CPU micro-archirtecture from a Linux script?
OS: Ubuntu (various versions)
A:
Model numbers do map to micro-architectures, but several model numbers can correspond to the same micro-architecture. To determine what model numbers to look for, you need to look at Intel’s “specification updates”; these provide exhaustive lists of model identifications.
For example, for Haswell you need to look at the mobile 4th gen update, the desktop 4th gen update, and probably the server 4th gen update. The first two list models 60, 69, and 70 (look for the “identification information” page, then take the “extended model” and “model number” values).
For Skylake, the X-series 6th gen update lists model 85, the generic 6th gen update lists models 78 and 94.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to assemble and run raw CPU instructions using `as`?
There are a couple of related questions here.
Consider a program consisting only of the following two instructions
movq 1, %rax
cpuid
If I throw this into a file called Foo.asm, and run as Foo.asm, where as is the portable GNU assembler, I will get a file called a.out, of size 665 bytes on my system.
If I then chmod 700 a.out and try ./a.out, I will get an error saying cannot execute binary file.
Why is the file so large, if I am merely trying to translate two asm instructions into binary?
Why can the binary not be executed? I am providing valid instructions, so I would expect the CPU to be able to execute them.
How can I get exactly the binary opcodes for the asm instructions in my input file, instead of a bunch of extra stuff?
Once I have the answer to 3, how can I get my processor to execute them? (Assuming that I am not running privileged instructions.)
A:
Why is the file so large, if I am merely trying to translate two asm instructions into binary?
Because the assembler creates a relocatable object file which includes additional information, like memory Sections and Symbol tables.
Why can the binary not be executed?
Because it is an (relocatable) object file, not a loadable file. You need to link it in order to make it executable so that it can be loaded by the operating system:
$ ld -o Foo a.out
You also need to give the linker a hint about where your program starts, by specifying the _start symbol.
But then, still, the Foo executable is larger than you might expect since it still contains additional information (e.g. the elf header) required by the operating system to actually launch the program.
Also, if you launch the executable now, it will result in a segmentation fault, since you are loading the contents of address 1, which is not mapped into your address space, into rax. Still, if you fix this, the program will run into undefined code at the end - you need to make sure to gracefully exit the program through a syscall.
A minimal running example (assumed x86_64 architecture) would look like
.globl _start
_start:
movq $1, %rax
cpuid
mov $60, %rax # System-call "sys_exit"
mov $0, %rdi # exit code 0
syscall
How can I get exactly the binary opcodes for the asm instructions in my input file, instead of a bunch of extra stuff?
You can use objcopy to generate a raw binary image from an object file:
$ objcopy -O binary a.out Foo.bin
Then, Foo.bin will only contain the instruction opcodes.
nasm has a -f bin option which creates a binary-only representation of your assembly code. I used this to implement a bare boot loader for VirtualBox (warning: undocumented, protoype only!) to directly launch binary code inside a VirtualBox image without operating system.
Once I have the answer to 3, how can I get my processor to execute them?
You will not be able to directly execute the raw binary file under Linux. You will need to write your own loader for that or not use an operating system at all. For an example, see my bare boot loader link above - this writes the opcodes into the boot loader of a VirtualBox disc image, so that the instructions are getting executed when launching the VirtualBox machine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python variable value adding a double quotes
input_file.txt has below
'123','345','567'|001
'1234','3456','5678'|0011
below is the code I am using to assign the values from input_file.txt to v_order_nbr_lst, which is working fine , but when I am using that variable inside a POST message API call like below , it is adding double quotes.
read the input file
fileHandle = open(input_file.txt,'r')
for line in fileHandle.readlines()[0:]:
line = line.rstrip('\n')
fields = line.split('|')
v_order_nbr_lst = (fields[0])
variable used below
postdata = {
"parameters": [
{
"Order_Nbr": [v_order_nbr_lst]
}
]
}
Now I am getting values with double quotes like this , i tried to replace & rstrip but not able to get rid of ".
postdata = {
"parameters": [
{
"Order_Nbr": ["'123','345','567'"]
}
]
}
expected result
postdata = {
"parameters": [
{
"Order_Nbr": ['123','345','567']
}
]
}
A:
The value in v_order_nbr_lst is not what you think, look:
line = "'123','345','567'|001"
fields = line.split('|')
v_order_nbr_lst = fields[0]
v_order_nbr_lst
=> "'123','345','567'" # this is a string, not a list!
Try this instead:
v_order_nbr_lst = fields[0].replace("'", '').split(',')
And assign the value like this:
"Order_Nbr": v_order_nbr_lst
| {
"pile_set_name": "StackExchange"
} |
Q:
I want to get characters out of a string in Crystal Reports
How can i write this SQL formula in Crystal Reports?
SUBSTRING(text, 6, 4))
Sample String: A003-A113-02
Using SUBSTRING in SQL, output = A113
Tried to use the Trim function, but not getting any good result.
A:
Trim removes whitespace-characters at the beginning and end of the string.
The equivalent of the SQL SUBSTRING-function in Crystal Reports is the Mid-Function:
Mid("A003-A113-02",6,4)
| {
"pile_set_name": "StackExchange"
} |
Q:
check if a value is in several lists
The task: check if 'value' is in list_1 AND list_2
Approach below - is the result of 2 minutes intuitive playing
list_1 = ['3', '5']
list_2 = ['5', '7', '4']
r = '5' in (list_1 and list_2) # 'and' gets an intersection
print(r) #True
And it works in a way I expect. I've already seen solution like that - it works, but there is a little room of my misunderstanding, that's why I ask
(1) Can't find docs, describing how 'and' operator (should)works,
for list, dicts, tuples etc.
(2) Why the following code returns 'False'
list_1 = ['3', '5']
list_2 = ['5', '7', '4']
r = '5' in (list_1, list_2) # Tuple?
print(r) #False
(3) Why it returns ['5', '7', '4']
list_1 = ['3', '5']
list_2 = ['5', '7', '4']
r = '5' in list_1 and list_2
print(r) # ['5', '7', '4']
(4) Why it returns (True, ['5', '7', '4'])
list_1 = ['3', '5']
list_2 = ['5', '7', '4']
r = '5' in list_1, list_2
print(r) # (True, ['5', '7', '4'])
I believe there is some doc at python docs web site, which enlightens questions above. It is possible to spend some time learning python 3 source code to see implementation details, but I am wondering of some language standart(like ECMAScript) which was used when Python 3 implementing
A:
Your intuition about the first snippet is False. and returns the second of its operators if both are truthy, so here it returns the second list; so your statement is actually equivalent to '5' in list_2, which happens to be True.
The second is false because the tuple is actually now (['3', '5'], ['5', '7', '4']) - ie a tuple of two elements, both of which are lists. in will check if any members of the tuple are the string '5', but neither of them are.
The other two answers are just to do with operator precedence; the third is equivalent to ('5' in list_1) and list_2 which returns list_2 as explained above; and the third is equivalent to (('5' in list_1), list_2).
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I remove "Older Posts" option at the bottom of the Wordpress Home page?
I want to show limited number of posts on homepage so how can I remove the option.
A:
You can put "display:none" to the container and also remove the navigation script from the home page. Can you post the code of the home page, So that i can help to remove the pagination.
| {
"pile_set_name": "StackExchange"
} |
Q:
rsync in non-daemon
I want to know how rsync works in non-daemon mode ,and what it is exactly ?
From rsync man pages , I came to know how daemon mode works .
I know something about daemon mode. Daemon is a process continuously listening for connections in background.
Now , the scene is ,I don't want to use Daemon mode ,as it will require some dedicated port always to be in listening.
I want to know,how does the client(say, local machine) in non-daemon mode technically invokes the rsync listener on server(say,remote machine) and vice versa?
The reason for this approach is that , *I don't want client should know the port number of server before-hand * .
Any detail explanations will be appreciated.
A:
From rsync man-page:
There are two different ways for rsync to contact a remote
system:
using a remote-shell program as the transport (such as ssh or rsh) or
contacting an rsync daemon directly via TCP.
So in non-deamon mode you can use ssh to connect and update your clients. In this case the initial connection through ssh will setup the client side so that rsync can connect without knowing the port number.
| {
"pile_set_name": "StackExchange"
} |
Q:
jqGrid Grouping state when filtering
I am using a filter for my jqGrid grid, and the data is in groups, defaulting first state of collapsed. If a user open a group or 2 (expaning the groups) , then does the filter, the grid reloads the data, filters it correctly, but then I loose the expanded state of the groups the user opened. Is there a way to not have it, toggle back to the default state of collapsed when doing a filter?
Thanks in Advance.
A:
I find your question interesting. So +1 from me. I made a demo which shows how to implement your requirements.
The main idea of the implementation is the same as in the answer. I suggest just hold the state of expanded groups in an array expandedGroups. I use onClickGroup callback added in jqGrid 4.0.0 (see here). Inside of loadComplete callback I try to expand all items from the array expandedGroups.
The advantage of the implementation is that the expanded state not disappear during paging, sorting and filtering.
The demo you can see here. Below in the code from the demo:
var $grid = $("#list"), expandedGroups = [];
$grid.jqGrid({
// ... some jqGrid parameters
grouping: true,
groupingView: {
groupField: ['name'],
groupCollapse: true,
groupDataSorted: true
},
onClickGroup: function (hid, collapsed) {
var idPrefix = this.id + "ghead_", id, groupItem, i;
if (hid.length > idPrefix.length && hid.substr(0, idPrefix.length) === idPrefix) {
id = hid.substr(idPrefix.length);
groupItem = this.p.groupingView.sortnames[0][id];
if (typeof (groupItem) !== "undefined") {
i = $.inArray(expandedGroups[i], groups);
if (!collapsed && i < 0) {
expandedGroups.push(groupItem);
} else if (collapsed && i >= 0) {
expandedGroups.splice(i, 1); // remove groupItem from the list
}
}
}
},
loadComplete: function () {
var $this = $(this), i, l, index, groups = this.p.groupingView.sortnames[0];
for (i = 0, l = expandedGroups.length; i < l; i++) {
index = groups.indexOf(expandedGroups[i]);
if (i >= 0) {
$this.jqGrid('groupingToggle', this.id + 'ghead_' + index);
}
}
}
});
$grid.jqGrid('navGrid', '#pager', {add: false, edit: false, del: false}, {}, {}, {},
{multipleSearch: true, multipleGroup: true, closeOnEscape: true, showQuery: true,
closeAfterSearch: true});
UPDATED: Grouping module of jqGrid are changed in many parts since my original answer. The modified demo one can find here. The most important part of the code used one can see below
grouping: true,
groupingView: {
groupField: ["invdate"],
groupCollapse: true,
groupDataSorted: true
},
onClickGroup: function (hid, collapsed) {
var idPrefix = this.id + "ghead_", i, groupid,
$this = $(this),
groups = $(this).jqGrid("getGridParam", "groupingView").groups,
l = groups.length;
if (!inOnClickGroup) {
inOnClickGroup = true; // set to skip recursion
for (i = 0; i < l; i++) {
groupid = idPrefix + groups[i].idx + "_" + i;
if (groupid !== hid) {
$this.jqGrid("groupingToggle", groupid);
}
}
inOnClickGroup = false;
}
}
The variable inOnClickGroup are defined in the outer scope.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sort directory list
I would like to sort the output from this script.
It show's an output from a complete directory with some exclusions.
<?php
if ($handle = opendir('.')) {
$blacklist = array('.', '..', '.svn', 'pagina.php','index.php','index.html');
echo "<h1>Statistics for:</h1>";
echo "<TABLE align=left border=1 cellpadding=5 cellspacing=0 class=whitelinks>";
while (false !== ($file = readdir($handle))) {
if (!in_array($file, $blacklist)) {
echo "<TR><TD><a href='./$file'>$file\n</a></TD></TR>";
}
}
closedir($handle);
echo"</TABLE>";
}
?>
What i would like to do is to sort the output from the directory on the alphabet.
A --> B --> C ...
How can i fix this. I have tried something with sort. But i can get it work
A:
put $file into an array first, use sort on the array then print out the html
$files = array();
while (false !== ($file = readdir($handle))) {
if (!in_array($file, $blacklist)) {
$files[] = $file;
}
}
sort($files,SORT_NATURAL); //use natsort if php is below 5.4
foreach($files as $file) {
echo "<TR><TD><a href='./$file'>$file\n</a></TD></TR>";
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Illustrator: How to accurately align shapes
i didn't really use Illustrator before, but i'm having troubles with some basic things such as aligning shapes together accurately. I'm using this auto-snap feature to align things but it's never really pixel-accurate as shown in the screenshots:
Whenever i try to resize the shape so that it fits the edges of the circle it snaps back as shown in the screenshot. Don't get me wrong, i just want to have the shape the same size as the outter circle.
A:
If you cut out the central circle from the larger circle the object path will run around the remaining "O" shape. The auto align features will then snap to this path easily.
| {
"pile_set_name": "StackExchange"
} |
Q:
Best way to make mouse clicks not pass through disabled components?
I'm using common windows controls such as "BUTTON" and "EDIT" for my application. There are cases where I want to disable components, so I use the EnableWindow function to make the components look disabled and not receive events.
The problem is however that the disabled component doesn't just block the mouse click events - instead it passes them to the components below it. Is there any way to prevent mouse click events from passing through disabled components? Or alternativly, an easy way to check for this case and discard these events?
I thought of making transparent windows on top, but that sounds somehow too complex for something which seems so trivial. I also though about hit testing of the mouse coordinates with the children of each container before accepting the event.
Is there any better way? I already have a custom area in my WndProc (I subclassed the button class) to catch the mouse button events if it helps.
Thanks in advance!
A:
From the EnableWindow documentation:
When input is disabled, the window does not receive input such as mouse clicks and key presses.
So by definition, when the window is disabled, it doesn't receive mouse clicks. What you're seeing is the expected, intended behavior, and I don't think there's any way to change it.
I'm not sure why you're trying to train your users to click on something that's disabled (every other Windows app will just ignore those clicks, so you're training your users to be confused by either your app or by every other app on the planet), but if you really want to support this, the simplest way is probably to put the button inside a panel that's exactly the same size as the button.
| {
"pile_set_name": "StackExchange"
} |
Q:
Number Theory: Proving polynomials with parity
Prove that if P(x) is a polynomial with integer coefficients such that P(0) and P(1) are both odd, then it has no integer roots.
A:
Well, $a\equiv b\mod 2$ implies $P(a)\equiv P(b)\mod 2$, and so if $P(0)$ and $P(1)$ are both odd, so is $P(n)$ for all other integers $n$.
| {
"pile_set_name": "StackExchange"
} |
Q:
why using eval and parsonJson together?
I think jquery $.parseJSON can convert jsons string to JavaScript object, why someone still use eval($.parseJSON) together?
A:
Seems like redundant at all.
jQuery parseJSON function uses native JSON in browsers that support it. According to Douglas Crockford (the author of original JSON specification), "the parse method uses the eval method to do the parsing, guarding it with several regular expressions to defend against accidental code execution hazards."
If the browser does not support JSON natively, jQuery uses new Function constructor to return parsed object, which is eval() equivalent with some scoping differences.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create own steam overlay
My end goal is to create a overlay to steam games similar in functionality to the discord steam overlay. I know this is a monstrous task so I am exploring all of my possibilities. The overlay built into steam is good, but you cannot play a game with it open.
Looking into steam's VGUI editing and steam skins system it seems like I can edit most things about the UI including steam notifications, which seems like the perfect candidate for an overlay. Either update one notification (if possible) or send many notifications.
So the question is, is it possible to:
Update one persistent notification or Send multiple notifications
Change notification content from outside sources (i.e. scripts, google, game servers)
Change notification dimensions and transparency
And if so, where in the steam files do I find the notification code? And is this the right direction or would it be easier to start on a standalone general application overlay?
A:
If you're talking about modifying the Steam overlay by injecting something that may end up getting a cease & desist letter, although maybe not -- Valve has effectively allowed/not stopped many other services and programs based on Steam so I don't know for sure. Valve is also currently very slowly working on updating the UI which could change any of this at any time. If you really do want to try this way I'd suggest looking into SteamKit, which is basically a partial reverse-engineered Steam client. Launching Steam in developer mode can help you find the files/variables for some of the definition of the skin, but I'm not sure where the notification coloring/styling is at. The old discontinued Enhanced Steam plugin that was for the client itself may help you figure out how to do this, but I've never looked at it's code and it may be outdated and no longer possible to do that way.
Overall though, yeah, your own app instead of doing shady stuff with the official client would likely be a better idea both because of legality and because it's likely going to be very difficult to install otherwise.
| {
"pile_set_name": "StackExchange"
} |
Q:
Accessing modified files in repository using JGit
I am using JGit to access a local repository using Java. I need to access the changed files of a repository which is typically executed using the git status command in git. What is the JGit implementation for this command?
So basically I need the JGit representation of a typical:
git status
My current implementation:
private void initRepository(String path){
try {
File workTree = new File(path);
Git git = Git.open(workTree);
//I need to get all the modified/changed files here
} catch (IOException ex) {
//handle exception
}
}
A:
The equivalent of a git status command can be run as follows
Status status = git.status().call();
With the various bits of information then being retrieved from the status object:
System.out.println("Added: " + status.getAdded());
System.out.println("Changed: " + status.getChanged());
System.out.println("Conflicting: " + status.getConflicting());
System.out.println("ConflictingStageState: " + status.getConflictingStageState());
System.out.println("IgnoredNotInIndex: " + status.getIgnoredNotInIndex());
System.out.println("Missing: " + status.getMissing());
System.out.println("Modified: " + status.getModified());
System.out.println("Removed: " + status.getRemoved());
System.out.println("Untracked: " + status.getUntracked());
System.out.println("UntrackedFolders: " + status.getUntrackedFolders());
Source: JGit Cookbook
| {
"pile_set_name": "StackExchange"
} |
Q:
Static cast of enum to bool, performance warning from Compiler
I have the following declared in my project:
enum class OType : bool { Dynamic=true, Static=false };
OType getotype();
I'm using the following function:
double ComputeO(double K,bool type)
I'm calling it this way :
ComputeO(some double, static_cast<bool>(getotype()))
For this static_cast I'm getting a nice:
warning C4800: 'const dmodel::OType ' : forcing value to bool 'true' or 'false' (performance warning)
I don't know how to get rid of it,I specify the cast explicitly shouldnt it be enough ?
Note: I'm using VC11 ( Visual Studio 2012 )
Thks.
A:
See https://msdn.microsoft.com/en-us/library/b6801kcy.aspx, which describes the warning. In particular, it says:
Casting the expression to type bool will not disable the warning,
which is by design.
Just rewrite your call like this:
enum class OType : bool { Dynamic=true, Static=false };
OType getotype();
double ComputeO(double K,bool type);
int main()
{
ComputeO(1.0, getotype() == OType::Dynamic);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server SPID is sleeping or runnable but nothing happens for over an hour
I use SQL Server 2012 BI edition.
I've executed two SQL Agent Jobs that run SSIS packages. Historically, the jobs have been running absolutely fine. Today, the jobs just stopped/hanged just before completing step 1 out of 4.
I've run sp_who2 and nothing is blocking anything. What can I do to "awake" my jobs? Details of sp_who2:
Status sleeping
BlkBy .
Command AWAITING COMMAND
CPUTime 131276
DiskIO 607734
LastBatch 01/12/2017 15:55
The jobs have not failed yet but have not done anything for over an hour.
CPU and RAM do not indicate much activity.
Solution:
It feels iSeries AS/400 (IBM) has corrupted .net framework. Reinstalling .net framework fixed an issue. I hope it helps someone.
A:
It feels iSeries AS/400 (IBM) has corrupted .net framework. Reinstalling .net framework fixed the issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is my Systemd unit arkos-redis loaded, but inactive (dead)?
Here's what I have in my service file, arkos-redis.service:
GNU nano 2.4.2 File: /usr/lib/systemd/user/arkos-redis.service
[Unit]
Description=Advanced key-value store
[Service]
ExecStart=/usr/bin/redis-server /etc/arkos/arkos-redis.conf
ExecStop=/usr/bin/redis-cli shutdown
[Install]
WantedBy=default.target
But when boot I get the following status:
[vagrant@arkos-vagrant etc]$ systemctl --user status arkos-redis.service
��arkos-redis.service - Advanced key-value store
Loaded: loaded (/usr/lib/systemd/user/arkos-redis.service; enabled; vendor preset: enabled)
Active: inactive (dead)
A:
Because your service file is in /usr/lib/systemd/user, it is treated as a user service, and is started by your own instance of systemd (run as systemd --user). This means, among other things, that the process is started under your user, not root, and is started for each user that logs in. Based on the reference to the config file in /etc, I would guess that only one instance of this process should be running at any given time, and that it should run as root (or some other system accout). If this process is supposed to start as root, move this file to /usr/lib/systemd/system (or better yet, /etc/systemd/system, since it's your own service file) and ignore the rest of this answer.
If your service file is supposed to start under your own user, then note that only the following targets are available in user mode:
When systemd runs as a user instance, the following special units are available, which have
similar definitions as their system counterparts: default.target, shutdown.target,
sockets.target, timers.target, paths.target, bluetooth.target, printer.target,
smartcard.target, sound.target.
Neither multi-user.target nor network.target are available, and so your service won't start automatically. If you want it to start, change multi-user.target to default.target, and get rid of After=network.target. Then, run systemctl --user enable arkos-redis.service.
| {
"pile_set_name": "StackExchange"
} |
Q:
MS Access Limit
What's the equivalent of mysql Limit in ms access. TOP is not sufficient since I'm going to use it for pagination.
Thanks
A:
There isn't one. Your best bet is to add an ID column as a primary key (if you don't already have one) and chunk output by looping through:
SELECT * FROM table
WHERE id >= offset AND id <= offset + chunk_size - 1
until you get all the rows.
A:
Curiously, there are a few references in Microsoft documentation to a LIMIT TO nn ROWS syntax for the Access Database Engine:
ACC2002: Setting ANSI 92 Compatibility in a Database Does Not Allow DISTINCT Keyword in Aggregate Functions
About ANSI SQL query mode (MDB)
However, actual testing seems to confirm that this syntax has never existed in a release version of the Access Database Engine. Perhaps this is one of those features that the SQL Server team wanted to put into Jet 4.0 but were ordered to rollback by the Windows team? Whatever, it seem we must simply put it down to a bad documentation error that Microsoft won't take the time to correct :(
If you need to do pagination on the server** side then I suggest you consider a more capable, modern SQL product with better documentation ;)
** conceptually, that is: the Access Database Engine is not a server DBMS.
A:
Since it doesn't appear that you have any type of sequencial unique key number for these rows, you'll need to create a ranking column: How to Rank Records Within a Query
You need to determine how many rows at a time you will return N = (10, 25,100).
You need to keep track of what "page" the user is on and the values of the first and last rank.
Then when you make the call for the next page it is either the next N rows that are > or < the first and last ranks (depending if the users is going to the previous or next page.).
I'm sure there is a way to calculate the last page, first page, etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to apply ModelState.IsValid to just one table of a Data Entity Model?
So I currently have a view that needs an entire data entity for display purposes, but I only want to post data for one table to the controller and validate it.
@model MvcExample.Models.DataEntities
@using(Html.BeginForm("ActionMethod", "Controller")){
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<table id="setupTable">
<tr>
<td>@Html.LabelFor(model => model.DataField.Local.First().data, "Data:")</td>
<td>@Html.TextBoxFor(model => model.DataField.Local.First().data, new{id="dataField"})
@Html.ValidationMessageFor(model => model.DataField.Local.First().dataField)
</td>
</tr>
<input type="submit" value="submit" />
}
Is it possible to post this to an ActionMethod and use ModelState.IsValid?
[ActionName("Setup")]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult ActionMethod(FormCollection formCollection)
{
if( ModelState.IsValid )
{
// Do Stuff
db.SaveChanges();
}
var dataField= new DataField();
db.DataField.Add( dataField);
return View( db );
}
A:
Imagine you have these two models. The MainModel is your entire dataset and the SubsetModel is the data you need to post back to a Controller Action.
public class MainModel
{
public FieldOne First {get;set}
public FieldTwo Second {get;set}
public FieldThree Third {get;set;}
public FieldFour Fourth {get;set;}
}
public class SubsetModel
{
public FieldOne First {get;set;}
public FieldTwo Second {get;set;}
}
your Controller Action can be told to just expect the SubSetModel back on post.
public ActionResult DoSomething(SubsetModel subset)
{
//do something
}
In your View, you need to just have the relevant fields within the form, or use Javascript/JQuery to post the data back to the Controller. As long as the fields in your form has the correct names, the model binder will create the SubsetModel which your action expects
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make "uses-library" optional in android
I have built an android app which use Google Map feature. I want my app installed on phones which does not install Google Map, in that case, I would disable the map feature.
There is a "uses-library" tag in manifest file, what can I do with that?
A:
@CommonsWare: I think you are refering to android:required and not to android:enabled
Something like this:
<uses-library
android:name="com.google.android.maps"
android:required="false" />
| {
"pile_set_name": "StackExchange"
} |
Q:
C# linq Files.ReadAllLines() fails for large 650MB CSV file
The following code works when I work with CSV files under 1MB but fails when I try to read 600MB file. Any reason why? Or any fixes?
What I am trying to do is read a large raw CSV file in Visual C# 2010 and manipulate the contents, could be line by line or to memory at one go and export 5 files with certain selections using LINQ. These 5 files are to be used in various processes so need them to be split into 5 different files with very different content.
When the file is small the codes work perfect but when it's too big it gives me the messagebox from Exception handling "Cannot write to source destination". I have tried both ReadAllLines() and ReadLines() Please could you advise me. Thanks.
public void button2_Click(object sender, EventArgs e)
{
string file_name = textBox1.Text.ToString();
// Get the directories to split the file in.
string directoryPath = Path.GetDirectoryName(textBox1.Text.ToString());
if (File.Exists(file_name) == true)
{
try
{
StreamReader readerfile = new StreamReader(file_name);
var BillSummaryQuery1 =
(from line in File.ReadAllLines(file_name)
let linerecord = line.Split(',').ToList()
select line).ToList();
#region Start Writing BillSummary.CSV
//lines removed
#endregion End writing BillSummary.CSV
#region Start writing Notes.CSV
//lines removed
#endregion Notes.CSV
string message =
"Bill Translated Successfully! \r\nFiles located in: " + directoryPath;
MessageBox.Show(message, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception)
{
string message2 = "Cannot write to source destination";
MessageBox.Show(message2, "Error");
}
}
else
{
MessageBox.Show("No such file exists","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
A:
If you are using a StreamReader, why don't use it ?
public void button2_Click(object sender, EventArgs e)
{
string file_name = textBox1.Text.ToString();
// Get the directories to split the file in.
string directoryPath = Path.GetDirectoryName(textBox1.Text.ToString());
if (File.Exists(file_name) == true)
{
try
{
using (StreamReader reader= new StreamReader(file_name))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{
// Do your stuff
}
}
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
string message2 = "Cannot write to source destination";
MessageBox.Show(message2, "Error");
}
}
else
{
MessageBox.Show("No such file exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
A:
Rolling your own CSV reader is a waste of time unless the files that you're reading are guaranteed to be very simple. Use a pre-existing, tried-and-tested implementation instead.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.