text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Add the values of a text field into an array
I need to add the values typed into the textfield into an array list.
I implemented it as follows:
public class MainActivity extends ActionBarActivity {
Spinner spinner1,spinner2,spinner3;
Button add;
EditText subject;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Spinner element
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner3 = (Spinner) findViewById(R.id.spinner3);
add = (Button) findViewById(R.id.button1);
subject = (EditText) findViewById(R.id.editText1);
// Spinner click listener
//spinner2.setOnItemSelectedListener(this);
//spinner3.setOnItemSelectedListener(this);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
String item = adapter.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(getApplicationContext(),
"Selected Subject : " + item, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
add.setOnClickListener(new OnClickListener() {
Context context;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String content;
content = subject.getText().toString();
List list = new ArrayList();
list.add(content);
ArrayAdapter dataAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
ListIterator it = list.listIterator();
it.hasNext();
}
});
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//do something here
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
//optionally do something here
}
});
}
But , every time I enter a new value in the text field the previous value is overwritten. How do I use arrays to implement this? every time I enter a value I want it to be saved separately in the drop down menu.
A:
The previous value is overwritten because you always adding new list instance into adapter.
So make list instance only once,i.e. globally in your activity.i.e. add this line
List list = new ArrayList();
below to
public class MainActivity extends ActionBarActivity {
Spinner spinner1,spinner2,spinner3;
Button add;
EditText subject;
And use below code in your onClick function. as
String content;
content = subject.getText().toString();
list.add(content);
ArrayAdapter dataAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
| {
"pile_set_name": "StackExchange"
} |
Q:
I am trying to direct print my report
I am using Visual studio 2015. and trying to print my report. my Preview report its working good. but when i am trying to Direct print then its default print of crystal report. i think my function is wrong.
somebody please help me. thanks you.
This is my Preview Code (its Working Good):
Private Function GetDeliveryChallanPreviewPrint() As DataTable
Dim Data As New DataTable
Using conn
Using cmd As New SqlCommand("select * from DcMaster dm
Left join DcDetail dd on dm.ID = dd.ID where dm.id = '" & PrinByIDTextBox.Text.ToString() & "'", conn)
conn.Open()
Using adp As New SqlDataAdapter
adp.SelectCommand = cmd
adp.Fill(Data)
Dim DcPrint As New Rpt_DeliveryChallan
Dim FILEPATH As String = CurDir() & "\Reports\Rpt_DeliveryChallan.rpt"
DcPrint.Load(FILEPATH)
DcPrint.SetDataSource(Data)
CrystalReportViewer1.ReportSource = DcPrint
CrystalReportViewer1.Refresh()
StatusLabel.Visible = False
conn.Close()
End Using
End Using
End Using
End Function
This is my Direct Print Code: (its not Working) Please Help me.
Private Function GetDeliveryChallanDirectPrint() As DataTable
Dim Data As New DataTable
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("VKDBx").ConnectionString)
Using cmd As New SqlCommand("select * from DcMaster dm
Left join DcDetail dd on dm.ID = dd.ID where dm.id = '" & PrinByIDTextBox.Text.ToString() & "'", conn)
conn.Open()
Using adp As New SqlDataAdapter
adp.SelectCommand = cmd
adp.Fill(Data)
Dim DcPrint As New Rpt_DeliveryChallan
Dim FILEPATH As String = CurDir() & "\Reports\Rpt_DeliveryChallan.rpt"
DcPrint.PrintOptions.PrinterName = PrinterComboBox.Text
DcPrint.Load(FILEPATH)
DcPrint.PrintToPrinter(1, False, 0, 0)
DcPrint.SetDataSource(Data)
conn.Close()
End Using
End Using
End Using
End Function
A:
i am doing successfully. just some changing place PrintTOPrinter line Down.
Private Function GetDeliveryChallanPrint() As DataTable
Dim Data As New DataTable
Using conn As New SqlConnection(_SqlCon)
Using cmd As New SqlCommand("select * from DcMaster dm
Left join DcDetail dd on dm.ID = dd.ID where dm.id = '" & PrintByIDLabel.Text.ToString() & "'", conn)
conn.Open()
Using adp As New SqlDataAdapter
adp.SelectCommand = cmd
adp.Fill(Data)
Dim Printrpt As New Rpt_DeliveryChallan
Dim FILEPATH As String = CurDir() & "\Reports\Rpt_DeliveryChallan.rpt"
Printrpt.PrintOptions.PrinterName = PrinterComboBox.Text
Printrpt.Load(FILEPATH)
Printrpt.SetDataSource(Data)
Printrpt.PrintToPrinter(NumberOfCopiesNumericUpDown.Value, False, 0, 0)
End Using
End Using
End Using
End Function
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple sed replace with back reference (parse SQL for joined tables)
I'm trying to parse through some massive SQL query logs using sed and want to extract the names of all the tables that are joined in each query. Here's what I'm trying:
echo '[SQL_STMT="SELECT A FROM TABLEA JOIN TABLEB ON SOMETHING JOIN TABLEC ON SOMETHINGELSE WHERE A = 1"]' \
| sed -e 's/SQL_STMT=.*JOIN \([A-Z0-9_]*\) .*\]$/SQL_JOINS="\1"]/g'
but this only returns the following:
[SQL_JOINS="TABLEC"]
what I'd like to see is something like this:
[SQL_JOINS="TABLEB TABLEC"]
and have it work for any number of joins
So how do I structure the backreference so that it gets all the joined tables?
A:
If you are ok with perl solution, try this:
$ echo "......" | perl -ne '@x=/JOIN (\w+)/g;print "[SQL_JOINS=\""."@x"."\"]";'
On testing with above:
$ echo "[SQL_STMT=\"SELECT A FROM TABLEA JOIN TABLEB ON SOMETHING JOIN TABLEC ON SOMETHINGELSE WHERE A = 1\"]" | perl -ne '@x=/JOIN (\w+)/g;print "[SQL_JOINS=\""."@x"."\"]";'
[SQL_JOINS="TABLEB TABLEC"]
Sed solution:
echo ...|sed -n ':a;/JOIN/{s/[^J]*JOIN \([A-Z0-9_]*\)/\1\n/;P;D;ta}' | sed -e ':a;N;s/\n/ /;ta' | sed 's/.*/[SQL_JOINS=\"&\"]/'
The first sed prints all the table names, the second joins all lines of table names into one, and the last one formats it to get in the required format.
| {
"pile_set_name": "StackExchange"
} |
Q:
Repeated column in mapping for entity: Hiv_AnswerForEntities column: variant_id (should be mapped with insert="false" update="false")
I have problem with inheritance in ORM.
I use JPA/hibernate. I am getting an error that I do not understand. I have declared once column, but error tell me that I've done this twice. It can be messed with inheritance somehow.
But I don't know why. Please help
Error I get:
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: myInsurance.models.liability.hivAndVHProtection.Hiv_AnswerForEntities column: variant_id (should be mapped with insert="false" update="false")
Entities code:
@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Answer extends Generic<Answer> {
@OneToOne public Variant variant;
}
@Entity
@DiscriminatorValue("Answer")
@Table(name="mi__Liability_Part_Hiv_Answer")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class Hiv_Answer extends Answer {
@OneToOne public HivAndVHProtection_Variant variant;
}
@Entity
@DiscriminatorValue("AnswerForEntities")
public class Hiv_AnswerForEntities extends Hiv_Answer {
public int proffesionGroup;
public int personCount;
public int contributionPerPerson;
@Transient public int totalContribution;
}
And full stack trace:
play.api.UnexpectedException: Unexpected exception[PersistenceException: [PersistenceUnit: defaultPersistenceUnit] Unable to build EntityManagerFactory]
at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1$$anonfun$1.apply(ApplicationProvider.scala:148) ~[play_2.10.jar:2.2.6]
at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1$$anonfun$1.apply(ApplicationProvider.scala:112) ~[play_2.10.jar:2.2.6]
at scala.Option.map(Option.scala:145) ~[scala-library.jar:na]
at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1.apply(ApplicationProvider.scala:112) ~[play_2.10.jar:2.2.6]
at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1.apply(ApplicationProvider.scala:110) ~[play_2.10.jar:2.2.6]
at scala.util.Success.flatMap(Try.scala:200) ~[scala-library.jar:na]
at play.core.ReloadableApplication$$anonfun$get$1.apply(ApplicationProvider.scala:110) ~[play_2.10.jar:2.2.6]
at play.core.ReloadableApplication$$anonfun$get$1.apply(ApplicationProvider.scala:102) ~[play_2.10.jar:2.2.6]
at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24) ~[scala-library.jar:na]
at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24) ~[scala-library.jar:na]
at scala.concurrent.forkjoin.ForkJoinTask$AdaptedRunnableAction.exec(ForkJoinTask.java:1361) ~[scala-library.jar:na]
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260) ~[scala-library.jar:na]
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339) ~[scala-library.jar:na]
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979) ~[scala-library.jar:na]
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107) ~[scala-library.jar:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: defaultPersistenceUnit] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915) ~[hibernate-entitymanager-4.2.0.CR1.jar:4.2.0.CR1]
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:890) ~[hibernate-entitymanager-4.2.0.CR1.jar:4.2.0.CR1]
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:57) ~[hibernate-entitymanager-4.2.0.CR1.jar:4.2.0.CR1]
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63) ~[hibernate-jpa-2.0-api.jar:1.0.1.Final]
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47) ~[hibernate-jpa-2.0-api.jar:1.0.1.Final]
at play.db.jpa.JPAPlugin.onStart(JPAPlugin.java:35) ~[play-java-jpa_2.10.jar:2.2.6]
at play.api.Play$$anonfun$start$1$$anonfun$apply$mcV$sp$1.apply(Play.scala:88) ~[play_2.10.jar:2.2.6]
at play.api.Play$$anonfun$start$1$$anonfun$apply$mcV$sp$1.apply(Play.scala:88) ~[play_2.10.jar:2.2.6]
at scala.collection.immutable.List.foreach(List.scala:318) ~[scala-library.jar:na]
at play.api.Play$$anonfun$start$1.apply$mcV$sp(Play.scala:88) ~[play_2.10.jar:2.2.6]
at play.api.Play$$anonfun$start$1.apply(Play.scala:88) ~[play_2.10.jar:2.2.6]
at play.api.Play$$anonfun$start$1.apply(Play.scala:88) ~[play_2.10.jar:2.2.6]
at play.utils.Threads$.withContextClassLoader(Threads.scala:18) ~[play_2.10.jar:2.2.6]
at play.api.Play$.start(Play.scala:87) ~[play_2.10.jar:2.2.6]
at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1$$anonfun$1.apply(ApplicationProvider.scala:139) ~[play_2.10.jar:2.2.6]
... 14 common frames omitted
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: myInsurance.models.liability.hivAndVHProtection.Hiv_AnswerForEntities column: variant_id (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:682) ~[hibernate-core-4.2.0.CR1.jar:4.2.0.CR1]
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:704) ~[hibernate-core-4.2.0.CR1.jar:4.2.0.CR1]
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:726) ~[hibernate-core-4.2.0.CR1.jar:4.2.0.CR1]
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:479) ~[hibernate-core-4.2.0.CR1.jar:4.2.0.CR1]
at org.hibernate.mapping.UnionSubclass.validate(UnionSubclass.java:61) ~[hibernate-core-4.2.0.CR1.jar:4.2.0.CR1]
at org.hibernate.cfg.Configuration.validate(Configuration.java:1283) ~[hibernate-core-4.2.0.CR1.jar:4.2.0.CR1]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1734) ~[hibernate-core-4.2.0.CR1.jar:4.2.0.CR1]
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94) ~[hibernate-entitymanager-4.2.0.CR1.jar:4.2.0.CR1]
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:905) ~[hibernate-entitymanager-4.2.0.CR1.jar:4.2.0.CR1]
... 28 common frames omitted
--EDIT--
All my Variant classes that I use As relation in my Entities
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Variant extends GenericDictionary<Variant> {}
@Entity
@Table(name="mi__Liability_Part_Hiv_Var")
public class HivAndVHProtection_Variant extends Variant {
@OneToMany public List<HivAndVHProtection_VariantValue> hivAndVHProtection_VariantValue = new LinkedList<HivAndVHProtection_VariantValue>();
}
@Entity
@Table(name="mi__Liability_Part_Legal_Var")
public class LegalExpensesInsurance_Variant extends GenericDictionary<LegalExpensesInsurance_Variant> {
@OneToMany private List<LegalExpensesInsurance_VariantValue> legalExpensesInsurance_VariantValues = new LinkedList<LegalExpensesInsurance_VariantValue>();
}
All of this Variant like classes extends superclass Variant
I've tried also:
@OneToOne public Class<? extends Variant> variant;
but getting an error:
Caused by: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on myInsurance.models.liability.hivAndVHProtection.Hiv_Answer.variant references an unknown entity: java.lang.Class
A:
In Answer you have
@OneToOne public Variant variant;
And in Hiv_Answer you have
@OneToOne public HivAndVHProtection_Variant variant;
Join column's name for both of these mappings defaults to variant_id, in which case JPA forces you to mark one of them with insertable = "false", updateable = "false" because you can't maintain the same field through multiple mappings.
Your options are:
Change variable name variant to something else in one of these mappings (preferred)
Use @JoinColumn on at least one mapping to specify a different join column instead of the default one (variant_id)
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS dropdown menu - 3rd level issue
Ive got a 3 leve dropdown menu and the 3rd level sub-menu displays next to the 2nd level menu item like it should, except for a gap.
The 2nd level is set to a width of 100px so I've absolutely positioned the 3rd level to top:0, left:100px so it displays to the right of the 2nd level, but there's a gap. If I change left:100px to left:97px there is no gap. Why is this?
The HTML:
<nav>
<ul>
<li><a href="#">Menu 1</a></li>
<li><a href="#">Menu 2</a>
<ul>
<li><a href="#">Sub-Menu 1</a></li>
<li><a href="#">Sub-Menu 2</a></li>
<li><a href="#">Sub-Menu 3</a></li>
</ul>
</li>
<li><a href="#">Menu 3</a></li>
<li><a href="#">Menu 4</a>
<ul>
<li><a href="#">Sub-Menu 1</a></li>
<li><a href="#">Sub-Menu 2</a></li>
<li><a href="#">Sub-Menu 3</a>
<ul>
<li><a href="#">Sub-Menu 4</a></li>
<li><a href="#">Sub-Menu 5</a></li>
<li><a href="#">Sub-Menu 6</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Menu 5</a></li>
</ul>
</nav>
The CSS:
/* Initialise for 3 tiers */
nav ul, ul li ul, ul li ul li ul {
margin:0;
padding:0;
}
nav ul li, ul li ul li, ul li ul li ul li {
list-style-type:none;
float:left;
}
/* Link Appearance for 3 tiers */
nav ul li a, ul li ul li a, ul li ul li ul li a {
text-decoration:none;
color:#fff;
background:#666;
padding:5px 10px;
float:left;
}
nav ul li a:hover, ul li ul li a:hover, ul li ul li ul li a:hover {
background:#C00;
}
/* 2nd Tier */
nav ul li {
position:relative;
}
nav ul li > ul {
display:none;
position:absolute;
top:30px;
left:0;
width:100px;
}
nav ul li:hover > ul{
display:block;
}
/* 3rd Tier */
nav ul li ul li {
position:relative;
}
nav ul li ul li:hover > ul {
display:block;
}
nav ul li ul li ul {
display:none;
position:absolute;
top:0;
left:100px;
}
JSFiddle
A:
The issue is the gap between the menus. They need to be adjacent or even overlap for this hover trick to work.
So instead of specifying
left: 100px;
do something like
left: 100%;
/* or even */
left: 99%;
This will cause the 3rd layer to be adjacent to the second layer menu, or even overlap the second slightly (for 99%), allowing you to move the mouse without any interruptions that close the menu. And you won't have to worry about the width of the menus either.
Updated fiddle: http://jsfiddle.net/tqEfW/5/
If you want to keep the gap for the look of it, you can give the 3rd layer ul a padding:
nav ul li ul li ul {
....
left: 100%;
padding-left: 4px;
}
Ad demonstrated here: http://jsfiddle.net/tqEfW/9/
That said, from a UX point of view, menus with 3 layers are very hard to use and should be avoided when possible.
| {
"pile_set_name": "StackExchange"
} |
Q:
Failed to send direct email message via aws Pinpoint
I am trying to send email message to a specific email address via the aws pinpoint. My from email address is verified. However, whenever I try to send the email it gives me an error "Failed to submit email message to ". I don't understand where am I going wrong with this.
A:
@Krishna gave the right clue, however to be precise, all of the following must be true:
Your From email address is verified in Amazon Pinpoint/SES.
Either your To email address(es) is verified, OR you have requested Sending Limit Increase specifically for Amazon Pinpoint, not just SES.
In my case it was problem no. 2, I have increased my sending limit for SES but not Pinpoint yet. Amazon treats them somewhat differently, however the error message it gave me was totally undecipherable:
Message not sent: We weren't able to send your email message to [email protected]. Request Id 982 : Failed to send message.
Specifically, check the Pinpoint project's right sidebar here:
A:
By default Pinpoint provides an sandbox environment.
In order to send emails you need to white-list your from email address as well. ( i.e. got to SES and verify the from email id as well)
You should them be able to send emails via Pinpoint.
The receiver should acknowledge to terms and condition that AWS can send automated emails.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get data from XML file Python
<Fruits>
<Fruit>
<Family>Citrus</Family>
<Explanation>this is a Citrus fruit.</Explanation>
<Type>Orange</Type>
<Type>Lemon</Type>
</Fruit>
</Fruits>
I want to extract the Explanation of this XML code and assign it to both fruits(Type) next to them. This is my code:
import os
from xml.etree import ElementTree
file_name = "example.xml"
full_file = os.path.abspath(os.path.join("xml", file_name))
dom = ElementTree.parse(full_file)
Fruit = dom.findall("Fruit")
for f in Fruit:
Type = f.find("Type").text
Explanation = f.find("Explanation").text
print (Type, Explanation)
I am just getting the result for the first fruit of the tree structure.
Orange, this is a Citrus fruit.
But I would like to get all types with their explanation assigned next to it. Therefore the result should look like this:
Orange, this is a Citrus fruit.
Lemon, this is a Citrus fruit.
A:
You're looping through the Fruit element, not the types within. So, you would need to do something like this (there are other ways, too) to get those results:
import os
from xml.etree import ElementTree
file_name = "example.xml"
full_file = os.path.abspath(os.path.join("xml", file_name))
dom = ElementTree.parse(full_file)
Fruit = dom.findall("Fruit")
for f in Fruit:
Explanation = f.find("Explanation").text
Types = f.findall("Type")
for t in Types:
Type = t.text
print ("{0}, {1}".format(Type, Explanation))
| {
"pile_set_name": "StackExchange"
} |
Q:
Java retainAll() not working?
Let's say I have two Arraylists.
a.add("Isabella");
a.add("Angelina");
a.add("Pille");
a.add("Hazem");
b.add("Isabella");
b.add("Angelina");
b.add("Bianca");
a.retainAll(b);
This should give me Arraylist a with the following elements: Isabella, Angelina, Pille, Hazem. But, when I try a.size() I get 0. Why?
My output:
[DEBUG] The Karate Kid
[DEBUG] The Day the Earth Stood Still
[DEBUG] The Pursuit of Happyness
[DEBUG] Justin Bieber: Never Say Never
[DEBUG] After Earth
[DEBUG] Independence Day
[DEBUG] Men in Black
[DEBUG] Men in Black II
[DEBUG] Hancock
[DEBUG] Shark Tale
[DEBUG] Made in America
[DEBUG] Six Degrees of Separation
[DEBUG] Jersey Girl
[DEBUG] The Legend of Bagger Vance
[DEBUG] Men in Black 3
[DEBUG] Seven Pounds
[DEBUG] Bad Boys II
[DEBUG] Bad Boys 3
[DEBUG] Enemy of the State
[DEBUG] Wild Wild West
[DEBUG] Hitch
[DEBUG] Ali
[DEBUG] I, Robot
[DEBUG] Live 8
[DEBUG] Where The Day Takes You
[DEBUG] Independence Day 3
[DEBUG] I, Robot 2
[DEBUG] The Pursuit of Happyness
[DEBUG] I Am Legend
[DEBUG] Independence Day 2
[DEBUG] After Earth
[DEBUG] Bad Boys
[DEBUG] Partners in Time: The Making of MIB 3
[DEBUG] David Blaine: Real or Magic
[DEBUG] Size: 0
The first part are films starring Jaden Smith, and second are films starring Will Smith, I want only films that have both. Is retainAll() the best method for this kind of work?
A:
I suspect that you are storing instances of your own class in the lists and not Strings.
retainAll compares the content using the equals method. If you are storing instances of your own class and that class do not override equals it will compare references. Since you do not have the same instance in both lists (but rather different instances, which contain the same value), it will remove all movies from the first list.
You can prevent this by implementing equals in your class. To do this you can take a look at this answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fixing "unknown runtime error" in IE8
I don't see anyone else really trying to accomplish what I am...
LOADS of people want to replace some node via innerHTML property however, I not only want to do this but I ALSO want to replace it with javascript.
Here is my example script which is working fine in all versions of Firefox:
http://syn4k.site90.net/working_test/
EDIT: If the above link does not work, try this one: http://www.syn4k.freehosting.com/working_test/
You will note that it is NOT working in IE8. I'm guessing it is not working in any version of IE...
The process I have created at the link is simple:
1. The user clicks to being the process.
2. A new window is opened.
3. Data from the new window is sent back to the opener and inserted into the DOM.
3.note. The data being sent back is javacript and should execute as it does in Firefox.
A:
I got a look before your hosting went dowm; You cannot set innerHTML of a script node in IE, instead you need to newdiv.text = your_string_with_js; (or append a createTextNode() to it).
| {
"pile_set_name": "StackExchange"
} |
Q:
Filtering xts objects in Shiny apps
I'd like to display a basic Shiny dygraph in my Rmarkdown that toggles between networks. Here is a sample of the data:
> head(df)
nightTrips dayTrips network
2014-05-03 0 16 1
2014-05-04 0 5 1
2014-05-05 0 8 1
2014-05-06 0 3 1
2014-05-07 0 0 1
2014-05-08 0 3 1
> nrow(df)
[1] 2239
If I subset the dataframe df where network=1, I can successfully render a dygraph for a single network with:
> head(test)
nightTrips dayTrips
2014-05-03 0 16
2014-05-04 0 5
2014-05-05 0 8
2014-05-06 0 3
2014-05-07 0 0
2014-05-08 0 3
dygraph(test, main = "Network1") %>%
dySeries("nightTrips", label = "Night Trips") %>%
dySeries("dayTrips", label = "dayTrips") %>%
dyOptions(stackedGraph = FALSE) %>%
dyRangeSelector(height = 20)
But when I bind my data into one dataframe, add an extra column netowrk that specifies network, convert it to an xts object, and try to start a Shiny server - I get an error that a filter cannot be applied to xts object:
Is there a known workaround for this issue?
Here is the code for the inline Shiny app:
```{r, echo = FALSE}
shinyApp(
ui = fluidPage(
titlePanel("Sample Timeseries"),
sidebarLayout(
sidebarPanel(
uiOutput("networknames")
),
mainPanel(
dygraphOutput("networksgraph"))
)
),
server = function(input, output) {
data <- df
data <- as_xts(data, date_col = day)
output$networksgraph <- renderDygraph({
if (is.null(input$networkname)) return (NULL)
filtered <- filter(data,
network == intput$networkname) %>%
dygraph()
})
output$networknames <- renderUI({
selectInput("networkname", "Select your Network",
choices = c(1,2,3))
})
}
)
```
A:
The problem of applying dplyr functions to xts objects was identified but maybe has not been solved. If your dygraph() function has nothing to do with the time index, then you can simply use the coredata() as in filtered <- filter(coredata(data), network == intput$networkname). In the other case, you have to convert back and forth between xts and data.frame.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert following code from C to VB.NET
Hey guys,
Can you please give me a hand to convert the following C code into VB.NET. I have a feeling it would be pretty simple... but my C knowledge is very very limited!
Any help would be great!
Thanks
buf[0] = (num1 & 0xff000000) >> 24;
buf[1] = (num1 & 0xff0000) >> 16;
buf[2] = (num1 & 0xff00) >> 8;
buf[3] = num1 & 0xff;
buf[4] = (num2 & 0xff000000) >> 24;
buf[5] = (num2 & 0xff0000) >> 16;
buf[6] = (num2 & 0xff00) >> 8;
buf[7] = num2 & 0xff;
strncpy(buf+8, headers->key3, 8);
buf[16] = '\0';
md5_buffer(buf, 16, target);
target[16] = '\0';
A:
byte[] temp1 = BitConvert.GetBytes(num1);
byte[] temp2 = BitConvert.GetBytes(num2);
Array.Copy(temp1, 0, buf, 0, 4);
Array.Copy(temp2, 0, buf, 4, 4);
Array.Copy(buf, 8, headers.key3, 0, 8)
buf[16] = 0;
Array.Copy(buf, target, 16)
target[16] = 0;
Using MD5 hasher = new MD5CryptoServiceProvider()
target = hasher.ComputeHash(buf);
End Using
| {
"pile_set_name": "StackExchange"
} |
Q:
Como movimentar animação em sentido horário?
Bom galera, estou desenvolvendo um projetinho que visa simular o ambiente controlado de trilhos de trem, onde tenho 3 trens circulando em sentido horário, onde os três passam pelo mesmo local em determinados trechos. Minha dúvida primeiramente é, como fazer a movimentação desses trens que na figura abaixo representei por quadrinhos, e consequentemente poder alterar a velocidade de cada um dos mesmo.
No meu código, tem apenas a parte gráfica, porque justamente não sei desenvolver a animação dos objetos.
public class SistemasOperacionais extends JFrame {
public SistemasOperacionais(){
setSize(1200,900);
setTitle("Semáforo");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics g){
g.drawRect(300, 100, 300, 170);
g.fillRect(350, 95, 10, 10);
g.drawRect(600, 100, 300, 170);
g.fillRect(650, 95, 10, 10);
g.drawRect(450, 270, 300, 170);
g.fillRect(445, 330, 10, 10);
}
public static void main(String[] args) {
new SistemasOperacionais();
}
}
A:
Consegui assim:
package trens;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Trens {
private static final double QUADROS_POR_SEGUNDO = 20.0;
public static void preparar() {
JFrame t = new JFrame();
t.setLayout(null);
t.setSize(1200, 900);
t.setTitle("Semáforo");
t.setLocationRelativeTo(null);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Trilho t1 = new Trilho(300, 100, 300, 170);
Trilho t2 = new Trilho(600, 100, 300, 170);
Trilho t3 = new Trilho(450, 270, 300, 170);
Trem a = new Trem(t1, Color.BLUE, 350, 100, -170.0);
Trem b = new Trem(t2, Color.GREEN, 650, 100, 0.5);
Trem c = new Trem(t3, Color.RED, 450, 335, 44.0);
t.add(a);
t.add(b);
t.add(c);
t.add(t1);
t.add(t2);
t.add(t3);
Runnable moverTudo = () -> {
EventQueue.invokeLater(() -> {
a.mover(1 / QUADROS_POR_SEGUNDO);
b.mover(1 / QUADROS_POR_SEGUNDO);
c.mover(1 / QUADROS_POR_SEGUNDO);
});
};
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(moverTudo, 0, (int) (1000 / QUADROS_POR_SEGUNDO), TimeUnit.MILLISECONDS);
t.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(Trens::preparar);
}
public static class Trilho extends JComponent {
public Trilho(int x, int y, int width, int height) {
this.setBounds(x, y, width, height);
this.setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
}
public static class Trem extends JComponent {
private Color cor;
private Trilho trilho;
private int x;
private int y;
private double velocidade; // pixels por segundo
private double restante; // Frações de pixels que faltou andar.
public Trem(Trilho trilho, Color cor, int x, int y, double velocidade) {
this.trilho = trilho;
this.cor = cor;
this.x = x;
this.y = y;
this.velocidade = velocidade;
this.setBounds(x - 5, y - 5, 10, 10);
}
@Override
public void paintComponent(Graphics g) {
g.setColor(cor);
g.fillRect(0, 0, getWidth(), getHeight());
}
public void mover(double deltaT) {
if (velocidade == 0) return;
boolean sentidoHorario = velocidade > 0;
double distancia = Math.abs(restante + velocidade * deltaT);
int tLeft = trilho.getX();
int tTop = trilho.getY();
int tRight = tLeft + trilho.getWidth();
int tBottom = tTop + trilho.getHeight();
for (int i = 0; i < (int) distancia; i++) {
// Se deve ir à esquerda:
if (x > tLeft && y == (sentidoHorario ? tBottom : tTop)) {
x--;
// Se deve ir à direita:
} else if (x < tRight && y == (sentidoHorario ? tTop : tBottom)) {
x++;
// Se deve ir para cima:
} else if (y > tTop && x == (sentidoHorario ? tLeft : tRight)) {
y--;
// Se deve ir para baixo:
} else if (y < tBottom && x == (sentidoHorario ? tRight : tLeft)) {
y++;
// Se não for nenhum dos anteriores, o trem está descarrilhado. Coloca de novo no trilho.
} else {
x = tLeft;
y = tTop;
}
}
restante = distancia % 1;
setLocation(x - 5, y - 5);
}
}
}
A velocidade da animação (não a dos trens) é definida por aquela constante QUADROS_POR_SEGUNDO. Como está definida em 20, ele vai (re)calcular a posição dos objetos 20 vezes por segundo. Utilizo o Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(...) para chamar um Runnable a cada 1/20 segundos, arredondado em um número inteiro de milisegundos (ou seja, se você quiser 30 quadros por segundo, ele daria 33 milissegundos por quadro, e não 331/3 milissegundos por quadro).
O trem azul está a uma velocidade de -170.0 pixels por segundo. Ou seja, ele vai bem rápido no sentido anti-horário.
O trem vermelho está a uma velocidade de 44.0 pixels por segundo no sentido horário.
O trem verde está a uma velocidade de 0.5 pixels por segundo. Ou seja, ele se move bem lentamente no sentido horário. Coloquei este valor pequeno para comprovar que ele funciona corretamente mesmo se a velocidade for menor que um pixel a cada passo e que ele não acaba nem ficando parado e nem forçando um movimento em cada quadro de animação.
Observe que tenho uma classe para o Trem e uma para o Trilho. Ambas herdam de JComponent, e portanto, são componentes Swing e desenhados pelo Swing. Onde é necessário, eu sobreescrevo o método paintComponent, e não o paint.
Utilizo as chamadas a EventQueue.invokeLater para não manipular objetos Swing fora da EDT. Há três threads aqui: a EDT, a thread principal e a thread do Executors. Assim sendo, para que os componentes sejam manipulados apenas na EDT, as outras duas threads executam todo o seu trabalho apenas através do EventQueue.invokeLater.
Já o método mover da classe Trem descobre em que parte do trilho o trem está e move ele na direção adequada. A abordagem que usei não é a mais eficiente, mas deve funcionar no seu caso. Essa abordagem consiste em calcular a posição iterativamente, pixel a pixel de acordo com a velocidade, a fim de que as curvas dos trilhos sejam obedecidas. A abordagem ideal calcularia a posição final sem precisar usar um for para isso.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multi-Step Image Submission To Load Balanced Server Problem
We have two apache/php web servers load balanced with squid page caching proxy. The squid caching is not active on image submission pages. We have a form where users can submit images.
It's a two step process. They first upload the images. The second step they can enter details about the images and images are then moved over to correct folders once they submit the image details.
Problem is when there is high traffic the second step might be served from a different server then the one with the uploaded images. So the second step might not find the uploaded images and upload fails to complete.
We have thousands of image files on these servers so the syncing between them is slow. Is there anyway that we can force a specific page to always to be served from a specific server? Basically to bypass the load balancing feature.
A:
There are a few solutions to this.
Switch to nginx as a reverse proxy and you can stick clients to the host
Make the upload directory a NFS share mounted on both hosts
Upload the file into a mysql table (probarbly best to use a hash table) so both servers can access it.
Personally I would go with option 1 as you still get round robin load balancing, but each connection is stuck to the host that it was initially connected to.
Option 2 has the benefit of still equally balancing requests, but the downside is the NFS share is a single point of failure.
Option 3 can cause issues if there is not enough ram on the DB server if you use a hash table.
| {
"pile_set_name": "StackExchange"
} |
Q:
div resized according to the number of divs in a row
I'm currently building an online editor, and I was wondering if it is possible to resize a <div> according to the number of divs that are not in a display:none state.
For example, I have a row with three div columns, each of them are 32% large, I want that if one is in a display:none state the two others will be 48% large.
So the code I have is in the html:
<input type="checkbox" onclick="showHide('.text1')" checked="" />
<input type="checkbox" onclick="showHide('.text2')" checked="" />
<input type="checkbox" onclick="showHide('.text3')" checked="" />
<div id="line1">
<div id="text1"></div>
<div id="text2"></div>
<div id="text3"></div>
</div>
and in the javascript only this using jquery:
function showHide(divId)
{$(divId).slideToggle('slow');}
What I want is that when I uncheck any of the text, the two other remaining go from 33% to 50%, and if another one is removed from 50% to 100%.
A:
If your HTML is something like this:
<div class="container">
<div></div>
<div></div>
<div></div>
</div>
After you've applied the display values, you could use :visible to figure out how many elements are visible, and apply a width based on that:
// select visible children
var visibleDivs = $('.container div:visible');
// use whatever width calculation you'd like...
var targetWidth = 100 / visibleDivs.length - 1;
// apply the width to the divs
visibleDivs.width(targetWidth);
| {
"pile_set_name": "StackExchange"
} |
Q:
Re-sizing the partition after installing Ubuntu
So I just finished installing Ubuntu (13.10) alongside Windows 7 (on the same hard drive). However, I ran into a small problem when I was installing that had to do with the partition sizes. I wanted my partitions to look like this:
/dev/sda
/dev/sda1 (Windows Reserved Partition)
/dev/sda2 (Windows Partition C:)
/dev/sda3 (Ubuntu SWAP)
/dev/sda4 (Ubuntu ROOT)
/dev/sda5 (Ubunutu (HOME)
But unfortunately, I was unable to make more than 2 more partitions due to "unusable space" which I figured out was due to not being able to have more than 4 partitions. So now I have:
/dev/sda
/dev/sda1 (Windows Reserved Partition)
/dev/sda2 (Windows Partition C:)
/dev/sda3 (Ubuntu SWAP)
/dev/sda4 (Ubuntu ROOT)
Is there any way to go about fixing this or should I not be worried about this kind of thing? Sorry, I'm pretty new to Linux in general.
EDIT:
After doing sudo parted -i, this is what I get:
Model: ATA WDC WD5000BPVT-2 (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/4096B
Partition Table: msdos
Number Start End Size Type File system Flags
1 1049kB 106MB 105MB primary ntfs boot
2 106MB 395GB 395GB primary ntfs
3 395GB 397GB 2000MB primary linux-swap(v1)
4 397GB 500GB 103GB primary ext4
A:
The restriction to 4 primary partitions is not specifically a Linux thing but bound to the used MBR partitioning scheme in general.
To overcome this limitation, extended partitions was invented.
So what you actually want is this:
/dev/sda
/dev/sda1 (Windows Reserved Partition)
/dev/sda2 (Windows Partition C:)
/dev/sda3 (Ubuntu SWAP)
/dev/sda4 <- Extended partition
/dev/sda5 (Ubuntu ROOT) <- Logical partition
/dev/sda6 (Ubunutu (HOME)) <- Logical partition
Some good documentation is found here: https://help.ubuntu.com/community/HowtoPartition
| {
"pile_set_name": "StackExchange"
} |
Q:
Existence of a parallel vector field
I came across the following sentence in a comment on this
question: Local existence of parallel vector field
"the existence of a parallel vector field is equivalent to the condition that the metric splits locally into a Riemannian product of a one-dimensional manifold and an (n−1)-dimensional one. This implies, in particular, that the sectional curvatures of planes containing V are all zero."
and I want to know what the poster mean by the metric splitting locally into a Riemannian product and what that has to do with sectional curvatures.
A:
The metric splitting locally means that you can pick local coordinates around any point $p$ such that in those coordinates, the metric tensor looks like a block matrix which is the direct sum of a $1 \times 1$ matrix and an $(n-1) \times (n-1)$ matrix. Observe that this isn't very hard to do for a single point, in fact, at a point, the key information we're getting out of this is that we can write the metric tensor in this form in an entire neighbourhood.
In particular, this implies that if we just restrict our attention to the coordinate neighbourhood, the neighbourhood can be written as a product of a $1$-dimensional Riemannian manifold, and an $(n-1)$-dimensional Riemannian manifold, since the metric decomposes in a nice manner.
Now if you pick any pair of orthogonal vectors at $p$, one of which is the tangent vector corresponding to the $1$-dimensional subspace, and flow along all linear combinations of the two vectors, you'll span out a surface whose scalar curvature is the sectional curvature along the two vectors. The key point to note here is that the Riemannian metric on the spanned surface will essentially be the Euclidean metric, which has $0$ scalar curvature, which means you're done.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Travis-CI for Node.js project
I'm trying to set up travis-ci for my node.js project hosted on github. For some reason travis keeps using ruby worker for building/testing the project.
My .travis.yml looks like:
language: node_js
node_js:
- 0.6
script:
- "make test"
What am I missing?
A:
OK got it.
The .travis.yml file must not contain 'tab' characters. Instead I have replaced them with spaces.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mapping the most gentle route for my single speed
I commute to work on a single-speed road bike, so it's a lot easier if I avoid any steep hills (preferring to cover the same gradient gradually). Taking a look at a map, there are seemingly 3-4 sensible routes to get from point A to point B. Short of trying them all, is there any way to evaluate which has the most gradual climb?
A:
That's 4 days to evaluate all the routes. I'd just ride them. You can spend a lot of time with mapping tools trying to evaluate gradients and still get it wrong. Unless you can find a cycling guide that discusses the issue you will almost certainly not get a good answer. For a motor transport engineer (the people who design roads) anything under 1:10 is fine on a minor road, 1:20 on a major road. They just don't care about short steep sections vs long gentle sections. The flattest route could easily be the one where you come out of a compulsory stop onto a short steep section that climbs less than the 5m interval between contours on a most-detailed map.
One electronic solution would be to use google streetview to survey each route. Look at the angle between the street and the vertical walls or horizontal floors. That will give you a rough idea of the slope of the road at each point.
A:
A lot of the online mapping websites have elevation data you can use to figure it out.
Example 1: Go to http://maps.google.com/ choose the bicycle icon and ask for directions. Once it gives you the map, switch to the "map" instead of satellite view and turn on the terrain overlay. When you ask for bicycle directions it tries to avoid steep climbs and the terrain data overlay can give you some idea how bad things are. You can drag points on the route to force it into giving you a specific route.
Example 2: Go to http://www.mapmyride.com/ -- go through the annoying interface to create a new ride (there's some annoying ad stuff). Once you've done that, you can see some data including a graph of the climbs. Do that for all the routes and compare side by side.
There's a lot of competing websites for that kind of thing that you can search for out there.
A:
A very good solution is Google Earth. If you create a route (either create one or get a recorded track from a GPS device), you can see it's elevation profile (right click on the route and "Show Elevation Profile"):
The profiling is interactive and linked to the map, so you can easily see where the "problem" (eg too high elevation) is on the map and modify your track accordingly.
| {
"pile_set_name": "StackExchange"
} |
Q:
in Rails, database call works in development but stalls in test
I am running a test for a controller method as shown below:
it "should assigns an instance var @items including my item" do
@item = FactoryGirl.create(:item)
get :index
response.should include(@item)
end
The controller method is:
def index
@Item = Item.select_items
end
where select_items is a scope method in the Items model:
scope :select_items, where(Items.arel_table[:select_field].not_eq(nil))
In development, this works fine. In test however, I get
A 500 error when I test the controller method itself in the console
No error when I simply test the model method in the console
A permanent hang when I run the spec
In test.log, the hang happens at the last line of the following:
Connecting to database specified by database.yml
Admin Load (0.5ms) SELECT `admins`.* FROM `admins`
(0.6ms) RELEASE SAVEPOINT active_record_1
(0.2ms) SAVEPOINT active_record_1
SQL (1.1ms) INSERT INTO `items` (`various fields')
(0.1ms) RELEASE SAVEPOINT active_record_1
Processing by Admin::ItemsController#index as HTML
Admin Load (0.4ms) SELECT `admins`.* FROM `admins` WHERE `admins`.`id` = 1 LIMIT 1
Rendered admin/items/index.haml within layouts/tabs (0.2ms)
Completed 200 OK in 15ms (Views: 3.9ms | ActiveRecord: 0.4ms)
Item Load (1.2ms) SELECT `items`.* FROM `items` WHERE (`item`.`select_field` IS NOT NULL) LIMIT 25 OFFSET 0
If I run the test in rspec, the spec stops at this point. Why?
A:
Your test should be like this:
it "should assigns an instance var @items including my item" do
@item = FactoryGirl.create(:item)
get :index
assigns(:Item).should include(@item)
end
Your controller assigned an instance variable, and that is how you access them. The response holds a lot of information you probably never need to look at in your test. The exception is if you are returning things like JSON or XML, in which case you'd look at response.body.
In addition, considering your controller instance variable is grabbing possible multiple items, you should name your variable @Items, pluralized. Furthermore, you never capitalize instance variables, so it should be @items. And lastly for nitpicky things, in your test, you don't need to make @item an instance variable as it exists just for your single it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Search keyword highlight in ASP.Net
I am outputting a list of search results for a given string of keywords, and I want any matching keywords in my search results to be highlighted. Each word should be wrapped in a span or similar. I am looking for an efficient function to do this.
E.g.
Keywords: "lorem ipsum"
Result: "Some text containing lorem and ipsum"
Desired HTML output: "Some text containing <span class="hit">lorem</span> and <span class="hit">ipsum</span>"
My results are case insensitive.
A:
Here's what I've decided on. An extension function that I can call on the relevant strings within my page / section of my page:
public static string HighlightKeywords(this string input, string keywords)
{
if (input == string.Empty || keywords == string.Empty)
{
return input;
}
string[] sKeywords = keywords.Split(' ');
foreach (string sKeyword in sKeywords)
{
try
{
input = Regex.Replace(input, sKeyword, string.Format("<span class=\"hit\">{0}</span>", "$0"), RegexOptions.IgnoreCase);
}
catch
{
//
}
}
return input;
}
Any further suggestions or comments?
| {
"pile_set_name": "StackExchange"
} |
Q:
Count elements in recursive list
How can I count elements in recursive list?
Here is data, but it could be bigger list.
data <- list(list(list("a"), list("b"), list("c","d","e")), list("f"))
> str(data)
List of 2
$ :List of 3
..$ :List of 1
.. ..$ : chr "a"
..$ :List of 1
.. ..$ : chr "b"
..$ :List of 3
.. ..$ : chr "c"
.. ..$ : chr "d"
.. ..$ : chr "e"
$ :List of 1
..$ : chr "f"
On output I want to have vector with % usage which sums to 100%:
o <- c(1/2/3/1, 1/2/3/1, 1/2/3/3, 1/2/3/3, 1/2/3/3, 1/2/1)
[1] 0.16666667 0.16666667 0.05555556 0.05555556 0.05555556 0.50000000
sum(o)
[1] 1
So I need v1 (is just rep of allocation = 100%):
v1 <- rep(1, length( unlist(data) ))
v1
[1] 1 1 1 1 1 1
v2:
> v2 <- rep(length(data), length( unlist(data) ))
> v2
[1] 2 2 2 2 2 2
v3,
> v3 = c(3, 3, 3, 3, 3, 1)
v4:
v4 = c(1, 1, 3, 3, 3, 1)
etc.
In result:
> v1/v2/v3/v4
[1] 0.16666667 0.16666667 0.05555556 0.05555556 0.05555556 0.50000000
sum(v1/v2/v3/v4)
[1] 1
So question is how I can make v3 and v4 etc. ?
Maybe is there way to get vector of str(data) count length of each child like:
out <- c("2/3/1", "2/3/1", "2/3/3", "2/3/3", "2/3/3", "2/1")
Then with this vector I can do math:
> sapply(out, function(x) last(cumprod(1 / c(1, as.numeric(unlist(strsplit(x, "/")))))))
2/3/1 2/3/1 2/3/3 2/3/3 2/3/3 2/1
0.16666667 0.16666667 0.05555556 0.05555556 0.05555556 0.50000000
A:
This lends itself to a recursive solution, possibly something like:
data <- list(list(list("a"), list("b"), list("c","d","e")), list("f"))
f <- function(x, prop=1)
{
if(is.list(x)) lapply(x, f, prop=prop/length(x))
else prop/length(x)
}
unlist(f(data))
#[1] 0.16666667 0.16666667 0.05555556 0.05555556 0.05555556 0.50000000
| {
"pile_set_name": "StackExchange"
} |
Q:
Arduino IDE get stuck while uploading sketch
I was trying to use my L293D motor driver module. But when I upload the following sketch to try and run my motor, but it would get stuck on "Uploading". This happens with this sketch only, and happens randomly, with odds of happening being 3 in 5 times. After a bit fiddling around I found an error
Programmer is not responding.
When I try to reset the board or just reconnect it to my PC it might work.
Here's the sketch-
int RightMotorForward = 12;
int RightMotorReverse = 13;
void setup()
{
pinMode(RightMotorForward, OUTPUT);
pinMode(RightMotorReverse, OUTPUT);
}
void loop()
{
digitalWrite(RightMotorForward, HIGH);
delay(10000);
digitalWrite(RightMotorForward,LOW);
delay(1000);
}
Can anybody point out where I am going wrong? I am using Arduino UNO. Is this just some problem in my code?
A:
Found the solution... Just connect the 5v from arduino to the 5v on the Module. Then another battery (12-36 V, I tried a 9v one... it worked but only for about 40 seconds), to the 12 V input, keeping the ground common... That's gonna make the motors run!
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I use a different graphical driver while booting, and the proprietery NVIDIA driver once my computer has started?
I have a bit of a problem in that as I am booting my PC, the boot screen isn't exactly pretty because I am using the proprietary NVIDIA drivers.
I am wondering if there is a method to use the VESA drivers while my computer boots to get the pretty splash screen (Either that, or make NVIDIA display the pretty splash screen -- I assume it is because of Kernel Mode Setting that it doesn't work properly)
Any advise is much appreciated!
(Note: I cannot use the nouveau drivers because they are faulty with my video card, making Ubuntu particularly difficult to install [NVIDIA GTX 580])
A:
This is more of a workaround to what you are asking but it is as close as you are going to get
This is a old guide but still works as of 13.04
http://news.softpedia.com/news/How-to-Fix-the-Big-and-Ugly-Plymouth-Logo-in-Ubuntu-10-04-140810.shtml
I have a [NVIDIA GTX 550 TI] if you are wondering
| {
"pile_set_name": "StackExchange"
} |
Q:
Issue getting distinct values from column into array from mySQL via PHP
I'm trying to get the unique values in a specific column into an array, so I can validate what's being sent to my PHP to avoid mySQL injection. Here's what I have:
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$sessiont = 'SET SESSION group_concat_max_len=6000';
$fixed = $dbh->query($sessiont);
$stmt = $dbh->prepare("select distinct `category` as cats FROM {$table}");
$stmt->execute();
$row = $stmt->fetch();
$categories = explode(",",$row["cats"]);
$whatCategory = isset($_GET['category']) ? "{$_GET['category']}" : '';
if (in_array($whatCategory, $categories))
{
$sql = "select distinct value from {$table} where category = '{$whatCategory}';";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json');
echo json_encode($result);
}
else
{
echo ("unauthorized!");
}
Right now, this is only giving me the first value in the column category and isn't creating a valid array, which means I'm getting "unauthorized!"
If I make a replacement to the above for $categories like this:
$categories = array ('category1','category2','category3');
Then it works (i.e., I don't get unauthorized!)
A:
Totally untested but looking at the sql you use initially you will get several rows probably containing 'cats' rather than one field with comma separated values of cats. Perhaps you would wish to use group_concat( category ) as 'cats' to return a single row?
You then go on to test whether '$whereCategory' is in the array of categories. I see no previous mention of $whereCategory!
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a performance hit for using EXTERNAL working storage variables
This question is regarding IBM Enterprise COBOL 4.2.
I have a program that requires a change and an increase to a working storage buffer. Unfortunately, this increase in buffer size has put me over the 128M max for the working storage section. My plan was to take some of the bigger 01 variables and make them EXTERNAL, but I am concerned that this will impact system performance.
Does anyone know if making working storage variables external will slow down system performance?
I have been told that in about a year we will be switching to COBOL 6.1, so if it is a small performance decrease, we should be able to handle it until we get 6.1 (where the working storage limits have been increased to 2G)
A:
As a practical matter, using EXTERNAL is no different than the system calling a program with each external data item as if it were a linkage section data item. I suggest compiling a small program and examining the generated code to see what the differences are.
working-storage section.
01 ws-data pic x(8).
01 ext-data pic x(8) external.
linkage section.
01 ls-data pic x(8).
procedure division using ls-data.
begin.
move spaces to ws-data
move spaces tp ext-data
move spaces to ls-data
goback
.
I suspect there is no difference between accessing ext-data and ls-data.
This would provide specific information on how much of a "hit" to expect.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is servlet just like httpHandler in .Net?
Anone can compare those two? Any similarity and difference?
A:
Not Exactly, but you can achieve more and less the same functionality as sync HTTPHandler.
| {
"pile_set_name": "StackExchange"
} |
Q:
Resolving a question that has answers that don't cover the entire question
This is the question that I am referring to if needed.
I asked a question regarding media queries and the detection of mobile devices. The answers that were relevant focused on the detection of devices and orientation using JavaScript, but failed to tie it together with the media queries and LESS CSS implementation side of things.
The comments within the answers here were relevant to helping solve the problem, but not fully (vanilla CSS, not nested LESS), and additionally were not posted by the original answerer. I have since solved the LESS issue, and thus the entire problem.
Should I accept the closest answer / the one that helped me the most and leave it at that? (this has already been awarded a bounty)
Should I write and accept my own answer that compiles it all?
Should I alter the question with a compiled solution and accept the closest answer?
A:
I personally would accept the closest/most helpful answer, and then leave a comment on it. Sometimes if the posted answer wasn't actually how I solved the problem, I've accepted my own answers.
Also, in the future, try as best you can to ask only one question per question, so you don't have to deal with this as much
| {
"pile_set_name": "StackExchange"
} |
Q:
Check to see if user has their microphone plugged in
I have a function that checks to see if a browser supports speech recognition or not, and it alerts whether it supports or not, and it works well, except that it does not alert anything when the user is using Google Chrome, but DOES NOT have the microphone plugged in.
I would like it to check to see if the user has their microphone plugged in or not. Is that possible?
function recognize() {
window.speechRecognition = window.speechRecognition || window.webkitSpeechRecognition || window.mozSpeechRecognition || window.webkitSpeechRecognition;
if (window.speechRecognition == undefined) {
alert("Speech Recognition Only Supported in Google Chrome");
} //end of if (window.speechRecognition == undefined)
else {
alert("Speech Recognition is Supported.");
} //end of else if (window.speechRecognition != undefined)
} //end of function recognize()
A:
if(confirm('Is your microphone plugged in?')) {
//they said yes :-)
} else {
//they said no :-(
}
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery .after with effect
i would like to ask, if is it possible to use .after function in correlation with some effect like fadeIn or so.
The whole flow should work like this:
get some AJAX content depend on user action (.click or so)
render response html right after current element
I already try to mix .get, .after, .show or .fadeIn methods, but without success.
Any help is highly appreciated.
A:
It's easy
jQuery.ajax({
url:"//Your URL//"
success: function(response){
jQuery(".defineYOURSELECTOR").after(jQuery(response).fadeIn());
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there guidelines in the peer reviewing process on assessing methodology?
Usually an article goes through a peer-review process before it is published, and from what I here it is quite common that the reviewers "demand" some changes.
Are there guidelines for peer- reviewers, especially as the methodological side of things is concerned?
Are "methodology specialists" incorporated in the process?
A:
This does not really answer your question (because it doesn't deal in detail with methodological issues), but there is a nice journal article that deals with problems of the peer review process in general by evaluating "great scientific works of the past" from the perspective of current social sciences:
Trafimov, D., & Rice, S. (2009). What if social scientists had reviewed great scientific works of the past? Perspectives on Psychological Science, 4, 65-78. doi:10.1111/j.1745-6924.2009.01107.x Available online at http://cda.psych.uiuc.edu/writing_class_material/perspectives_articles/trafimow.pdf
The reference list has some articles on statistical/mathematical methodology questions.
In another interesting article, Gerd Gigerenzer shows how p-values are misinterpreted in current research and null hypothesis testing is made a false requirement for the acceptance of papers by major journals:
Gigerenzer, G., Krauss, S., & Vitouch, O. (2004). The null ritual: What you always wanted to know about significance testing but were afraid to ask. In D. Kaplan (Ed.), The Sage Handbook of Quantitative Methodology for the Social Sciences (pp. 391-408). Thousand Oaks, CA: Sage. Available online at http://www.sozialpsychologie.uni-frankfurt.de/wp-content/uploads/2010/09/GG_Null_20042.pdf
A Google search for "peer review guidelines" brings many hits from publishers and institutions. Maybe some of them deal with methodological issues in more detail.
A:
I get the impression that good journal editors will get at least one reviewer who is skilled in the methodology used in the paper. The importance of this reviewer role would presumably vary with the statistical or other methodological complexity of the paper.
That said, reviewing is well known to be imperfect particularly when it comes to checking all the possible smaller errors that can be made. Errors in statistical analysis and reporting are wide-spread in published articles in psychology. For example, Bakker and Wicherts (2011) did a review, where to quote the abstract
we checked the consistency of reported
test statistics, degrees of freedom, and p values in a random sample
of high- and low-impact psychology journals... On the basis of 281
articles ... [we estimate that] around 18% of statistical results in the
psychological literature are incorrectly reported. Inconsistencies
were more common in low-impact journals than in high-impact journals.
Moreover, around 15% of the articles contained at least one
statistical conclusion that proved, upon recalculation, to be
incorrect; that is, recalculation rendered the previously significant
result insignificant, or vice versa.
References
Bakker, M., & Wicherts, J. M. (2011). The (mis) reporting of statistical results in psychology journals. Behavior Research Methods, 43(3), 666-678. FULL-TEXT
| {
"pile_set_name": "StackExchange"
} |
Q:
Objects, boolean logic, and boxing nil in Objective-C
I would like to return an NSDictionary which might contain an NSError value for one key, and if not, should contain a null value. I know that I cannot actually set a value to nil because it is not an object, but why can I not use the || operator to return NSNull if my NSError is nil?
if (requestError || ![matches count]) {
return @{@"success": @NO,
@"error": requestError || [NSNull null],
@"country": country};
}
The error I get is Collection element of type 'int' is not an Objective-C object. I understand that nil is an int value, but why does nil || NSObject not guarentee that an NSObject will be returned?
A:
The || operator returns a boolean, so requestError || [NSNull null] returns YES or NO. You could use the ternary operator instead:
@"error": requestError ? requestError : [NSNull null],
| {
"pile_set_name": "StackExchange"
} |
Q:
AJAX request not working in IE8 and IE9
This AJAX code is working in IE10+ and Chrome and another browser, but it is not working in IE8 and IE9.
<table id="table" border="1">
<tbody style="display: table-row-group"></tbody>
</table>
jQuery(document).ready(function(){
$.support.cors = true;
var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22EURUSD%22%2C%20%22CADUSD%22%2C%20%22GBPUSD%22%2C%20%22AEDUSD%22%2C%20%22TRYUSD%22%2C%20%22RUBUSD%22%2C%20%22INRUSD%22%2C%20%22SARUSD%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
var $tbody = $('#table').find('tbody');
var $thead = $('#table').find('thead');
$.ajaxSetup({ cache: false });
$.ajax({
crossDomain: true,
type: "GET",
url: url,
cache: false
}).done(function (data) {
alert("lev 2 ");
var ObjectKeys = Object.keys(data.query.results.rate[0]);
var row = "<tr>";
row += "</tr>";
$thead.append(row);
$.each(data.query.results.rate, function (i, el) {
console.log("lev 3 = " + i);
$tbody.append($('<tr />').append($('<td />').text(el.id)).append($('<td />').text(el.Name)).append($('<td />').text(el.Rate)).append($('<td />').text(el.Ask)).append($('<td />').text(el.Bid)));
});
});
});
How can I solve this problem?
DEMO Fiddle Here
A:
The issue is IE8 doesn't support the Cross Origin Resource Sharing (CORS) XHR, so you can't do a cross domain ajax call with the native XHR or jQuery's $.ajax.
For IE8, Microsoft decided to come up with their own cross domain XHR instead of using the CORS XHR, which is called XDomainRequest, so you'll have to implement that to support IE8 users. An example usage can be found in this answer.
Alternatively, you could proxy the cross domain request through your local server side, making the external request a server to server situation, which won't be subject to Same Origin Policy.
| {
"pile_set_name": "StackExchange"
} |
Q:
c# MSMQ between 2 local apps not receiving all messages sent
I have created my own MSMQ wrapper class like this:
public class MsgQueue
{
private MessageQueue messageQueue;
public delegate void ReadMessageDelegate(string message);
public event ReadMessageDelegate NewMessageAvailable;
public MsgQueue(string queueName)
{
var queuePath = @".\Private$\" + queueName;
if (!MessageQueue.Exists(queuePath)) MessageQueue.Create(queuePath);
messageQueue = new MessageQueue(queuePath);
messageQueue.Label = queueName;
messageQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string)});
messageQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(MsgReceivedHandler);
messageQueue.BeginReceive();
}
private void MsgReceivedHandler(object sender, ReceiveCompletedEventArgs e)
{
try
{
MessageQueue mq = (MessageQueue)sender;
var message = mq.EndReceive(e.AsyncResult);
NewMessageAvailable(message.Body.ToString());
mq.BeginReceive();
}
catch (MessageQueueException)
{
// Handle sources of MessageQueueException.
}
return;
}
public void SendMessage(string message)
{
messageQueue.Send(message);
}
}
I tested it on two separate WinForms applications.
First app sends a text message when button is clicked:
private void btn_Click(object sender, EventArgs e)
{
var queue = new MsgQueue.MsgQueue("GBMqueue");
queue.SendMessage("some message text");
}
Second app is listening for any incoming messages and then tries to process it:
// declaration
private MsgQueue queue;
// preparation of the queue
private void Form1_Load(object sender, EventArgs e)
{
queue = new MsgQueue.MsgQueue("GBMqueue");
queue.NewMessageAvailable += Queue_NewMessageAvailable;
}
// Handler for the incoming messages
private void Queue_NewMessageAvailable(string message)
{
// Hits here very rarely!!!
}
The problem is that I can send the message from App1 several times, but the Queue_NewMessageAvailable handler catches only one random message, not the first one - just one of those which were sent.
No exception is thrown, it just does not catch the incoming messages.
What am I doing wrong here?
A:
I think the first App should not listen for new messages. It's possible that it takes away the messages for the second App. It should only send messages.
When you split the functionality it should work.
| {
"pile_set_name": "StackExchange"
} |
Q:
OS Error file path and name being changed without user interference
I am trying to read a midi file in the following manner using an in-built function from the library - mido to read such files.
mid = mido.MidiFile('..\Datasets\abel.mid')
Error:
OSError Traceback (most recent call last)
<ipython-input-34-5c67b78f0caf> in <module>()
----> 1 mid = mido.MidiFile('F:\AI\Music classification\Datasets\abel.mid')
~\Anaconda3\lib\site-packages\mido\midifiles\midifiles.py in __init__(self, filename, file, type, ticks_per_beat, charset, debug, clip)
313 self._load(file)
314 elif self.filename is not None:
--> 315 with io.open(filename, 'rb') as file:
316 self._load(file)
317
OSError: [Errno 22] Invalid argument: '..\\Datasets\x07bel.mid'
If we observe the last line of the error, we notice that the file name seems to have been changed. Why does this happen?
If I change the code in the following manner by adding an extra \wherever the file name seems to have been changed, then the file is read perfectly:
mid = mido.MidiFile('..\Datasets\\abel.mid')
Why is it that when I add an extra \, the code works?
A:
Python uses backslash for string escapes - which lets you define different values for a character sequence. Just as \n is a newline, \a is the hex byte 07. You can escape the backslash itself, so \\ is just a backslash. And you can use "raw" strings (e.g., `r"\a") to disable escaping all together.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where is "navigate to" in Visual Studio 2010 Express C#
Is "Navigate to" one of the "missing" features from Visual Studio Express 2010?
A:
that is indeed missing in the express edition.
| {
"pile_set_name": "StackExchange"
} |
Q:
SOQL - UserLogin relationship from User
I am trying to check if a user is frozen but i can't figure out the relationship query. It seems like one doesn't exist even though there is a lookup. This older post hints at it but I can't figure out how to form my query.
SOQL error with relationship
Tried all of these:
List<User> Users = new list<User>([
SELECT Id,FirstName,LastName, (Select isFrozen FROM UserLogin)
FROM User
WHere LastLoginDate >= :SixtyDaysAgo
]);
List<UserLogin> uLogins = new list<UserLogin>([
Select Id, UserId, UserId.FirstName, UserId.LastName
FROM UserLogin
WHERE IsFrozen = FALSE
AND LastLoginDate >= :SixtyDaysAgo
])
List<UserLogin> uLogins = new list<UserLogin>([
Select Id, UserId, (Select FirstName, LastName FROM User WHERE LastLoginDate >= :SixtyDaysAgo)
FROM UserLogin
WHERE IsFrozen = FALSE
])
A:
Try a Left Inner Join:
SELECT FirstName, LastName FROM User
WHERE Id IN (SELECT UserId FROM UserLogin WHERE IsFrozen = true)
Also note that the query syntax returns a List<User>, and you are being excessively verbose. No need to do new List<User>([/*query*/]) where [/*query*/] will suffice.
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between tomcat and resin?
I like to know what are the differences between Tomcat container and Resin container
A:
Tomcat is a stand alone web server supporting the J2EE web technologies (eg. Servlets, JSP) and Resin is a full blown J2EE Application server which includes a web server plus the rest of the J2EE family of technologies (eg. EJB). Tomcat is always free to use for any purpose. Resin is free only for open source or hobby use. Commercial use of Resin is not free. One interesting feature of Resin is the ability to run PHP applications under the JVM through Quercus.
| {
"pile_set_name": "StackExchange"
} |
Q:
Animate.css not working on hover
Why doesn't this hover Animate.css animation work after the initial page load animation?
$(document).ready(function(){
$("h1").addClass("animated zoomInDown")
$("h1").hover(function(){
$(this).addClass('animated shake');
});
A:
If you're using hover() make sure you have handlers for both hover-in and hover-out events. CSS animation will only re-run if it's removed then added again:
$(document).ready(function() {
$("h1").addClass("animated zoomInDown")
$("h1").hover(function() {
$(this).addClass('animated shake');
}, function() {
$(this).removeClass('animated shake');
});
});
h1 {
background: yellow;
position: relative;
}
.animated {
animation: animate-color 0.2s linear;
animation-iteration-count: 5;
}
@keyframes animate-color {
0% {
left: 0;
}
50% {
left: 5px;
background: red;
}
100% {
left: 0px;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Hello</h1>
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery unable to find same div if i remove and add it back?
I'm attempting to load different content into a div, the refresh code I have is quite similar to this: http://jsfiddle.net/TbJQ3/6/ but is more complex, it takes padding and magin etc into account.
The difference is that in my actual code, I used .load() to feed the content into my div rather than empty() and append().
When my page first loaded, I call my resizeContainer() function to render my layout dynamically set the size of my DIVs, everything looks good. I looked at firebug and this is what I got (all the sizes are there, set by my function):
<div id="divWrapper" class="fullscreen">
<div id="divTop" class="Top " style="height: 0px;"> </div>
<div id="divContainer" class="Container round" style="width: 1024px; height: 560px;">
<div id="divContent" class="Content round" onclick="javascript: jQfn.testclick();" style="width: 701px; height: 542px;"> Content </div>
<div id="divQuery" class="Query round" onclick="javascript: jQfn.testclick();" style="width: 292.2px; height: 558px;"> Query </div>
<div id="divStatus" class="Status " onclick="javascript: jQfn.testclick();" style="width: 701px; float: left;"> Status </div>
</div>
</div>
I made a test function to basically swap the content just to test the concept out...
jQfn.testclick = function(){
if (jQ.busy == true) {
console.log('Using busy.jsp');
jQ('#divContainer').load('busy.jsp');
jQ.busy = false;
} else {
console.log('Using login.jsp');
jQ('#divContainer').load('login.jsp');
jQ.busy = true;
}
jQ(window).trigger('resize');
}
However, if i click it twice just to swap it back to the original content, my resizeContainer function won't render anything at all.
I've been hammering this problem for the past 5+ hours now, I tried to use:
empty, append
detach
calling the resize function in many different ways
calling my custom resizeContainer function in many different ways
combination of all of the above and some more
I noticed that after i loaded my content, jQuery was unable to find the divs that got reinserted anymore... which would explain why my resizeContainer function couldn't set the width and height properly... But why? I could see it on the div on the screen as well as in the firebug...
This is what I see after i swap the content, obviously the styles is not present, as my custom resizeContainer function couldn't find the div.
<div id="divWrapper" class="fullscreen">
<div id="divTop" class="Top " style="height: 0px;"> </div>
<div id="divContainer" class="Container round" style="width: 1024px; height: 560px;">
<div id="divContent" class="Content round" onclick="javascript: jQfn.testclick();"> Content </div>
<div id="divQuery" class="Query round" onclick="javascript: jQfn.testclick();"> Query </div>
<div id="divStatus" class="Status " onclick="javascript: jQfn.testclick();" style="width: 701px; float: left;"> Status </div>
</div>
</div>
The reason why I know jQuery couldn't find my divs, is because I used the following code, and it logged some empty element:
var content = jQuery('#divContent');
console.log(content);
What could be wrong? I even tried to manually detach those DIVs before loading in the new content.
A:
Load is an Ajax method, and inserts content from external files, when using ajax methods and not the append methods you will in most cases have to use jQuery's live(); to gain access to the inserted DOM elements.
Once the content is inserted the first time with Ajax, try using detach and one of the append methods instead of Ajax to reinsert it, otherwise it will not work, as load just reinserts new DOM elements, and not the content you just detached.
| {
"pile_set_name": "StackExchange"
} |
Q:
Graphs of different orders( at different powers)
Given a connected graph $G =(V,E)$ and a positive integer $k$,
the k-th power of $G$, denoted $G^k$ , is the graph whose set of
nodes is $V$ and where vertices $u$ and $v$ are adjacent in $G_k$ if
and only if $d(u,v) \le k$ in $G$.
$P_8$ is a path graph with 8 vertices such as: o-o-o-o-o-o-o-o
$C_{10}$ is a cycle graph: $C_{10}$ has 10 vertices.
$d(u,v)$ is the distance between $u$ and $v$, which is the length of
the shortest path $u-v$ from $u$ to $v$ in graph $G$.
I know that two vertices are adjacent in the 2nd power if and only if there's a path of length at most 2 between them in $P_8$.
Draw the 2-nd and 3-rd powers of $P_8$ and $C_{10}$ .
For a graph $G$ of order $n$, what is $G^{diam(G)}$
I know the stuff above and I am asking for any answers and help, appreciate it.
A:
I'll give you the graphs of $P_8^2$ and $P_8^3$, and hopefully this will help you figure out $C_{10}^2$ and $C_{10}^3$. As for the diameter problem, recall that the diameter is the least non-negative integer $d$ such that $d(u,v)\le d$ for all $u,v\in V$. Knowing this and the definition of $G^k$, can you figure out what $G^d$ is?
Here are $P_8^2$ and $P_8^3$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i represent multiple m:n relations from two tables?
My tables:
medic->id_medic, name
patient->id_patient, name
I have the following situacion:
A medic can have many patients and a patient can have many medics
A medic can send many messages to a patient and a patient can send many messages to a medic.
how i represent this in the E-R model?
A:
you will have two another tables messages and medic_patient :
medic->id_medic, name
patient->id_patient, name
messages -> id_message,content, #id_medic_receiver,#id_patient_sender,#id_patient_receiver,#id_medic_sender
medic_patient -> #id_medic,#id_patient
| {
"pile_set_name": "StackExchange"
} |
Q:
Sidekiq stopped processing jobs in queue
Sidekiq had been processing jobs just fine (finished 30 jobs overnight). This morning, it completely shut off processing the queue (now up to 28 jobs).
Running on Heroku (1 Standard-2x Web Dyno, 1 Standard-1x Worker Dyno).
Procfile (where I have had the most trouble finding documentation to configure)
web: bundle exec puma -C config/puma.rb
worker: bundle exec sidekiq -e production -C config/sidekiq.yml
sidekiq.yml
development:
:concurrency: 5
production:
:concurrency: 20
:queues:
- ["default", 1]
- ["mailers", 2]
sidekiq.rb
if Rails.env.production?
Sidekiq.configure_client do |config|
config.redis = { url: ENV['REDIS_URL'], size: 2 }
end
Sidekiq.configure_server do |config|
config.redis = { url: ENV['REDIS_URL'], size: 20 }
Rails.application.config.after_initialize do
Rails.logger.info("DB Connection Pool size for Sidekiq Server before disconnect is: #{ActiveRecord::Base.connection.pool.instance_variable_get('@size')}")
ActiveRecord::Base.connection_pool.disconnect!
ActiveSupport.on_load(:active_record) do
config = Rails.application.config.database_configuration[Rails.env]
config['reaping_frequency'] = ENV['DATABASE_REAP_FREQ'] || 10 # seconds
# config['pool'] = ENV['WORKER_DB_POOL_SIZE'] || Sidekiq.options[:concurrency]
config['pool'] = 16
ActiveRecord::Base.establish_connection(config)
Rails.logger.info("DB Connection Pool size for Sidekiq Server is now: #{ActiveRecord::Base.connection.pool.instance_variable_get('@size')}")
end
end
end
end
Also, with all the jobs in the queue (default, mailers) is it possible to have Sidekiq force run the jobs?
UPDATE
I have narrowed the error to the Heroku worker. Upon restart, the worker quickly crashes.
The first error had to do with Sidekiq not spawning enough connections (Redis required 22, I had set the limit to 20).
Now, I am getting the following error:
Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
I am running PG Hobby via Heroku. Its connection limit is 20. Is this the source of the issue?
A:
After 2 days on this venture, answer discovered thanks to this SO question. Hopefully, this helps the SEO for future onlookers.
I changed my sidekiq.rb file to
sidekiq.rb
require 'sidekiq/web'
Sidekiq.configure_server do |config|
ActiveRecord::Base.configurations[Rails.env.to_s]['pool'] = 30
end
if Rails.env.production?
Sidekiq.configure_server do |config|
config.redis = { url: ENV["REDISTOGO_URL"]}
end
Sidekiq.configure_client do |config|
config.redis = { url: ENV["REDISTOGO_URL"]}
end
end
Then, I updated my sidekiq.yml to
sidekiq.yml
queues:
- default
- mailers
:verbose: false
:concurrency: 5 # Important to set depending on your Redis provider
:timeout: 8 # Set timeout to 8 on Heroku, longer if you manage your own systems.
Note: There is also the option to leave out everything in the if statement in the initializer file. As stated by the creator of Sidekiq, you can set your heroku config to:
heroku config:set REDIS_PROVIDER=REDISTOGO_URL
and Sidekiq will figure out the rest.
| {
"pile_set_name": "StackExchange"
} |
Q:
The category of posets
I am trying to teach myself category theory and, as a beginner, I am looking for
examples that I have a hands-on experience with.
Almost every introductory text in category theory contains following facts.
The class of all posets with isotone maps is a category (called $Pos$).
Every individual poset $P$ is a category, with comparable pairs $x\leq y$ as arrows. This can be called "a categorified poset".
Sometimes, product and coproduct in $Pos$ is characterized and (less frequently) it is pointed out that a Galois connection can be characterized as a pair of adjoint functors of categorified posets. Also, it
is sometimes mentioned that products and coproducts in categorified posets are joins
$\vee$ and meets $\wedge$, so a categorified poset has products and coproducts iff it is
a latttice.
Moreover, some texts contain the fact that the category of finite posets and the category of finite distributive lattices are dually equivalent -- this is extremely useful.
But I cannot find much more. For example, when I tried to search for equalizers and coequalizers in $Pos$, the only source I found is the
PhD thesis by Pietro Codara, available here, which is from 2004 and characterizes (co)equalizers
in $Pos$.
Does anyone know about some other sources of information about $Pos$ from the category-theoretic viewpoint?
Specifically, I am looking for things like
useful functors to $Pos$ and from $Pos$,
pullbacks, pushouts and other universal constructions in $Pos$,
examples of adjoint functors, applications of Yoneda lemma etc.
A:
Here is a fact that should be much more widely known than it is.
The category of posets is isomorphic (not just equivalent) to the
category of $T_0$ Alexandrof spaces. A topological space is said to be
Alexandrof if arbitrary (not just finite) intersections of open
sets are open. For example, every finite topological space is an
Alexandrov space. Finite spaces are fascinating and the connection
with algebraic topology is very close: finite spaces have associated
finite simplicial complexes. Don't just look categorically: that
takes the fun out of it! There are notes on my web page and there
is a book by Barmak.
A:
Here are some basic remarks and examples:
(Caution. This answer refers to preorders; but many of the remarks also apply to partially ordered sets aka posets)
Many concepts of category theory have a nice illustration when applied to preorders; but also the other way round: Many concepts familiar from preorders carry over to categories (for example suprema motivate colimits; see also below).
This is partially justified by the following observation: An arbitrary category is a sort of a preorder but where you have to specify in addition a reason why $x \leq y$, in form of an arrow $x \to y$. The axioms for a category tell you: For every $x$ there is a distinguished reason for $x \leq x$, and whenever you have a reason for $x \leq y$ and for $y \leq z$, you also get a reason for $x \leq z$.
A preorder is a category such that every diagram commutes.
In a preorder, the limit of a diagram is the same as the infimum of the involved objects. Similarly, a colimit is just a supremum. The transition morphisms don't matter.
When $f^* : P \to Q$ is a cocontinuous functor between preorders, where $P$ is complete, then $f^*$ has a right adjoint $f_*$; you can write it down explicitly: $f_*(q)$ is the infimum of the $p$ with $f^*(p) \leq q$. This construction motivates the General Adjoint Functor Theorem. In this setting we only have to add the solution set condition, so that the a priori big limit can be replaced by a small one and therefore exists.
Let $f : X \to Y$ be a map of sets. Then the preimage functor $\mathcal{P}(Y) \to \mathcal{P}(X)$ between the power sets is right adjoint to image functor $\mathcal{P}(X) \to \mathcal{P}(Y)$. Every cocontinuous monoidal functor $\mathcal{P}(Y) \to \mathcal{P}(X)$ arises this way.
The inclusion functor $\mathrm{Pre} \to \mathrm{Cat}$ has a left adjoint: It sends every category to its set of objects with the order $x \leq y$ if there is a morphism $x \to y$. In particular, it preserves all limits. In fact, it creates all limits, and limits in $\mathrm{Cat}$ are constructed "pointwise". Thus, the same is true for limits in $\mathrm{Pre}$ (which one could equally well see directly). For example, the pullback of $f : P \to Q$ and $g : P' \to Q$ is the pullback of sets $P \times_Q P'$ equipped with the order $(a,b) \leq (c,d)$ iff $a \leq c$ and $b \leq d$. If we apply this to difference kernels, we see that $f : P \to Q$ is a monomorphism iff the underlying map of $f$ is injective.
The forgetful functor $\mathrm{Pre} \to \mathrm{Set}$ creates coproducts: Take the disjoint union $\coprod_i P_i$ and take the order $a \leq b$ iff $a,b$ lie in the same $P_i$, and with respect to that preorder we have $a \leq_i b$.
The construction of coequalizers seems to be more delicate; see this SE discussion.
I don't have a reference for all these observations, but they are easy. A general reference for basic category-theoretic constructions (and it surely says something about preorders and posets) is the book "Abstract and Concrete Categories - The Joy of Cats" by Adamek, Herrlich, Strecker which you can find online.
EDIT: Here is something not so basic: Sefi Ladkani studied the notion of derived equivalent posets. Two posets $X,Y$ are called (universally) derived equivalent if for some specific (every) abelian category $\mathcal{A}$ the diagram categories $\mathcal{A}^X$, $\mathcal{A}^Y$ are derived equivalent.
A:
Probably not what you are looking for, but:
There is this recent paper by George Raptis:
Homotopy theory of posets, 2010
discussing about model category structures on the category of posets.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I control error level of NSLog messages on iOS?
I observed the NSLog() does log all my messages with error level Warning but when I look to the console I see other messages with different error levels like Info, or `Error.
How can I control the error level of my messages?
A:
I don't believe you can alter the logging level of NSLog() messages. You can use 3rd party logging solutions (or write your own macro) to insert different error level strings into the logs that can then be filtered on.
Check out the following libraries for pre-built logging solutions.
http://0xc0.de/LibComponentLogging
https://github.com/robbiehanson/CocoaLumberjack
http://labs.grupow.com/index.php/2010/12/objective-c-logging-with-sosmax/
A:
Use the ASL log:
asl_log(NULL, NULL, ASL_LEVEL_INFO, "Hello World!!!");
Where the ASL_LEVEL_INFO can be any of these:
ASL_LEVEL_EMERG
ASL_LEVEL_ALERT
ASL_LEVEL_CRIT
ASL_LEVEL_ERR
ASL_LEVEL_WARNING
ASL_LEVEL_NOTICE
ASL_LEVEL_INFO
ASL_LEVEL_DEBUG
| {
"pile_set_name": "StackExchange"
} |
Q:
¿Transformacion de punteros?
Tengo una duda sobre los punteros.
Al declarar un puntero sea short, int, float, etc este lo podemos pasar a un puntero void ¿porque?. Y ¿como se testea para hacer lo opuesto?. Gracias
A:
Un puntero a void* es un puntero genérico, es decir, puede apuntar a cualquier tipo de dato.
Por ejemplo:
int x = 9;
void* px = &x;
En ese ejemplo, le estás asignando la dirección de memoria de la variable "x" al puntero "px".
Para poder escribir/leer algún dato en la variable "x" a través del puntero, debes hacer un casting (el compilador necesita saber a que tipo apunta el puntero) al puntero genérico al momento de desreferenciar.
int x = 9;
void* px = &x;
*(int*)px = 10;
Para hacer el proceso inverso es muy sencillo, mirad este ejemplo:
int main()
{
int x = 9;
void* px = &x;
*(int*)px = 10;
int* y = (int*)px;
//Resultado en pantalla: 10
printf("%d\n", *y);
return 0;
}
Si te puedes dar cuenta, es necesario hacer un casting al momento de asignar el contenido de "px" al puntero "y", dado que el compilador de C++ nos obliga a hacer una conversión explicita (algo que en lenguaje C es innecesario).
EDIT:
El motivo de porqué se necesita hacer un casting al momento de desreferenciar un puntero genérico, es debido a que, el compilador necesita calcular un offset a través de ese tamaño en bytes y de ese modo, crear el modo de direccionamiento adecuado para poder calcular la dirección de memoria de un elemento en específico.
Por ejemplo:
int main(void)
{
char n[5] = {"ABCD"};
void* pn = n;
for(int i = 0; i != sizeof n; ++i)
printf("%c\n", *(pn + i));
getchar();
return 0;
}
Ese código no compilaría, porqué el compilador no sabe cual es el tipo de dato al que apunta el puntero genérico, de eso depende que se pueda calcular correctamente la dirección de memoria del dato.
Ahora que pasaría si engañamos al compilador y hacemos esta conversión explicita:
for(int i = 0; i != sizeof n; ++i)
printf("%c\n", *((double*)pn + i));
Asumiremos que las direcciones de memoria del arreglo n son:
|0x01| |0x02| |0x03| |0x04| |0x05|
A B C D \0
Entonces, el código de arriba debería imprimir los caracteres A, B, C, D, pero eso no ocurrirá porqué se estaría calculando otras direcciones de memoria que no corresponde al arreglo de caracteres.
Antes de comprobar el porqué, necesitamos comprender esta parte:
*((double*)pn + i)
El compilador interpretaría esa sentencia de esta forma:
*((double*)pn + i* 8)
Se multiplica por 8 bytes porqué el tamaño de un tipo double es de 8 bytes. Básicamente esto lo hace el compilador para obtener el offset necesario y así poderlo sumar a la dirección base del búfer y de ese modo hallar la dirección de memoria del elemento.
Entonces, sabiendo esto, ¿qué pasaría si la variable i vale 1? ¿Obtendrá la dirección de memoria del caracter B? La respuesta sería no. Cuando i valga 1, la expresión sería evaluada de esta manera:
//Asumiendo que puntero el pn apunta a la dirección 0x01.
*(0x01 + 1* 8)
*(0x01 + 0x08)
*(0x09)
El resultado fue 0x09, pero si revisamos la tabla de ejemplo, la dirección de memoria del caracter B es 0x02, por lo tanto, estaríamos desreferenciando una dirección que ni sabemos si le pertenece al programa, haciéndolo abortar de inmediato (lo más probable que sea así).
Aquí concluimos que es fundamental especificar a que tipo apunta el puntero genérico, ya que de ese modo, se va a generar una dirección de memoria que sea correspondiente a lo que se quiere acceder.
La solución del ejemplo anterior sería:
for(int i = 0; i != sizeof n; ++i)
printf("%c\n", *((char*)pn + i));
¿Cuando no es necesario especificar el tipo al que apunta el puntero a void*?
Pues cuando un puntero tiene más de un nivel de direccionamiento indirecto (es decir, habrá más trayectos para llegar al dato) no se necesitaría especificar el tamaño, siempre y cuando no se acceda al dato.
Por ejemplo:
int main(void)
{
char* n[5] = {"AA", "BB", "CC", "DD", "EE"};
void** pn = n;
for(int i = 0; i != 5; ++i)
printf("%d\n", *(pn + i));
getchar();
return 0;
}
En este ejemplo, se declara un arreglo de punteros de tipo char, luego, se le pasa la dirección base del arreglo al puntero doble pn.
Hay que recalcar que pn no es un puntero genérico. El puntero pn apunta a un puntero genérico de tipo void*, que a su vez apunta a un dato de cualquier tipo (int, float, char, entre otros).
El código de arriba compilaría, porqué el compilador conoce el tamaño en bytes (a lo que apunta pn), en este caso podría ser 4 o 8 bytes, esto depende de la arquitectura de la máquina (si es de 32 bits o 64 bits).
Si analizamos esta línea:
printf("%d\n", *(pn + i));
Y además, asumimos que compilamos este ejemplo en una máquina de 32 bits, el compilador interpretaría este código de esta forma:
printf("%d\n", *(pn + i* 4));
Aquí el tamaño en bytes es conocido, porqué el compilador sabe que la dirección de memoria que se va a calcular es la de un puntero, no la de un dato.
Pero si ahora hacemos esto:
for(int i = 0; i != 5; ++i)
printf("%c\n", *(char*)*(pn + i));
En este caso es fundamental especificar el tamaño, porqué queremos acceder a la dirección de memoria de un caracter, no la de un puntero.
¿Cuando podemos utilizar un puntero genérico?
Pues eso dependerá del problema que quieras resolver, por ejemplo, si quisiéramos crear una función que reserve memoria dinámica para la creación de una matriz dinámica, sería ideal usar punteros genéricos, ya que, la matriz podría ser de cualquier tipo.
Por ejemplo:
He creado dos funciones, una función para crear una matriz dinámica de cualquier tipo (ya sea integer, float, short, etc.), además de eso, también se creó la subrutina para liberar la memoria reservada.
La función CrearMatriz:
void** CrearMatriz(int filas, int columnas, size_t size)
{
//Se reserva memoria para las filas (que en realidad es un arreglo de punteros).
void** n = (void**)malloc(filas * sizeof *n);
if(n == NULL)
{
printf("Error: Hubo un problema al momento de asignar memoria para las filas\n");
return NULL;
}
for(int i = 0; i != filas; ++i)
{
//Se reserva memoria para las columnas (que en realidad es el array dinámico al que apuntará un puntero X del arreglo de punteros).
n[i] = (void*)malloc(columnas * size);
if(n[i] == NULL)
{
printf("Error: Hubo un problema al momento de asignar memoria para las columnas\n");
//Se debe liberar la memoria hasta lo que se haya reservado
liberar(n, i);
return NULL;
}
}
return n;
}
Para liberar la memoria:
void liberar(void* p, int filas)
{
void** n = (void**)p;
//Se libera cada array dinámico al que apunta un puntero X del arreglo de punteros
for(int i = 0; i != filas; ++i)
free(n[i]);
//Se libera el arreglo de punteros
free(n);
}
Modo de uso:
int main(void)
{
int** i;
float** f;
//El sizeof **i es equivalente a sizeof(int)
i = (int**)CrearMatriz(5, 10, sizeof **i);
if(i == NULL) return 1;
//El sizeof **f es equivalente a sizeof(float)
f = (float**)CrearMatriz(2, 5, sizeof **f);
if(f == NULL)
{
//Se debe liberar la primera matriz que se haya reservado dinámicamente.
liberar(i, 5);
return 1;
}
liberar(i, 5);
liberar(f, 2);
getchar();
return 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Split a string into multiple elements
I need to split a string into multiple elements so that they can be inserted into an array. Below is an idea of what'd i'd like this to look like. The number of users is dynamic, but the string format never changes.
string Usernames = "User1, User2, User3, User4";
String[] Users = Usernames;
Console.WriteLine("First User: " + Usernames[0] + "Second User: " + Usernames[1]);
//output..
//First User: User1
//Second User: User2
A:
var users = Usernames.Split(new string[] { ", " }, int.MaxValue, StringSplitOptions.None);
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ return by value - what happens with the pointer inside?
So I'm having a bit of SegFaults and was wondering if someone can explain me in higher depth how does this work.
I have a wrapper class around a numeric variable, and I'm trying to build a compute tree of the expression. Here is a sample code:
class DoubleWrap{
public:
static int id;
DoubleWrap(double value){this->value = value;myid=++id;}
double value;
int myid;
std::vector<DoubleWrap*> parents;
DoubleWrap operator+(DoubleWrap& x){
DoubleWrap result(this->value + x.value);
setParents(*this,result);
setParents(x,result);
return result;
}
void setParents(DoubleWrap& parent,DoubleWrap& child){
child.parents.push_back(&parent);
}
void printTree(){
std::cout<< "[" << this->myid << "]-(";
for (auto& elem: this->parents)
std::cout<< elem->myid << "," << elem <<",";
std::cout<<")"<<std::endl;
for (auto& elem: this->parents)
elem->printTree();
}
}
The problem I got is for an expression like x = a+b+c+d; When I try to look for the parents of x, it has 2 parents, but parents[0].parents[0] is nil, e.g. for some reason the pointer to the allocated place does not work or the allocated memory is destroyed?
I'm quite interested if anyone can advise me on a workaround and why this happens.
To give an example on this code:
DoubleWrap dw(12.6);
DoubleWrap dw2(12.5);
DoubleWrap dw3(12.4);
DoubleWrap dw4(12.3);
DoubleWrap a = dw + dw2 + dw3;
DoubleWrap b = a + dw+ dw2+ dw3 + dw4;
b.printTree();
I expect the output:
[10]-(9,0x13a4b50,4,0x7fff5bdb62f0,)
[9]-(8,0x13a4b00,3,0x7fff5bdb62c0,)
[8]-(7,0x13a49f0,2,0x7fff5bdb6290,)
[7]-(6,0x7fff5bdb6320,1,0x7fff5bdb6260,)
[6]-(5,0x13a4db0,3,0x7fff5bdb62c0,)
[5]-(1,0x7fff5bdb6260,2,0x7fff5bdb6290,)
[1]-()
[2]-()
[3]-()
[1]-()
[2]-()
[3]-()
[4]-()
But the result I get (usually different on different runs):
[10]-(9,0x7ffffd5e2f00,4,0x7ffffd5e2de0,)
[9]-(33,0x1c6da10,3,0x7ffffd5e2db0,)
Process finished with exit code 139
My guess is that the return of the operator in fact copies the DoubleWrap variable, thus value to which the pointer in parents is pointing to goes out of scope and the memory is released?
The temporary solution was to return by reference, but the question is why and is there a proper one?
PS: Fixed a previous mistake I got which is a mistake in setParents.
A:
Your problem is that you're adding pointers to temporary objects to the vector.
DoubleWrap a = dw + dw2 + dw3;
The above will first call dw.operator+(dw2). That creates a temporary object, let's name it temp. It then calls temp.operator+(dw3). Now inside operator+ there's this call to setParents where you pass temp as the parent. You then take the address of temp (at least that's what the code should be doing in order to compile) and add it to the vector of child.
Now when the call to operator+ returns, temp gets destroyed, and the vector in a contains a pointer to a non-existing object.
You could solve this by storing the elements in the vector using shared_ptr. Note that if referential cycles are possible you should be careful to break those cycles with weak_ptr (I didn't include an implementation for that in the below code). Here's what the final code could look like:
class DoubleWrap {
public:
static int id;
DoubleWrap(double value) : value(value), myid(++id) {}
double value;
int myid;
std::vector<std::shared_ptr<DoubleWrap>> parents;
DoubleWrap operator+(const DoubleWrap& x) const {
DoubleWrap result(this->value + x.value);
setParents(*this, result);
setParents(x, result);
return result;
}
static void setParents(const DoubleWrap& parent, DoubleWrap& child) {
child.parents.push_back(std::make_shared<DoubleWrap>(parent)); // makes a copy of parent
}
void printTree() const {
std::cout << "[" << this->myid << "]-(";
for (const auto& elem: this->parents)
std::cout << elem->myid << "," << elem.get() << ",";
std::cout << ")" << std::endl;
for (const auto& elem: this->parents)
elem->printTree();
}
};
int DoubleWrap::id = 0;
| {
"pile_set_name": "StackExchange"
} |
Q:
Longest shortest path between any two nodes of a graph
I am trying to find two nodes that are furthest from each other in my Neo4j Database. For the purposes of my analysis, I am considering shortest distance between the two nodes as the distance between them. Therefore, the two nodes that are furthest will have longest shortest path between them. I am using the following syntax from Cypher to find the shortest node.
Given two nodes as shown in the Neo4j example documentation http://docs.neo4j.org/chunked/milestone/query-match.html#match-shortest-path, I can run the following Cypher query.
MATCH p = shortestPath((martin:Person)-[*..15]-(oliver:Person))
WHERE martin.name = 'Martin Sheen' AND oliver.name = 'Oliver Stone'
RETURN p
My database has over 1/2 million nodes. The brute force way will obviously take a long time. Is there any easy or faster way to get the two nodes?
[As an extra wrinkle .. the graph is weighted but this detail can be ignored.]
A:
If I'm reading this correctly, you want all-pairs shortest path. This will give you a list with each node as a source and the shortest path to every other node. While it does do it by weight, you can simple use a weight of 1 for everything.
You'll have to implement this yourself in Java as Cypher doesn't have anything for this.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I use parallel processing for a function acting on a numpy array, when part of the function is to add rows to the array and keep updating it?
The code I have below functions perfectly fine.
But what I want to change is: if the "variable" I have is greater than 0, I want to add a row, for example [0,1,0,0], to the existing array, and then have the function and parallel processing work on this updated array.
I wrote down the code I've already tried below.
I get the error message: "IndexError: index 2 is out of bounds for axis 0 with size 2".
The message also says this is a direct cause of this line:
master_array = np.vstack((pool.map(third_three_part_function, array)))
import numpy as np
import multiprocessing
array = np.zeros((4, 4))
for i in range(np.size(array,1)):
array[i,0] = 10
def third_three_part_function(array):
for i in range(np.size(array) - 1):
variable = (np.random.poisson( 1, 1))
array[i+1] =array[i ]+ variable
return(array)
from multiprocessing import Pool
if __name__ == '__main__':
pool = Pool(processes=2)
master_array = np.vstack((pool.map(third_three_part_function, array)))
print(master_array)
#### What I've already tried, but doesn't work:
for i in range(np.size(array) - 1):
variable = (np.random.poisson( 1, 1))
array[i+1] =array[i ]+ variable
if variable>0:
addition = [0,1,0,0]
array = np.vstack([array,addition])
return(array)
The goal is that for each new row I add to the array, the function and parallel processing also works on those new rows, as opposed to only the original rows of the array.
A:
When you use Pool.map to run a function over an array, your function is run in parallel in two processes (in this case). Each of these two processes has a copy of array.
Whatever you do to the array in one process does not change the array in the other process! Nor does it influence the array in the parent process that calls Pool.map!
So for a Pool.map to work properly, your worker function has to take a single argument (this can be a list or tuple, though). It works on that argument and then returns a result. The multiprocessing module then sends this result back to the parent process. All these return values are gathered in a list and returned by Pool.map.
For example, suppose you want to count the number of words in files.
You call Pool.map with a worker function and a list of file names.
The worker function takes a single filename as an argument. It reads that file, count the words and returns the number of words in that file.
So Pool.map returns a list of word counts, corresponding to the list of file names given.
Edit: If you are not bound to numpy arrays, you could use shared memory in the form of a multiprocessing.Array.
But you need to think about how to use this. When you create such an array you can specify if it should be protected with a lock (which is the default). This wil serialize access to the array and prevent memory corruption, but it will show things down. The other option is to not use a lock. But in that case, you have to prevent memory corruption.
For example, say you have an array of 100 numbers, and you want to use two processes. Then you should program your worker function to take an offset argument. The first worker gets offset 0, and only works on array elements 0 to 49. The second worker gets offset 50 and only works on elments 50 to 99.
If you do it like this, you should be able to use shared memory without locks and without memory corruption.
| {
"pile_set_name": "StackExchange"
} |
Q:
hash code of different objects are the same
I am facing a bizarre outcome in a java application (Spring batch job) after one of the internal custom dependencies -a library we have developed in my company- has been upgraded.
After the upgrade in the code two new different objects of the same type show to have the same hash code.
CustomObject oj1 = new CustomObject();
oj1.setId(1234L);
CustomObject oj2 = new CustomObject();
oj2.setId(9999L);
System.out.println(oj1); //Prints CustomObject@1
System.out.println(oj2); //Prints CustomObject@1
System.out.println(oj1.hashCode()); //Prints 1
System.out.println(oj2.hashCode()); //Prints 1
I noticed this issue after realizing that one of the unit test which has a HashSet variable was only adding the very first object and ignoring the rests. Obviously the hashSet is doing what is supposed to do but the objects are not supposed to be the same and are new instances with different Ids. I tested the same thing outside of the unit test within the application and still the same issue. As soon as I revert back to the old dependency code behaves normally and the above print statements show different numbers!
I am sure one of the dependencies is causing this issue abut I am not able to determine the root cause.
CustomObject is being pulled indirectly through that same dependency and does not have equals() and hashcode() implemented, it only has
private static final long serialVersionUID = 1L;
Looking at the source of CustomObject reveals this implementation
public class CustomObject extends BaseModel implements Serializable
and BaseModel has the equals and hashCode methods defined
import org.jvnet.jaxb2_commons.lang.*;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import java.io.Serializable;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BaseModel")
@XmlSeeAlso({
CustomObject.class
})
public abstract class BaseModel implements Serializable, Equals2, HashCode2
{
private final static long serialVersionUID = 1L;
public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy2 strategy) {
if ((object == null)||(this.getClass()!= object.getClass())) {
return false;
}
if (this == object) {
return true;
}
return true;
}
public boolean equals(Object object) {
final EqualsStrategy2 strategy = JAXBEqualsStrategy.INSTANCE;
return equals(null, null, object, strategy);
}
public int hashCode(ObjectLocator locator, HashCodeStrategy2 strategy) {
int currentHashCode = 1;
return currentHashCode;
}
public int hashCode() {
final HashCodeStrategy2 strategy = JAXBHashCodeStrategy.INSTANCE;
return this.hashCode(null, strategy);
}
}
Thank you in advance.
A:
Clearly something has changed in a base class, and you will just have to find it and fix it, or else implement hashCode() and equals() acceptably in this class.
Somebody somewhere has implemented hashCode() to return 1, which is idiotic. They would have been better off not to implement it at all. And it's not hard to find. Just look at the Javadoc for CustomObject and see where it inherits hashCode() from.
A:
I think you have already realized what the answer to your question is, but the code that you added in your update makes it clear:
Your CustomClass extends the BaseClass.
The BaseClass overrides Object::hashCode()
The override in the version of BaseClass that you showed us will always return 1. It is calling a hashCode(ObjectLocator, HashCodeStrategy2) method with a specific strategy, but the implementation of that method simply ignores the strategy argument.
Now is pretty clear that that version the BaseClass code can only ever return 1 as the hashcode. But you say that your code used to work, and you only changed the dependency. From that, we must conclude that the dependency has changed, and that the new version of the dependency is broken.
If anything is "bizarre" about this, it is that someone decided to implement the (new) BaseClass like that, and release it without testing it properly.
Actually, there is a possible way that you can get your CustomClass to work. The BaseClass::hashCode(ObjectLocator, HashCodeStrategy2) method is public and not final, so you could override it on your CustomClass as follows:.
@Override
public int hashCode(ObjectLocator locator, HashCodeStrategy2 strategy) {
return System.identityHashCode(this);
}
And indeed, it may be that the implementers of BaseClass intend you to do this. But I would still argue that BaseClass is broken:
Coding the class so that hashCode returns 1 as the default behavior is nasty.
There is no javadoc in BaseClass to explain the need to override the method.
Their (unannounced?) change to the behavior of BaseClass is an API breaking change. You shouldn't do stuff like that, without very good reason, and without warning.
The default behavior of the corresponding equals method is objectively wrong.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to merge 2 database results in one column
I have 2 columns as follow:
A | B
---|---
7 | 1
7 | 2
3 | 7
4 | 5
-------
I want to get 1 column containing (1,2,3).
Currently i'm quering this:
SELECT `A` , `B`
FROM `mytable`
WHERE `A` =7
OR `B` =7
but I'm getting 2 columns containing the number 7 in both sides A and B.
i'm sure there is a way to get what I want but I don't know how to google that!!
A:
You could use this:
SELECT
case when A=7 then B else A end
FROM
yourtable
WHERE
7 IN (A, B)
If you want a single column, you could use this:
SELECT
GROUP_CONCAT(case when A=7 then B else A end
ORDER BY case when A=7 then B else A end)
FROM
yourtable
WHERE 7 IN (A, B)
See fiddle here.
If value of both A and B could be 7 at the same time, and you want to skip that row, you could substitute:
WHERE 7 IN (A, B)
with
WHERE A=7 XOR B=7
| {
"pile_set_name": "StackExchange"
} |
Q:
Is the Three-Eyed Raven incapable of emotion?
(Game of Thrones, S07E03–E04)
When Meera leaves Bran at Winterfell and is unsatisfied with his lack of gratitude for all of her help (which you would be after all they went through), she concludes that 'Bran' died in the cave, leaving only the Three-Eyed Raven.
Bran tells Meera that he remembers being 'Bran' but remembers "so much else now", without even trying to express any more thanks, consolation or sorrow for her/their losses along the way. What's more he now constantly talks in a slow and monotonous tone, appearing devoid of any emotion.
He clearly does still possess all of Bran's memories when conversing with Sansa and Arya in the Weirwood and can express reason as he gives the dagger to Arya claiming "it is wasted on a cripple".
He does, however, in S07E03, express sorrow at what has happened to Sansa and that "it happened at home".
So now that he has assumed the identity of the Three-Eyed Raven and the associated memories, is he losing the capability of expressing or feeling emotion to the point where it will disappear completely?
A:
From the mouth of the actor in charge of playing the current Three-Eyed Raven, Isaac Hempstead-Wright:
"He's got this wealth of important information that really needs to get to the right people. And so by the start of season seven, Bran is in many ways a very different character," Hempstead Wright said. "He's the Three-Eyed Raven — he's not Bran Stark, which means he's really just a vehicle for the greater world's fate. That is what Bran's destiny is and what he's doing in season seven."
— Isaac Hempstead-Wright, INSIDER
and
"Bran is existing in thousands of planes of existence at any one time. So it’s quite difficult for Bran to have any kind of semblance of personality anymore because he’s really like a giant computer."
— Isaac Hempstead-Wright, Entertainment Weekly
Essentially: being in all places at once, throughout time (past, present and potential future) has been a gift and a curse for Bran, as he is no longer the Bran Stark we knew before, even though he says himself that he remembers what it was like to be Bran Stark, a boy from Winterfell, scattering your mind to bear witness to every event ever in the world, as well as being given the burden of the responsibility of seeing the world through the peril of the Night King, seems to have this extreme and literal greater-goal effect on his character. He repeatedly confirms what the actor has also clarified: he is no longer Bran Stark.
His apparent apathy and emotionlessness are a consequence of not having the same perspective that normal people have. We see Meera saying, "My brother died for you", having no effect on Bran because he has watched hundreds of thousands of deaths and births and horrific events, he has a completely shifted perspective, almost god-like, on the relatively smaller events or interactions, due to his omniscience.
Since I first wrote this answer, an official HBO interview with actor Isaac Hempstead-Wright, over at the official behind the scenes blog, Making Game of Thrones, has come out, further confirming what has been said, as well as adding some more insight:
HBO: Do you agree with Meera’s assessment that Bran died in the cave back in Season 6?
Isaac Hempstead Wright: It’s quite a bold thing for Meera to have said. Sadly, I think in many ways she was right. It’s just this whole idea that Bran has become a much smaller part of the character’s brain, when before 100 percent of his head was taken up with being Bran Stark. Now, that’s just one tiny file in a huge system. But certainly, he’s almost completely a different character. He acts utterly differently, and really any semblance of personality he used to have has gone.
HBO: Is there anything left of the old Bran?
Isaac Hempstead Wright: In Episode 4 [“The Spoils of War”] he says, “I remember what it felt like to be Brandon Stark, but I remember so much else now,” which sums up exactly the situation Bran is in. There is a flicker of Bran left in him, but really, can you imagine putting the entire history of the universe, every single moment, every single second that ever existed in one person’s brain? You’d think it would just short circuit. Bran just becomes this calm, zen character. He’s really like a human supercomputer.
HBO: How challenging was it to essentially take on that new character while still maintaining the fact that you are in some small way Bran?
Isaac Hempstead Wright: It was definitely difficult to get it right. I had a meeting with [series creators] David [Benioff] and Dan [Weiss], and they wanted him to be quite monotone and agenda-less, but at the same time have a slight flair, so it wasn’t just like listening to a robot talk. There had to be a sense of mystery and wisdom to him. He was sort of inspired by Dr. Manhattan in The Watchmen series — being in all these places at once, in all these time zones at once. I tried to base it on the old Three-Eyed Raven [played by Max von Sydow in Season 6] and have a sense of this wise, old, man sitting in a tree. At the same time, still have that slight spark somewhere in there where you know this is Bran Stark. It was a fine balance.
—"Isaac Hempstead Wright on the 'Fine Balance' of Playing Bran", Making of Game of Thrones
A:
I think, first of all, that kind of broad, over-arching knowledge of everything is distinctly not a human experience (think of Dr Manhattan in the Watchmen). The previous three-eyed raven became detached enough from normal human feelings and emotions that he sat there and allowed tree roots to grow through him over the decades/centuries. To be the three-eyed raven is to sacrifice your humanity and enter a different plane of existence, clearly.
But, on the other hand, I'd think you'd have to lose touch with your human emotions, and empathy. You're able to see and experience everything that has ever happened to everyone. Which means Bran can see and experience his father's final moments of fear, despair, his actual death getting his head chopped off. He'd feel his own grief and despair seeing his father betrayed, he'd see and experience Arya's and Sansa's grief, despair and loss in that moment, and other awful moments ("How is Sansa doing? Oh, looks like she got married, awesome...." then he gets to experience and see her being raped and tortured by her husband).
If he doesn't develop a powerful detachment from his former feelings and empathy, the Three-Eyed Raven would experience, first-hand, all the tragedy and loss to fill thousands of lifetimes, on a constant basis. It would drive a normal human mad or to suicide, very quickly.
I suspect that part of his "training" is not only learning to control the ability to see the visions, but learning how to deal with what he sees, as well. When he gives into his natural human inclinations and tries to go back and see what he was deemed not ready to see yet, he encounters the Night King, gets touched, and the dead are unleashed upon the sanctuary he was in. Behaving like a normal human has disastrous consequences, and he was being trained not to behave that way.
None of this is canon, just my own speculation on why he has to become detached as he more fully develops into this other, non-human being.
A:
Alright to elaborate on my comment
In short wargs leave part of their selves in the animal and so when the animal dies part of the warg dies as well. So the death of summer resulted in Bran losing his emotions as he spent a lot of time in Summer which Jojen warned him about
From Westeros
Once an animal has been joined to a man, any skinchanger can slip inside and ride him. The joining works both ways, however, for a dead skinchanger's animal carries a part of him and the new master of the beast will find the dead man's voice whispering to him (III: 835)
-
When the beast is warged the skingchanger/warg/greenseer can sense where the animal is
As such we see that Wargs/Skin Changers/Greenseer leave part of their selves in their animal. As such when that animal dies we can assume that that piece dies and as the entire Greenseeing thing is very pagan/Celtic it fits that the greenseer put their souls in objects.
It also appears to work in reverse with Rickon acting more like his wolf in the books
A large list of skin changing/warging references in the books
Westeros: http://www.westeros.org/Citadel/Concordance/Section/14.1.2./
Additional: http://awoiaf.westeros.org/index.php/Skinchanger
BONUS
Also From Westeros
As a powerful skinchanger dies, his ability expands to encompass all
animals in his vicinity (V: 14)
Just including this because I did not know it and am wondering if it could happen in the show.
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting a text file to a CSV file
I'm attempting to learn more about Java and have created a method that takes a text file with stdout (space separated file) and converts it to a CSV file.
I was attempting to use standard Java SE version 8.
Is there a better, more efficient, way of doing this?
The logic is:
Open file
Read file by line into string so it can be split
Split string removing spaces, back into array
Join with StringJoiner using ,
Convert back to string to remove leading ,
Update final array to be returned
Method to open file:
public void OpenFile(String fileName)
{
try
{
subFile = new Scanner (new File(fileName));
}
catch (Exception e)
{
System.out.println("File dosn't exist.");
}
}
Method to convert:
public String[] TextToCsvArray(String[] fileArray)
{
int i=0;
while(subFile.hasNext())
{
String line = subFile.nextLine();
String[] split = line.split("\\s+");
StringJoiner joiner = new StringJoiner(",");
for (String strVal: split)
joiner.add(strVal);
line = joiner.toString();
line = line.startsWith(",") ? line.substring(1) : line;
fileArray[i++] = line;
}
return fileArray;
}
A:
If your input is already separated correctly by spaces, it seems all you need to do is to convert those into commas and you're good. I'm not sure you need to go to/from arrays.
I would replace the code inside the loop:
{
String line = subFile.nextLine();
String[] split = line.split("\\s+");
StringJoiner joiner = new StringJoiner(",");
for (String strVal: split)
joiner.add(strVal);
line = joiner.toString();
line = line.startsWith(",") ? line.substring(1) : line;
fileArray[i++] = line;
}
with this:
{
String line = subFile.nextLine();
line.trim().replaceAll(" +", " "); //check for double spaces
line.replace(' ', ','); //replace space with comma
fileArray[i++] = line;
}
Oh, and check for the array size like someone else mentioned.
A:
Since you are using Java 8 it is good to use the great streaming methods it give you. You can write your code simply like the following:
public static void main(String[] args) {
String fileName = "./a.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
String result = stream.map(s -> s.split("\\s+"))
.map(s -> Arrays.stream(s).collect(Collectors.joining(","))+"\n")
.collect(Collectors.joining());
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
The final result is stored in result and you just need simply to write it into the file!
| {
"pile_set_name": "StackExchange"
} |
Q:
NHibernate QueryOver and string.format
I am working with QueryOver in NHibernate and I want to customize one property of my projected DTO using the following syntax:
IEnumerable<PersonResponseMessage> persons =
session.QueryOver<PersonEntity>()
.SelectList(list => list
.Select(p => p.Active).WithAlias(() => dto.Active)
.Select(p => p.Alert).WithAlias(() => dto.Alert)
.Select(p => p.Comments).WithAlias(() => dto.Comments)
.Select(p => string.Format("{0}api/Person/{1}", uriHelper.Root, p.Id)).WithAlias(() => dto.DetailsUrl)
)
.TransformUsing(Transformers.AliasToBean<PersonResponseMessage>())
.List<PersonResponseMessage>();
Unfortunately NHibernate cannot do this and throws an exception saying that:
Variable P referenced from scope "" is not defined
A:
There are in common two ways. Partially we can move that concat operation on the DB side, as documented here:
16.7. Projection Functions
In this case, we'll use the Projections.Concat:
.SelectList(list => list
.Select(p => p.Active).WithAlias(() => dto.Active)
.Select(p => p.Alert).WithAlias(() => dto.Alert)
.Select(p => p.Comments).WithAlias(() => dto.Comments)
// instead of this
//.Select(p => string.Format("{0}api/Person/{1}", uriHelper.Root, p.Id))
// .WithAlias(() => dto.DetailsUrl)
// use this
.Select(p => Projections.Concat(uriHelper.Root, Projections.Concat, p.Id))
.WithAlias(() => dto.DetailsUrl)
)
.TransformUsing(Transformers.AliasToBean<PersonResponseMessage>())
.List<PersonResponseMessage>();
But I would vote for ex-post processing on the Application tier, in C#:
.SelectList(list => list
.Select(p => p.Active).WithAlias(() => dto.Active)
.Select(p => p.Alert).WithAlias(() => dto.Alert)
.Select(p => p.Comments).WithAlias(() => dto.Comments)
// just the ID
.Select(p => p.Id).WithAlias(() => dto.Id)
)
.TransformUsing(Transformers.AliasToBean<PersonResponseMessage>())
.List<PersonResponseMessage>()
// do the concat here, once the data are transformed and in memory
.Select(result =>
{
result.DetailsUrl = string.Format("{0}api/Person/{1}", uriHelper.Root, p.Id)
return result;
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Where is $page['sidebar_second'] rendered? I want to edit the style of the listing of the recent comments
The comments in the block recent comments is styled with an unordered list. I want the points of the list beginn exactly under the N of New Comments.
Google Chrome tells me that there is a padding-left: 40px; attribute:
I do not know from where i get this attribute. I looked in my themes css files but there is no attribut padding-left: 40px;
Here is the element lookup in Firefox:
I need to set the padding-left attribute to exactly 15px. This is how it should look like:
I'm using the mas Theme in markapot.
Can I define the style of the ul in the function $page['sidebar_second']? If so, where is the sidebar built?
Thanks for any help!
A:
I think you have to look in how theme works in Drupal. However, as per your question, $page['sidebar_second'] is the variable that stores the region "sidebar_second".
This region doesn't have any specific styles and this goes for all the other regions as well. If a block is created in your system it needs a region to be displayed. So The blocks are always assigned to the desired regions.
If you want to style the block then you have to find the candidate files via devel & devel_themer module and then in the theme directory have to create the file and style. Also if you are not wiling to do that then write a overriding css for your theme that will override the styles like,
.class-name {
padding: 15px !important;
}
But I would recommend not to use !important unless its really needed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any API to fetch both rear and front camera view at the same time?
I have a requirement to show both rear and front camera in a single display. Is it possible to show both simultaneously. Is there any api to fetch both views at the same time?
A:
Same as a single camera... Just double.
Two SurfaceHolders, and two Camera instances.
http://developer.android.com/reference/android/hardware/Camera.html
| {
"pile_set_name": "StackExchange"
} |
Q:
High-pitched noise from boost converter. Need your help
I'm experiencing some high-pitched squealing noise from my boost converter, I'm getting some resonating frequency when I start increasing the load current.The inductor is a 47uH inductor. The part number for the diode is MBRD640CTT4G.
This is my schematic:
[1]
I checked the power line with the scope and this is the 12V line @ 100mA using AC Coupling:
[2]
As you can see, the ripple noise isn't so bad, I'm getting about 200mV peak to peak.
But when I run it at 500mA load this is what happens:
[3]
The ripple is horrible, I'm getting about 4V p-to-p.
Any ideas what is going on?
A:
I went into AN19 http://cds.linear.com/docs/Application%20Note/an19fc.pdf and it has a section for Frequency Compensation on pin VC. I simply increased the capacitance to 1uF and kept the resistor on 1K and I no longer have this problem. I am going to talk to Linear Tech to better fine tune this circuit and see if there is a more optimal value for that Capacitor (C112).
| {
"pile_set_name": "StackExchange"
} |
Q:
Git gets confused with ä in file name
I'm in a bad git situation because of a filename with an ä. It's an old file that probably has been there for ages:
So it's marked as untracked with \303\244 but then if I remove it, it's instead marked as deleted, but with \314\210. Very confusing. I don't really care about the file, but want to know for the future…
~/d/p/uniply ❯❯❯ git status master ◼
On branch master
Your branch is up-to-date with 'origin/master'.
Untracked files:
(use "git add <file>..." to include in what will be committed)
"deployment/ec2/Prods\303\244ttning"
nothing added to commit but untracked files present (use "git add" to track)
~/d/p/uniply ❯❯❯ rm deployment/ec2/Prodsättning master ◼
~/d/p/uniply ❯❯❯ git status master ✖
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
deleted: "deployment/ec2/Prodsa\314\210ttning"
no changes added to commit (use "git add" and/or "git commit -a")
~/d/p/uniply ❯❯❯ git checkout -- deployment/ec2 master ✖
~/d/p/uniply ❯❯❯ git status master ◼
On branch master
Your branch is up-to-date with 'origin/master'.
Untracked files:
(use "git add <file>..." to include in what will be committed)
"deployment/ec2/Prods\303\244ttning"
nothing added to commit but untracked files present (use "git add" to track)
A:
Short version: You’re clearly using a Mac, which converts all filenames to NFD, and git used to blindly treat filenames as bytes but now converts filenames to NFC on Mac for better compatibility with other systems. As a result, old paths in commits will behave strangely.
$ python3
>>> import unicodedata
>>> unicodedata.normalize('NFC', b'a\314\210'.decode()).encode()
b'\xc3\xa4'
>>> unicodedata.normalize('NFD', b'\303\244'.decode()).encode()
b'a\xcc\x88'
The full names for these formats are Normalization Form D (Canonical Decomposition) and Normalization Form C (Canonical Decomposition, followed by Canonical Composition), and they are defined in UAX #15.
Similar things can happen on case-insensitive filesystems — try checking out the Linux kernel tree on a Windows or Mac! — with the exception that you might expect to find a few repos containing both Makefile and makefile, but nobody in their right mind would check in files named both a\314\210 and \303\244, at least not deliberately.
The core problem is that the operating system makes the same file appear under different names, so git sees something different depending on what it’s looking for, if what it’s looking for is not the default name that the operating system is presenting.
Here’s how that path would behave today, starting fresh:
$ git init
Initialized empty Git repository
$ git config --get core.precomposeUnicode
true # this is the default in git 1.8.5 and higher
$ touch Prodsättning
$ env -u LANG /bin/ls -b
Prodsa\314\210ttning
$ git status -s
?? "Prods\303\244ttning"
By using ls in C locale, I can see the bytes in the filename, which contains the decomposed values. But git is composing the character into a single code point, so that users on different platforms will not produce different results. The patch that introduced precomposed unicode explains in detail what happens for various git commands.
If two files in a commit have the same name up to Unicode normalization (or case folding), then they will appear to "fight" when git checks out the files:
$ git clone https://gist.github.com/jleedev/228395a4378a75f9e630b989c346f153
$ git reset --hard && git status -s
HEAD is now at fe1abe4
M "Prods\303\244ttning"
$ git reset --hard && git status -s
HEAD is now at fe1abe4
M "Prodsa\314\210ttning"
So, if you just want to remove the file, you can proceed as you like. If you want to reliably manipulate these files, look at setting the core.precomposeUnicode option to false, so that git will store exactly the filename bytes you tell it, but that is probably more trouble than it’s worth. I might suggest creating a commit that converts all the filenames to NFC so that git will not think a file is missing.
There are some older answers to this question at Git and the Umlaut problem on Mac OS X, but many of them predate git’s ability to normalize Unicode, and setting core.quotepath=false will only cause confusion in this case.
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing the toolbar in Emacs Lisp
I'm trying to customize the Emacs toolbar with my own images and commands. I have two images for each button, a "disabled" and an "enabled" image. Unfortunately, elisp only provides tool-bar-add-item, which allows you to specify a single image. However, the extended menu item syntax for the toolbar has an :image property, which can be set to either a single image or a vector of four images, for all combinations of enabled/disabled and selected/deselected. I'm storing my two images in "filename.xpm" and "filename-disabled.xpm", and I've defined a helper function to allow me to easily define new toolbar items in this format:
(defun wk-add-toolbar-button (display-name icon definition &rest properties)
"Add an item to the toolbar
Automatically look for ICON.xpm and ICON-disabled.xpm"
(let ((images
`((,(concat icon ".xpm") xpm nil)
(,(concat icon ".xpm") xpm nil)
(,(concat icon "-disabled.xpm") xpm nil)
(,(concat icon "-disabled.xpm") xpm nil))))
(define-key
global-map
(vector 'tool-bar (make-symbol display-name))
`(menu-item
,display-name
,(make-symbol display-name)
,definition
:image ,(vconcat (mapcar (lambda (xs) (apply 'create-image xs)) images))
,@properties))))
But when I call this function, like:
(setq tool-bar-map (make-sparse-keymap))
(wk-add-toolbar-button "Build" "c:/Users/William/Desktop/emacs-icons/build" 'smart-compile)
my toolbar remains empty.
Adding an image manually, like this:
(define-key global-map [tool-bar build]
`(menu-item ,(symbol-name 'build) ,'smart-compile :image [
,(create-image "c:/Users/William/Desktop/emacs-icons/build.xpm" 'xpm nil)
,(create-image "c:/Users/William/Desktop/emacs-icons/build.xpm" 'xpm nil)
,(create-image "c:/Users/William/Desktop/emacs-icons/build-disabled.xpm" 'xpm nil)
,(create-image "c:/Users/William/Desktop/emacs-icons/build-disabled.xpm" 'xpm nil)]))
causes the menu item to appear, but then it quickly disappears, with no obvious trigger.
How can I correct this behavior?
A:
This part is faulty:
`(menu-item
,display-name
,(make-symbol display-name) ; <=========== GET RID OF THIS
,definition
Get rid of the make-symbol part and you get what you used manually. And an icon appears in the tool bar.
You can see what's wrong if you print the result of calling wk-add-toolbar-button:
(menu-item "Build" Build smart-compile :image
[(image :type xpm :file "c:/Users/William/Desktop/emacs-icons/build.xpm")
(image :type xpm :file "c:/Users/William/Desktop/emacs-icons/build.xpm")
(image :type xpm :file "c:/Users/William/Desktop/emacs-icons/build-disabled.xpm")
(image :type xpm :file "c:/Users/William/Desktop/emacs-icons/build-disabled.xpm")])
That Build symbol is extaneous. You want only the "Build" string and the smart-compile symbol.
| {
"pile_set_name": "StackExchange"
} |
Q:
Authorization error on gdata Spreadsheet
Was using gdata to update a spreadsheet file on my drive using python on appengine. Everything works fine until recently, the code started encountering error.
import webapp2
import gdata.spreadsheet.text_db
from google.appengine.api import mail
client = gdata.spreadsheet.text_db.DatabaseClient(username='[email protected]', password='passsword')
class createSurvey(webapp2.RequestHandler):
def get(self):
db = client.CreateDatabase("Project")// this line started to show the error below.
.
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
db = client.CreateDatabase("Project")
File "C:\Python27\lib\gdata\spreadsheet\text_db.py", line 146, in CreateDatabase
db_entry = self.__docs_client.UploadSpreadsheet(virtual_media_source, name)
File "C:\Python27\lib\atom\__init__.py", line 1475, in deprecated_function
return f(*args, **kwargs)
File "C:\Python27\lib\gdata\docs\service.py", line 466, in UploadSpreadsheet
folder_or_uri=folder_or_uri)
File "C:\Python27\lib\gdata\docs\service.py", line 161, in _UploadFile
converter=gdata.docs.DocumentListEntryFromString)
File "C:\Python27\lib\gdata\service.py", line 1236, in Post
media_source=media_source, converter=converter)
File "C:\Python27\lib\gdata\service.py", line 1358, in PostOrPut
'reason': server_response.reason, 'body': result_body}
RequestError: {'status': 401, 'body': '<HTML>\n<HEAD>\n<TITLE>Authorization required</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Authorization required</H1>\n<H2>Error 401</H2>\n</BODY>\n</HTML>\n', 'reason': 'Authorization required'}
Initially thought it was the restriction on the file but i have made it open and it still didn't work. How can i fix this .
A:
Google stopped allowing such method of authentication. Developers have to create credentials on google console. see this for more help and if you are using Google Data Protocol for to access help use spreadsheet as db like i was trying to do, This should also be of help.
| {
"pile_set_name": "StackExchange"
} |
Q:
error: `itoa` was not declared in this scope
I have a sample c file called itoa.cpp as below:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,buffer,10);
printf ("decimal: %s\n",buffer);
return 0;
}
When i compile the above code with the below command:
gcc itoa.cpp -o itoa
i am getting this error:
[root@inhyuvelite1 u02]# gcc itoa.cpp -o itoa
itoa.cpp: In function "int main()":
itoa.cpp:10: error: "itoa" was not declared in this scope
What is wrong in this code? How to get rid of this?
A:
itoa is not ansi C standard and you should probably avoid it. Here are some roll-your-own implementations if you really want to use it anyway:
http://www.strudel.org.uk/itoa/
If you need in memory string formatting, a better option is to use snprintf. Working from your example:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
snprintf(buffer, sizeof(buffer), "%d", i);
printf ("decimal: %s\n",buffer);
return 0;
}
A:
If you are only interested in base 10, 8 or 16. you can use sprintf
sprintf(buf,"%d",i);
A:
Look into stdlib.h. Maybe _itoa instead itoa was defined there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Slick handle a collection like List/Set etc?
My question is:
My Scala's case class has parameters where a collection(i.e., List) is a part of its constructor parameters, and I wonder how to map my case class into Slick style database table or tables if necessary?
In other words, I would like to "Join tables in Slick way to map to a Json formatted case class, which is to be represented to the frontend (javascript) bits"?
Please kindly give me a shout if my question is not clear enough.
The same question is at:
https://groups.google.com/forum/#!topic/scalaquery/QqZz_M-1VTg
For example,
case class ClassA (id: Int, lists: List[ClassB])
object ClassA extends TableQuery(new ClassATable(_)) {
// JSON formatter
implicit val classAFormat: Format[ClassA] = (
(JsPath \ "id").formatNullable[Int] and
(JsPath \ "lists").format[List[ClassB]]
)(ClassA.apply, unlift(ClassA.unapply))
}
case class ClassB (id: Int, name: String)
object ClassB extends TableQuery(new ClassBTable(_)) {
implicit val classBFormat: Format[ClassB] = (
(JsPath \ "id").formatNullable[Int] and
(JsPath \ "name").format[String]
)(ClassB.apply, unlift(ClassB.unapply))
}
So, the missing bit is to create ClassATable and ClassBTable in such a way that there is a bi-directional relationship by means of each one's "id"?
Many thanks,
A:
A class like this
case class ClassA (id: Int, lists: List[ClassB]) implies that table B has to be loaded when Table A is loaded. This hard-codes the loading strategy. This is avoided in idiomatic Slick code. Instead, in Slick this is usually solved with tuples to make it more flexible. The Slick tables are then simply mapped to versions of ClassA and ClassB, which do NOT contain references to each other, only the column data. Instead, a join can produce a result of type List[(ClassA,ClassB)] and with a groupBy and map you get (ClassA,List[ClassB]). (Alternatively you get the same with two separate queries.) This is roughly what you want. Instead of a Tuple you can define a small case class AWithBs(a: ClassA, bs: List[ClassB]) to associate them. You can .map(AWithBs.apply) to create them from the list of tuples.
| {
"pile_set_name": "StackExchange"
} |
Q:
Saving java file in maven project fails
when I try to save a java file in my project the following error occurs.
Failed to (re)build the JAX-RS metamodel for projet TestApp
java.lang.NullPointerException
It only occurs when I create the default constructor so
public class Account {
public Account () {}
}
gets the error, while
public class Account {
}
does not get it.
I was using the jboss-javaee6-webapp-blank-archetype to create my project
A:
I found the failure by myself, there was no src/main/java folder created(I had my files in the resources folder), I reinstalled Eclipse, now the folder gets created and when I have my java files there, I don't get an error anymore.
| {
"pile_set_name": "StackExchange"
} |
Q:
How response.end and response.send differs?
Hi I am trying to build a simple application using express js. I am new to node and express js. Can somebody explain the difference in response.end and response.send
I tried this command and both sent the request(message) to the Server.
res.send('Send the message');
res.end('send the message');
A:
res.send() is a method built into express, and will make it automatically assume a Content-Type of html.
res.end(), on the other hand, just uses the underlying end() implementation built into nodejs on the response stream (aka. not express), so it doesn't attempt to assume the Content-Type.
| {
"pile_set_name": "StackExchange"
} |
Q:
How good is current tsunami prediction?
We all know that predicting tsunami and earthquake is difficult, with too many variables involved.
But with the advent in data collection and computing power and better models, one should be able to predict tsunami better than in the past. How accurate is current tsunami prediction?
A:
Well, immediately after the earthquake, they created the map showing when the tsunami arrives at different places:
I guess that it ended up being pretty accurate but I haven't checked. The speed of ocean waves actually depends on the frequency...
Your ordering "tsunami and earthquake" is somewhat bizarre. You do acknowledge and realize that the tsunami was a consequence of the earthquake, don't you? ;-) Predicting earthquakes themselves is not really possible. I think that no one knew about the Japanese earthquake until the very moment when it took place.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple passes with awk and execution order
Two part question:
Part One:
First I have a sequence AATTCCGG which I want to change to TAAGGCC. I used gsub to change A to T, C to G, G to C and T to A. Unfortunetly awk executes these orders sequentially, so I ended up with AAACCCC. I got around this by using upper and lower case, then converting back to upper case values, but I would like to do this in a single step if possible.
example:
echo AATTCCGG | awk '{gsub("A","T",$1);gsub("T","A",$1);gsub("C","G",$1);gsub("G","C",$1);print $0}'
OUTPUT:
AAAACCCC
Part Two:
Is there a way to get awk to run to the end of a file for one set of instructions before starting a second set? I tried some of the following, but with no success
for the data set
1 A
2 B
3 C
4 D
5 E
I am using the following pipe to get the data I want (Just an example)
awk '{if ($1%2==0)print $1,"E";else print $0}' test | awk '{if ($1%2==0 && $2=="E") print $0}'
I am using a pipe to rerun the program, however I have found that it is quicker if I don't have to rerun the program.
A:
This can be efficiently solved with tr:
$ echo AATTCCGG | tr ATCG TAGC
Regarding part two (this should be a different question, really): no, it is not possible with awk, pipe is the way to go.
A:
Here is a method I have found for the first part of the question using awk. It uses an array and a for loop.
cat sub.awk
awk '
BEGIN{d["G"]="C";d["C"]="G";d["T"]="A";d["A"]="T";FS="";OFS=""}
{for(i=1;i<(NF+1);i++)
{if($i in d)
$i=d[$i]}
}
{print}'
Input/Output:
ATCG
TAGC
| {
"pile_set_name": "StackExchange"
} |
Q:
how to solve orientation issue?
I want to make 480x800, 600x800, 600x1024 and 800x1280 resolution layouts.
i have to show both orientation(portrait and landscape) with resolution 600x800, 600x1024 and 800x1280 and resolution 480x800 show only landscape mode.
Right now it is showing both orientation mode.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nga.swp" android:versionCode="1" android:versionName="1.0">
<supports-screens android:resizeable="true"
android:largeScreens="true" android:normalScreens="false"
android:smallScreens="false" android:anyDensity="true" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:label="@string/app_name" android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PhraseListActivity"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:label="@string/app_name" android:windowSoftInputMode="adjustPan" />
<activity android:name=".ViewActivity" android:theme="@android:style/Theme.NoTitleBar"
android:label="@string/app_name" />
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-sdk android:minSdkVersion="8" />
</manifest>
my issue is how i am able to show landscape mode only with resolution 480x800.
what changes i have to do in my menifest file.
A:
The best way to have conditional layouts is by using qualified directory names inside the /res directory.
But in your case, you would need to change the android:screenOrientation of your activity. Alas, it is in the manifest and it does not seem to be setable in your activity layout.
So, I guess you have to use code in your activity onCreate.
First get the screen dimension using:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Then conditionally adapt screen orientation using :
if((width != 480) && (height !=800))
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
See ActivityInfo.screenOrientation for further orientation modes.
| {
"pile_set_name": "StackExchange"
} |
Q:
The set $\{1,2,3,\ldots,n\}$, where $n \geq 5$, can be divided into two subsets so that the sum of the first is equal to the product of the second
A peer of mine showed me earlier today this problem, taken from a 7th grade math contest :
Let $A=\{1,2,3,\ldots,n\}$; (where $n \geq 5$) prove that $A$ can be divided into two disjoint subsets such that the sum of the elements in the first subset is equal to the product of the elements in the second subset.
This has been puzzling me for 15 minutes already, but I'm sure there's a simple, straight-forward way to do it since it's a 7th grade problem, albeit I can't see it.
Can anyone shed some wisdom here ?
A:
Going by the assumption that for an odd $n$ the product of $1, (n-1), (n-a)$ is equal to the sum of the rest of the numbers, we have
$$
1(n-1)(n-a) = \frac{n(n+1)}{2} - 1 -(n-1) - (n-a)
$$
solving this gives $a=\frac{n+1}{2}$
Now for odd $n \ge 5$, we have
$$n-a = \frac{n-1}{2} \ge 2$$
Therefore the numbers $1, n-1, n-a$ are distinct.
A similar assumption for even $n$ with $1, n, (n-a)$ gives
$$
1*n(n-a) = \frac{n(n+1)}{2} - 1 -n - (n-a)
$$
and the solution is $a=\frac{n+2}{2}$
And for even $n \ge 6$ we have
$$n-a = \frac{n-2}{2} \ge 2$$
And therefore the numbers $1, n, n-a$ are distinct.
A:
You can always do it with the product being three elements, one of them $1$.
$$1+2+3+4+\cdots +n = n(n+1)/2$$
Find $a,b$ so that $n(n+1)/2-(1+a+b) = ab$. This is easy to do since $1+a+b+ab=(1+a)(1+b)$.
So, when $n$ odd, choose $a=n-1,b=\frac{n-1}{2}$. E.g., for $n=7$, that gives $1\cdot 3\cdot 6=2+4+5+7$.
For $n$ even, $a=n,b=\frac{n-2}{2}$. For example, $n=6$ yields $a=6,b=2$ and $1\cdot 2\cdot 6=3+4+5$.
When $n<5$, $\{a,b,1\}$ are not distinct.
It's harder to do it in two elements in the product. Then you'd need $ab=n(n+1)/2-(a+b)$ or $(1+a)(1+b)=\frac{n^2+n+2}{2}$. So you'd need to factor $\frac{n^2+n+2}{2}$ into two distinct numbers $\leq n+1$.
You can do this for $n=17$, for example, then $\frac{n^2+n+2}{2}=154=11\cdot 14$. so $a=10,b=13$. Then $$10\cdot 13 =1+2+3+4+5+6+7+8+9+11+12+14+15+16+17$$
The question came up about products of $4$ numbers. Let's still try to seek simple answers, so a product of the form $1\cdot 2\cdot a\cdot b = \frac{n(n+1)}{2}-(a+b+1+2)$, or:
$$2ab +a+b+3=\frac{n(n+1)}{2}$$ Multiply both sides by $2$ and you get:
$$(2a+1)(2b+1)+5 = n(n+1)$$
So we need to factor $n(n+1)-5$ into two distinct odd numbers $\leq 2n+1$. For example, $n=10$ then $n(n+1)-5=105=15\cdot 7$. So $a=3,b=7$. Then:
$$1\cdot2\cdot3\cdot 7 = 4+5+6+8+9+10$$
An example with the product containing $5$ elements, $n=20$ then:
$$1\cdot 2\cdot 3\cdot 4\cdot 8 = 5+6+7+9+10+\cdots + 20$$
An example with a product of $4$ numbers, none equal to $1$ (with $n=26$):
$$2\cdot 3\cdot 5\cdot 11 = 1+4+6+7+8+9+10+12+\cdots +26$$
Another with $4$ in the product:
$$3\cdot 5\cdot 7\cdot 16 = \frac{58\cdot 59}{2} - (3+5+7+16)$$
We can get arbitrarily long product solutions. You can show that for $n=k!-k$, let $A=\frac{k!}{2}-k$, then:
$$1\cdot 2\cdot3\cdots k\cdot A = \frac{(k!-k)(k!-k+1)}{2}-(1+2+\cdots + k + A)$$
For example:
$$\begin{align}4!\cdot 8 &= \frac{20\cdot21}{2}-(1+2+3+4+8)\\
5!\cdot 55 &= \frac{115\cdot116}{2}-(1+2+3+4+5+55)\\
6!\cdot 354 &= \frac{714\cdot715}{2}-(1+2+3+4+5+6+354)\\
7!\cdot 2513 &= \frac{5033\cdot 5034}{2}-(1+2+3+4+5+6+7+2513)
\end{align}$$
More generally, if $\{x_i\}_{i=1,\cdot,m}$ are distinct positive integers with at least one even, let $S=\sum x_i$ and $P=\prod x_i$. Then if $S=\frac{k(k+1)}2$ for some $k$, then let $A=\frac{P}{2}-k$ and $n=P-k$. Then:
$$A\cdot \prod x_i = \frac{n(n+1)}{2} - (x_1+\cdots + x_m + A)$$
For small collections of small values $x_i$ this doesn't always give a good $A$, but in most cases, it does.
For example $5+10=\frac{5(5+1)}2$. So $n=45$ and $A=20$, and you get $$5\cdot 10\cdot 20 = \frac{45\cdot 46}{2}-(5 + 10+20)$$
This means that we can always extend any $x_1,\cdots,x_m$ with a larger $x_{m+1}$ so that $\sum_{i=1}^{m+1} x_i$ is a triangular number, and then find the $A$ above. Indeed, we can write an explicit formula. If $S=\sum_{i=1}^m x_i$ and $P=\prod_{i=1}^m x_i$ then you can define $$\begin{align}x_{m+1}&=2S(S-1)\\x_{m+2}&=PS(S-1)-2S+1\\n&=2PS(S-1)-2S+1.\end{align}$$
A:
This can't be done for $n=4$.
One element of the product side won't do.
Two elements on the product side won't do. ($1*2=2\neq 7, 1*3=3\neq 8, 1*4\neq6, 2*3=6\neq 4, 2*4, nope$)
Surely it doesn't work for three elements on the product side.
It doesn't work.
For $n\geq 5$, certainly seems to be true. What I've found so far:
1*2*4 = 3+5
1*2*6 = 3+4+5
1*3*6 = 2+4+5+7
1*3*8 = 2+4+5+6+7
1*4*8 = 2+3+5+6+7+9
6*7 = 1+2+3+4+5+8+9+10
1*5*10 = 2+3+4+6+7+8+9+11
1*5*12 = 2+3+4+6+7+8+9+10+11
1*6*12 = 2+3+4+5+7+8+9+10+11+13
1*6*14 = 2+3+4+5+7+8+9+10+11+12+13
1*7*14 = 2+3+4+5+6+8+9+10+11+12+13+15
1*7*16 = 2+3+4+5+6+8+9+10+11+12+13+14+15
10*13 = 1+2+3+4+5+6+7+8+9+11+12+14+15+16+17
1*8*18 = 2+3+4+5+6+7+9+10+11+12+13+14+15+16+17
1*9*18 = 2+3+4+5+6+7+8+10+11+12+13+14+15+16+17+19
1*9*20 = 2+3+4+5+6+7+8+10+11+12+13+14+15+16+17+18+19
1*10*20 = 2+3+4+5+6+7+8+9+11+12+13+14+15+16+17+18+19+21
1*10*22 = 2+3+4+5+6+7+8+9+11+12+13+14+15+16+17+18+19+20+21
1*11*22 = 2+3+4+5+6+7+8+9+10+12+13+14+15+16+17+18+19+20+21+23
1*11*24 = 2+3+4+5+6+7+8+9+10+12+13+14+15+16+17+18+19+20+21+22+23
1*12*24 = 2+3+4+5+6+7+8+9+10+11+13+14+15+16+17+18+19+20+21+22+23+25
15*21 = 1+2+3+4+5+6+7+8+9+10+11+12+13+14+16+17+18+19+20+22+23+24+25+26
1*13*26 = 2+3+4+5+6+7+8+9+10+11+12+14+15+16+17+18+19+20+21+22+23+24+25+27
1*13*28 = 2+3+4+5+6+7+8+9+10+11+12+14+15+16+17+18+19+20+21+22+23+24+25+26+27
1*14*28 = 2+3+4+5+6+7+8+9+10+11+12+13+15+16+17+18+19+20+21+22+23+24+25+26+27+29
1*14*30 = 2+3+4+5+6+7+8+9+10+11+12+13+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29
1*15*30 = 2+3+4+5+6+7+8+9+10+11+12+13+14+16+17+18+19+20+21+22+23+24+25+26+27+28+29+31
1*15*32 = 2+3+4+5+6+7+8+9+10+11+12+13+14+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31
1*16*32 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+33
1*16*34 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33
1*17*34 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+35
22*28 = 1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+23+24+25+26+27+29+30+31+32+33+34+35+36
21*31 = 1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+22+23+24+25+26+27+28+29+30+32+33+34+35+36+37
1*18*38 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37
1*19*38 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+39
1*19*40 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39
1*20*40 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+41
1*20*42 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41
1*21*42 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+43
1*21*44 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43
27*36 = 1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+28+29+30+31+32+33+34+35+37+38+39+40+41+42+43+44+45
1*22*46 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45
1*23*46 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+47
1*23*48 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47
For $n=39$, I found these $7$ partitions:
1*19*38 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+39
1*25*29 = 2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+26+27+28+30+31+32+33+34+35+36+37+38+39
3*7*35 = 1+2+4+5+6+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+36+37+38+39
4*11*17 = 1+2+3+5+6+7+8+9+10+12+13+14+15+16+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39
5*10*15 = 1+2+3+4+6+7+8+9+11+12+13+14+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39
2*6*7*9 = 1+3+4+5+8+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39
1*3*4*7*9 = 2+5+6+8+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39
Amazingly good question!
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails - All tests fail - ' ... ConstraintException: UNIQUE constraint failed: admins.email ... '
When I run this: rails test, then all my (10) tests fail, with the same error (Unique constraint failed). Here's the error-message:
E
Error:
WelcomeControllerTest#test_the_truth:
ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE
constraint failed: admins.email: INSERT INTO "admins" ("created_at",
"updated_at", "id") VALUES ('2017-02-20 16:22:33.516784', '2017-02-20
16:22:33.516784', 298486374)
bin/rails test test/controllers/welcome_controller_test.rb:4
One of the tests are this one:
test "the truth" do
assert true
end
By browsing around, I saw that it probably was something about the fixtures. In /test/fixtures/admin.yml then this was there:
# This model initially had no columns defined. If you
# add columns to the model remove the '{}' from the fixture
# names and add the columns immediately below each fixture,
# per the syntax in the comments below
#
one: {}
# column: value
#
two: {}
# column: value
If I then comment out one: {} and two: {}, then it works. I have no idea why this is? Can anyone explain it, please?
A:
It doesn't like you using two emails that are nil, it is expecting unique email addresses for each model. Change it to this:
# This model initially had no columns defined. If you
# add columns to the model remove the '{}' from the fixture
# names and add the columns immediately below each fixture,
# per the syntax in the comments below
#
one:
email: '[email protected]'
two:
email: '[email protected]'
| {
"pile_set_name": "StackExchange"
} |
Q:
Employee and Customer = People Table?
Is it bad to store information such as: name, phone number, address etc. in one table? That would result in the Employee and Customer Table having a foreign key referencing to the "People" Table.
If we don't store such information in one table, we would have the Employee and Customer Table have a lot of similar type of information.
What would be the best design?
A:
My personal preference: separate out customer and employee database. While some of the data may be same between customer and employee, it won't be long before data requirements and rules start differing. For example, for employees you may want to store birth dates but you may not need that for customer.
Keeping the table also prevents error in selects. If customers and employees were reference in people and a newcomer doesn't know what to join and when to use the where clause to separate customers and employees, the result may be unexpected and may go undetected. Having customer and employee separate avoids such issues.
Having them separate is also helpful in adding customer table to schema associated with customers/orders etc., and employee tables can go to hr related schema. Different levels of protection can be applied to them.
People table's maintenance may affect customer and employee tables. For example, if you had to add a column in a large people table, some RDBMS may lock the table too long. If tables were separate, you would be able to prepare only the relevant group.
Overall, I see little benefit in creating people table with FK related to customer and employees. Perhaps others on SO may raise benefits of people table.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why are there many different ways to pronounce a phoneme?
A phoneme may be pronounced in different ways, depending on its position in the utterance, and still remain the same phoneme. Why?
A:
People don't produce phonemes.
Instead, they produce phones.
A listener then maps phone to phoneme.
So, if two speakers produce two phones, but both map to a single phoneme, an average listener would say these represent the same phoneme.
Note, this mapping is language-specific.
Further reading:
What languages have a three-way vowel distinction with backness?
| {
"pile_set_name": "StackExchange"
} |
Q:
WatchKit issue retaining data between classes
I have two classes named InterfaceController and LoadInterfaceController.
I'm fetching information in the LoadInterfaceController that I wish to pass-on to a variable in my InterfaceController class.
LoadInterfaceController:
- (void)fetchData {
NSArray *database = //fetched information
//... on fetch complete
InterfaceController *interfaceController = [InterfaceController alloc];
[interfaceController initilizeDatabase:database];
}
InterfaceController:
@property (nonatomic) NSArray *db;
- (void)initilizeDatabase:(NSArray *)database {
self.db = database;
NSLog(@"database count: %d", database.count); //: 3
NSLog(@"db count: %d", self.db.count); //: 3
[self utilizeInformation];
}
- (void)utilizeInformation {
NSLog(@"db count: %d", self.db.count); //: 0
//...
}
db's information is not retained outside of the initilizeDatabase: function.
I have tried running it on the main thread (as explained here), but the information is still not retained. How may I specify the thread to pass-on the information from my second class?
A:
There are no problems with the threads or retention, everything is right from this perspective. But there is another issue: when you initialise the InterfaceController programmatically you create an instance of it and the db property is perfectly stored until your Watch loads it again, because Watch creates another instance of InterfaceController on its own as a result you get the empty db property on a new instance.
The solution I'd suggest here is to add a model entity into your architecture that will act as a singleton class and it ensures your data always will be available.
Here is an implementation considering your example:
XYZDataBaseManager:
@interface XYZDataBaseManager : NSObject
+ (nonnull XYZDataBaseManager *)sharedInstance;
- @property (nonnull, strong) NSMutableArray *data;
@end
@implementation XYZDataBaseManager
+ (XYZDataBaseManager *)sharedInstance {
static dispatch_once_t once;
static XYZDataBaseManager *instance;
dispatch_once(&once, ^{
instance = [[XYZDataBaseManager alloc] init];
});
return instance;
}
@end
LoadInterfaceController:
- (void)fetchData {
NSArray *database = //fetched information
[XYZDataBaseManager sharedInstance].data = database;
}
InterfaceController:
@property (nonatomic) NSArray *db;
- (void)utilizeInformation {
NSLog(@"db count: %d", [XYZDataBaseManager sharedInstance].data.count]);
}
Of course there are a lot of things to improve but I think the main idea is clear. And also I didn't execute this code so there might be some typos (I'm more swift-oriented).
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a makefile for OpenEdge ABL?
I'm desperately looking for a way to make a makefile for Progress OpenEdge ABL, and let it compile only a subset of the application, based on what source file has changed.
Has anyone set up anything like this? I've used makefiles before in C applications, but never under Windows with an environment where not all files follow a set naming convention (e.g. abc/xxx may be a program, or an include).
A:
PCT could be the answer, is a JAR that you can use in an ANT script and manages Progress compilations with many several options, including multithreading or just recompiling what is required.
| {
"pile_set_name": "StackExchange"
} |
Q:
SSMS 2014 Addin ServiceCache Error
I'm trying to get the current connection using sql server 2014 (visual studio 2013), but I keep getting ServiceCache The type 'Microsoft.SqlServer.Management.UI.VSIntegration.ServiceCache' exists in both 'SqlPackageBase.dll' and 'Microsoft.SqlServer.SqlTools.VSIntegration.dll' when I put a breakpoint on the servicecache call. Anyone know of a fix for this? Any help is much appreciated!
my references are:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.SqlStudio.dll
Microsoft.SqlServer.Management.SqlStudio.Explorer.dll
Microsoft.SqlServer.RegSvrEnum.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.SqlTools.VSIntegration.dll
ObjectExplorer.dll
SQLEditors.dll
SqlWorkbench.Interfaces.dll
using System.Reflection;
using System.Globalization;
using Microsoft.SqlServer.Management.UI.VSIntegration;
using Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.RegSvrEnum;
using Microsoft.SqlServer.Management.SqlStudio.Explorer;
namespace NewAddin
{
/// <summary>The object for implementing an Add-in.</summary>
/// <seealso class='IDTExtensibility2' />
public class Connect : IDTExtensibility2, IDTCommandTarget
{
/// <summary>Implements the constructor for the Add-in object. Place your initialization code within this method.</summary>
public Connect()
{
}
SqlConnectionInfo _myCurrentConnection = null;
private UIConnectionInfo currentUIConnection;
/// <summary>Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary>
/// <param term='application'>Root object of the host application.</param>
/// <param term='connectMode'>Describes how the Add-in is being loaded.</param>
/// <param term='addInInst'>Object representing this Add-in.</param>
/// <seealso class='IDTExtensibility2' />
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
if (Microsoft.SqlServer.Management.UI.VSIntegration.ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo != null)
{
// _myCurrentConnection = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo;
currentUIConnection = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo;
}
A:
Remove reference to Microsoft.SqlServer.SqlTools.VSIntegration.dll. Then explicitly add a reference to the SQLPackageBase.dll
From the same location
C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\
That fixed it for me locally.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display child elements of at 100% height?
I am having an issue trying to make a specific element inside my <li> tag to take up 100% of the <li> height. Specifically I want an icon I added with a border on its right to fill the entire height of the <li> element.
as you can see from the last item in the list, the border for the download icon does not take the entire height of its <li> element. How can I fix this?
My code:
<ul>
<li>طلب المشروع من قبل الجهة المستفيدة<div class="download"><a href="#" class="active"><i class="fa fa-download"></i></a></div></li>
<li class="list_background">وجود قرار تخصيص موقع من قبل المجلس البلدي<div class="download"><a href="#" class="active"><i class="fa fa-download"></i></a></div></li>
<li>بكتاب الامانة العامة لمجلس الوزراء رقم 344 - 3679 المؤرخ<div class="download"><a href="#" class="inactive"><i class="fa fa-download"></i></a></div></li>
<li class="list_background">على مهندس المشروع التأكد من استيفاء ما يلي حسب ما جاء بكتاب الأمانة العامة لمجلس الوزراء رقم 344-3679
المؤرخ (مرفق صورة من الكتاب المذكور) :
<br>- استلام متطلبات المشروع معتمدة من قبل الجهة المستفيدة.
<br>- إعداد كراسة طلب المشروع.
<br>- الحصول على موافقة وزارة المالية على اعتماد ميزانية المشروع.
<br>- شهادة خلو الموقع من العوائق.<div class="download"><a href="#" class="inactive"><i class="fa fa-download"></i></a></div></li>
</ul>
CSS:
ul {
padding: 0;
margin: 0;
list-style: none;
width: 100%;
}
ul li {
direction: rtl;
text-align: right;
padding: 0 1rem 0 0;
margin: 0;
font-size: 1.1rem;
color: #8c97b2;
font-weight: 400;
border-bottom-style: solid;
border-bottom-width: 1px;
border-bottom-color: #dadfea;
line-height: 54px;
height: 100%;
}
ul li .download {
height: 100%;
float: left;
border-right-style: solid;
border-right-width: 1px;
border-right-color: #dadfea;
display: block;
}
ul li .download i {
font-size: 22px;
width: 54px;
text-align: center;
height: 100%;
}
A:
To achieve that you have to use table structure which mean make the li tag act as table and content act as tabel-cell and icon act as another table cell.
also add a container for the text and never let it flow on any container
ul {
padding: 0;
margin: 0;
list-style: none;
width: 100%;
}
ul li {
direction: rtl;
text-align: right;
padding: 0 1rem 0 0;
margin: 0;
font-size: 1.1rem;
color: #8c97b2;
font-weight: 400;
border-bottom-style: solid;
border-bottom-width: 1px;
border-bottom-color: #dadfea;
line-height: 54px;
height: 100%;
display: table;
width:100%;
}
ul li .download {
height: 100%;
float: left;
border-right-style: solid;
border-right-width: 1px;
border-right-color: #dadfea;
display: tablle-cell;
}
ul li p{
display:table-cell;
}
ul li .download i {
font-size: 22px;
width: 54px;
text-align: center;
height: 100%;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<ul>
<li><p>طلب المشروع من قبل الجهة المستفيدة</p><div class="download"><a href="#" class="active"><i class="fa fa-download"></i></a></div></li>
<li class="list_background"><p>وجود قرار تخصيص موقع من قبل المجلس البلدي</p><div class="download"><a href="#" class="active"><i class="fa fa-download"></i></a></div></li>
<li><p>بكتاب الامانة العامة لمجلس الوزراء رقم 344 - 3679 المؤرخ</p><div class="download"><a href="#" class="inactive"><i class="fa fa-download"></i></a></div></li>
<li class="list_background">على مهندس المشروع التأكد من استيفاء ما يلي حسب ما جاء بكتاب الأمانة العامة لمجلس الوزراء رقم 344-3679
المؤرخ (مرفق صورة من الكتاب المذكور) :
<br>- استلام متطلبات المشروع معتمدة من قبل الجهة المستفيدة.
<br>- إعداد كراسة طلب المشروع.
<br>- الحصول على موافقة وزارة المالية على اعتماد ميزانية المشروع.
<br>- شهادة خلو الموقع من العوائق.</p><div class="download"><a href="#" class="inactive"><i class="fa fa-download"></i></a></div></li>
</ul>
| {
"pile_set_name": "StackExchange"
} |
Q:
Symfony3 : choice type field filled with array of objects
I have an entity Product. My product can have multiple names in different languages. A name in french, a name in english, etc. I don't want to use an automatic translation.
The user will have to write the names in the Product form and select the corresponding language. He can add so many names as he wants thanks to an Add button.
All the languages are created by the admin user (in another form). So, Language is also an Entity which have a name (ex: English) and a code (ex: EN).
I created the Entity ProductName which have a name and a language (that conform to what the user writes in the Product form).
In that case, I don't need to associate Entity ProductName with Entity Language. I just want the language code. So, in my ProductName entity, I have this property :
/**
* @ORM\Column(name="Language_Code", type="string", length=2)
*/
private $language;
My Product form (ProductType) has a CollectionType field in order to add several names.
// Form/ProductType.php
->add('infos', CollectionType::class, array(
'entry_type' => ProductInfosType::class,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'label' => false,
'mapped' => false
))
And ProductInfosType form has 2 fields :
// Form/ProductInfosType.php
->add('name', TextType::class, array(
'attr' => array('size' => 40)
))
->add('language', EntityType::class, array(
'placeholder' => '',
'class' => 'AppBundle:Language',
'choice_label' => 'code',
'attr' => array('class' => 'lang'),
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('l')->orderBy('l.code', 'ASC');
}
))
So, when I go on my form page, I have a block which contains an input text field (Name) and a select field (language). The select field is like this :
<select id="product_infos_0_language" required="required" name="product[infos][0][language]">
<option value=""></option>
<option value="DE">DE</option>
<option value="EN">EN</option>
<option value="ES">ES</option>
<option selected="selected" value="FR">FR</option>
</select>
At this point, everything works well. I created an add button so that the user can add other names, etc...
But, when I submit the form, when I check form data in my ProductController, I noticed that it does not correspond to what I want to store in database.
print_r($form->get('infos')->getData());
// returns :
Array
(
[0] => AppBundle\Entity\ProductName Object
(
[language:AppBundle\Entity\ProductName:private] => AppBundle\Entity\Language Object
(
[code:AppBundle\Entity\Language:private] => FR
[name:AppBundle\Entity\Language:private] => Français
)
[name:AppBundle\Entity\ProductName:private] => Ceinture lombaire LombaSkin
)
)
What I would like is :
Array
(
[0] => AppBundle\Entity\ProductName Object
(
[language:AppBundle\Entity\ProductName:private] => FR
[name:AppBundle\Entity\ProductName:private] => Ceinture lombaire LombaSkin
)
)
I don't want the language object but directly the language code !
That's why I think that I should not use EntityField in ProductNameType form but ChoiceType field.
How can I load all the languages stored in db in the choice field ?
I hope that this explanation is more understandable ;-)
A:
I found the solution thanks to this post : Passing data to buildForm() in Symfony 2.8/3.0
ProductController.php : pass custom data as an option in the createForm() method.
// ...
// build the form
$em = $this->getDoctrine()->getManager();
$product = new Product();
$languages = $em->getRepository('AppBundle:Language')->findAllOrderedByCode();
$form = $this->createForm(ProductType::class, $product, array(
'languages' => $languages
));
ProductType form : pass custom data in the options resolver
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Product',
'languages' => null
));
}
Then, in the buildForm() function, add an entry_options option in the CollectionType field :
$builder->add('infos', CollectionType::class, array(
'entry_type' => ProductInfosType::class,
'entry_options' => array('languages' => $options['languages']),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'label' => false,
'by_reference' => false
));
ProductInfosType form : pass custom data in the options resolver (exactly the same as in the ProductForm)
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\ProductName',
'languages' => null
));
}
Now, you have two alternatives : either you want that your form returns entities or simple strings.
In my example, I just want the language code (like FR, EN, etc.).
Case 1 : return only the language code when the form is posted :
// Form/ProductInfosType.php
// ...
// Convert array of objects in an array of strings
$choices = array();
foreach ($options['languages'] as $lang) {
$code = $lang->getCode();
$choices[$code] = $code;
}
$builder->add('language', ChoiceType::class, array(
'placeholder' => '',
'choices' => $choices
));
// returns :
Array
(
[0] => AppBundle\Entity\ProductName Object
(
[name:AppBundle\Entity\ProductName:private] => Ceinture lombaire LombaSkin
[language:AppBundle\Entity\ProductName:private] => FR
)
)
Case 2 : return Language Entity when the form is posted :
// Form/ProductInfosType.php
// ...
$builder->add('language', ChoiceType::class, array(
'placeholder' => '',
'choices' => $options['languages'],
'choice_label' => 'code',
'choice_value' => 'code'
));
// returns :
Array
(
[0] => AppBundle\Entity\ProductName Object
(
[name:AppBundle\Entity\ProductName:private] => Ceinture lombaire LombaSkin
[language:AppBundle\Entity\ProductName:private] => AppBundle\Entity\Language Object
(
[code:AppBundle\Entity\Language:private] => FR
[name:AppBundle\Entity\Language:private] => Français
)
)
)
With this solution, we don't need to create our form as a service in order to pass entity manager as an argument. All is managed in the controller and form options.
| {
"pile_set_name": "StackExchange"
} |
Q:
React-Select : How to rotate dropdown indicator when menu open
in example : https://codesandbox.io/s/jz33xx66q9?module=/example.js
i want to rotate emoji to up size down when menu open
how to do that
A:
react-select provides a styling api which offers such customization. Each attribute in the object given to the styles prop is a function which is getting the current component state as a prop. The state also has props from the base component (Select).
<Select
{ ... }
styles={{
dropdownIndicator: (provided, state) => ({
...provided,
transform: state.selectProps.menuIsOpen && 'rotate(180deg)'
})
}}
/>
CodeSandbox example
| {
"pile_set_name": "StackExchange"
} |
Q:
how to work with jprogress bar in Java Swing
i have a desktop GUI in swing , i want to show status of user storage used in the GUI using jProgressBar, Please suggest some attractive way to do.
A:
I suggest you read this tutorial. I think it is the most attractive way to learn how to use JProgressBar.
To elaborate the answer a little:
JProgressBar progress = new JProgressBar(0, totalAvailableStorage);
progress.setValue(occupiedStorage);
Of course, you have to add the progress bar to its container and call progress.setValue() whenever needed.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to iterate through a list of Data frames and drop all data if a specific string isnt found
I am using the python library Camelot to parse through multiple PDFs and pull out all tables within those PDF files. The first line of code yields back all of the tables that were scraped from the pdf in list format. I am looking for one table in particular that has a unique string in it. Thankfully, this string is unique to this table so I can, theoretically, use it to isolate the table that I want to grab.
These pdfs are more or less created in the same format, however there is enough variance that I cant just have a static call on the table that I want. For example, sometimes the table I want will be the first table scraped, and sometimes it will be the third. Therefore, I need to write some code to be able to select the table dynamically.
The workflow I have in my mind logically goes like this:
Create an empty list before the for loop to append the tables to. Call a for loop and iterate over each table in the list outputted by the Camelot code. If the table does not have the string I am looking for, delete all data in that table and then append the empty data frame to the empty list. If it does have the string I am looking for, append it to the empty list without deleting anything.
Is there a better way to go about this? Im sure there probably is.
I have put what I have so far put together in my code. Im struggling putting together a conditional statement to drop all of the rows of the dataframe if the string is present. I have found plenty of examples of dropping columns and rows if the string is present, but nothing for the entire data frame
import camelot
import pandas as pd
#this creates a list of all the tables that Camelot scrapes from the pdf
tables = camelot.read_pdf('pdffile', flavor ='stream', pages = '1-end')
#empty list to append the tables to
elist = []
for t in tables:
dftemp = t.df
#my attempt at dropping all the value if the unique value isnt found. THIS DOESNT WORK
dftemp[dftemp.values != "Unique Value", dftemp.iloc[0:0]]
#append to the list
elist.append(dftemp)
#combine all the dataframes in the list into one dataframe
dfcombined = pd.concat(elist)
A:
You can use the 'in' operator on the numpy array returned by dftemp.values
link
for t in tables:
dftemp = t.df
#my attempt
if "Unique Value" in dftemp.values:
#append to the list
elist.append(dftemp)
| {
"pile_set_name": "StackExchange"
} |
Q:
Conversion Error
can someone please tell me why i am getting the following error, when i run through my code, im not to sure if its a problem with my sql statement as this seems to be ok, but i added it below so that i can get a second opinion
"Conversion failed when converting date/time from character string"
public static int GetConveyorProductionCount(string machineNameV, string StartTimeV, string EndTimeV)
{
try
{
int count;
SqlParameter param01 = new SqlParameter("@param01", SqlDbType.VarChar, 5);
param01.Value = machineNameV;
SqlParameter param02 = new SqlParameter("@param02", SqlDbType.VarChar, 5);
param02.Value = StartTimeV;
SqlParameter param03 = new SqlParameter("@param03", SqlDbType.VarChar, 5);
param03.Value = EndTimeV;
SqlCommand getConveyorProductionSC = new SqlCommand("SELECT cast([" + machineNameV + "] as int) FROM VWCONVEYORPRODUCTION WHERE([DA_TE] BETWEEN @param02 AND @param03)", myConnection);
getConveyorProductionSC.Parameters.Add(param01);
getConveyorProductionSC.Parameters.Add(param02);
getConveyorProductionSC.Parameters.Add(param03);
myConnection.Open();
object result = getConveyorProductionSC.ExecuteScalar();
myConnection.Close();
if (result == DBNull.Value)
{
count = 0;
}
else
{
count = Convert.ToInt32(result);
}
return count;
}
catch (Exception e)
{
throw new Exception("Error retrieving the Conveyor production count. Error: " + e.Message);
}
A:
Well aside from the large amount of other problems with this code
SqlParameter param02 = new SqlParameter("@param02", SqlDbType.DateTime);
param02.Value = StartTimeV;
SqlParameter param03 = new SqlParameter("@param03", SqlDbType.DateTime);
param03.Value = EndTimeV;
Would be a good start
Assuming of course the DA_TE column in the table is a datetime?
Of course you need to pass them in as DateTimes as well
I do commend you for using parameterised queries though.
If it was me my code would look something like
public static int GetConveyorProductionCount(string machineNameV, DateTime StartTimeV, DateTime EndTimeV)
{
{
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
connection.Open();
using(SqlCommand command = new SqlCommand(String.Format(CultureInfo.InvariantCulture, "SELECT cast([{0}] as int) FROM VWCONVEYORPRODUCTION WHERE([DA_TE] BETWEEN @StartDate AND @EndDate)", machineNameV), connection);
{
command.Parameters.AddWithValue("StartDate",StartTimeV);
command.Parameters.AddWithValue("EndDate",EndTimeV);
object result = command.ExecuteScalar();
if (result == DBNull.Value)
{
return 0;
}
else
{
return (Int32)result;
}
}
}
}
Anything you create one the fly that implements IDisposable put inside a using block.
Don't unless you are doing explicit transactions, or have connection caching turned off persist Ado.Net db connections.
Pass DateTimes as DateTimes
Give your variables decent names, param02 doesn't mean anything, and count was misleading.
Don't create stuff before you need it
The thing you did with exception
I personally wouldn't bother trapping in this code, especially simply to throw it again, after throwing all the useful details about the exception away.
If you want to do that, define a CustomException, then do
throw new MyCustomException("Error retrieving the Conveyor production count.",e);
That way we you'll be able to trap this specific exception if you need to, but you'll have the entire exception chain and all the stack traces.
Last but not least treat all coding examples including mine, as though they were constructed by the village idiot's thick cousin. :D
| {
"pile_set_name": "StackExchange"
} |
Q:
For the long-term evolution of atmosphere/orbit, when is perihelion more important than mean distance?
When we want to figure out the long-term evolution of a planet's atmosphere/orbit, when is perihelion more important than mean distance?
E.g. some processes (like Jeans Escape and escape of atmospheres) are disproportionately affected during perihelion (point of closest approach) rather than during aphelion.
A:
Well, you basically answered your own question- The more elliptical an orbit, the more pronounced the perihelion-only effects are. For planets, I don't think any have orbits so elliptical that it matters very much. Comets, on the other hand... I think outgassing is so pronounced for comets whose perihelion is in the inner Solar System that it actually affects their orbits, not just their atmospheres (er, tails).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to iterate over a nested TreeMap without creating temporary Objects
I'm working on a nGrams, and I'm using a nested TreeMap kind of datastructure to store the ngrams. The template for Quadgrams looks like this.
public TreeMap<String, TreeMap<String, TreeMap<String, TreeMap<String, Integer>>>> ngramWordCounter;
The problem is arising when i'm trying to dump it to a file, basically i'm iterating over keySet of first map, and then into the keymap of the second and so on and so forth. As a result a lot of temporary objects are created and i'm getting GCOverlimitExceeded Error. The code snippet for iterating is as follows,
for(String key: ((Quadgram)quadgram).ngramWordCounter.keySet())
{
for(String key1: ((Quadgram)quadgram).ngramWordCounter.get(key).keySet())
{
for(String key2: ((Quadgram)quadgram).ngramWordCounter.get(key).get(key1).keySet())
{
for(String key3:((Quadgram)quadgram).ngramWordCounter.get(key).get(key1).get(key2).keySet())
{
//Do something
}
}
}
}
Is there a better way to iterate over this list without creating temporary objects?
A:
New objects won't be created. new references will be created.
Map returns reference to key in keyset. Use this reference to explore this concept or you can read java tutorials about this concept.
I prefer following way to iterate map is
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// process key and value
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Sharepoint or MS Project?
We currently use a web based project management system (less than 30 users) that we pay way too much for. I'm trying to decide if we want to move to a Project or Sharepoint environment.
I understand what MS Project is and how it works, but I've never really understood what Sharepoint does other than managing Office Documents. Is there a reason why Sharepoint won't manage projects? Is there a very informative overview of what Sharepoint does and how it can benefit us?
Thank you!
A:
I use Sharepoint for managing projects all the time, but it is very different to MS Project. Sharepoint gives me lots of freeform lists and tables that allow me to manage things like incoming information, issued documents, reports being prepared, refeneces, risk assessments etc. You can configure views to give you some basic information like how many comments still need to be addressed, what is the current status of xxxx etc. As a project management tool it can therefore manage the whole process.
MS Project is suited to planning a project in terms of time and resource and then monitoring the projects progress against that plan. This gives it a very different emphasis compared with Sharepoint. It is more suited to managing larger projects with specific time and resource constraints and lots of complex interactions. It doesn't necesserily help manage a project, it is more of a planning and monitoring tool.
Which one to plump for very much depends on how you would like to manage a project but I wouldn't say that either is mutually exlclusive. They both achieve different things, but you can also acheive the basics of either using other less sophisticated approaches.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adopt a consistent policy on what "Requires Editing" means in the review queues
In the review queues (and the triage queue in particular), there are three options for a post. One of those options is labeled "Requires Editing". In the description of what those options mean, it says:
Requires Editing for questions where edits by the author or others would result in a question that is clear and answerable
However, by consensus here on Meta, it has been decided that "Requires Editing" actually should be applied only to posts that the community can edit into shape, not posts that require editing by the original author. Such posts, it is argued, should be marked instead as "Unsalvageable" since the community can do nothing on its own to salvage them.
I don't want to debate the policy or the interpretation. I want to draw attention to the fact that there is currently a massive disconnect between the official guidance in the UI and the policy as it is enforced by the moderation team.
I know this has been asked before, and subsequently closed as a duplicate of a major triage review reworking proposal, but this text has not yet been fixed and I recently became aware that moderators are handing out review bans for users who choose "Requires Editing" for posts that…require editing.
This is completely unacceptable as far as I'm concerned. To be clear, I'm not proposing that we be less harsh on people who make bad decisions in the review queues, like choosing "Looks OK" on these problematic questions. I am, however, saying that we need to be fair. Either change the guidelines in the official UI, or stop manually issuing bans to people who choose what appears to be a completely valid choice.
A:
As of today, the guidance now reads:
...and also includes a second link to this meta answer as the last line in the expanded instructions (same answer linked to in "help separating questions" in the short explanation at the top).
This is based on a suggestion by K.Davis a few months back, and I think it nicely side-steps the problems inherent in asking reviewers to guess at what others are able to fix. If a majority of reviewers think they can fix it themselves (with or without help from the author), chances are it's probably fixable...
Of course, we'll see how much of an effect it actually has in practice.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to time an arbitrary function in f#
here's the problem. I need to time a function in f# using another function. I have this piece of code
let time f a =
let start = System.DateTime.Now in
let res = (fun f a -> f(a)) in
let finish = System.DateTime.Now in
(res, finish - start)
which I'm trying to call saying
time ackermann (2,9);;
I have a function ackermann that takes a tuple (s,n) as argument
Probably something fundamentally wrong with this but I don't think I'm far away from a solution that could and looks somewhat like this.
Any suggestions?
Oh btw. the error message I'm getting is saying :
stdin(19,1): error FS0030: Value restriction. The value 'it' has been inferred to have generic type
val it : (('_a -> '_b) -> '_a -> '_b) * System.TimeSpan
Either define 'it' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation.
A:
You have at least two issues:
Try let res = f a. You already have values f and a in scope, but you're currently defining res as a function which takes a new f and applies it to a new a.
Don't use DateTimes (which are appropriate for representing dates and times, but not short durations). Instead, you should be using a System.Diagnostics.Stopwatch.
A:
You can do something like this:
let time f =
let sw = System.Diagnostics.Stopwatch.StartNew()
let r = f()
sw.Stop()
printfn "%O" sw.Elapsed
r
Usage
time (fun () -> System.Threading.Thread.Sleep(100))
I usually keep the following in my code files when sending a bunch of stuff to fsi.
#if INTERACTIVE
#time "on"
#endif
That turns on fsi's built-in timing, which provides more than just execution time:
Real: 00:00:00.099, CPU: 00:00:00.000, GC gen0: 0, gen1: 0, gen2: 0
| {
"pile_set_name": "StackExchange"
} |
Q:
Covariant derivative of second fundamental form
Picture below is from 1706th page of Zhao Liang's The first eigenvalue of Laplace operator under powers of mean curvature flow.
$g_{ij}$ is Riemannian metric, $h_{ij}$ is second fundamental form, and $H=g^{ij}h_{ij}$. $\nabla$ is Riemannian connect, and $\nabla^pH=g^{pl}\nabla_lH$. $h$ is a constant independ to $x$.
For getting the below equation, I get stuck at
$$
g^{ij}g^{pl}H^k\nabla_lh_{ij}-2g^{ij}g^{pl}H^k\nabla_ih_{jl}=-H^k\nabla^pH
$$
How should I to do it ?
A:
Note
$$g^{ij} \nabla_l h_{ij} = \nabla_l (g^{ij} h_{ij}) = \nabla _l H$$
as $\nabla_l g^{ij} = 0$. Thus
$$g^{ij}g^{pl}H^k\nabla_lh_{ij}=g^{pl} H^k\nabla_l H = H^k\nabla^pH$$
by definition of $\nabla ^p = g^{pl}\nabla_l$.
For the next term, it is important to remark that one is working on hypersurfaces in $\mathbb R^{n+1}$. In particular the ambient curvature is zero and the Codazzi equation gives
$$\nabla_i h_{lj} - \nabla_l h_{ij} =0.$$
Thus we have
$$-2g^{ij}g^{pl}H^k\nabla_ih_{jl}=-2g^{ij}g^{pl}H^k\nabla_lh_{ij}=-2g^{pl}H^k\nabla_lH = -2H^k\nabla^pH.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP Repairing Bad Text
This is something I'm working on and I'd like input from the intelligent people here on StackOverflow.
What I'm attempting is a function to repair text based on combining various bad versions of the same text page. Basically this can be used to combine different OCR results into one with greater accuracy than any of them individually.
I start with a dictionary of 600,000 English words, that's pretty much everything including legal and medical terms and common names. I have this already.
Then I have 4 versions of the text sample.
Something like this:
$text[0] = 'Fir5t text sample is thisline';
$text[1] = 'Fir5t text Smplee is this line.';
$text[2] = 'First te*t sample i this l1ne.';
$text[3] = 'F i r st text s ample is this line.';
I attempting to combine the above to get an output which looks like:
$text = 'First text sample is this line.';
Don't tell me it's impossible, because it is certainly not, just very difficult.
I would very much appreciate any ideas anyone has towards this.
Thank you!
My current thoughts:
Just checking the words against the dictionary will not work, since some of the spaces are in the wrong place and occasionally the word will not be in the dictionary.
The major concern is repairing broken spacings, once this is fixed then then the most commonly occurring dictionary word can be chosen if exists, or else the most commonly occurring non-dictionary word.
A:
Have you tried using a longest common subsequence algorithm? These are commonly seen in the "diff" text comparison tools used in source control apps and some text editors. A diff algorithm helps identify changed and unchanged characters in two text samples.
http://en.wikipedia.org/wiki/Diff
Some years ago I worked on an OCR app similar to yours. Rather than applying multiple OCR engines to one image, I used one OCR engine to analyze multiple versions of the same image. Each of the processed images was the result of applying different denoising technique to the original image: one technique worked better for low contrast, another technique worked better when the characters were poorly formed. A "voting" scheme that compared OCR results on each image improved the read rate for arbitrary strings of text such as "BQCM10032". Other voting schemes are described in the academic literature for OCR.
On occasion you may need to match a word for which no combination of OCR results will yield all the letters. For example, a middle letter may be missing, as in either "w rd" or "c tch" (likely "word" and "catch"). In this case it can help to access your dictionary with any of three keys: initial letters, middle letters, and final letters (or letter combinations). Each key is associated with a list of words sorted by frequency of occurrence in the language. (I used this sort of multi-key lookup to improve the speed of a crossword generation app; there may well be better methods out there, but this one is easy to implement.)
To save on memory, you could apply the multi-key method only to the first few thousand common words in the language, and then have only one lookup technique for less common words.
There are several online lists of word frequency.
http://en.wiktionary.org/wiki/Wiktionary:Frequency_lists
If you want to get fancy, you can also rely on prior frequency of occurrence in the text. For example, if "Byrd" appears multiple times, then it may be the better choice if the OCR engine(s) reports either "bird" or "bard" with a low confidence score. You might load a medical dictionary into memory only if there is a statistically unlikely occurrence of medical terms on the same page--otherwise leave medical terms out of your working dictionary, or at least assign them reasonable likelihoods. "Prosthetics" is a common word; "prostatitis" less so.
If you have experience with image processing techniques such as denoising and morphological operations, you can also try preprocessing the image before passing it to the OCR engine(s). Image processing could also be applied to select areas after your software identifies the words or regions where the OCR engine(s) fared poorly.
Certain letter/letter and letter/numeral substitutions are common. The numeral 0 (zero) can be confused with the letter O, C for O, 8 for B, E for F, P for R, and so on. If a word is found with low confidence, or if there are two common words that could match an incompletely read word, then ad hoc shape-matching rules could help. For example, "bcth" could match either "both" or "bath", but for many fonts (and contexts) "both" is the more likely match since "o" is more similar to "c" in shape. In a long string of words such as a a paragraph from a novel or magazine article, "bath" is a better match than "b8th."
Finally, you could probably write a plugin or script to pass the results into a spellcheck engine that checks for noun-verb agreement and other grammar checks. This may catch a few additional errors. Maybe you could try VBA for Word or whatever other script/app combo is popular these days.
| {
"pile_set_name": "StackExchange"
} |
Q:
QueryDSL - order by count as alias
I'm using queryDSL to get users with some additional data from base:
public List<Tuple> getUsersWithData (final SomeParam someParam) {
QUser user = QUser.user;
QRecord record = QRecord.record;
JPQLQuery = query = new JPAQuery(getEntityManager());
NumberPath<Long> cAlias = Expressions.numberPath(Long.class, "cAlias");
return query.from(user)
.leftJoin(record).on(record.someParam.eq(someParam))
.where(user.active.eq(true))
.groupBy(user)
.orderBy(cAlias.asc())
.list(user, record.countDistinct().as(cAlias));
}
Despite it's working as desired, it generates two COUNT() in SQL:
SELECT
t0.ID
t0.NAME
to.ACTIVE
COUNT(DISTINCT (t1.ID))
FROM USERS t0 LEFT OUTER JOIN t1 ON (t1.SOME_PARAM_ID = ?)
WHERE t0.ACTIVE = true
GROUP BY t0.ID, to.NAME, t0.ACTIVE
ORDER BY COUNT(DISTINCT (t1.ID))
I want to know if it's possible to get something like this:
SELECT
t0.ID
t0.NAME
to.ACTIVE
COUNT(DISTINCT (t1.ID)) as cAlias
FROM USERS t0 LEFT OUTER JOIN t1 ON (t1.SOME_PARAM_ID = ?)
WHERE t0.ACTIVE = true
GROUP BY t0.ID, to.NAME, t0.ACTIVE
ORDER BY cAlias
I failed to understand this from documentation, please, give me some directions if it's possible.
A:
QVehicle qVehicle = QVehicle.vehicle;
NumberPath<Long> aliasQuantity = Expressions.numberPath(Long.class, "quantity");
final List<QuantityByTypeVO> quantityByTypeVO = new JPAQueryFactory(getEntityManager())
.select(Projections.constructor(QuantityByTypeVO.class, qVehicle.tipo, qVehicle.count().as(aliasQuantity)))
.from(qVehicle)
.groupBy(qVehicle.type)
.orderBy(aliasQuantity.desc())
.fetch();
select
vehicleges0_.type as col_0_0_, count(vehicleges0_.pk) as col_1_0_
from vehicle vehicleges0_
group by vehicleges0_.type
order by col_1_0_ desc;
I did something like that, but I did count first before ordering. Look the query and the select generated.
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.NET MVC Core DateTime format using jQuery DateTimePicker
I have an ASP.NET Core MVC application with a view model which has a DateTime property for "Date of Birth":
[Required]
public DateTime DateOfBirth { get; set; }
I want to let the user to pick/enter date in dd/mm/yyyy format.
In the view originally I was using html Date type and it was working fine in Chrome but some issues in Edge and not working in IE 11 at all. Therefore I have decided to replace it with the jQuery DatePicker:
<input class="form-control datepicker" name="DateOfBirth" type="text" required>
In Js file:
$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });
It all works fine as long as I pass value as mm/dd/yyyy format (12/12/2017). As soon as I change it to 13/12/2017 (dd/mm/yyyy) I get server side error saying that method arguments are not valid.
A:
You need to set the culture of your server to one that accepts dates in dd/MM/yyyy format.
To set the default culture in your startup.cs file, in the ConfigureServices method (note the following sets the culture to en-AU (Australia))
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture("en-AU");
});
services.AddMvc();
}
and in the Configure method
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseRequestLocalization();
app.UseMvc();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
print out the position of vertices after rotation
i drawn a cube and i can rotate it. I would want to print out the position of vertices after rotation.
in some tutorials i found that i can use QMatrix4x4 to rotate my cube and the to get the new position of vertices. the i changed mu code:
void MyWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
QMatrix4x4 matrix; // new matrice for transformation
matrix.translate(0.0, 0.0, -10.0);
matrix.Rotate(xRot / 16.0, 1.0, 0.0, 0.0);
matrix.Rotate(yRot / 16.0, 0.0, 1.0, 0.0);
matrix.Rotate(zRot / 16.0, 0.0, 0.0, 1.0);
glBegin(GL_QUADS); //1st quad
qglColor(Qt::green);
glNormal3f(0.0f, 0.0f, -1.0f);
---
glEnd();
}
my question is how to apply the matrix to draw the vertice because glvertex3f can't take that matrix. Then i will print out the new position as follow: ( matrix * QVector3D(0.0f, 0.0f, -1.0f)) for example;
After Some days and thanks to the links you gave me, i had tried to read about Modern OpenGL: Here is my code now:
void GLWidget::paintGL()
{
--------
QMatrix4x4 matrixTransformation;
matrixTransformation.rotate(alpha, 0,1,0);
matrixTransformation.rotate(beta, 0, 1, 0);
QVector3D cameraPosition = matrixTransformation * QVector3D(0,0,distance);
QVector3D cameraUpDirection = matrixTransformation * QVector3D(0, 1, 0);
vMatrix.lookAt(cameraPosition, QVector3D(), cameraUpDirection);
// display the coordinates
foreach(const QVector3D& p, cameraPosition) {
qDebug() << "Rotated position =" << matrixTransformation * p;
}
shaderProgram.bind();
shaderProgram.setUniformValue("mvpMatrix", pMatrix * vMatrix *mMatrix);
shaderProgram.setUniformValue("color", QColor(Qt::white));
shaderProgram.setAttributeArray("vertex", vertices.constData());
shaderProgram.enableAttributeArray("vertex");
glDrawArrays(GL_TRIANGLES, 0,vertices.size());
shaderProgram.disableAttributeArray("vertex");
shaderProgram.release();}
}
an error appeared : error C2039: ‘const_iterator’ : is not a member of ‘QVector3D’
error C2039: ‘i’ : is not a member of ‘QForeachContainer’
I had included and in my header but the error still there.
Is the way i used correct to get the coordinates of vertices??
the error is from my foreach loop code, and is maybe about the declaration of QVector3D in a qvector3d.h of Qt. How to solve it??
if the use of transformation matrix , how can iuse a transform feedback object to pass the vertex positions that come out of the vertex shader back into another buffer object.
I seen that its another solution to get coordinates of vertices after rotation.
Thanks and sory for my questions which are may be for beginners.
A:
You can upload a QMatrix4x4 to the OpenGL matrixstack. Uploading a matrix is done by using the glLoadMatrixf methode, where your data comes from the QMatrix4x4's constData() function. The code could look like the following:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
QMatrix4x4 matrix; // new matrice for transformation
matrix.translate(0.0, 0.0, -10.0);
matrix.Rotate(xRot / 16.0, 1.0, 0.0, 0.0);
matrix.Rotate(yRot / 16.0, 0.0, 1.0, 0.0);
matrix.Rotate(zRot / 16.0, 0.0, 0.0, 1.0);
glLoadMatrixf(matrix.constData());
//Draw as already done before
More information about how qt's matrices and vectors can be used together with OpenGL can be found in this very good answer here
| {
"pile_set_name": "StackExchange"
} |
Q:
Sed find and delete single word
I would like to remove a username from a .htaccess file.
Example .htaccess:
RewriteEngine On
RewriteBase /~usern/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /~usern/index.php [L]
I want to us a sort of dynamic command in that I don't have to manually type /~username every time for each user.
I tried
sed 's/$whoami##g' .htaccess
but this does not achieve the desired result.
A:
You could sed -i "s/$(whoami)//g" .htaccess
If you only want to remove the first entry on a line, remove the last g option.
sed -i (inline sed, do actions directly on file) "s/find_this/replace_with_this/" (search and replace)
If you want to search for ~/username and remove that instead of only username entries, just change the expression to:
sed -i "s/~\/$(whoami)//g" .htaccess
| {
"pile_set_name": "StackExchange"
} |
Q:
Swift: implement a protocol variable as a lazy var?
It seems that it's not possible to implement a variable that's required by a protocol, with a lazy variable. For example:
protocol Foo {
var foo: String { get }
}
struct Bar: Foo {
lazy var foo: String = "Hello World"
}
Compiler complains that Type 'Bar' does not conform to protocol 'Foo'.
It's also not possible to add the lazy keyword in the protocol declaration, since then you get 'lazy' isn't allowed on a protocol requirement error.
So is this not at all possible?
A:
Citing the Language Guide - Properties - Lazy Stored Properties [emphasis mine]:
A lazy stored property is a property whose initial value is not
calculated until the first time it is used.
I.e., the value is mutated upon first usage. Since foo has been blueprinted in the Foo protocol as get, implicitly nonmutating get, the value type Bar does not fulfil this promise with its lazy property foo, a property with a mutating getter.
Changing Bar to a reference type will allow it to fulfil the Foo blueprint (as mutating a property of a reference type doesn't mutate the type instance itself):
protocol Foo {
var foo: String { get }
}
class Bar: Foo {
lazy var foo: String = "Hello World"
}
Alternative, specify in the blueprint of the foo property of Foo that it has a mutating getter.
protocol Foo {
var foo: String { mutating get }
}
struct Bar: Foo {
lazy var foo: String = "Hello World"
}
See the following Q&A for some additional details of the mutating/nonmutating specifiers for getters and setters:
Swift mutable set in property
| {
"pile_set_name": "StackExchange"
} |
Q:
How to improve swimming performance in the gym?
Question is quite simple. I'm looking for gym-specific bunch of exercises which can help me to build up swimming performance/endurance/speed.
So, when I'm not in the water I can still be continuously improving my swimming. Of course I know that I need to go into water because of technique training, feel of water etc.
Edit: focused on crawl performance. Not interested in strength improvement in other styles at this moment.
A:
I found huge improvements from taking on gyming while swimming - specifically muscular strength and endurance. That is, until I overtrained and heavily damaged my back. Be wise and know your limits!
How often?
I think two to three swim sessions to one gym session is a good ratio. If you're a sprinter, maybe more towards two to one swim sessions to one gym session.
How many sessions a week that ends up being depends on how into the sport you are! A competitive swimmer may be doing 7-10 swim sessions a week, coupled with 3-4 gym sessions would be a nice mix.
Make sure you give enough time for your muscles to recover. Throwing gym into the mix puts a much higher demand on your muscles.
Sets and Reps
I did freestyle mid-distance events, 200 m up to 800 m, so my focus was more on endurance reps.
For standard workouts, I would do 3 sets of 20, and gradually increased weights accordingly. I did them at a similar speed to swimming stroke rate, except for legs of course.
I frequently did circuit training - 30 seconds on, 30 seconds off, go to the next exercise, around 70% of my max or greater. This was the money, I loved these workouts!
One stupid set I frequently did was pyramid sets on quads until muscle strain. 20 reps, climb weight until you injure your muscles, then climb back down. I actually didn't realise that I was straining my muscles, the 5+ days for my quads to recover despite my well conditioned muscles should have been an obvious clue!
Routines
Think through what muscles hold you back the most, and focus on them.
Cable flys - these were my favourite! Go for pulling from
full extension, this is great for having a powerful pull at maximum
reach. Slight bend in the elbow, just like your initial underwater pull.
Biceps curls - pretty boring, but important
Triceps - use free weights, extend from half to full. Heaps of ways to do this and they're all pretty similar.
Shoulders - free weights, extend to horizontal on your side and front
Rows - your traps are helpful in the pull sequence, but more so it's just good to work the opposite muscles so you keep your muscle development equal.
Bench press - covers the above muscles quite well.
Pull ups/machine pull downs - real important
Abs with weights - whether it be sit ups with plates or pulling on a cable, it's all good - gives your off the wall dolphin kicks more grunt
Back extensions with weights - just as important as the abs
I know some people like to throw squats in the mix for more off the wall push power, but I'd say that it's lesser importance unless you're in some serious competitions. In which case, you would have asked this question to your team physio/gym trainer!
| {
"pile_set_name": "StackExchange"
} |
Q:
ServiceMix config change for a bundle in scripting mode using `client` binary
I have a ServiceMix 5.1.4 instance (localhost) and I want to script some property change with the provided client (smx_home/bin/client).
If I test manually my commands in the smx console (without using client)
config:edit org.myspace.test.mybundle
config:propset propertyOne false
config:propset propertyTwo true
config:update
... it works great.
Now I want to execute these command from a bash, then I wrote a simple bash like this:
#!/bin/bash
smxcli='/opt/mysmxdir/bin/client'
$smxcli -h localhost -a 8101 -u smx -p smx config:edit org.myspace.test.mybundle
$smxcli -h localhost -a 8101 -u smx -p smx config:propset propertyOne false
$smxcli -h localhost -a 8101 -u smx -p smx config:propset propertyTwo true
$smxcli -h localhost -a 8101 -u smx -p smx config:update
or if I tried with the client itself in the command line, it fails on the second line as it does not look to keep track of the first edit command.
No configuration is being edited--run the edit command first
I tried to provide the commands like a list:
./client -h localhost -a 8101 -u smx -p smx "config:edit org.myspace.test.mybundle" "config:propset propertyOne true" "config:propset propertyTwo false" "config:update"
and with the option -b (batch)
./client -h localhost -a 8101 -u smx -p smx -b "config:edit org.myspace.test.mybundle" "config:propset propertyOne true" "config:propset propertyTwo false" "config:update"
but it does not work.
I know I can use the option -f (writing all smx commands in one file and execute them with client -f myfile.cmd) but I am wondering if it is possible from a single bash script without extra file.
A:
In fact the solution was very simple: like in unix/linux you can separate commands by a semicolon ; in the same command string.
Example:
./client -h localhost -a 8101 -u smx -p smx "config:edit org.myspace.test.mybundle; config:propset propertyOne true; config:propset propertyTwo false; config:update"
I found it is also possible to send all commands at once for several bundles. If I try to send two different command, for changing properties for two different bundles the second one is not working.
In that case the solution is to concatenate all the changes with only one command like this:
./client -h localhost -a 8101 -u smx -p smx "config:edit org.myspace.test.bundle-1; config:propset propertyOne true; config:propset propertyTwo false; config:update; config:edit org.myspace.test.bundle-2; config:propset propertyX true; config:propset propertyY false; config:update"
| {
"pile_set_name": "StackExchange"
} |
Q:
Compare two tables in different databases and change one table
I have two databases in the same sql instance. One is backup2 which is a restored backup of my original database.
Database Table
Original.Payments
Backup2.Payments
I have two fields in each that I need to compare:
PaymentsId - guid
IsProcessed - bit
I need to compare the PaymentsId in each and if the payment exists in Backup2 and is marked Processed, I need to mark the Original.Payments.Backup as true.
I have the first part of the query done but I'm not sure how to link it to the Original database:
SELECT [PaymentId]
,[CorporationId]
,[IsProcessed]
FROM [Backup2].[Web].[Payment]
WHERE CorporationId = '2aa2dfw-20d2-4694-8e01-72288a1e8d4'
and IsProcessed = 'true'
This gives me my list of payments but I need to compare those to the original database and I'm not sure how.
Where do I go from here?
Thank you!
A:
you can use update with join syntax
update OP
set IsProcessed = 'true'
FROM [Original].[Payments].[Backup] OP
JOIN [Backup2].[Web].[Payment] BP
on OP.PaymentId = BP.PaymentId
and BP.corporationId = '2aa2dfw-20d2-4694-8e01-72288a1e8d4'
and BP.IsProcessed ='true'
and OP.corporationId = '2aa2dfw-20d2-4694-8e01-72288a1e8d4'
| {
"pile_set_name": "StackExchange"
} |
Q:
Check multiple tables in one single query
I want to SELECT data from my MySQL using PHP but the WHERE clause can be kind of confusing.
Basically i want to select the appointments that are coming up, then checking if the business is wanting to send out reminders, then checking if the user wants to receive reminders. But I want to do all that in one query.
Here are my tables:
appointments
- appointment_date
- appointment_time
- business_id
- user_id
businesses
- reminders_enabled
users
- reminders_enabled
Here are the steps of what I want to do before I select the right data:
SELECT * FROM appointments WHERE DATE(appointment_date) = CURDATE() AND appointment_time is within the next 1 hour
From the data selected above from step #1, I want to filter it. I want to SELECT * FROM businesses WHERE business_id = business_id_from_step_1 AND reminders_enabled = 1
Then I want to filter it even more. If results are found after step 2, do another select: SELECT * FROM users WHERE user_id = user_id_from_step_1 AND reminders_enabled = 1
That's it after that. How can I do that? Thanks!
A:
Something like this should work. The JOINs do the filtering as you describe in your steps 1-3:
SELECT *
FROM appointments a
JOIN businesses b ON b.business_id = a.business_id AND b.reminders_enabled = 1
JOIN users u ON u.user_id = a.user_id AND u.reminders_enabled = 1
WHERE DATE(a.appointment_date) = CURDATE() AND
a.appointment_time BETWEEN NOW() AND NOW() + INTERVAL 1 HOUR
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the best practices in adding custom header fields for a .net web api call on Swagger?
I can see a lot of ways to do it online but most of them are messy, for me I was using these two ways
Using scopes, I did one for mobile and another one for the website
var webScope = apiDescription.ActionDescriptor.GetFilterPipeline()
.Select(filterInfo => filterInfo.Instance)
.OfType<WebAuthorize>()
.SelectMany(attr => attr.Roles.Split(','))
.Distinct();
var mobileScope = apiDescription.ActionDescriptor.GetFilterPipeline()
.Select(filterInfo => filterInfo.Instance)
.OfType<MobileAuthorize>()
.SelectMany(attr => attr.Roles.Split(','))
.Distinct();
And it worked because I had two different ways in authorizing the api calls, as you can see I had a Mobile Authorize and a Web Authorize so my api calls would look something like this:
[HttpGet]
[Route("something")]
[WebAuthorize(Code = PermissionCode, Type =PermissionType)]
public async Task<Dto> Getsomething()
{
return await unitOfWork.GetService<ISomething>().GetSomething();
}
Issues I face when using scopes is that all calls that have web authorize will share the same headers so for the special calls I used another way to add custom headers.
Using apiDescription.RelativePath, and I will check it if the relative path is equal to the api call I want to add that custom header, example:
[HttpPost]
[Route("rename")]
[InHouseAuthorize(Code = PermissionCode, Type =PermissionType)]
public async Task<HttpResponseMessage> RenameDevice()
{
HttpRequestMessage request = Request ?? new HttpRequestMessage();
String deviceName = request.Headers.GetValues("deviceName").FirstOrDefault();
String deviceGuid = request.Headers.GetValues("deviceGuid").FirstOrDefault();
await unitOfWork.GetService<IDeviceService>().RenameDevice(deviceGuid, deviceName);
await unitOfWork.Commit();
return new HttpResponseMessage(HttpStatusCode.OK);
}
And then I would add to the AddRequiredHeaderParameter.cs the following
if (apiDescription.RelativePath.Contains("device/rename"))
{
operation.parameters.Add(new Parameter
{
name = "deviceGuid",
@in = "header",
description = "Add the Device Guid",
type = "string",
required = false
});
operation.parameters.Add(new Parameter
{
name = "DeviceName",
@in = "header",
description = "Add the Device Name",
type = "string",
required = false
});
}
At first this was convenient and good enough fix but things are turning ugly as I'm adding a lot of calls that need custom headers and if the same URL have a Get and Post then it will even get uglier.
I am searching for the best way to deal with this issue.
A:
It's possible to use attribute [FromHeader] for web methods parameters (or properties in a Model class) which should be sent in custom headers. Something like this:
[HttpGet]
public ActionResult Products([FromHeader(Name = "User-Identity")]string userIdentity)
For me it looks like the easiest solution. At least it works fine for ASP.NET Core 2.1 and Swashbuckle.AspNetCore 2.5.0.
| {
"pile_set_name": "StackExchange"
} |
Q:
Integrating Gluon Scene Builder into Eclipse?
I've been figuring out how to integrate Gluon Scene Builder into my IDE of choice and decided it would be a good share with the Stack Overflow community for those of you who have had trouble with this in the past. Keep in mind this is for those who have had prior experience with JavaFX and Gluon Scene Builder, minimal at least.
A:
I haven't "scene" any posts directly addressing integration of SceneBuilder as a tutorial so I figured I would set it nice and simple since there were a few questions roaming around.
THIS GUIDE IS FOR ECLIPSE
AND USES GLUON'S SCENEBUILDER
Note this guide is intended for those lightly to moderately experienced with JavaFX as an application builder
//INTELLIJ AND NETBEANS WILL COME LATER PER DEMAND FOR EACH
Alright guys, here we go.
Step 1) Open up your Eclipse IDE(preferably with JavaFX installed prior to installing SceneBuilder) and a web browser of your choice.
You will need elements of JavaFX in order to properly implement SceneBuilder.
Step 2) Click or browse with this link: http://gluonhq.com/open-source/scene-builder/
Select your current operating system on which you will be installing SceneBuilder.
SceneBuilder's default location on Windows is in C:\Users\YourUserFolder\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Gluon, but of course it is more than possible and recommended to change the path while downloading.
Step 3) Once SceneBuilder is downloaded and installed, close SceneBuilder and find the .exe file on your PC(or Mac) where you chose to install it to or in it's default location.
Copy SceneBuilder.exe's file path. For example if you allowed SceneBuilder to install in it's default location, the file path would be: C:\Users\YourUserFolder\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Gluon\SceneBuilder.exe
Now we need to associate FXML files with SceneBuilder
Step 4) Associate FXML with SceneBuilder.
Still inside Eclipse, click Windows at the top > Preferences > search "File Associations"
Browse for the SceneBuilder.exe file path we copied earlier and click OK.
Step 5) Return to the Eclipse IDE and open up a JavaFX Project and name it "test".
File > New > Other > JavaFX Project OR (Ctrl + N) > JavaFX Project
Go into the src folder of test project.
Create an FXML file: test > src > application > New > Other > New FXML Document
Name your FXML file "testfx"
Congratulations, upon firing up your FXML document, you should be billed with a SceneBuilder window. If not you may not have associated FXML documents correctly.
Now how to implement the code is for a different time. For now this tutorial is all I've got within me! If you guys found this helpful, shoot me a pm and let me know! I appreciate your feedback and would like to be able to build upon this greatly.
Thanks guys,
Happy Programming!
A:
Eclipse integration with Gluon Executable JAR on Windows
Parameters/Preconditions used in this example:
Folder for SceneBuilder: c:\example\
Version: scenebuilder-all-8.3.0-all.jar
Eclipse Version: Neon.3 Release (4.6.3)
Install e(fx)clipse Plugin: http://www.eclipse.org/efxclipse/install.html
e(fx)clipse Version used: 2.4.0
Step by Step
Download "Executable JAR" from Gluon to folder c:\example\.
http://gluonhq.com/products/scene-builder/#download
Create Batch File "c:\example\scene_builder.bat" and add the following line:
"java.exe" -jar "%~dp0\scenebuilder-all-8.3.0-all.jar" %*
Double click batch file to test it, SceneBuilder should start
In Eclipse open Window - Preferences - JavaFX
SceneBuilder executable: c:\example\scene_builder.bat
Right click on fmxl File in Eclipse and click Open in ScenenBuilder
Comments
"java.exe"
If Java is not installed in the default way, specify the whole path to executable in quotation mark. "C:\Program Files\Java\jre1.8.0_131\bin\java.exe"
%~dp0\
Will open SceneBuilder JAR in the directory of the batch file
%*
Will pass all command line arguments passed to the batch file to SceneBuilder call
| {
"pile_set_name": "StackExchange"
} |
Q:
level shifting 5V pulse to 12V pulse
When I search for level shifting 5V pulse to 12V, I came to know about the circuit given below.
It is simply based on a push-pull amplifier configuration as you all know. And what I have understood is, when the input reaches 5V (high) level, then Q1 conducts and since it is an NPN transistor, it will make the gate of the MOSFETs both low so that Q3 starts to conduct and vice versa for when an input is 0V.
When we see a graph in an oscilloscope it will show 12V pulse as in the attached graph given below.
But when input pulse goes low (0V), I cannot see an output voltage at 0V. Instead, I am getting 6.366V in output wave instead of 0V. why does that happen and how to resolve this problem?
Thanks for the help in advance!
Edit: As per suggestions from the comment, I have attached an output node.
A:
The most apparent serious problem with the circuit is that you have the Source and Drain of this FET wrong way around in the circuit. Note how the body diode will conduct a lot of current when the lower FET tries to pull low.
If you want a chance of getting a 5V to 12V driver circuit working prepare it more like this configuration and get rid of a couple of transistors in the process.
| {
"pile_set_name": "StackExchange"
} |
Q:
Objective-C and C interoperability
We're going to have to write a C library and this library has to be accessible from Objective-C. Now I don't know anything about Objective-C so I wonder how simple Objective-C <-> C interoperability is. Is that as simple as including the C header in the Objective-C code and linking to the library? Is there anything special I'm supposed to do (like the extern "C" bit with C++)?
A:
Objective-C is a strict superset of C. You don't need to use extern "C" or anything like that.
A:
Objective-C is a strict superset of GNU C (note, this is not the same as ISO C90).
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.