qid
int64 20
74.4M
| question
stringlengths 36
16.3k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 33
24k
| response_k
stringlengths 33
23k
|
---|---|---|---|---|---|
61,717,941 | I have configured the connection to IBM MQ using application properties. As below,
```
ibm.mq.conn-name=localhost(1415)
ibm.mq.queue-manager=QMGR
ibm.mq.channel=QMGR.SVR.CON.C
ibm.mq.user=xxxxx
ibm.mq.password=xxxxx
```
I have class annotated @service which has method as below that reads messages from queue,
```
@Service
public class JMSService {
@Inject
private JmsTemplate queueTemplate;
public JmsMessageBean readMessage(String responseQueueName, Logger logger) throws JMSException, Exception {
JmsMessageBean bean = new JmsMessageBean();
MQQueue queue = new MQQueue(responseQueueName);
queue.setTargetClient(WMQConstants.WMQ_CLIENT_NONJMS_MQ);
queueTemplate.setReceiveTimeout(JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT);
Message message = queueTemplate.receive(queue);
if(message!=null){
String jmsCorrelationID = hexStringToByteArrayToString(message.getJMSCorrelationID());
bean.setJmsCorrelationID(jmsCorrelationID);
bean.setMessage(message.getBody(Object.class));
bean.setJmsMessageID(message.getJMSMessageID());
}
return bean;
}
}
```
and i m running a scheduler at fixedRate of 50milliseconds and calling above method in the scheduler,
```
@Component
public class QueueConnectionService{
@Scheduled(fixedRate = 50)
public void connectQueueManager() {
JmsMessageBean bean = null;
int umacIndex;
String body = "";
try {
bean = jmsService.readMessage(env.getProperty("inwardQueueName"), inwardqueue);
if (bean != null && bean.getMessage() != null) {
String messagetxt = "";
if (bean.getMessage().getClass().getSimpleName().equals("String")) {
messagetxt = (String) bean.getMessage();
} else {
byte[] messagebytes = (byte[]) bean.getMessage();
messagetxt = new String(messagebytes);
}
umacIndex = messagetxt.indexOf("{UMAC:");
if (umacIndex > 0)
message = messagetxt.substring(0, umacIndex);
else
message = messagetxt;
//sending this message to further processing
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
This is working but I m sure this is not the right and efficient way to read messages from queue and probably wrong implementation when there can be large amount messages. And the spring TaskSchedulerPool will be overloaded as there are other data migration schedulers. Please verify and suggest me efficient methods in reading messages from IBM MQ. thank you. | 2020/05/10 | [
"https://Stackoverflow.com/questions/61717941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9180615/"
] | As @JoshMc suggested, you should use a `JmsListener`.
There is good [JMS Getting Started Guide](https://spring.io/guides/gs/messaging-jms/) from Spring. For you it will look like this (definition for `myFactory` you can see in the mentioned Spring guide):
```
package hello;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class Receiver {
@JmsListener(destination = "${inwardQueueName}", containerFactory = "myFactory")
public void receiveMessage(javax.jms.Message message) throws javax.jms.JMSException {
String messagetxt = "";
if (message instanceof javax.jms.TextMessage) {
messagetxt = message.getBody(String.class);
}
...
}
}
``` | ```
@SpringBootApplication
@EnableJms
@EnableScheduling
public class MyApplication extends SpringBootServletInitializer implements SchedulingConfigurer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(MyApplication.class);
}
@Bean
public JmsListenerContainerFactory<?> conFactory(ConnectionFactory connectionFactory,
DefaultJmsListenerContainerFactoryConfigurer configurer) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
// This provides all boot's default to this factory, including the
// message converter
configurer.configure(factory, connectionFactory);
// You could still override some of Boot's default if necessary.
return factory;
}
public static void main(String[] args) {
SpringApplication.run(OmnipApplication.class, args);
}
}
```
above is the application configuration class and below is the listener code;
```
@Component
public class MessageReceiverService {
@Autowired
MessageValidationService messageValidationService;
@JmsListener(destination="${inwardQueueName}", containerFactory="conFactory")
public void receiveMessage(javax.jms.Message message) throws javax.jms.JMSException{
String messagetxt = "";
JmsMessageBean bean = new JmsMessageBean();
if(message!=null){
bean.setMessage(message.getBody(Object.class));
bean.setJmsMessageID(message.getJMSMessageID());
}
if (bean.getMessage().getClass().getSimpleName().equals("String")) {
messagetxt = (String) bean.getMessage();
} else {
byte[] messagebytes = (byte[]) bean.getMessage();
messagetxt = new String(messagebytes);
}
messagetxt = messagetxt.split(Constants.MESSAGE_END_CHAR)[0].concat(Constants.MESSAGE_END_CHAR);
messageValidationService.messageIdentifier(messagetxt);
}
}
``` |
30,223,119 | I would like to know how to create a clickable button in HTML format that sits on in the center of a header image.
I have tried to use the button tags along with the href attribute along with the img tags to try to wrap the code around the desired image but it doesn't work. An example of the result that I am trying to achieve can be found in the header on [github.com](http://github.com). | 2015/05/13 | [
"https://Stackoverflow.com/questions/30223119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4897118/"
] | You need to call `WebView.enableSlowWholeDocumentDraw()` before creating *any* WebViews in your app.
That is, if you have a WebView somewhere in your static layout, make sure you call `WebView.enableSlowWholeDocumentDraw()` before your first call to `setContentView()` that inflates a layout with WebView.
Also make sure that your WebView is indeed big. For example, if its layout size is set to `match_parent`, then your WebView will have the size of the screen, and this is what will be captured. You need to set some artificially high values for width and height. This question contains a nice illustration for that: [WebView.draw() not properly working on latest Android System WebView Update](https://stackoverflow.com/questions/30078157/webview-draw-not-properly-working-on-latest-android-system-webview-update) | ```
if(Build.VERSION.SDK_INT>=21) {
WebView.enableSlowWholeDocumentDraw();
}
public void capture(WebView webView) {
WebView lObjWebView = webView;
lObjWebView.measure(MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
lObjWebView.layout(0, 0, lObjWebView.getMeasuredWidth(), lObjWebView.getMeasuredHeight());
Bitmap bm = Bitmap.createBitmap(lObjWebView.getMeasuredWidth(), lObjWebView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas bigcanvas = new Canvas(bm);
Paint paint = new Paint();
int iHeight = bm.getHeight();
bigcanvas.drawBitmap(bm, 0, iHeight, paint);
lObjWebView.draw(bigcanvas);
if (bm != null) {
try {
File dir = new File(Environment.getExternalStorageDirectory() + "/" + "folder");
Calendar lObjCalendar = Calendar.getInstance();
int hour = lObjCalendar.get(Calendar.HOUR);
int min = lObjCalendar.get(Calendar.MINUTE);
int sec = lObjCalendar.get(Calendar.SECOND);
int mili = lObjCalendar.get(Calendar.MILLISECOND);
int day = lObjCalendar.get(Calendar.DAY_OF_YEAR);
int month = lObjCalendar.get(Calendar.MONTH);
int year = lObjCalendar.get(Calendar.YEAR);
String realDate = "ERS_" + day + month + year + "_" + hour + min + sec + mili;
if (dir.exists()) {
OutputStream fOut = null;
File file = new File(dir, realDate + ".jpg");
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 50, fOut);
fOut.flush();
fOut.close();
bm.recycle();
}
else {
if (dir.mkdir()) {
OutputStream fOut = null;
File file = new File(dir, realDate + ".jpg");
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 50, fOut);
fOut.flush();
fOut.close();
bm.recycle();
}
else {
ProjectUtil.showToast(WebPayment.this, "Problem in saving webview in external storage");
}
}
}
catch (FileNotFoundException e) {
ProjectUtil.showToast(WebPayment.this, "Problem in saving webview in external storage");
}
catch (IOException e) {
ProjectUtil.showToast(WebPayment.this, "Problem in saving webview in external storage");
}
catch (Exception e) {
ProjectUtil.showToast(WebPayment.this, "Problem in saving webview in external storage");
}
}
}
``` |
30,223,119 | I would like to know how to create a clickable button in HTML format that sits on in the center of a header image.
I have tried to use the button tags along with the href attribute along with the img tags to try to wrap the code around the desired image but it doesn't work. An example of the result that I am trying to achieve can be found in the header on [github.com](http://github.com). | 2015/05/13 | [
"https://Stackoverflow.com/questions/30223119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4897118/"
] | I am the author of [this question](https://stackoverflow.com/questions/30078157/webview-draw-not-properly-working-on-latest-android-system-webview-update).
To fix this problem, I had to call `WebView.enableSlowWholeDocumentDraw()` *before* inflating the view in your fragment. In the comments of Mikhail Naganov's answer, I saw that you tried a lot of options but not this one. Below is the code that I use in the `onCreateView()` method of your fragment with the WebView.
```
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle bundle){
//Enable the drawing of the whole document for Lollipop to get the whole WebView
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
WebView.enableSlowWholeDocumentDraw();
}
View view = inflater.inflate(R.layout.my_layout, parent, false);
/* Rest of code */
}
```
There's really nothing else to it. If that doesn't work, then it might be a bug and you should report as Mikhail had suggested.
Hope this helps ! | ```
if(Build.VERSION.SDK_INT>=21) {
WebView.enableSlowWholeDocumentDraw();
}
public void capture(WebView webView) {
WebView lObjWebView = webView;
lObjWebView.measure(MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
lObjWebView.layout(0, 0, lObjWebView.getMeasuredWidth(), lObjWebView.getMeasuredHeight());
Bitmap bm = Bitmap.createBitmap(lObjWebView.getMeasuredWidth(), lObjWebView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas bigcanvas = new Canvas(bm);
Paint paint = new Paint();
int iHeight = bm.getHeight();
bigcanvas.drawBitmap(bm, 0, iHeight, paint);
lObjWebView.draw(bigcanvas);
if (bm != null) {
try {
File dir = new File(Environment.getExternalStorageDirectory() + "/" + "folder");
Calendar lObjCalendar = Calendar.getInstance();
int hour = lObjCalendar.get(Calendar.HOUR);
int min = lObjCalendar.get(Calendar.MINUTE);
int sec = lObjCalendar.get(Calendar.SECOND);
int mili = lObjCalendar.get(Calendar.MILLISECOND);
int day = lObjCalendar.get(Calendar.DAY_OF_YEAR);
int month = lObjCalendar.get(Calendar.MONTH);
int year = lObjCalendar.get(Calendar.YEAR);
String realDate = "ERS_" + day + month + year + "_" + hour + min + sec + mili;
if (dir.exists()) {
OutputStream fOut = null;
File file = new File(dir, realDate + ".jpg");
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 50, fOut);
fOut.flush();
fOut.close();
bm.recycle();
}
else {
if (dir.mkdir()) {
OutputStream fOut = null;
File file = new File(dir, realDate + ".jpg");
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 50, fOut);
fOut.flush();
fOut.close();
bm.recycle();
}
else {
ProjectUtil.showToast(WebPayment.this, "Problem in saving webview in external storage");
}
}
}
catch (FileNotFoundException e) {
ProjectUtil.showToast(WebPayment.this, "Problem in saving webview in external storage");
}
catch (IOException e) {
ProjectUtil.showToast(WebPayment.this, "Problem in saving webview in external storage");
}
catch (Exception e) {
ProjectUtil.showToast(WebPayment.this, "Problem in saving webview in external storage");
}
}
}
``` |
30,223,119 | I would like to know how to create a clickable button in HTML format that sits on in the center of a header image.
I have tried to use the button tags along with the href attribute along with the img tags to try to wrap the code around the desired image but it doesn't work. An example of the result that I am trying to achieve can be found in the header on [github.com](http://github.com). | 2015/05/13 | [
"https://Stackoverflow.com/questions/30223119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4897118/"
] | Struggled with this/similar issue myself for ages. Finally found a solution, for some reason `webView.draw(page.getCanvas())` renders the whole content with KitKat but not with Lollipop (even with `enableSlowWholeDocumentDraw()`).
However, using `(webView.capturePicture()).draw(page.getCanvas())` in combination with `enableSlowWholeDocumentDraw()` DOES work for Lollipop, although `capturePicture()` is deprecated.
A final potentially important point to note is that typically you see many calls to "onDraw" as a webView loads its data and I found that with Lollipop my snapshot was getting taken prematurely (before the content had been fully loaded - annoyingly even the `onPageFinished()` callback method of webViewClient does not guarantee this!) - my solution was to have a custom webView and in the onDraw method, add this as the FIRST LINE: `if(this.getContentHeight() == 0) return;`
i.e. don't bother to do any drawing unless there is some proper content.
That way you should never get a blank page snapshot - although from your description it sounds like this might not be impacting you.... | ```
if(Build.VERSION.SDK_INT>=21) {
WebView.enableSlowWholeDocumentDraw();
}
public void capture(WebView webView) {
WebView lObjWebView = webView;
lObjWebView.measure(MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
lObjWebView.layout(0, 0, lObjWebView.getMeasuredWidth(), lObjWebView.getMeasuredHeight());
Bitmap bm = Bitmap.createBitmap(lObjWebView.getMeasuredWidth(), lObjWebView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas bigcanvas = new Canvas(bm);
Paint paint = new Paint();
int iHeight = bm.getHeight();
bigcanvas.drawBitmap(bm, 0, iHeight, paint);
lObjWebView.draw(bigcanvas);
if (bm != null) {
try {
File dir = new File(Environment.getExternalStorageDirectory() + "/" + "folder");
Calendar lObjCalendar = Calendar.getInstance();
int hour = lObjCalendar.get(Calendar.HOUR);
int min = lObjCalendar.get(Calendar.MINUTE);
int sec = lObjCalendar.get(Calendar.SECOND);
int mili = lObjCalendar.get(Calendar.MILLISECOND);
int day = lObjCalendar.get(Calendar.DAY_OF_YEAR);
int month = lObjCalendar.get(Calendar.MONTH);
int year = lObjCalendar.get(Calendar.YEAR);
String realDate = "ERS_" + day + month + year + "_" + hour + min + sec + mili;
if (dir.exists()) {
OutputStream fOut = null;
File file = new File(dir, realDate + ".jpg");
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 50, fOut);
fOut.flush();
fOut.close();
bm.recycle();
}
else {
if (dir.mkdir()) {
OutputStream fOut = null;
File file = new File(dir, realDate + ".jpg");
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 50, fOut);
fOut.flush();
fOut.close();
bm.recycle();
}
else {
ProjectUtil.showToast(WebPayment.this, "Problem in saving webview in external storage");
}
}
}
catch (FileNotFoundException e) {
ProjectUtil.showToast(WebPayment.this, "Problem in saving webview in external storage");
}
catch (IOException e) {
ProjectUtil.showToast(WebPayment.this, "Problem in saving webview in external storage");
}
catch (Exception e) {
ProjectUtil.showToast(WebPayment.this, "Problem in saving webview in external storage");
}
}
}
``` |
3,130,701 | How to kill a running thread in java | 2010/06/28 | [
"https://Stackoverflow.com/questions/3130701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/297115/"
] | You can ask the thread to interrupt, by calling [`Thread.interrupt()`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#interrupt%28%29)
Note that a few other methods with similar semantics exist - `stop()` and `destroy()` - but they are *deprecated*, because they are [unsafe](http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html). Don't be tempted to use them. | Shortly you need [`Thread.interrupt()`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#interrupt%28%29)
For more details check the section `How do I stop a thread that waits for long periods (e.g., for input)` in this article [Why Are `Thread.stop`, `Thread.suspend`,`Thread.resume` and `Runtime.runFinalizersOnExit` Deprecated?](http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html). |
3,130,701 | How to kill a running thread in java | 2010/06/28 | [
"https://Stackoverflow.com/questions/3130701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/297115/"
] | You can ask the thread to interrupt, by calling [`Thread.interrupt()`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#interrupt%28%29)
Note that a few other methods with similar semantics exist - `stop()` and `destroy()` - but they are *deprecated*, because they are [unsafe](http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html). Don't be tempted to use them. | As Bozho said, Thread.interrupt() is the generic and right way to do it. But remember that it requires the thread to cooperate; It is very easy to implement a thread that ignores interruption requests.
In order for a piece of code to be interruptible this way, it shouldn't ignore any InterruptedException, and it should check the interruption flag on each loop iteration (using Thread.currentThread().isInterrupted()). Also, it shouldn't have any non-interruptible blocking operations. If such operations exist (e.g. waiting on a socket), then you'll need a more specific interruption implementation (e.g. closing the socket). |
3,130,701 | How to kill a running thread in java | 2010/06/28 | [
"https://Stackoverflow.com/questions/3130701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/297115/"
] | As Bozho said, Thread.interrupt() is the generic and right way to do it. But remember that it requires the thread to cooperate; It is very easy to implement a thread that ignores interruption requests.
In order for a piece of code to be interruptible this way, it shouldn't ignore any InterruptedException, and it should check the interruption flag on each loop iteration (using Thread.currentThread().isInterrupted()). Also, it shouldn't have any non-interruptible blocking operations. If such operations exist (e.g. waiting on a socket), then you'll need a more specific interruption implementation (e.g. closing the socket). | Shortly you need [`Thread.interrupt()`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#interrupt%28%29)
For more details check the section `How do I stop a thread that waits for long periods (e.g., for input)` in this article [Why Are `Thread.stop`, `Thread.suspend`,`Thread.resume` and `Runtime.runFinalizersOnExit` Deprecated?](http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html). |
36,425,945 | I want to display picture from access and show that on a form in vb.net
I have this for display information:
```
info.TextBox5.Text = DataGridView1.SelectedRows(0).Cells(5).Value
```
Now I tried something like this for pictures:
```
info.PictureBox1.Image = DataGridView1.SelectedRows(0).Cells(6).Value
```
But I got an error:
>
> Can not associate the type of Object ' System.Byte []' to type '
> System.Drawing.Image ' .
>
>
>
Can you help me? | 2016/04/05 | [
"https://Stackoverflow.com/questions/36425945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5433094/"
] | Based on Google Maps [docs](https://developers.google.com/maps/faq#usage-limits):
>
> Excess usage over the complimentary quota for each Google Maps API
> service is calculated at the end of each day.
>
>
> Web service APIs offer 2,500 free requests per day. If you enable
> billing to access higher quotas, once you exceed 2,500 requests in a
> day, you will be billed $0.50 USD / 1,000 additional requests, up to
> 100,000 daily.
>
>
> The Google Maps JavaScript API, Google Static Maps API, and Google
> Street View Image API offer 25,000 free map loads per day. If your
> site generates excess usage every day for 90 consecutive days, Google
> will attempt to contact you with information about payment options.
>
>
> Learn more about what happens if you exceed the usage limits.
>
>
> If you chose to enable billing you will need to provide your credit
> card details. Your excess usage will continue to be calculated at the
> end of each day, and the total charged to the credit card provided at
> the end of every month, priced as given below.
>
>
>
So, unsless you want to hack Google, who is owner of this forum, the answer is no. | There is an opensource map library,
<https://www.openstreetmap.org>
And they have services for geocoding: <http://wiki.openstreetmap.org/wiki/Nominatim>
So you can also take a look at the different solutions like this one. |
163 | I was tasked with figuring out whether carbon or nitrogen has a more negative electron affinity value. I initially picked nitrogen, just because nitrogen has a higher $Z\_\mathrm{eff}$, creating a larger attraction between electrons and protons, decreasing the radius, causing a higher ionization energy, and therefore decreasing the electron affinity value, but I was actually wrong, and the solutions manual explains it as this:
>
> "As you go from C to N across the Periodic Table you would normally expect N to have the more negative electron affinity. However, N has a half-filled p subshell, which lends it extra stability; therefore, it is harder to add an electron."
>
>
>
Are there any major exceptions to the rules when comparing electron affinity? I'm hesitant to use nitrogen as an exception, because I don't know how far it extends. If nitrogen has a more positive EA than carbon, does that also extend to boron, aluminium, or phosphorus?
I later found that this also applies when comparing silicon and phosphorus. The explanation given was the same.
What exceptions should be noted when comparing electron affinities? Are there any at all? And how far does the exception with atoms with half-filled p subshells extend? | 2012/04/29 | [
"https://chemistry.stackexchange.com/questions/163",
"https://chemistry.stackexchange.com",
"https://chemistry.stackexchange.com/users/85/"
] | This exception rule is actually orbital filling rule. For two electrons to be in same orbital they need to have different spins (Pauli exclusion principal). This electron pairing requires additional energy and thus it is easier to add electrons if there are free orbitals. When element has a half-filled p sublevel all 3 orbitals have one electron and pairing takes place (difference between energy levels of 2p and 3s is greater than electron pairing energy).
Electron pairing effects have significant impact to physical properties of coordination complexes (like color and magnetic properties). | I say the reason why the electron affinity of fluorine is not as negative as chlorine and that of O is not as negative as S is because of the electron repulsions in the small compact atoms keep the added electrons from being tightly bound as we might expect. . . |
163 | I was tasked with figuring out whether carbon or nitrogen has a more negative electron affinity value. I initially picked nitrogen, just because nitrogen has a higher $Z\_\mathrm{eff}$, creating a larger attraction between electrons and protons, decreasing the radius, causing a higher ionization energy, and therefore decreasing the electron affinity value, but I was actually wrong, and the solutions manual explains it as this:
>
> "As you go from C to N across the Periodic Table you would normally expect N to have the more negative electron affinity. However, N has a half-filled p subshell, which lends it extra stability; therefore, it is harder to add an electron."
>
>
>
Are there any major exceptions to the rules when comparing electron affinity? I'm hesitant to use nitrogen as an exception, because I don't know how far it extends. If nitrogen has a more positive EA than carbon, does that also extend to boron, aluminium, or phosphorus?
I later found that this also applies when comparing silicon and phosphorus. The explanation given was the same.
What exceptions should be noted when comparing electron affinities? Are there any at all? And how far does the exception with atoms with half-filled p subshells extend? | 2012/04/29 | [
"https://chemistry.stackexchange.com/questions/163",
"https://chemistry.stackexchange.com",
"https://chemistry.stackexchange.com/users/85/"
] | This exception rule is actually orbital filling rule. For two electrons to be in same orbital they need to have different spins (Pauli exclusion principal). This electron pairing requires additional energy and thus it is easier to add electrons if there are free orbitals. When element has a half-filled p sublevel all 3 orbitals have one electron and pairing takes place (difference between energy levels of 2p and 3s is greater than electron pairing energy).
Electron pairing effects have significant impact to physical properties of coordination complexes (like color and magnetic properties). | Exceptions abound in electron affinity. Another case is in that of $\ce{F}$ versus that of $\ce{Cl}$. You would think that $\ce{F}$ being far more electronegative, would have the more negative electron affinity, but actually, that is not the case. The small size of $\ce{F}$ makes another electron energetically unfavorable due to electron-electron repulsion. $E\ce{(F)} = -328 kJ/mol$, while $E\ce{(Cl)} = -349 kJ/mol$
In general, exceptions arise when new subshells are being filled/half-filled, or in cases where the atom is too small. In the first case, $\ce{Be}$ and $\ce{Mg}$ are interesting examples: they have a positive electron affinity (just like $\ce{N}$, in fact) because of the energy difference between the s and p subshells. This is no longer the case in $\ce{Ca}$, which as a low-lying 3d orbital; $E\ce{(Ca)}$ is $-2 kJ/mol$. |
36,105,068 | I am currently learning Meteor and I found out something that intrigued me.
I can load HTML and CSS assets from a JS file using the import statement.
```
import '../imports/hello/myapp.html';
import '../imports/hello/myapp.css';
import * as myApp from '../imports/hello/myapp.js';
```
This was a surprise to me so I ran to google but could not find this behavior documented in the specification for ES6 `import` or in Meteor's Docs.
So my questions are:
* Can I rely on this behavior to build my apps?
* Will my app will break when Meteor gets around to fix it -- if it's a bug --?
**Notes**
* I am using Meteor v1.3, not sure if this works also with previous versions.
* You can download the app to see this behavior from [Github](https://github.com/pgpbpadilla/meteor-playground/tree/so-es6-meteor-import-bounty) | 2016/03/19 | [
"https://Stackoverflow.com/questions/36105068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/400544/"
] | One of the features in Meteor 1.3 is lazy-loading where you place your files in the `/imports` folder and will not be evaluated eagerly.
Quote from Meteor Guide:
>
> To fully use the module system and ensure that our code only runs when
> we ask it to, we recommend that all of your application code should be
> placed inside the imports/ directory. This means that the Meteor build
> system will only bundle and include that file if it is referenced from
> another file using an import.
>
>
>
So you can lazy load your css files by importing them from the `/imports` folder. I would say it's a feature. | ES6 export and import functionally are available in Meteor 1.3. You should not be importing HTML and CSS files if you are using Blaze, the current default templating enginge. The import/export functionality is there, but you may be using the wrong approach for building your views. |
36,105,068 | I am currently learning Meteor and I found out something that intrigued me.
I can load HTML and CSS assets from a JS file using the import statement.
```
import '../imports/hello/myapp.html';
import '../imports/hello/myapp.css';
import * as myApp from '../imports/hello/myapp.js';
```
This was a surprise to me so I ran to google but could not find this behavior documented in the specification for ES6 `import` or in Meteor's Docs.
So my questions are:
* Can I rely on this behavior to build my apps?
* Will my app will break when Meteor gets around to fix it -- if it's a bug --?
**Notes**
* I am using Meteor v1.3, not sure if this works also with previous versions.
* You can download the app to see this behavior from [Github](https://github.com/pgpbpadilla/meteor-playground/tree/so-es6-meteor-import-bounty) | 2016/03/19 | [
"https://Stackoverflow.com/questions/36105068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/400544/"
] | After going through the implementation of the built files for my app
I found out why this works.
**HTML**
Files are read from the file system and their contents added to the global Template object, e.g.,
```
== myapp.html ==
<body>
<h1>Welcome to Meteor!</h1>
{{> hello}}
</body>
```
results in the following JS code:
```
Template.body.addContent((function () {
var view = this;
return [
HTML.Raw("<h1>Welcome to Meteor!</h1>\n\n "),
Spacebars.include(view.lookupTemplate("hello"))
];
}));
```
Which is wrapped in a function with the name of the file as it's key:
```
"myapp.html": function (require, exports, module) {
Template.body.addContent((function () {
var view = this;
return [
HTML.Raw("<h1>Welcome to Meteor!</h1>\n\n "),
Spacebars.include(view.lookupTemplate("hello"))];
}));
Meteor.startup(Template.body.renderToDocument);
Template.__checkName("hello");
Template["hello"] = new Template("Template.hello", (
function () {
var view = this;
return [
HTML.Raw("<button>Click Me</button>\n "),
HTML.P("You've pressed the button ",
Blaze.View("lookup:counter",
function () {
return Spacebars.mustache(view.lookup("counter"));
}), " times.")
];
}));
},
```
So all of our HTML is now pure JS code which will be included by using `require` like any other module.
**CSS**
The files are also read from the file system and their contents are embedded also in JS functions, e.g.
```
== myapp.css ==
/* CSS declarations go here */
body {
background-color: lightblue;
}
```
Gets transformed into:
```
"myapp.css": ["meteor/modules", function (require, exports, module) {
module.exports = require("meteor/modules").addStyles("/* CSS declarations go here */\n\nbody {\n background-color: lightblue;\n}\n");
}]
```
So all of our CSS is also now a JS module that's again imported later on by using `require`.
**Conclusion**
All files are in one way or another converted to JS modules that follow similar rules for inclusion as AMD/CommonJS modules.
They will be included/bundled if another module refers to them. And since all of them are transformed to JS code
there's no magic behind the deceitful syntax:
```
import '../imports/hello/myapp.html';
import '../imports/hello/myapp.css';
```
They both are transpiled to their equivalent forms with `require` once the assets have been transformed to JS modules.
Whereas the approach of placing static assets in the `imports` directory is not mentioned in the official documentation,
this way of importing static assets works.
This seems to be at the core of how Meteor works so I'd bet this functionality is going to be there for a long while.
I don't know if to call this a feature maybe a more appropriate description is unexpected consequence but that would
only be true from the user's perspective, I assume the people who wrote the code understood this would happen and perhaps even
designed it purposely this way. | ES6 export and import functionally are available in Meteor 1.3. You should not be importing HTML and CSS files if you are using Blaze, the current default templating enginge. The import/export functionality is there, but you may be using the wrong approach for building your views. |
36,105,068 | I am currently learning Meteor and I found out something that intrigued me.
I can load HTML and CSS assets from a JS file using the import statement.
```
import '../imports/hello/myapp.html';
import '../imports/hello/myapp.css';
import * as myApp from '../imports/hello/myapp.js';
```
This was a surprise to me so I ran to google but could not find this behavior documented in the specification for ES6 `import` or in Meteor's Docs.
So my questions are:
* Can I rely on this behavior to build my apps?
* Will my app will break when Meteor gets around to fix it -- if it's a bug --?
**Notes**
* I am using Meteor v1.3, not sure if this works also with previous versions.
* You can download the app to see this behavior from [Github](https://github.com/pgpbpadilla/meteor-playground/tree/so-es6-meteor-import-bounty) | 2016/03/19 | [
"https://Stackoverflow.com/questions/36105068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/400544/"
] | After going through the implementation of the built files for my app
I found out why this works.
**HTML**
Files are read from the file system and their contents added to the global Template object, e.g.,
```
== myapp.html ==
<body>
<h1>Welcome to Meteor!</h1>
{{> hello}}
</body>
```
results in the following JS code:
```
Template.body.addContent((function () {
var view = this;
return [
HTML.Raw("<h1>Welcome to Meteor!</h1>\n\n "),
Spacebars.include(view.lookupTemplate("hello"))
];
}));
```
Which is wrapped in a function with the name of the file as it's key:
```
"myapp.html": function (require, exports, module) {
Template.body.addContent((function () {
var view = this;
return [
HTML.Raw("<h1>Welcome to Meteor!</h1>\n\n "),
Spacebars.include(view.lookupTemplate("hello"))];
}));
Meteor.startup(Template.body.renderToDocument);
Template.__checkName("hello");
Template["hello"] = new Template("Template.hello", (
function () {
var view = this;
return [
HTML.Raw("<button>Click Me</button>\n "),
HTML.P("You've pressed the button ",
Blaze.View("lookup:counter",
function () {
return Spacebars.mustache(view.lookup("counter"));
}), " times.")
];
}));
},
```
So all of our HTML is now pure JS code which will be included by using `require` like any other module.
**CSS**
The files are also read from the file system and their contents are embedded also in JS functions, e.g.
```
== myapp.css ==
/* CSS declarations go here */
body {
background-color: lightblue;
}
```
Gets transformed into:
```
"myapp.css": ["meteor/modules", function (require, exports, module) {
module.exports = require("meteor/modules").addStyles("/* CSS declarations go here */\n\nbody {\n background-color: lightblue;\n}\n");
}]
```
So all of our CSS is also now a JS module that's again imported later on by using `require`.
**Conclusion**
All files are in one way or another converted to JS modules that follow similar rules for inclusion as AMD/CommonJS modules.
They will be included/bundled if another module refers to them. And since all of them are transformed to JS code
there's no magic behind the deceitful syntax:
```
import '../imports/hello/myapp.html';
import '../imports/hello/myapp.css';
```
They both are transpiled to their equivalent forms with `require` once the assets have been transformed to JS modules.
Whereas the approach of placing static assets in the `imports` directory is not mentioned in the official documentation,
this way of importing static assets works.
This seems to be at the core of how Meteor works so I'd bet this functionality is going to be there for a long while.
I don't know if to call this a feature maybe a more appropriate description is unexpected consequence but that would
only be true from the user's perspective, I assume the people who wrote the code understood this would happen and perhaps even
designed it purposely this way. | One of the features in Meteor 1.3 is lazy-loading where you place your files in the `/imports` folder and will not be evaluated eagerly.
Quote from Meteor Guide:
>
> To fully use the module system and ensure that our code only runs when
> we ask it to, we recommend that all of your application code should be
> placed inside the imports/ directory. This means that the Meteor build
> system will only bundle and include that file if it is referenced from
> another file using an import.
>
>
>
So you can lazy load your css files by importing them from the `/imports` folder. I would say it's a feature. |
3,852,932 | I am working application in which i calling `presentModalViewController` and once finished(calling `dismissModalViewControllerAnimated:YES`) it should immediately call `popToRootViewControllerAnimated`.
But the issue is `dismissModalViewControllerAnimated:YES` is working properly but `popToRootViewControllerAnimated`is not working after it.
The code is shown below:
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
[self.navigationController popToRootViewControllerAnimated:YES];
``` | 2010/10/04 | [
"https://Stackoverflow.com/questions/3852932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384150/"
] | Try something like this:
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
[self performSelector:@selector(patchSelector) withObject:nil afterDelay:0.3];
-(void)patchSelector{
[self.navigationController popToRootViewControllerAnimated:YES];
}
```
It is not so neat but it should work.
**UPDATE:**
You should use
```
[self dismissModalViewControllerAnimated:YES];
```
instead
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
```
The object that is presenting the modal is the view controller, not the navigation controller. | I guess, you are not calling the
```
[self.navigationController popToRootViewControllerAnimated:YES];
```
in the target modal viewcontroller. check that. |
3,852,932 | I am working application in which i calling `presentModalViewController` and once finished(calling `dismissModalViewControllerAnimated:YES`) it should immediately call `popToRootViewControllerAnimated`.
But the issue is `dismissModalViewControllerAnimated:YES` is working properly but `popToRootViewControllerAnimated`is not working after it.
The code is shown below:
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
[self.navigationController popToRootViewControllerAnimated:YES];
``` | 2010/10/04 | [
"https://Stackoverflow.com/questions/3852932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384150/"
] | Try something like this:
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
[self performSelector:@selector(patchSelector) withObject:nil afterDelay:0.3];
-(void)patchSelector{
[self.navigationController popToRootViewControllerAnimated:YES];
}
```
It is not so neat but it should work.
**UPDATE:**
You should use
```
[self dismissModalViewControllerAnimated:YES];
```
instead
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
```
The object that is presenting the modal is the view controller, not the navigation controller. | If you have a navigation controller with a stack of UIViewControllers:
```
[self dismissModalViewControllerAnimated:YES];
[(UINavigationController*)self.parentViewController popToRootViewControllerAnimated:YES];
//UIViewController *vc = [[UIViewController new] autorelease];
//[(UINavigationController*)self.parentViewController pushViewController:vc animated:YES];
```
Assumes, that view controller in which called modal view controller has navigationController. |
3,852,932 | I am working application in which i calling `presentModalViewController` and once finished(calling `dismissModalViewControllerAnimated:YES`) it should immediately call `popToRootViewControllerAnimated`.
But the issue is `dismissModalViewControllerAnimated:YES` is working properly but `popToRootViewControllerAnimated`is not working after it.
The code is shown below:
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
[self.navigationController popToRootViewControllerAnimated:YES];
``` | 2010/10/04 | [
"https://Stackoverflow.com/questions/3852932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384150/"
] | Try something like this:
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
[self performSelector:@selector(patchSelector) withObject:nil afterDelay:0.3];
-(void)patchSelector{
[self.navigationController popToRootViewControllerAnimated:YES];
}
```
It is not so neat but it should work.
**UPDATE:**
You should use
```
[self dismissModalViewControllerAnimated:YES];
```
instead
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
```
The object that is presenting the modal is the view controller, not the navigation controller. | I ran into something similar to this. You need to make a copy of your self.navigationcontroller first and also retain yourself, so when you call the second pop, there is still a reference to the NC and you still exist.
```
// locally store the navigation controller since
// self.navigationController will be nil once we are popped
UINavigationController *navController = self.navigationController;
// retain ourselves so that the controller will still exist once it's popped off
[[self retain] autorelease];
// Pop this controller and replace with another
[navController popViewControllerAnimated:NO];
[navController pushViewController:someViewController animated:NO];
```
see : [How can I pop a view from a UINavigationController and replace it with another in one operation?](https://stackoverflow.com/questions/410471/how-can-i-pop-a-view-from-a-uinavigationcontroller-and-replace-it-with-another-i) |
3,852,932 | I am working application in which i calling `presentModalViewController` and once finished(calling `dismissModalViewControllerAnimated:YES`) it should immediately call `popToRootViewControllerAnimated`.
But the issue is `dismissModalViewControllerAnimated:YES` is working properly but `popToRootViewControllerAnimated`is not working after it.
The code is shown below:
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
[self.navigationController popToRootViewControllerAnimated:YES];
``` | 2010/10/04 | [
"https://Stackoverflow.com/questions/3852932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384150/"
] | If you have a navigation controller with a stack of UIViewControllers:
```
[self dismissModalViewControllerAnimated:YES];
[(UINavigationController*)self.parentViewController popToRootViewControllerAnimated:YES];
//UIViewController *vc = [[UIViewController new] autorelease];
//[(UINavigationController*)self.parentViewController pushViewController:vc animated:YES];
```
Assumes, that view controller in which called modal view controller has navigationController. | I guess, you are not calling the
```
[self.navigationController popToRootViewControllerAnimated:YES];
```
in the target modal viewcontroller. check that. |
3,852,932 | I am working application in which i calling `presentModalViewController` and once finished(calling `dismissModalViewControllerAnimated:YES`) it should immediately call `popToRootViewControllerAnimated`.
But the issue is `dismissModalViewControllerAnimated:YES` is working properly but `popToRootViewControllerAnimated`is not working after it.
The code is shown below:
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
[self.navigationController popToRootViewControllerAnimated:YES];
``` | 2010/10/04 | [
"https://Stackoverflow.com/questions/3852932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384150/"
] | I ran into something similar to this. You need to make a copy of your self.navigationcontroller first and also retain yourself, so when you call the second pop, there is still a reference to the NC and you still exist.
```
// locally store the navigation controller since
// self.navigationController will be nil once we are popped
UINavigationController *navController = self.navigationController;
// retain ourselves so that the controller will still exist once it's popped off
[[self retain] autorelease];
// Pop this controller and replace with another
[navController popViewControllerAnimated:NO];
[navController pushViewController:someViewController animated:NO];
```
see : [How can I pop a view from a UINavigationController and replace it with another in one operation?](https://stackoverflow.com/questions/410471/how-can-i-pop-a-view-from-a-uinavigationcontroller-and-replace-it-with-another-i) | I guess, you are not calling the
```
[self.navigationController popToRootViewControllerAnimated:YES];
```
in the target modal viewcontroller. check that. |
3,852,932 | I am working application in which i calling `presentModalViewController` and once finished(calling `dismissModalViewControllerAnimated:YES`) it should immediately call `popToRootViewControllerAnimated`.
But the issue is `dismissModalViewControllerAnimated:YES` is working properly but `popToRootViewControllerAnimated`is not working after it.
The code is shown below:
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
[self.navigationController popToRootViewControllerAnimated:YES];
``` | 2010/10/04 | [
"https://Stackoverflow.com/questions/3852932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384150/"
] | If you have a navigation controller with a stack of UIViewControllers:
```
[self dismissModalViewControllerAnimated:YES];
[(UINavigationController*)self.parentViewController popToRootViewControllerAnimated:YES];
//UIViewController *vc = [[UIViewController new] autorelease];
//[(UINavigationController*)self.parentViewController pushViewController:vc animated:YES];
```
Assumes, that view controller in which called modal view controller has navigationController. | I ran into something similar to this. You need to make a copy of your self.navigationcontroller first and also retain yourself, so when you call the second pop, there is still a reference to the NC and you still exist.
```
// locally store the navigation controller since
// self.navigationController will be nil once we are popped
UINavigationController *navController = self.navigationController;
// retain ourselves so that the controller will still exist once it's popped off
[[self retain] autorelease];
// Pop this controller and replace with another
[navController popViewControllerAnimated:NO];
[navController pushViewController:someViewController animated:NO];
```
see : [How can I pop a view from a UINavigationController and replace it with another in one operation?](https://stackoverflow.com/questions/410471/how-can-i-pop-a-view-from-a-uinavigationcontroller-and-replace-it-with-another-i) |
58,369,989 | Need help passing state as a prop to another state component. I'm very new to React and I'm not sure what I'm doing wrong. When I console.log inside the Timer component it displays undefined but when I console.log in the Main component it displays the object perfectly.
```
class Main extends React.Component {
constructor() {
super()
this.state = {
isLoaded: false,
itemsP:{}
}
}
componentDidMount() {
fetch("https://api.spacexdata.com/v3/launches/next")
.then(response => response.json())
.then(
(resData) =>
this.setState({
isLoaded: true,
itemsP: resData
})
)
}
render() {
console.log(this.state.itemsP) //this will console.log the object from the api
return (
<main>
<Timer nextLaunch={this.state.itemsP} />
</main>
)
}
}
//Timer component
class Timer extends React.Component{
constructor(props) {
super(props)
this.state = {
nextDate: props.nextLaunch.launch_date_utc
}
}
render() {
console.log(this.state.nextDate) //will console log UNDEFINED why is this?
return (
<div>
//display something....
</div>
)
}
}
```
[here](https://docs.spacexdata.com/?version=latest#c75a20cf-50e7-4a4a-8856-ee729e0d3868) is the link for the API that I'm using for reference. | 2019/10/14 | [
"https://Stackoverflow.com/questions/58369989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6383688/"
] | @tlrmacl might have answered it there. It's missing the `this` keyword. In theory, you might be assigning the initial value still to the state.
It is due to how react lifecycle works
On your `componentDidMount()`, you are calling setState after the jsx gets mounted to the DOM. `this.state.itemsP` is given an initial value of `{}` then after the mount, it will receive its new value from `comopnentDidMount()`
Inside your `Timer` component, you are assigning the first value of `this.props.nextLaunch` to a new state. It doesn't have the chance to update the value. Instead of doing this:
```
this.state = {
nextDate: props.nextLaunch.launch_date_utc
}
```
use `props.nextLaunch.launch_date_utc` directly:
```
console.log(props.nextLaunch.launch_date_utc)
```
For more information check out this tweet by Dan Abramov [here](https://twitter.com/dan_abramov/status/981712092611989509) | From ur parent component u pass value as `nextLaunch`
Dont forget to call props in ur parent component constructor
```
constructor(props) {
super(props);
this.state = {
isLoaded: false,
itemsP: 'myValue'
}
}
<Timer nextLaunch={this.state.itemsP} />
```
So in your Timer Component to print ur value you have to call ur props this way `this.props.nextLaunch`
```
class Timer extends React.Component {
render() {
return <p>My nextLaunch data are {this.props.nextLaunch}.</p>;
}
}
```
Hope it helps |
58,369,989 | Need help passing state as a prop to another state component. I'm very new to React and I'm not sure what I'm doing wrong. When I console.log inside the Timer component it displays undefined but when I console.log in the Main component it displays the object perfectly.
```
class Main extends React.Component {
constructor() {
super()
this.state = {
isLoaded: false,
itemsP:{}
}
}
componentDidMount() {
fetch("https://api.spacexdata.com/v3/launches/next")
.then(response => response.json())
.then(
(resData) =>
this.setState({
isLoaded: true,
itemsP: resData
})
)
}
render() {
console.log(this.state.itemsP) //this will console.log the object from the api
return (
<main>
<Timer nextLaunch={this.state.itemsP} />
</main>
)
}
}
//Timer component
class Timer extends React.Component{
constructor(props) {
super(props)
this.state = {
nextDate: props.nextLaunch.launch_date_utc
}
}
render() {
console.log(this.state.nextDate) //will console log UNDEFINED why is this?
return (
<div>
//display something....
</div>
)
}
}
```
[here](https://docs.spacexdata.com/?version=latest#c75a20cf-50e7-4a4a-8856-ee729e0d3868) is the link for the API that I'm using for reference. | 2019/10/14 | [
"https://Stackoverflow.com/questions/58369989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6383688/"
] | @tlrmacl might have answered it there. It's missing the `this` keyword. In theory, you might be assigning the initial value still to the state.
It is due to how react lifecycle works
On your `componentDidMount()`, you are calling setState after the jsx gets mounted to the DOM. `this.state.itemsP` is given an initial value of `{}` then after the mount, it will receive its new value from `comopnentDidMount()`
Inside your `Timer` component, you are assigning the first value of `this.props.nextLaunch` to a new state. It doesn't have the chance to update the value. Instead of doing this:
```
this.state = {
nextDate: props.nextLaunch.launch_date_utc
}
```
use `props.nextLaunch.launch_date_utc` directly:
```
console.log(props.nextLaunch.launch_date_utc)
```
For more information check out this tweet by Dan Abramov [here](https://twitter.com/dan_abramov/status/981712092611989509) | ```
//Timer component
class Timer extends React.Component{
constructor(props) {
super(props)
this.state = {
nextDate: this.props.nextLaunch.launch_date_utc
}
}
```
You need this.props instead of props in your constructor |
52,436,015 | I'm trying to mimic the Web Audio API multitrack demo from the 'Mozilla Web Audio API for games' Web doc.
<https://developer.mozilla.org/en-US/docs/Games/Techniques/Audio_for_Web_Games#Web_Audio_API_for_games>
The only caveat I have is that I want the previous track to stop, once a new track is clicked (instead of playing layered on top of each other).
An example would be, click drums, the drums start playing, then click guitar, the drums stop and the guitar starts right where the drums left off.
Any ideas? Are there better tools/libraries for handling web audio?
<http://jsfiddle.net/c87z11jj/1/>
```
<ul>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-leadguitar.mp3">Lead Guitar</a></li>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-drums.mp3">Drums</a></li>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-bassguitar.mp3">Bass Guitar</a></li>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-horns.mp3">Horns</a></li>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-clav.mp3">Clavi</a></li>
</ul>
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var offset = 0;
var context = new AudioContext();
function playTrack(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
var audiobuffer;
// Decode asynchronously
request.onload = function() {
if (request.status == 200) {
context.decodeAudioData(request.response, function(buffer) {
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
console.log('context.currentTime '+context.currentTime);
if (offset == 0) {
source.start();
offset = context.currentTime;
} else {
source.start(0,context.currentTime - offset);
}
}, function(e) {
console.log('Error decoding audio data:' + e);
});
} else {
console.log('Audio didn\'t load successfully; error code:' + request.statusText);
}
}
request.send();
}
var tracks = document.getElementsByClassName('track');
for (var i = 0, len = tracks.length; i < len; i++) {
tracks[i].addEventListener('click', function(e){
console.log(this.href);
playTrack(this.href);
e.preventDefault();
});
}
``` | 2018/09/21 | [
"https://Stackoverflow.com/questions/52436015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10241361/"
] | Simply store the BufferSources somewhere in the outer scope and then call their `stop()` method.
I took the liberty to rewrite a bit your loading logic, you shouldn't create a new request every time you start a new track, in that case you loose the main advantages of AudioBuffers against Audio element: they're truly fast to instantiate.
```js
var active_source = null;
function stopActiveSource() {
if (active_source) {
active_source.onended = null; // manual stop, no event
active_source.stop(0);
}
}
// instead of requesting a new ArrayBuffer every time
// store them in a dictionnary
var buffers = {};
var context = new(window.AudioContext || window.webkitAudioContext)();
function playTrack(url) {
// get fom our dictionnary
var buffer = buffers[url];
// stop the active one if any
stopActiveSource();
// create a new BufferSource
var source = context.createBufferSource();
// it is now the active one
active_source = source;
source.onended = function() {
active_source = null;
};
source.buffer = buffer;
source.connect(context.destination);
source.start(0);
}
// start by getting all AudioBuffers
var tracks = document.getElementsByClassName('track');
for (var i = 0, len = tracks.length; i < len; i++) {
tracks[i].addEventListener('click', function(e) {
playTrack(this.href);
e.preventDefault();
});
getBuffer(tracks[i].href);
}
function getBuffer(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function(evt) {
context.decodeAudioData(request.response, store);
};
request.send();
function store(buffer) {
buffers[url] = buffer;
}
}
```
```html
<base href="https://dl.dropboxusercontent.com/s/">
<ul>
<li><a class="track" href="kbgd2jm7ezk3u3x/hihat.mp3">HiHat</a></li>
<li><a class="track" href="h2j6vm17r07jf03/snare.mp3">Snare</a></li>
<li><a class="track" href="1cdwpm3gca9mlo0/kick.mp3">Kick</a></li>
<li><a class="track" href="h8pvqqol3ovyle8/tom.mp3">Tom</a></li>
</ul>
``` | Figured it out with help from @Kaiido
Example with both synchronization and starting a new track where a previous track stops:
```
<ul>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-leadguitar.mp3">Lead Guitar</a></li>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-drums.mp3">Drums</a></li>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-bassguitar.mp3">Bass Guitar</a></li>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-horns.mp3">Horns</a></li>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-clav.mp3">Clavi</a></li>
</ul>
let active_source = null;
let buffers = {};
const context = new(window.AudioContext || window.webkitAudioContext)();
let offset = 0;
const tempo = 3.074074076;
const tracks = document.getElementsByClassName('track');
function playTrack(url) {
let buffer = buffers[url];
let source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.loop = true;
if (offset == 0) {
source.start();
offset = context.currentTime;
active_source = source;
} else {
let relativeTime = context.currentTime - offset;
let beats = relativeTime / tempo;
let remainder = beats - Math.floor(beats);
let delay = tempo - (remainder*tempo);
let when = context.currentTime+delay;
stopActiveSource(when);
source.start(context.currentTime+delay,relativeTime+delay);
active_source = source;
source.onended = function() {
active_source = null;
};
}
}
for (var i = 0, len = tracks.length; i < len; i++) {
tracks[i].addEventListener('click', function(e) {
playTrack(this.href);
e.preventDefault();
});
getBuffer(tracks[i].href);
}
function getBuffer(url) {
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function(evt) {
context.decodeAudioData(request.response, store);
};
request.send();
function store(buffer) {
buffers[url] = buffer;
}
}
function stopActiveSource(when) {
if (active_source) {
active_source.onended = null;
active_source.stop(when);
}
}
```
<http://jsfiddle.net/mdq2c1wv/1/> |
34,538,571 | I am trying run cucumber tests using maven with following command
```
mvn test -Dcucumber.options="--tag @debug1"
```
This command works fine, however if i try something like following, i get error
```
mvn test -Dcucumber.options="--tag @debug1 @debug2"
```
Is there a way to pass in multiple tag names with cucumber run-time options? | 2015/12/30 | [
"https://Stackoverflow.com/questions/34538571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3062121/"
] | I using this commandline to run multiple tags
```
mvn test -Dcucumber.options="--tags '@tag1 or @tag2' --plugin io.qameta.allure.cucumber4jvm.AllureCucumber4Jvm --plugin rerun:rerun/failed_scenarios.txt"
```
Cucumber version 4.2.6 | In cucumber v5.X, only `mvn test -Dcucumber.options="--tags '@debug1 or @debug2'"`
is supported and working.
`mvn test -Dcucumber.options="--tags '@debug1 and @debug2'"` is not working and either scenarios won't get executed |
34,538,571 | I am trying run cucumber tests using maven with following command
```
mvn test -Dcucumber.options="--tag @debug1"
```
This command works fine, however if i try something like following, i get error
```
mvn test -Dcucumber.options="--tag @debug1 @debug2"
```
Is there a way to pass in multiple tag names with cucumber run-time options? | 2015/12/30 | [
"https://Stackoverflow.com/questions/34538571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3062121/"
] | In Cucumber 6, property name has changed. Use:
```
mvn verify -Dcucumber.filter.tags="@debug1 or @debug2"
``` | In cucumber v5.X, only `mvn test -Dcucumber.options="--tags '@debug1 or @debug2'"`
is supported and working.
`mvn test -Dcucumber.options="--tags '@debug1 and @debug2'"` is not working and either scenarios won't get executed |
34,538,571 | I am trying run cucumber tests using maven with following command
```
mvn test -Dcucumber.options="--tag @debug1"
```
This command works fine, however if i try something like following, i get error
```
mvn test -Dcucumber.options="--tag @debug1 @debug2"
```
Is there a way to pass in multiple tag names with cucumber run-time options? | 2015/12/30 | [
"https://Stackoverflow.com/questions/34538571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3062121/"
] | In Cucumber 6, property name has changed. Use:
```
mvn verify -Dcucumber.filter.tags="@debug1 or @debug2"
``` | `mvn clean verify -D tags="tagName"` |
34,538,571 | I am trying run cucumber tests using maven with following command
```
mvn test -Dcucumber.options="--tag @debug1"
```
This command works fine, however if i try something like following, i get error
```
mvn test -Dcucumber.options="--tag @debug1 @debug2"
```
Is there a way to pass in multiple tag names with cucumber run-time options? | 2015/12/30 | [
"https://Stackoverflow.com/questions/34538571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3062121/"
] | For me what was working with **surefire plugin**:
```
mvn clean test -D"cucumber.filter.tags=@tag1 or @tag2"
```
When I tried with this version:
```
mvn clean test -Dcucumber.filter.tags="not @MyTag"
```
I got this exception:
```
io.cucumber.core.exception.CucumberException: Failed to parse 'cucumber.filter.tags' with value '"not @MyTag"'
Caused by: io.cucumber.tagexpressions.TagExpressionException: Tag expression '"not @MyTag"' could not be parsed because of syntax error: expected operator
``` | In cucumber v5.X, only `mvn test -Dcucumber.options="--tags '@debug1 or @debug2'"`
is supported and working.
`mvn test -Dcucumber.options="--tags '@debug1 and @debug2'"` is not working and either scenarios won't get executed |
34,538,571 | I am trying run cucumber tests using maven with following command
```
mvn test -Dcucumber.options="--tag @debug1"
```
This command works fine, however if i try something like following, i get error
```
mvn test -Dcucumber.options="--tag @debug1 @debug2"
```
Is there a way to pass in multiple tag names with cucumber run-time options? | 2015/12/30 | [
"https://Stackoverflow.com/questions/34538571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3062121/"
] | In Cucumber 6, property name has changed. Use:
```
mvn verify -Dcucumber.filter.tags="@debug1 or @debug2"
``` | Little late to the party, but I am using something like:
```
mvn test -D tags="debug1 and debug2"
```
I am on Cucumber 2.4.
The `@` symbol is optional. You can use a `tags` Maven property. And you can use boolean logic to hook up multiple tags - [official docs](https://cucumber.io/docs/cucumber/api/#tags).
Reduces the amount of typing little bit. |
34,538,571 | I am trying run cucumber tests using maven with following command
```
mvn test -Dcucumber.options="--tag @debug1"
```
This command works fine, however if i try something like following, i get error
```
mvn test -Dcucumber.options="--tag @debug1 @debug2"
```
Is there a way to pass in multiple tag names with cucumber run-time options? | 2015/12/30 | [
"https://Stackoverflow.com/questions/34538571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3062121/"
] | For me what was working with **surefire plugin**:
```
mvn clean test -D"cucumber.filter.tags=@tag1 or @tag2"
```
When I tried with this version:
```
mvn clean test -Dcucumber.filter.tags="not @MyTag"
```
I got this exception:
```
io.cucumber.core.exception.CucumberException: Failed to parse 'cucumber.filter.tags' with value '"not @MyTag"'
Caused by: io.cucumber.tagexpressions.TagExpressionException: Tag expression '"not @MyTag"' could not be parsed because of syntax error: expected operator
``` | `mvn clean verify -D tags="tagName"` |
34,538,571 | I am trying run cucumber tests using maven with following command
```
mvn test -Dcucumber.options="--tag @debug1"
```
This command works fine, however if i try something like following, i get error
```
mvn test -Dcucumber.options="--tag @debug1 @debug2"
```
Is there a way to pass in multiple tag names with cucumber run-time options? | 2015/12/30 | [
"https://Stackoverflow.com/questions/34538571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3062121/"
] | In Cucumber 6, property name has changed. Use:
```
mvn verify -Dcucumber.filter.tags="@debug1 or @debug2"
``` | For me what was working with **surefire plugin**:
```
mvn clean test -D"cucumber.filter.tags=@tag1 or @tag2"
```
When I tried with this version:
```
mvn clean test -Dcucumber.filter.tags="not @MyTag"
```
I got this exception:
```
io.cucumber.core.exception.CucumberException: Failed to parse 'cucumber.filter.tags' with value '"not @MyTag"'
Caused by: io.cucumber.tagexpressions.TagExpressionException: Tag expression '"not @MyTag"' could not be parsed because of syntax error: expected operator
``` |
34,538,571 | I am trying run cucumber tests using maven with following command
```
mvn test -Dcucumber.options="--tag @debug1"
```
This command works fine, however if i try something like following, i get error
```
mvn test -Dcucumber.options="--tag @debug1 @debug2"
```
Is there a way to pass in multiple tag names with cucumber run-time options? | 2015/12/30 | [
"https://Stackoverflow.com/questions/34538571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3062121/"
] | for version 6.10.2 Cucumber and Junit 4.12
```
mvn test "-Dcucumber.filter.tags= (@Tag1 or @Tag2) and not @Tag3"
```
where "or" is equal to "and".... for no reason (thanks Cucumber...) | `mvn clean verify -D tags="tagName"` |
34,538,571 | I am trying run cucumber tests using maven with following command
```
mvn test -Dcucumber.options="--tag @debug1"
```
This command works fine, however if i try something like following, i get error
```
mvn test -Dcucumber.options="--tag @debug1 @debug2"
```
Is there a way to pass in multiple tag names with cucumber run-time options? | 2015/12/30 | [
"https://Stackoverflow.com/questions/34538571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3062121/"
] | Little late to the party, but I am using something like:
```
mvn test -D tags="debug1 and debug2"
```
I am on Cucumber 2.4.
The `@` symbol is optional. You can use a `tags` Maven property. And you can use boolean logic to hook up multiple tags - [official docs](https://cucumber.io/docs/cucumber/api/#tags).
Reduces the amount of typing little bit. | In cucumber v5.X, only `mvn test -Dcucumber.options="--tags '@debug1 or @debug2'"`
is supported and working.
`mvn test -Dcucumber.options="--tags '@debug1 and @debug2'"` is not working and either scenarios won't get executed |
34,538,571 | I am trying run cucumber tests using maven with following command
```
mvn test -Dcucumber.options="--tag @debug1"
```
This command works fine, however if i try something like following, i get error
```
mvn test -Dcucumber.options="--tag @debug1 @debug2"
```
Is there a way to pass in multiple tag names with cucumber run-time options? | 2015/12/30 | [
"https://Stackoverflow.com/questions/34538571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3062121/"
] | * To run scenarios with `@debug1` and `@debug2`:
**Old version of Cucumber-jvm:**
```
mvn test -Dcucumber.options="--tags @debug1 --tags @debug2"
```
**Actual version of Cucumber-jvm:**
```
mvn test -Dcucumber.options="--tags '@debug1 and @debug2'"
```
* To run scenarios with `@debug1` or `@debug2`:
**Old version of Cucumber-jvm:**
```
mvn test -Dcucumber.options="--tags @debug1,@debug2"
```
**Actual version of Cucumber-jvm:**
```
mvn test -Dcucumber.options="--tags '@debug1 or @debug2'"
``` | For me what was working with **surefire plugin**:
```
mvn clean test -D"cucumber.filter.tags=@tag1 or @tag2"
```
When I tried with this version:
```
mvn clean test -Dcucumber.filter.tags="not @MyTag"
```
I got this exception:
```
io.cucumber.core.exception.CucumberException: Failed to parse 'cucumber.filter.tags' with value '"not @MyTag"'
Caused by: io.cucumber.tagexpressions.TagExpressionException: Tag expression '"not @MyTag"' could not be parsed because of syntax error: expected operator
``` |
9,803,396 | I am looking for a lightweight, reliable and fast key/value database for storing binary data. Simple without server. Most of popular key/value databases like CDB and BerkeleyDB does not natively store `BLOB`. What can be the best choice that I missed?
My current choice is SQLite, but it is too advanced for my simple usage. | 2012/03/21 | [
"https://Stackoverflow.com/questions/9803396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943340/"
] | As it was previously pointed out, BerkeleyDB does support opaque values and keys, but I would suggest a better alternative: LevelDB.
**LevelDB:**
Google is your friend :), so much so that they even provide you with an embedded database: [A fast and lightweight key/value database library by Google.](https://github.com/google/leveldb)
**Features:**
* Keys and values are arbitrary byte arrays.
* Data is stored sorted by key.
* Callers can provide a custom comparison function to override the sort order.
* The basic operations are Put(key,value), Get(key), Delete(key).
* Multiple changes can be made in one atomic batch.
* Users can create a transient snapshot to get a consistent view of data.
* Forward and backward iteration is supported over the data.
* Data is automatically compressed using the Snappy compression library.
* External activity (file system operations etc.) is relayed through a virtual interface so users can customize the operating system interactions.
* Detailed documentation about how to use the library is included with the source code. | You may have a look at <http://www.codeproject.com/Articles/316816/RaptorDB-The-Key-Value-Store-V2> my friend of Databases. |
9,803,396 | I am looking for a lightweight, reliable and fast key/value database for storing binary data. Simple without server. Most of popular key/value databases like CDB and BerkeleyDB does not natively store `BLOB`. What can be the best choice that I missed?
My current choice is SQLite, but it is too advanced for my simple usage. | 2012/03/21 | [
"https://Stackoverflow.com/questions/9803396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943340/"
] | What makes you think BerkDB cannot store binary data? From their docs:
>
> Key and content arguments are objects described by the datum typedef. A datum specifies a string of dsize bytes pointed to by dptr. Arbitrary binary data, as well as normal text strings, are allowed.
>
>
>
Also see their [examples](http://docs.oracle.com/cd/E17076_02/html/gsg/C/usingDbt.html#databaseWrite):
```
money = 122.45;
key.data = &money;
key.size = sizeof(float);
...
ret = my_database->put(my_database, NULL, &key, &data, DB_NOOVERWRITE);
``` | You may have a look at <http://www.codeproject.com/Articles/316816/RaptorDB-The-Key-Value-Store-V2> my friend of Databases. |
9,803,396 | I am looking for a lightweight, reliable and fast key/value database for storing binary data. Simple without server. Most of popular key/value databases like CDB and BerkeleyDB does not natively store `BLOB`. What can be the best choice that I missed?
My current choice is SQLite, but it is too advanced for my simple usage. | 2012/03/21 | [
"https://Stackoverflow.com/questions/9803396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943340/"
] | As it was previously pointed out, BerkeleyDB does support opaque values and keys, but I would suggest a better alternative: LevelDB.
**LevelDB:**
Google is your friend :), so much so that they even provide you with an embedded database: [A fast and lightweight key/value database library by Google.](https://github.com/google/leveldb)
**Features:**
* Keys and values are arbitrary byte arrays.
* Data is stored sorted by key.
* Callers can provide a custom comparison function to override the sort order.
* The basic operations are Put(key,value), Get(key), Delete(key).
* Multiple changes can be made in one atomic batch.
* Users can create a transient snapshot to get a consistent view of data.
* Forward and backward iteration is supported over the data.
* Data is automatically compressed using the Snappy compression library.
* External activity (file system operations etc.) is relayed through a virtual interface so users can customize the operating system interactions.
* Detailed documentation about how to use the library is included with the source code. | Which OS are you running? For Windows you might want to check out [ESE](http://en.wikipedia.org/wiki/Extensible_Storage_Engine), which is a very robust storage engine which ships as part of the OS. It powers Active Directory, Exchange, DNS and a few other Microsoft server products, and is used by many 3rd party products ([RavenDB](http://ravendb.net/) comes to mind as a good example). |
9,803,396 | I am looking for a lightweight, reliable and fast key/value database for storing binary data. Simple without server. Most of popular key/value databases like CDB and BerkeleyDB does not natively store `BLOB`. What can be the best choice that I missed?
My current choice is SQLite, but it is too advanced for my simple usage. | 2012/03/21 | [
"https://Stackoverflow.com/questions/9803396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943340/"
] | If you don't need "multiple writer processes" (only multiple readers works), want something small and want something that is available on nearly every linux, you might want to take a look at gdbm, which is like berkeley db, but much simpler. Also it's possibly not as fast.
In nearly the same area are things like tokyocabinet, qdbm, and the already mentioned leveldb.
Berkeley db and sqlite are ahead of those, because they support multiple writers. berkeley db is a versioning desaster sometimes.
The major pro of gdbm: It's already on every linux, no versioning issues, small. | You may have a look at <http://www.codeproject.com/Articles/316816/RaptorDB-The-Key-Value-Store-V2> my friend of Databases. |
9,803,396 | I am looking for a lightweight, reliable and fast key/value database for storing binary data. Simple without server. Most of popular key/value databases like CDB and BerkeleyDB does not natively store `BLOB`. What can be the best choice that I missed?
My current choice is SQLite, but it is too advanced for my simple usage. | 2012/03/21 | [
"https://Stackoverflow.com/questions/9803396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943340/"
] | What makes you think BerkDB cannot store binary data? From their docs:
>
> Key and content arguments are objects described by the datum typedef. A datum specifies a string of dsize bytes pointed to by dptr. Arbitrary binary data, as well as normal text strings, are allowed.
>
>
>
Also see their [examples](http://docs.oracle.com/cd/E17076_02/html/gsg/C/usingDbt.html#databaseWrite):
```
money = 122.45;
key.data = &money;
key.size = sizeof(float);
...
ret = my_database->put(my_database, NULL, &key, &data, DB_NOOVERWRITE);
``` | Using sqlite is now straightforward with the new functions readfile(X) and writefile(X,Y) which are available since 2014-06. For example to save a blob in the database from a file and extract it again
```
CREATE TABLE images(name TEXT, type TEXT, img BLOB);
INSERT INTO images(name,type,img) VALUES('icon','jpeg',readfile('icon.jpg'));
SELECT writefile('icon-copy2.jpg',img) FROM images WHERE name='icon';
```
see <https://www.sqlite.org/cli.html> "File I/O Functions" |
9,803,396 | I am looking for a lightweight, reliable and fast key/value database for storing binary data. Simple without server. Most of popular key/value databases like CDB and BerkeleyDB does not natively store `BLOB`. What can be the best choice that I missed?
My current choice is SQLite, but it is too advanced for my simple usage. | 2012/03/21 | [
"https://Stackoverflow.com/questions/9803396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943340/"
] | What makes you think BerkDB cannot store binary data? From their docs:
>
> Key and content arguments are objects described by the datum typedef. A datum specifies a string of dsize bytes pointed to by dptr. Arbitrary binary data, as well as normal text strings, are allowed.
>
>
>
Also see their [examples](http://docs.oracle.com/cd/E17076_02/html/gsg/C/usingDbt.html#databaseWrite):
```
money = 122.45;
key.data = &money;
key.size = sizeof(float);
...
ret = my_database->put(my_database, NULL, &key, &data, DB_NOOVERWRITE);
``` | If you don't need "multiple writer processes" (only multiple readers works), want something small and want something that is available on nearly every linux, you might want to take a look at gdbm, which is like berkeley db, but much simpler. Also it's possibly not as fast.
In nearly the same area are things like tokyocabinet, qdbm, and the already mentioned leveldb.
Berkeley db and sqlite are ahead of those, because they support multiple writers. berkeley db is a versioning desaster sometimes.
The major pro of gdbm: It's already on every linux, no versioning issues, small. |
9,803,396 | I am looking for a lightweight, reliable and fast key/value database for storing binary data. Simple without server. Most of popular key/value databases like CDB and BerkeleyDB does not natively store `BLOB`. What can be the best choice that I missed?
My current choice is SQLite, but it is too advanced for my simple usage. | 2012/03/21 | [
"https://Stackoverflow.com/questions/9803396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943340/"
] | As it was previously pointed out, BerkeleyDB does support opaque values and keys, but I would suggest a better alternative: LevelDB.
**LevelDB:**
Google is your friend :), so much so that they even provide you with an embedded database: [A fast and lightweight key/value database library by Google.](https://github.com/google/leveldb)
**Features:**
* Keys and values are arbitrary byte arrays.
* Data is stored sorted by key.
* Callers can provide a custom comparison function to override the sort order.
* The basic operations are Put(key,value), Get(key), Delete(key).
* Multiple changes can be made in one atomic batch.
* Users can create a transient snapshot to get a consistent view of data.
* Forward and backward iteration is supported over the data.
* Data is automatically compressed using the Snappy compression library.
* External activity (file system operations etc.) is relayed through a virtual interface so users can customize the operating system interactions.
* Detailed documentation about how to use the library is included with the source code. | If you don't need "multiple writer processes" (only multiple readers works), want something small and want something that is available on nearly every linux, you might want to take a look at gdbm, which is like berkeley db, but much simpler. Also it's possibly not as fast.
In nearly the same area are things like tokyocabinet, qdbm, and the already mentioned leveldb.
Berkeley db and sqlite are ahead of those, because they support multiple writers. berkeley db is a versioning desaster sometimes.
The major pro of gdbm: It's already on every linux, no versioning issues, small. |
9,803,396 | I am looking for a lightweight, reliable and fast key/value database for storing binary data. Simple without server. Most of popular key/value databases like CDB and BerkeleyDB does not natively store `BLOB`. What can be the best choice that I missed?
My current choice is SQLite, but it is too advanced for my simple usage. | 2012/03/21 | [
"https://Stackoverflow.com/questions/9803396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943340/"
] | If you don't need "multiple writer processes" (only multiple readers works), want something small and want something that is available on nearly every linux, you might want to take a look at gdbm, which is like berkeley db, but much simpler. Also it's possibly not as fast.
In nearly the same area are things like tokyocabinet, qdbm, and the already mentioned leveldb.
Berkeley db and sqlite are ahead of those, because they support multiple writers. berkeley db is a versioning desaster sometimes.
The major pro of gdbm: It's already on every linux, no versioning issues, small. | Which OS are you running? For Windows you might want to check out [ESE](http://en.wikipedia.org/wiki/Extensible_Storage_Engine), which is a very robust storage engine which ships as part of the OS. It powers Active Directory, Exchange, DNS and a few other Microsoft server products, and is used by many 3rd party products ([RavenDB](http://ravendb.net/) comes to mind as a good example). |
9,803,396 | I am looking for a lightweight, reliable and fast key/value database for storing binary data. Simple without server. Most of popular key/value databases like CDB and BerkeleyDB does not natively store `BLOB`. What can be the best choice that I missed?
My current choice is SQLite, but it is too advanced for my simple usage. | 2012/03/21 | [
"https://Stackoverflow.com/questions/9803396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943340/"
] | As it was previously pointed out, BerkeleyDB does support opaque values and keys, but I would suggest a better alternative: LevelDB.
**LevelDB:**
Google is your friend :), so much so that they even provide you with an embedded database: [A fast and lightweight key/value database library by Google.](https://github.com/google/leveldb)
**Features:**
* Keys and values are arbitrary byte arrays.
* Data is stored sorted by key.
* Callers can provide a custom comparison function to override the sort order.
* The basic operations are Put(key,value), Get(key), Delete(key).
* Multiple changes can be made in one atomic batch.
* Users can create a transient snapshot to get a consistent view of data.
* Forward and backward iteration is supported over the data.
* Data is automatically compressed using the Snappy compression library.
* External activity (file system operations etc.) is relayed through a virtual interface so users can customize the operating system interactions.
* Detailed documentation about how to use the library is included with the source code. | Using sqlite is now straightforward with the new functions readfile(X) and writefile(X,Y) which are available since 2014-06. For example to save a blob in the database from a file and extract it again
```
CREATE TABLE images(name TEXT, type TEXT, img BLOB);
INSERT INTO images(name,type,img) VALUES('icon','jpeg',readfile('icon.jpg'));
SELECT writefile('icon-copy2.jpg',img) FROM images WHERE name='icon';
```
see <https://www.sqlite.org/cli.html> "File I/O Functions" |
9,803,396 | I am looking for a lightweight, reliable and fast key/value database for storing binary data. Simple without server. Most of popular key/value databases like CDB and BerkeleyDB does not natively store `BLOB`. What can be the best choice that I missed?
My current choice is SQLite, but it is too advanced for my simple usage. | 2012/03/21 | [
"https://Stackoverflow.com/questions/9803396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943340/"
] | If you don't need "multiple writer processes" (only multiple readers works), want something small and want something that is available on nearly every linux, you might want to take a look at gdbm, which is like berkeley db, but much simpler. Also it's possibly not as fast.
In nearly the same area are things like tokyocabinet, qdbm, and the already mentioned leveldb.
Berkeley db and sqlite are ahead of those, because they support multiple writers. berkeley db is a versioning desaster sometimes.
The major pro of gdbm: It's already on every linux, no versioning issues, small. | Using sqlite is now straightforward with the new functions readfile(X) and writefile(X,Y) which are available since 2014-06. For example to save a blob in the database from a file and extract it again
```
CREATE TABLE images(name TEXT, type TEXT, img BLOB);
INSERT INTO images(name,type,img) VALUES('icon','jpeg',readfile('icon.jpg'));
SELECT writefile('icon-copy2.jpg',img) FROM images WHERE name='icon';
```
see <https://www.sqlite.org/cli.html> "File I/O Functions" |
2,225,263 | Suppose I have a simple table, like this:
```
Smith | Select
Jones | Select
Johnson | Select
```
And I need to write a Selenium test to select the link corresponding to Jones. I can make it click the "Select" in the 2nd row, but I would rather have it find where "Jones" is and click the corresponding "Select". I'm thinking I may need to incorporate JQuery to accomplish this? | 2010/02/08 | [
"https://Stackoverflow.com/questions/2225263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16012/"
] | Use an xpath expression like "//tc[.//text() = 'Jones']/../tc[2]/a" which looks for a table cell whose text contents are 'Jones' and then naviagates up to that cells parent, selects the second table cell of that parent, and then a link inside the second table cell. | If you wanna use jQuery, here is some information:
* First you can read the jquery from a jquery.js or jquery.min.js file.
* Then using execute\_script(jquery) to enable jquery dynamically.
* Now you can interact with jquery.
here is some code:
```
browser = webdriver.Firefox() # Get local session of firefox
with open('jquery.min.js', 'r') as jquery_js: #read the jquery from a file
jquery = jquery_js.read()
browser.execute_script(jquery) #active the jquery lib
#now you can write some jquery code then execute_script them
js = """
var str = "div#myPager table a:[href=\\"javascript:__doPostBack('myPager','%s')\\"]"
console.log(str)
var $next_anchor = $(str);
if ($next_anchor.length) {
return $next_anchor.get(0).click(); //do click and redirect
} else {
return false;
}""" % str(25)
success = browser.execute_script(js)
if success == False:
break
``` |
117,095 | **Your task:**
Find the most efficient mowing path around the dark green bushes that mows (passes over) all of the grass (light green).
[](https://i.stack.imgur.com/hSmSr.png)
---
For those who cannot view the image above, there are 9 rows of 16, as follows:
```
- dark squares signify grass
- stars signify bushes
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ * * * * ■ ■ * * * ■ * * * * ■
■ * ■ ■ * ■ * ■ ■ ■ ■ * ■ ■ ■ ■
■ * ■ ■ * ■ ■ * ■ ■ ■ * ■ ■ ■ ■
■ * ■ * * ■ ■ ■ ■ ■ ■ ■ ■ * * ■
■ * ■ ■ ■ ■ ■ ■ * ■ ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ ■ ■ ■ * ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ * * * ■ ■ * * * * ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
```
---
**Rules:**
1. The mower can move only horizontally and vertically.
2. "Efficient" means the fewest number of total moves made.
3. You can start from any square you pick.
4. You must stay in bounds and cannot mow over, under, or through any bushes.
"Efficient" can also be thought of as minimizing the number of squares that are mowed more than once.
**Example:**
Here is an example of a 128-move mowing:
* orange squares mowed twice, red square mowed 3 times
* squares mowed more than once remain marked with their original number
[](https://i.stack.imgur.com/El9Gp.png)
---
For those who cannot view images:
```
- *** signifies a bush
- ### signifies the order mowed
- squares mowed more than once remain marked with their original number
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016
128 *** *** *** *** 073 074 *** *** *** 056 *** *** *** *** 017
127 *** 093 094 *** 072 *** 060 059 058 055 *** 037 038 039 018
126 *** 092 095 *** 071 070 *** 062 063 054 *** 036 041 040 019
125 *** 091 *** *** 078 069 068 067 064 033 034 035 *** *** 020
124 *** 090 089 088 079 080 081 *** 065 032 *** 044 045 046 021
123 *** 099 100 087 086 085 082 083 *** 031 *** 049 048 047 022
122 *** 118 101 102 103 *** *** *** 109 030 *** *** *** *** 023
121 120 117 116 115 104 105 106 107 108 029 028 027 026 025 024
```
---
There are 106 squares to be mowed, however, the optimal score is greater than 106.
**If your answer uses less moves than the lowest-move answer so far AND you suspect it could be optimal, then post it!**
**Otherwise, please don't post it**, even if it is significantly different than any other answer posted. The idea behind this request is to prevent answers that do not trend toward the optimal solution. | 2022/07/15 | [
"https://puzzling.stackexchange.com/questions/117095",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/463/"
] | **Proof of optimality for the solutions given**
>
> [](https://i.stack.imgur.com/V4Pam.png)
>
>
>
> There are 7 regions that have an odd number of accesses.
>
>
>
> For each such region you either have an endpoint inside the region
> or you lose a move going thru an already-used access.
> The reason is that you need to mow all accesses but you need to use an even number of accesses if you don't end inside.
>
>
>
> One important thing is that in the larger regions the accesses are squares that connect to only 2 other squares. If you decide to enter the square and turn around, you must retrace your steps to an already-visited square. So you still lose a point.
>
>
>
> Since there are 7 such regions and you have only 2 endpoints, you need
> to double at least 5 squares.
>
>
>
> Examples of such solutions have been given already.
>
>
> | Because of the [no-computers] tag, I waited to post this answer until somebody else already proved optimality.
A graph-based approach to this problem is to first compute all-pairs shortest-path distances in an undirected graph with a node for each grassy square and an edge between nodes that are horizontal or vertical neighbors. Then solve a traveling salesman problem on a complete graph where the shortest-path distances are the edge weights. As in [my answer to a similar problem](https://puzzling.stackexchange.com/questions/97771/what-is-the-minimum-count-of-steps-required-to-complete-this-dominoes-maze/97796#97796), introduce a dummy node adjacent to all other nodes to allow the starting and ending squares to be anywhere.
>
> As expected, the resulting optimal objective value is $110$, which corresponds to $111$ squares mowed:
>
>
>
>
> [](https://i.stack.imgur.com/2fLl4.png)
>
>
> |
117,095 | **Your task:**
Find the most efficient mowing path around the dark green bushes that mows (passes over) all of the grass (light green).
[](https://i.stack.imgur.com/hSmSr.png)
---
For those who cannot view the image above, there are 9 rows of 16, as follows:
```
- dark squares signify grass
- stars signify bushes
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ * * * * ■ ■ * * * ■ * * * * ■
■ * ■ ■ * ■ * ■ ■ ■ ■ * ■ ■ ■ ■
■ * ■ ■ * ■ ■ * ■ ■ ■ * ■ ■ ■ ■
■ * ■ * * ■ ■ ■ ■ ■ ■ ■ ■ * * ■
■ * ■ ■ ■ ■ ■ ■ * ■ ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ ■ ■ ■ * ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ * * * ■ ■ * * * * ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
```
---
**Rules:**
1. The mower can move only horizontally and vertically.
2. "Efficient" means the fewest number of total moves made.
3. You can start from any square you pick.
4. You must stay in bounds and cannot mow over, under, or through any bushes.
"Efficient" can also be thought of as minimizing the number of squares that are mowed more than once.
**Example:**
Here is an example of a 128-move mowing:
* orange squares mowed twice, red square mowed 3 times
* squares mowed more than once remain marked with their original number
[](https://i.stack.imgur.com/El9Gp.png)
---
For those who cannot view images:
```
- *** signifies a bush
- ### signifies the order mowed
- squares mowed more than once remain marked with their original number
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016
128 *** *** *** *** 073 074 *** *** *** 056 *** *** *** *** 017
127 *** 093 094 *** 072 *** 060 059 058 055 *** 037 038 039 018
126 *** 092 095 *** 071 070 *** 062 063 054 *** 036 041 040 019
125 *** 091 *** *** 078 069 068 067 064 033 034 035 *** *** 020
124 *** 090 089 088 079 080 081 *** 065 032 *** 044 045 046 021
123 *** 099 100 087 086 085 082 083 *** 031 *** 049 048 047 022
122 *** 118 101 102 103 *** *** *** 109 030 *** *** *** *** 023
121 120 117 116 115 104 105 106 107 108 029 028 027 026 025 024
```
---
There are 106 squares to be mowed, however, the optimal score is greater than 106.
**If your answer uses less moves than the lowest-move answer so far AND you suspect it could be optimal, then post it!**
**Otherwise, please don't post it**, even if it is significantly different than any other answer posted. The idea behind this request is to prevent answers that do not trend toward the optimal solution. | 2022/07/15 | [
"https://puzzling.stackexchange.com/questions/117095",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/463/"
] | >
> **Optimal : 111 moves**
>
>
>
> [](https://i.stack.imgur.com/cqYPf.png)
>
>
>
> [Visual of path](https://i.stack.imgur.com/WiFNJ.png)
>
>
>
Others of the same length exist, such as [this](https://i.stack.imgur.com/8daZH.png), [this](https://i.stack.imgur.com/fr6Av.png) and [SQLNoob's](https://puzzling.stackexchange.com/a/117100/18250), and several more.
---
Proof of optimality (see [FlorianF's](https://puzzling.stackexchange.com/a/117101/18250) for a more concrete proof:
>
> This problem can be split up in to certain areas, conveniently around the P, S and E, and we can deal with 'entrances' and 'exits'.
>
>
>
> [](https://i.stack.imgur.com/eF2t2.png)
>
>
>
> We must start in the P or the yellow squares would all have to be covered twice. Starting elsewhere may save 1/2, but would cost 3, whereas starting in the P saves 3, and costs 1.
>
>
>
> We must also end on a red square (you can technically end in several places in the E, [such as in the middle](https://i.stack.imgur.com/8daZH.png), but they all have the same result and just navigate the E slightly differently) as ending elsewhere will cause massive costs around the top/bottom of the E.
>
>
>
> The blue squares are always a +2, which is obvious as we are starting in the P.
>
>
>
> Now the pink squares are less obvious, but they best way to cover them is to dip in and out of them for a +3. By cutting through them you enter the edge, and no matter how you re-enter the inside areas, you will create a new isolated area that is more than +3 to cover, as no length along the edge is shorter than +3, they are all minimum 5 squares.
>
>
>
> So optimal paths that start in the P, dip in and out of the pinks for a +3, take the unavoidable +2 on the blues, and finish in the E can have a best score of **111 moves**
>
>
>
TL;DR:
>
> An optimal path must start inside the P and finish around one of the red squares at the end of the E. The blue squares in the S are then always a +2, and a +3 arises from dipping in and out of the pinks meaning that 111 is optimal
>
>
> | Because of the [no-computers] tag, I waited to post this answer until somebody else already proved optimality.
A graph-based approach to this problem is to first compute all-pairs shortest-path distances in an undirected graph with a node for each grassy square and an edge between nodes that are horizontal or vertical neighbors. Then solve a traveling salesman problem on a complete graph where the shortest-path distances are the edge weights. As in [my answer to a similar problem](https://puzzling.stackexchange.com/questions/97771/what-is-the-minimum-count-of-steps-required-to-complete-this-dominoes-maze/97796#97796), introduce a dummy node adjacent to all other nodes to allow the starting and ending squares to be anywhere.
>
> As expected, the resulting optimal objective value is $110$, which corresponds to $111$ squares mowed:
>
>
>
>
> [](https://i.stack.imgur.com/2fLl4.png)
>
>
> |
117,095 | **Your task:**
Find the most efficient mowing path around the dark green bushes that mows (passes over) all of the grass (light green).
[](https://i.stack.imgur.com/hSmSr.png)
---
For those who cannot view the image above, there are 9 rows of 16, as follows:
```
- dark squares signify grass
- stars signify bushes
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ * * * * ■ ■ * * * ■ * * * * ■
■ * ■ ■ * ■ * ■ ■ ■ ■ * ■ ■ ■ ■
■ * ■ ■ * ■ ■ * ■ ■ ■ * ■ ■ ■ ■
■ * ■ * * ■ ■ ■ ■ ■ ■ ■ ■ * * ■
■ * ■ ■ ■ ■ ■ ■ * ■ ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ ■ ■ ■ * ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ * * * ■ ■ * * * * ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
```
---
**Rules:**
1. The mower can move only horizontally and vertically.
2. "Efficient" means the fewest number of total moves made.
3. You can start from any square you pick.
4. You must stay in bounds and cannot mow over, under, or through any bushes.
"Efficient" can also be thought of as minimizing the number of squares that are mowed more than once.
**Example:**
Here is an example of a 128-move mowing:
* orange squares mowed twice, red square mowed 3 times
* squares mowed more than once remain marked with their original number
[](https://i.stack.imgur.com/El9Gp.png)
---
For those who cannot view images:
```
- *** signifies a bush
- ### signifies the order mowed
- squares mowed more than once remain marked with their original number
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016
128 *** *** *** *** 073 074 *** *** *** 056 *** *** *** *** 017
127 *** 093 094 *** 072 *** 060 059 058 055 *** 037 038 039 018
126 *** 092 095 *** 071 070 *** 062 063 054 *** 036 041 040 019
125 *** 091 *** *** 078 069 068 067 064 033 034 035 *** *** 020
124 *** 090 089 088 079 080 081 *** 065 032 *** 044 045 046 021
123 *** 099 100 087 086 085 082 083 *** 031 *** 049 048 047 022
122 *** 118 101 102 103 *** *** *** 109 030 *** *** *** *** 023
121 120 117 116 115 104 105 106 107 108 029 028 027 026 025 024
```
---
There are 106 squares to be mowed, however, the optimal score is greater than 106.
**If your answer uses less moves than the lowest-move answer so far AND you suspect it could be optimal, then post it!**
**Otherwise, please don't post it**, even if it is significantly different than any other answer posted. The idea behind this request is to prevent answers that do not trend toward the optimal solution. | 2022/07/15 | [
"https://puzzling.stackexchange.com/questions/117095",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/463/"
] | **Proof of optimality for the solutions given**
>
> [](https://i.stack.imgur.com/V4Pam.png)
>
>
>
> There are 7 regions that have an odd number of accesses.
>
>
>
> For each such region you either have an endpoint inside the region
> or you lose a move going thru an already-used access.
> The reason is that you need to mow all accesses but you need to use an even number of accesses if you don't end inside.
>
>
>
> One important thing is that in the larger regions the accesses are squares that connect to only 2 other squares. If you decide to enter the square and turn around, you must retrace your steps to an already-visited square. So you still lose a point.
>
>
>
> Since there are 7 such regions and you have only 2 endpoints, you need
> to double at least 5 squares.
>
>
>
> Examples of such solutions have been given already.
>
>
> | Here is a pretty long path that does not visit any square twice, but misses a few spots:
>
> [](https://i.stack.imgur.com/s74My.png)
>
> The path visits 96 squares.
>
>
>
To turn this into a solution, we have to add a few extra moves to mow those missed spots:
>
> The five squares inside of the P will take 8 extra moves to mow.
>
> The other five loose unmowed squares can be done individually using 2 moves each.
>
>
>
That gives a total number of moves of:
>
> 96+8+10=114 moves
>
>
>
I don't know if this is optimal |
117,095 | **Your task:**
Find the most efficient mowing path around the dark green bushes that mows (passes over) all of the grass (light green).
[](https://i.stack.imgur.com/hSmSr.png)
---
For those who cannot view the image above, there are 9 rows of 16, as follows:
```
- dark squares signify grass
- stars signify bushes
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ * * * * ■ ■ * * * ■ * * * * ■
■ * ■ ■ * ■ * ■ ■ ■ ■ * ■ ■ ■ ■
■ * ■ ■ * ■ ■ * ■ ■ ■ * ■ ■ ■ ■
■ * ■ * * ■ ■ ■ ■ ■ ■ ■ ■ * * ■
■ * ■ ■ ■ ■ ■ ■ * ■ ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ ■ ■ ■ * ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ * * * ■ ■ * * * * ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
```
---
**Rules:**
1. The mower can move only horizontally and vertically.
2. "Efficient" means the fewest number of total moves made.
3. You can start from any square you pick.
4. You must stay in bounds and cannot mow over, under, or through any bushes.
"Efficient" can also be thought of as minimizing the number of squares that are mowed more than once.
**Example:**
Here is an example of a 128-move mowing:
* orange squares mowed twice, red square mowed 3 times
* squares mowed more than once remain marked with their original number
[](https://i.stack.imgur.com/El9Gp.png)
---
For those who cannot view images:
```
- *** signifies a bush
- ### signifies the order mowed
- squares mowed more than once remain marked with their original number
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016
128 *** *** *** *** 073 074 *** *** *** 056 *** *** *** *** 017
127 *** 093 094 *** 072 *** 060 059 058 055 *** 037 038 039 018
126 *** 092 095 *** 071 070 *** 062 063 054 *** 036 041 040 019
125 *** 091 *** *** 078 069 068 067 064 033 034 035 *** *** 020
124 *** 090 089 088 079 080 081 *** 065 032 *** 044 045 046 021
123 *** 099 100 087 086 085 082 083 *** 031 *** 049 048 047 022
122 *** 118 101 102 103 *** *** *** 109 030 *** *** *** *** 023
121 120 117 116 115 104 105 106 107 108 029 028 027 026 025 024
```
---
There are 106 squares to be mowed, however, the optimal score is greater than 106.
**If your answer uses less moves than the lowest-move answer so far AND you suspect it could be optimal, then post it!**
**Otherwise, please don't post it**, even if it is significantly different than any other answer posted. The idea behind this request is to prevent answers that do not trend toward the optimal solution. | 2022/07/15 | [
"https://puzzling.stackexchange.com/questions/117095",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/463/"
] | Because of the [no-computers] tag, I waited to post this answer until somebody else already proved optimality.
A graph-based approach to this problem is to first compute all-pairs shortest-path distances in an undirected graph with a node for each grassy square and an edge between nodes that are horizontal or vertical neighbors. Then solve a traveling salesman problem on a complete graph where the shortest-path distances are the edge weights. As in [my answer to a similar problem](https://puzzling.stackexchange.com/questions/97771/what-is-the-minimum-count-of-steps-required-to-complete-this-dominoes-maze/97796#97796), introduce a dummy node adjacent to all other nodes to allow the starting and ending squares to be anywhere.
>
> As expected, the resulting optimal objective value is $110$, which corresponds to $111$ squares mowed:
>
>
>
>
> [](https://i.stack.imgur.com/2fLl4.png)
>
>
> | I was able to get 111 moves (assuming I counted correctly):
>
> [](https://i.stack.imgur.com/owj9A.png)
>
>
> |
117,095 | **Your task:**
Find the most efficient mowing path around the dark green bushes that mows (passes over) all of the grass (light green).
[](https://i.stack.imgur.com/hSmSr.png)
---
For those who cannot view the image above, there are 9 rows of 16, as follows:
```
- dark squares signify grass
- stars signify bushes
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ * * * * ■ ■ * * * ■ * * * * ■
■ * ■ ■ * ■ * ■ ■ ■ ■ * ■ ■ ■ ■
■ * ■ ■ * ■ ■ * ■ ■ ■ * ■ ■ ■ ■
■ * ■ * * ■ ■ ■ ■ ■ ■ ■ ■ * * ■
■ * ■ ■ ■ ■ ■ ■ * ■ ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ ■ ■ ■ * ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ * * * ■ ■ * * * * ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
```
---
**Rules:**
1. The mower can move only horizontally and vertically.
2. "Efficient" means the fewest number of total moves made.
3. You can start from any square you pick.
4. You must stay in bounds and cannot mow over, under, or through any bushes.
"Efficient" can also be thought of as minimizing the number of squares that are mowed more than once.
**Example:**
Here is an example of a 128-move mowing:
* orange squares mowed twice, red square mowed 3 times
* squares mowed more than once remain marked with their original number
[](https://i.stack.imgur.com/El9Gp.png)
---
For those who cannot view images:
```
- *** signifies a bush
- ### signifies the order mowed
- squares mowed more than once remain marked with their original number
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016
128 *** *** *** *** 073 074 *** *** *** 056 *** *** *** *** 017
127 *** 093 094 *** 072 *** 060 059 058 055 *** 037 038 039 018
126 *** 092 095 *** 071 070 *** 062 063 054 *** 036 041 040 019
125 *** 091 *** *** 078 069 068 067 064 033 034 035 *** *** 020
124 *** 090 089 088 079 080 081 *** 065 032 *** 044 045 046 021
123 *** 099 100 087 086 085 082 083 *** 031 *** 049 048 047 022
122 *** 118 101 102 103 *** *** *** 109 030 *** *** *** *** 023
121 120 117 116 115 104 105 106 107 108 029 028 027 026 025 024
```
---
There are 106 squares to be mowed, however, the optimal score is greater than 106.
**If your answer uses less moves than the lowest-move answer so far AND you suspect it could be optimal, then post it!**
**Otherwise, please don't post it**, even if it is significantly different than any other answer posted. The idea behind this request is to prevent answers that do not trend toward the optimal solution. | 2022/07/15 | [
"https://puzzling.stackexchange.com/questions/117095",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/463/"
] | Here's a path that uses just 111 mows:
>
> 
>
>
>
Proof of optimal starting and ending points and lower bound:
>
> First note that there are two obvious "dead ends":
> 
> If you don't start (or end) your path in those squares, they will cost you one extra move to get in and out of them. There are two other slightly less obvious dead ends nearby:
> 
> Here we see the blue square is adjacent to three areas that need to be mowed, and whichever direction we choose to move through the blue square (thus mowing two of the three adjacent squares), the third will become another dead end. Similarly:
> 
> Here we find another spot where no matter which way we choose to move through, we create a dead end.
> So we have four dead ends. We can only start and end our path in two of them, so the other two are going to cost us one square each. Additionally, if we DO start and end in two of them, then it's going to cost us three squares to get in and out of the P:
> 
> Therefore if we don't start inside the P, we will incur a cost of (at least) 5 additional squares, so 111 is the minimum. In order to improve on this solution, then, we need to start in the P. Now consider the entire right had side of the grid comprising the E. There are three distinct entrance/exit points that are one square wide, meaning we must either end our path within the E (which incurs the cost of all 4 of the aforementioned "dead ends") or we have to traverse one of these entrance/exit points twice, which would incur an even greater cost. Therefore we must end our path "inside" the E, and therefore the theoretical lower bound on a solution is 110. It just remains to be shown that there is 1 more additional point elsewhere in the grid that incurs a mandatory 1-square cost to prove that 111 is optimal.
>
>
>
>
>
>
>
>
>
>
> | I got 112 squares (assuming I counted correctly), visiting every one:
>
> [](https://i.stack.imgur.com/NAIHi.png)
>
>
>
However, this is not optimal. |
117,095 | **Your task:**
Find the most efficient mowing path around the dark green bushes that mows (passes over) all of the grass (light green).
[](https://i.stack.imgur.com/hSmSr.png)
---
For those who cannot view the image above, there are 9 rows of 16, as follows:
```
- dark squares signify grass
- stars signify bushes
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ * * * * ■ ■ * * * ■ * * * * ■
■ * ■ ■ * ■ * ■ ■ ■ ■ * ■ ■ ■ ■
■ * ■ ■ * ■ ■ * ■ ■ ■ * ■ ■ ■ ■
■ * ■ * * ■ ■ ■ ■ ■ ■ ■ ■ * * ■
■ * ■ ■ ■ ■ ■ ■ * ■ ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ ■ ■ ■ * ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ * * * ■ ■ * * * * ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
```
---
**Rules:**
1. The mower can move only horizontally and vertically.
2. "Efficient" means the fewest number of total moves made.
3. You can start from any square you pick.
4. You must stay in bounds and cannot mow over, under, or through any bushes.
"Efficient" can also be thought of as minimizing the number of squares that are mowed more than once.
**Example:**
Here is an example of a 128-move mowing:
* orange squares mowed twice, red square mowed 3 times
* squares mowed more than once remain marked with their original number
[](https://i.stack.imgur.com/El9Gp.png)
---
For those who cannot view images:
```
- *** signifies a bush
- ### signifies the order mowed
- squares mowed more than once remain marked with their original number
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016
128 *** *** *** *** 073 074 *** *** *** 056 *** *** *** *** 017
127 *** 093 094 *** 072 *** 060 059 058 055 *** 037 038 039 018
126 *** 092 095 *** 071 070 *** 062 063 054 *** 036 041 040 019
125 *** 091 *** *** 078 069 068 067 064 033 034 035 *** *** 020
124 *** 090 089 088 079 080 081 *** 065 032 *** 044 045 046 021
123 *** 099 100 087 086 085 082 083 *** 031 *** 049 048 047 022
122 *** 118 101 102 103 *** *** *** 109 030 *** *** *** *** 023
121 120 117 116 115 104 105 106 107 108 029 028 027 026 025 024
```
---
There are 106 squares to be mowed, however, the optimal score is greater than 106.
**If your answer uses less moves than the lowest-move answer so far AND you suspect it could be optimal, then post it!**
**Otherwise, please don't post it**, even if it is significantly different than any other answer posted. The idea behind this request is to prevent answers that do not trend toward the optimal solution. | 2022/07/15 | [
"https://puzzling.stackexchange.com/questions/117095",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/463/"
] | Here's a path that uses just 111 mows:
>
> 
>
>
>
Proof of optimal starting and ending points and lower bound:
>
> First note that there are two obvious "dead ends":
> 
> If you don't start (or end) your path in those squares, they will cost you one extra move to get in and out of them. There are two other slightly less obvious dead ends nearby:
> 
> Here we see the blue square is adjacent to three areas that need to be mowed, and whichever direction we choose to move through the blue square (thus mowing two of the three adjacent squares), the third will become another dead end. Similarly:
> 
> Here we find another spot where no matter which way we choose to move through, we create a dead end.
> So we have four dead ends. We can only start and end our path in two of them, so the other two are going to cost us one square each. Additionally, if we DO start and end in two of them, then it's going to cost us three squares to get in and out of the P:
> 
> Therefore if we don't start inside the P, we will incur a cost of (at least) 5 additional squares, so 111 is the minimum. In order to improve on this solution, then, we need to start in the P. Now consider the entire right had side of the grid comprising the E. There are three distinct entrance/exit points that are one square wide, meaning we must either end our path within the E (which incurs the cost of all 4 of the aforementioned "dead ends") or we have to traverse one of these entrance/exit points twice, which would incur an even greater cost. Therefore we must end our path "inside" the E, and therefore the theoretical lower bound on a solution is 110. It just remains to be shown that there is 1 more additional point elsewhere in the grid that incurs a mandatory 1-square cost to prove that 111 is optimal.
>
>
>
>
>
>
>
>
>
>
> | Here is a pretty long path that does not visit any square twice, but misses a few spots:
>
> [](https://i.stack.imgur.com/s74My.png)
>
> The path visits 96 squares.
>
>
>
To turn this into a solution, we have to add a few extra moves to mow those missed spots:
>
> The five squares inside of the P will take 8 extra moves to mow.
>
> The other five loose unmowed squares can be done individually using 2 moves each.
>
>
>
That gives a total number of moves of:
>
> 96+8+10=114 moves
>
>
>
I don't know if this is optimal |
117,095 | **Your task:**
Find the most efficient mowing path around the dark green bushes that mows (passes over) all of the grass (light green).
[](https://i.stack.imgur.com/hSmSr.png)
---
For those who cannot view the image above, there are 9 rows of 16, as follows:
```
- dark squares signify grass
- stars signify bushes
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ * * * * ■ ■ * * * ■ * * * * ■
■ * ■ ■ * ■ * ■ ■ ■ ■ * ■ ■ ■ ■
■ * ■ ■ * ■ ■ * ■ ■ ■ * ■ ■ ■ ■
■ * ■ * * ■ ■ ■ ■ ■ ■ ■ ■ * * ■
■ * ■ ■ ■ ■ ■ ■ * ■ ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ ■ ■ ■ * ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ * * * ■ ■ * * * * ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
```
---
**Rules:**
1. The mower can move only horizontally and vertically.
2. "Efficient" means the fewest number of total moves made.
3. You can start from any square you pick.
4. You must stay in bounds and cannot mow over, under, or through any bushes.
"Efficient" can also be thought of as minimizing the number of squares that are mowed more than once.
**Example:**
Here is an example of a 128-move mowing:
* orange squares mowed twice, red square mowed 3 times
* squares mowed more than once remain marked with their original number
[](https://i.stack.imgur.com/El9Gp.png)
---
For those who cannot view images:
```
- *** signifies a bush
- ### signifies the order mowed
- squares mowed more than once remain marked with their original number
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016
128 *** *** *** *** 073 074 *** *** *** 056 *** *** *** *** 017
127 *** 093 094 *** 072 *** 060 059 058 055 *** 037 038 039 018
126 *** 092 095 *** 071 070 *** 062 063 054 *** 036 041 040 019
125 *** 091 *** *** 078 069 068 067 064 033 034 035 *** *** 020
124 *** 090 089 088 079 080 081 *** 065 032 *** 044 045 046 021
123 *** 099 100 087 086 085 082 083 *** 031 *** 049 048 047 022
122 *** 118 101 102 103 *** *** *** 109 030 *** *** *** *** 023
121 120 117 116 115 104 105 106 107 108 029 028 027 026 025 024
```
---
There are 106 squares to be mowed, however, the optimal score is greater than 106.
**If your answer uses less moves than the lowest-move answer so far AND you suspect it could be optimal, then post it!**
**Otherwise, please don't post it**, even if it is significantly different than any other answer posted. The idea behind this request is to prevent answers that do not trend toward the optimal solution. | 2022/07/15 | [
"https://puzzling.stackexchange.com/questions/117095",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/463/"
] | >
> **Optimal : 111 moves**
>
>
>
> [](https://i.stack.imgur.com/cqYPf.png)
>
>
>
> [Visual of path](https://i.stack.imgur.com/WiFNJ.png)
>
>
>
Others of the same length exist, such as [this](https://i.stack.imgur.com/8daZH.png), [this](https://i.stack.imgur.com/fr6Av.png) and [SQLNoob's](https://puzzling.stackexchange.com/a/117100/18250), and several more.
---
Proof of optimality (see [FlorianF's](https://puzzling.stackexchange.com/a/117101/18250) for a more concrete proof:
>
> This problem can be split up in to certain areas, conveniently around the P, S and E, and we can deal with 'entrances' and 'exits'.
>
>
>
> [](https://i.stack.imgur.com/eF2t2.png)
>
>
>
> We must start in the P or the yellow squares would all have to be covered twice. Starting elsewhere may save 1/2, but would cost 3, whereas starting in the P saves 3, and costs 1.
>
>
>
> We must also end on a red square (you can technically end in several places in the E, [such as in the middle](https://i.stack.imgur.com/8daZH.png), but they all have the same result and just navigate the E slightly differently) as ending elsewhere will cause massive costs around the top/bottom of the E.
>
>
>
> The blue squares are always a +2, which is obvious as we are starting in the P.
>
>
>
> Now the pink squares are less obvious, but they best way to cover them is to dip in and out of them for a +3. By cutting through them you enter the edge, and no matter how you re-enter the inside areas, you will create a new isolated area that is more than +3 to cover, as no length along the edge is shorter than +3, they are all minimum 5 squares.
>
>
>
> So optimal paths that start in the P, dip in and out of the pinks for a +3, take the unavoidable +2 on the blues, and finish in the E can have a best score of **111 moves**
>
>
>
TL;DR:
>
> An optimal path must start inside the P and finish around one of the red squares at the end of the E. The blue squares in the S are then always a +2, and a +3 arises from dipping in and out of the pinks meaning that 111 is optimal
>
>
> | I got 112 squares (assuming I counted correctly), visiting every one:
>
> [](https://i.stack.imgur.com/NAIHi.png)
>
>
>
However, this is not optimal. |
117,095 | **Your task:**
Find the most efficient mowing path around the dark green bushes that mows (passes over) all of the grass (light green).
[](https://i.stack.imgur.com/hSmSr.png)
---
For those who cannot view the image above, there are 9 rows of 16, as follows:
```
- dark squares signify grass
- stars signify bushes
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ * * * * ■ ■ * * * ■ * * * * ■
■ * ■ ■ * ■ * ■ ■ ■ ■ * ■ ■ ■ ■
■ * ■ ■ * ■ ■ * ■ ■ ■ * ■ ■ ■ ■
■ * ■ * * ■ ■ ■ ■ ■ ■ ■ ■ * * ■
■ * ■ ■ ■ ■ ■ ■ * ■ ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ ■ ■ ■ * ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ * * * ■ ■ * * * * ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
```
---
**Rules:**
1. The mower can move only horizontally and vertically.
2. "Efficient" means the fewest number of total moves made.
3. You can start from any square you pick.
4. You must stay in bounds and cannot mow over, under, or through any bushes.
"Efficient" can also be thought of as minimizing the number of squares that are mowed more than once.
**Example:**
Here is an example of a 128-move mowing:
* orange squares mowed twice, red square mowed 3 times
* squares mowed more than once remain marked with their original number
[](https://i.stack.imgur.com/El9Gp.png)
---
For those who cannot view images:
```
- *** signifies a bush
- ### signifies the order mowed
- squares mowed more than once remain marked with their original number
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016
128 *** *** *** *** 073 074 *** *** *** 056 *** *** *** *** 017
127 *** 093 094 *** 072 *** 060 059 058 055 *** 037 038 039 018
126 *** 092 095 *** 071 070 *** 062 063 054 *** 036 041 040 019
125 *** 091 *** *** 078 069 068 067 064 033 034 035 *** *** 020
124 *** 090 089 088 079 080 081 *** 065 032 *** 044 045 046 021
123 *** 099 100 087 086 085 082 083 *** 031 *** 049 048 047 022
122 *** 118 101 102 103 *** *** *** 109 030 *** *** *** *** 023
121 120 117 116 115 104 105 106 107 108 029 028 027 026 025 024
```
---
There are 106 squares to be mowed, however, the optimal score is greater than 106.
**If your answer uses less moves than the lowest-move answer so far AND you suspect it could be optimal, then post it!**
**Otherwise, please don't post it**, even if it is significantly different than any other answer posted. The idea behind this request is to prevent answers that do not trend toward the optimal solution. | 2022/07/15 | [
"https://puzzling.stackexchange.com/questions/117095",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/463/"
] | Here is a pretty long path that does not visit any square twice, but misses a few spots:
>
> [](https://i.stack.imgur.com/s74My.png)
>
> The path visits 96 squares.
>
>
>
To turn this into a solution, we have to add a few extra moves to mow those missed spots:
>
> The five squares inside of the P will take 8 extra moves to mow.
>
> The other five loose unmowed squares can be done individually using 2 moves each.
>
>
>
That gives a total number of moves of:
>
> 96+8+10=114 moves
>
>
>
I don't know if this is optimal | I was able to get 111 moves (assuming I counted correctly):
>
> [](https://i.stack.imgur.com/owj9A.png)
>
>
> |
117,095 | **Your task:**
Find the most efficient mowing path around the dark green bushes that mows (passes over) all of the grass (light green).
[](https://i.stack.imgur.com/hSmSr.png)
---
For those who cannot view the image above, there are 9 rows of 16, as follows:
```
- dark squares signify grass
- stars signify bushes
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ * * * * ■ ■ * * * ■ * * * * ■
■ * ■ ■ * ■ * ■ ■ ■ ■ * ■ ■ ■ ■
■ * ■ ■ * ■ ■ * ■ ■ ■ * ■ ■ ■ ■
■ * ■ * * ■ ■ ■ ■ ■ ■ ■ ■ * * ■
■ * ■ ■ ■ ■ ■ ■ * ■ ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ ■ ■ ■ * ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ * * * ■ ■ * * * * ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
```
---
**Rules:**
1. The mower can move only horizontally and vertically.
2. "Efficient" means the fewest number of total moves made.
3. You can start from any square you pick.
4. You must stay in bounds and cannot mow over, under, or through any bushes.
"Efficient" can also be thought of as minimizing the number of squares that are mowed more than once.
**Example:**
Here is an example of a 128-move mowing:
* orange squares mowed twice, red square mowed 3 times
* squares mowed more than once remain marked with their original number
[](https://i.stack.imgur.com/El9Gp.png)
---
For those who cannot view images:
```
- *** signifies a bush
- ### signifies the order mowed
- squares mowed more than once remain marked with their original number
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016
128 *** *** *** *** 073 074 *** *** *** 056 *** *** *** *** 017
127 *** 093 094 *** 072 *** 060 059 058 055 *** 037 038 039 018
126 *** 092 095 *** 071 070 *** 062 063 054 *** 036 041 040 019
125 *** 091 *** *** 078 069 068 067 064 033 034 035 *** *** 020
124 *** 090 089 088 079 080 081 *** 065 032 *** 044 045 046 021
123 *** 099 100 087 086 085 082 083 *** 031 *** 049 048 047 022
122 *** 118 101 102 103 *** *** *** 109 030 *** *** *** *** 023
121 120 117 116 115 104 105 106 107 108 029 028 027 026 025 024
```
---
There are 106 squares to be mowed, however, the optimal score is greater than 106.
**If your answer uses less moves than the lowest-move answer so far AND you suspect it could be optimal, then post it!**
**Otherwise, please don't post it**, even if it is significantly different than any other answer posted. The idea behind this request is to prevent answers that do not trend toward the optimal solution. | 2022/07/15 | [
"https://puzzling.stackexchange.com/questions/117095",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/463/"
] | Here's a path that uses just 111 mows:
>
> 
>
>
>
Proof of optimal starting and ending points and lower bound:
>
> First note that there are two obvious "dead ends":
> 
> If you don't start (or end) your path in those squares, they will cost you one extra move to get in and out of them. There are two other slightly less obvious dead ends nearby:
> 
> Here we see the blue square is adjacent to three areas that need to be mowed, and whichever direction we choose to move through the blue square (thus mowing two of the three adjacent squares), the third will become another dead end. Similarly:
> 
> Here we find another spot where no matter which way we choose to move through, we create a dead end.
> So we have four dead ends. We can only start and end our path in two of them, so the other two are going to cost us one square each. Additionally, if we DO start and end in two of them, then it's going to cost us three squares to get in and out of the P:
> 
> Therefore if we don't start inside the P, we will incur a cost of (at least) 5 additional squares, so 111 is the minimum. In order to improve on this solution, then, we need to start in the P. Now consider the entire right had side of the grid comprising the E. There are three distinct entrance/exit points that are one square wide, meaning we must either end our path within the E (which incurs the cost of all 4 of the aforementioned "dead ends") or we have to traverse one of these entrance/exit points twice, which would incur an even greater cost. Therefore we must end our path "inside" the E, and therefore the theoretical lower bound on a solution is 110. It just remains to be shown that there is 1 more additional point elsewhere in the grid that incurs a mandatory 1-square cost to prove that 111 is optimal.
>
>
>
>
>
>
>
>
>
>
> | I was able to get 111 moves (assuming I counted correctly):
>
> [](https://i.stack.imgur.com/owj9A.png)
>
>
> |
117,095 | **Your task:**
Find the most efficient mowing path around the dark green bushes that mows (passes over) all of the grass (light green).
[](https://i.stack.imgur.com/hSmSr.png)
---
For those who cannot view the image above, there are 9 rows of 16, as follows:
```
- dark squares signify grass
- stars signify bushes
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ * * * * ■ ■ * * * ■ * * * * ■
■ * ■ ■ * ■ * ■ ■ ■ ■ * ■ ■ ■ ■
■ * ■ ■ * ■ ■ * ■ ■ ■ * ■ ■ ■ ■
■ * ■ * * ■ ■ ■ ■ ■ ■ ■ ■ * * ■
■ * ■ ■ ■ ■ ■ ■ * ■ ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ ■ ■ ■ * ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ * * * ■ ■ * * * * ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
```
---
**Rules:**
1. The mower can move only horizontally and vertically.
2. "Efficient" means the fewest number of total moves made.
3. You can start from any square you pick.
4. You must stay in bounds and cannot mow over, under, or through any bushes.
"Efficient" can also be thought of as minimizing the number of squares that are mowed more than once.
**Example:**
Here is an example of a 128-move mowing:
* orange squares mowed twice, red square mowed 3 times
* squares mowed more than once remain marked with their original number
[](https://i.stack.imgur.com/El9Gp.png)
---
For those who cannot view images:
```
- *** signifies a bush
- ### signifies the order mowed
- squares mowed more than once remain marked with their original number
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016
128 *** *** *** *** 073 074 *** *** *** 056 *** *** *** *** 017
127 *** 093 094 *** 072 *** 060 059 058 055 *** 037 038 039 018
126 *** 092 095 *** 071 070 *** 062 063 054 *** 036 041 040 019
125 *** 091 *** *** 078 069 068 067 064 033 034 035 *** *** 020
124 *** 090 089 088 079 080 081 *** 065 032 *** 044 045 046 021
123 *** 099 100 087 086 085 082 083 *** 031 *** 049 048 047 022
122 *** 118 101 102 103 *** *** *** 109 030 *** *** *** *** 023
121 120 117 116 115 104 105 106 107 108 029 028 027 026 025 024
```
---
There are 106 squares to be mowed, however, the optimal score is greater than 106.
**If your answer uses less moves than the lowest-move answer so far AND you suspect it could be optimal, then post it!**
**Otherwise, please don't post it**, even if it is significantly different than any other answer posted. The idea behind this request is to prevent answers that do not trend toward the optimal solution. | 2022/07/15 | [
"https://puzzling.stackexchange.com/questions/117095",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/463/"
] | I got 112 squares (assuming I counted correctly), visiting every one:
>
> [](https://i.stack.imgur.com/NAIHi.png)
>
>
>
However, this is not optimal. | I was able to get 111 moves (assuming I counted correctly):
>
> [](https://i.stack.imgur.com/owj9A.png)
>
>
> |
135,851 | Related to [Poker Hand Evaluator](https://codereview.stackexchange.com/questions/135649/poker-hand-evaluator). This it **not** the same. This is take best from all combinations of 7. The other is all combinations of 5.
Poker is 52 cards - 4 suits and 13 ranks:
* Texas holdem
* Hand is exactly 5 cards
* Order of hands
+ Straight-flush
all same suite and in order
ace high is royal straight flush
+ Quad four of same rank
+ Boat three of one rank and two of another rank
+ Flush all the same suit
+ Straight e.g. 56789
ace 0 counts as both low and high 01234 and 9,10,11,12,0
+ Two pair
+ One pair
+ High card
There are 23,294,460 distinct 7 card combinations in a deck of 52. I am not interested in a random sampling (Monte Carlo). Will add the as on option later but need the option to run all and have the correct answer from wiki.
This program makes the best 5 cards hand from every combination of 7 and tallies. That is how a poker game works. You have 2 hole cards and then 5 cards on the board. You make the best 5 cards card had from you hole cards plus the board.
Combination of 7 is harder in there are a lot more combination. Cannot assume if you have a straight and a flush you have a straight-flush as they may not be the same 5 cards. This separates a royal straight flush from a straight flush but they can be combined into just straight flush if that is faster.
Not interested in parallel processing. Have a pattern for doing that. For this question just optimize the raw code.
This code gives the correct answers to [poker hand probability](https://en.wikipedia.org/wiki/Poker_probability). It runs in about 200 seconds.
How to optimize this code to run faster? Or make it cleaner and not run any slower.
```
public void Deal7c()
{
Stopwatch sw = new Stopwatch();
sw.Start();
int counter = 0;
int counterFlush = 0;
int counterStraight = 0;
int counterStraightFlush = 0;
int counterStraightAndFlush = 0;
int counterRoyalFlush = 0;
int counterQuad = 0;
int counterBoat = 0;
int counterTrips = 0;
int counterPairTwo = 0;
int counterPairOne = 0;
int counterHigh = 0;
Card[] CardArray = new Card[7]; // hand plus board
bool haveStraight;
bool haveQuad;
bool haveBoat;
bool haveFlush;
int flushSuite;
bool haveStraightFlush;
bool haveRoyalFlush;
int flushCount;
int straightCount;
int straightCount2;
bool haveAce;
int? lastRank;
int firstCard;
//byte* rankArray = stackalloc byte[13];
//byte* rankCount = stackalloc byte[5];
int[] rankArray = new int[13];
int[] rankCount = new int[5];
Debug.WriteLine("");
for (int i = 51; i >= 6; i--)
{
Debug.WriteLine("Deal7a i = " + i + " milliseconds " + sw.ElapsedMilliseconds.ToString("N0"));
CardArray[0] = new Card(i % 13, i / 13);
for (int j = i - 1; j >= 5; j--)
{
CardArray[1] = new Card(j % 13, j / 13);
for (int k = j - 1; k >= 4; k--)
{
CardArray[2] = new Card(k % 13, k / 13);
for (int l = k - 1; l >= 3; l--)
{
CardArray[3] = new Card(l % 13, l / 13);
for (int m = l - 1; m >= 2; m--)
{
CardArray[4] = new Card(m % 13, m / 13);
for (int n = m - 1; n >= 1; n--)
{
CardArray[5] = new Card(n % 13, n / 13);
for (int p = n - 1; p >= 0; p--)
{
CardArray[6] = new Card(p % 13, p / 13);
counter++;
//if (rand.Next(4) != 0)
// continue;
haveStraight = false;
haveFlush = false;
haveStraightFlush = false;
haveRoyalFlush = false;
haveBoat = false;
haveQuad = false;
for (int q = 0; q <= 12; q++)
rankArray[q] = 0;
for (int c = 0; c < 7; c++)
rankArray[CardArray[c].Rank]++;
// this will build up the rank count
rankCount[0] = 0; // none - not used but it needs to be here to make this work
rankCount[1] = 0; // single - not used but it needs to be here to make this work
rankCount[2] = 0; // pair
rankCount[3] = 0; // trips
rankCount[4] = 0; // quad
for (int c = 0; c <= 12; c++)
rankCount[rankArray[c]]++;
if (rankCount[4] == 1)
haveQuad = true;
else if (rankCount[3] == 2) // with 7 could have two trips
haveBoat = true;
else if (rankCount[3] == 1 && rankCount[2] > 0)
haveBoat = true;
if (!haveQuad && !haveBoat && rankCount[2] != 3) // cannot make a straight or flush with a quad or boat
{
// flush
flushSuite = -1;
for (int f = 0; f <= 3; f++)
{ // can only have one flush in 7 cards
flushCount = 0;
for (int c = 0; c < 7; c++)
{
if (CardArray[c].Suit == f)
flushCount++;
}
if (flushCount >= 5)
{
haveFlush = true;
flushSuite = f;
break;
}
}
//straight
//first ace high
haveStraight = rankArray[0] > 0 &&
rankArray[12] > 0 &&
rankArray[11] > 0 &&
rankArray[10] > 0 &&
rankArray[9] > 0;
if (!haveStraight)
{
for (int s = 12; s >= 4; s--)
{
haveStraight = rankArray[s] > 0 &&
rankArray[s - 1] > 0 &&
rankArray[s - 2] > 0 &&
rankArray[s - 3] > 0 &&
rankArray[s - 4] > 0;
if (haveStraight)
break;
}
}
if (haveStraight && haveFlush)
{ // now for the difficult task of straightFlush
// this is kind of expensive but at least it does hot happen a lot
// note in 7 you could have gap and still have a straight xyxxxxx
counterStraightAndFlush++;
straightCount = 0;
haveAce = false;
for (int c = 0; c < 7; c++)
{
if (CardArray[c].Suit == flushSuite)
{
straightCount++;
if (CardArray[c].Rank == 0)
haveAce = true;
}
}
if (straightCount >= 5)
{
straightCount2 = 0;
lastRank = null;
firstCard = 0;
foreach (Card c in CardArray.Where(x => x.Suit == flushSuite).OrderByDescending(x => x.Rank))
{
//Debug.WriteLine(c.Rank + " " + c.Suit);
if (lastRank == null)
{
firstCard = c.Rank;
}
else
{
if (c.Rank == lastRank - 1)
{
straightCount2++;
if (haveAce && straightCount2 == 3 && firstCard == 12)
{
haveRoyalFlush = true;
haveFlush = false;
haveStraight = false;
break;
}
else if (straightCount2 == 4) //the first card is not in the straightCount
{
haveStraightFlush = true;
haveFlush = false;
haveStraight = false;
break;
}
}
else
{
if (straightCount < 6)
break;
straightCount2 = 0; // this is the
firstCard = c.Rank;
}
}
lastRank = c.Rank;
}
}
}
}
// hands in order
if (haveRoyalFlush)
counterRoyalFlush++;
else if (haveStraightFlush)
counterStraightFlush++;
else if (haveQuad)
counterQuad++;
else if (haveBoat) // with 7 could have two trips
counterBoat++;
else if (haveFlush)
counterFlush++;
else if (haveStraight)
counterStraight++;
else if (rankCount[3] == 1)
counterTrips++;
else if (rankCount[2] >= 2) // with 7 could have 3 trips
counterPairTwo++;
else if (rankCount[2] == 1)
counterPairOne++;
else
counterHigh++;
}
}
}
}
}
}
}
sw.Stop();
Debug.WriteLine("");
Debug.WriteLine("Deal7a");
Debug.WriteLine("stopwatch millisec " + sw.ElapsedMilliseconds.ToString("N0"));;
Debug.WriteLine("hand count " + counter.ToString("N0"));
int sum = counterHigh + counterPairOne + counterPairTwo + counterTrips + counterStraight
+ counterFlush + counterBoat + counterQuad + counterStraightFlush + counterRoyalFlush;
Debug.WriteLine("royalFlush counter " + counterRoyalFlush.ToString("N0") + " " + (100m * counterRoyalFlush / sum).ToString("N4"));
Debug.WriteLine("straightFlush counter " + counterStraightFlush.ToString("N0") + " " + (100m * counterStraightFlush / sum).ToString("N4"));
Debug.WriteLine("quad count " + counterQuad.ToString("N0") + " " + (100m * counterQuad / sum).ToString("N4"));
Debug.WriteLine("boat count " + counterBoat.ToString("N0") + " " + (100m * counterBoat / sum).ToString("N3"));
Debug.WriteLine("flush counter " + counterFlush.ToString("N0") + " " + (100m * counterFlush / sum).ToString("N3"));
Debug.WriteLine("straight counter " + counterStraight.ToString("N0") + " " + (100m * counterStraight / sum).ToString("N3"));
Debug.WriteLine("trips count " + counterTrips.ToString("N0") + " " + (100m * counterTrips / sum).ToString("N3"));
Debug.WriteLine("two pair count " + counterPairTwo.ToString("N0") + " " + (100m * counterPairTwo / sum).ToString("N2"));
Debug.WriteLine("one pair counter " + counterPairOne.ToString("N0") + " " + (100m * counterPairOne / sum).ToString("N2"));
Debug.WriteLine("high card counter " + counterHigh.ToString("N0") + " " + (100m * counterHigh / sum).ToString("N2"));
Debug.WriteLine("sum " + sum.ToString("N0"));
Debug.WriteLine("");
}
struct Card
{
public Card(int Rank, int Suit)
{
rank = Rank;
suit = Suit;
}
Int32 rank;
Int32 suit;
public int Rank { get { return rank; } }
public int Suit { get { return suit; } }
}
``` | 2016/07/25 | [
"https://codereview.stackexchange.com/questions/135851",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/105946/"
] | When checking for a flush, instead of looping through the cards 4 times, you could have an array of length 4 where each position represents a suit. Then loop over the 7 cards one time and use a switch statement to increment the element that corresponds to the suit. Then loop over the array and check if any of the elements is 5 or more.
If you want to get really down in the bit twiddling, consider changing your && conditionals to & non-short circuiting conditions where it makes sense. Your haveStraight section where you are doing 4 conditional ANDs on simple conditions seems like a strong candidate, for example. The reason is that the compiler will likely be able optimize the code much better if you get rid of the conditional branching. Usually this won't make a big enough difference to matter but since you are doing this many millions of times, it could be substantial.
Another bit-twiddling approach that might be faster is to take the rank array and write the results into a short where each bit represents whether the corresponding element was greater than 0 (set the 13th and 0th bit for the aces.) Then you can bitwise AND the value with 31 (binary 11111) and see if it equals 31. Right shift 1 and compare again. Do this 9 times or until you find a match.
Lastly, you could take advantage of the fact that in your inner most loop, only one card is changing. You would have to restructure your code substantially but you could avoid all the recalculations of the other 6 cards each time by adjusting for that one card. You can keep doing this recursively up the tree for the loops but the return on that will be progressive less for each level you move up.
Here's an example of using a single pass loop to evaluate the straight:
```
int contig = rankArray[0] > 0 ? 1 : 0;
for (int r = 12; r >= 0; r--) {
contig = rankArray[r] > 0 ? contig + 1 : 0;
if (contig > 4) {
haveStraight = true;
break;
} else if (contig + r < 4) {
/* not sure this if this helps or hurts */
break;
}
}
```
Does that align with what you did? | I believe you can use formulas to calculate your answer, which will be much faster than brute force. However, it is a good idea to code a brute force solution first, as you have, so that you can test against it. The biggest improvement you can make readability-wise is on how you generate all of the card combinations. Right now there is so much nesting that most of your logic starts in the middle of the screen. There are some nice solutions out there for generating "n choose k" type collections. [Here](https://stackoverflow.com/a/1898744/480799) is one in C#:
```
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
{
return k == 0 ? new[] { new T[0] } :
elements.SelectMany((e, i) =>
elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] {e}).Concat(c)));
}
```
It is elegant, but I'm not sure how fast it is. You can use it like this:
```
foreach(var combination in Enumerable.Range(0, 52).Combinations(7))
{
Card[] hand = combination.Select(x => new Card(x % 13, x / 13)).ToArray();
// ...
``` |
55,678,914 | Let's say I have a number from user, for exemple: 456789.
I know how to print in reverse the number, but I am not sure how I can stop the execution to print only 3 first reversed digits.
What I mean is that I want to print only 987 from the given number
I have to stop somehow with break; but I am not sure how.
```
public static void main(String[] args) {
int number= 0;
int numberInReverse = 0;
System.out.println("Input a number");
Scanner sc=new Scanner(System.in);
numar=sc.nextInt();
while (number !=0){
numberInReverse*=10;
numberInReverse=numar%10;
number/=10;
System.out.print(numberInReverse);
}
}
``` | 2019/04/14 | [
"https://Stackoverflow.com/questions/55678914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11301177/"
] | You could follow this algo:
1. modulo the number by 1000
2. reverse it
3. print | You can just convert to into a StringBuilder and use `reverse()` and `substring()`:
```
String result = new StringBuilder()
.append(numar)
.reverse()
.substring(0, 3);
System.out.print(result);
``` |
55,678,914 | Let's say I have a number from user, for exemple: 456789.
I know how to print in reverse the number, but I am not sure how I can stop the execution to print only 3 first reversed digits.
What I mean is that I want to print only 987 from the given number
I have to stop somehow with break; but I am not sure how.
```
public static void main(String[] args) {
int number= 0;
int numberInReverse = 0;
System.out.println("Input a number");
Scanner sc=new Scanner(System.in);
numar=sc.nextInt();
while (number !=0){
numberInReverse*=10;
numberInReverse=numar%10;
number/=10;
System.out.print(numberInReverse);
}
}
``` | 2019/04/14 | [
"https://Stackoverflow.com/questions/55678914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11301177/"
] | You could follow this algo:
1. modulo the number by 1000
2. reverse it
3. print | ```
System.out.println("Input a number");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int reversed = 0, counter = 0;
while (counter++ < 3) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println("Reversed Number: " + reversed);
``` |
55,678,914 | Let's say I have a number from user, for exemple: 456789.
I know how to print in reverse the number, but I am not sure how I can stop the execution to print only 3 first reversed digits.
What I mean is that I want to print only 987 from the given number
I have to stop somehow with break; but I am not sure how.
```
public static void main(String[] args) {
int number= 0;
int numberInReverse = 0;
System.out.println("Input a number");
Scanner sc=new Scanner(System.in);
numar=sc.nextInt();
while (number !=0){
numberInReverse*=10;
numberInReverse=numar%10;
number/=10;
System.out.print(numberInReverse);
}
}
``` | 2019/04/14 | [
"https://Stackoverflow.com/questions/55678914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11301177/"
] | You could follow this algo:
1. modulo the number by 1000
2. reverse it
3. print | For the example of num = 456789
We have:
a) A quotient of 45678 when we do an Integer division, i.e. 456789 / 10
b) A remainder of 9 when we use the Modulus operator, i.e. 456789 % 10
If we update the 'new' number to be the quotient and by iterating,
the following table shows what it looks like:
```
digit number quo rem Observations
----- ------ ----- --- --------------------------------------------
1 456789 45678 9
2 45678 4567 8
3 4567 456 7 STOP for 3 digits, i.e. number of iterations
4 456 45 6
5 45 4 5
6 4 0 4 BREAK when variable 'quo' equals ZERO
```
For a first approach, consider calling the following method from your `main()`:
```
static void firstApproach(){
int num= 456789;
int quo= num / 10;
int rem= num % 10;
System.out.println( num + " | " + quo + " | " + rem );
}
```
This is the output we get:
```
456789 | 45678 | 9
```
Now, consider a second iteration by calling this method from `main()`:
```
static void secondIteration() {
int num= 456789;
int quo= num / 10;
int rem= num % 10;
System.out.println( num + " | " + quo + " | " + rem );
num= quo;
quo= num / 10;
rem= num % 10;
System.out.println( num + " | " + quo + " | " + rem );
}
```
Here's the output for two iterations:
```
456789 | 45678 | 9
45678 | 4567 | 8
```
Carry on for yet a third iteration:
```
static void thirdIteration() {
int num= 456789;
int quo= num / 10;
int rem= num % 10;
System.out.println( num + " | " + quo + " | " + rem );
num= quo;
quo= num / 10;
rem= num % 10;
System.out.println( num + " | " + quo + " | " + rem );
num= quo;
quo= num / 10;
rem= num % 10;
System.out.println( num + " | " + quo + " | " + rem );
// ... and so on ...
}
```
And the output, after 3 iterations:
```
456789 | 45678 | 9
45678 | 4567 | 8
4567 | 456 | 7
```
Looking at the code for third iteration, observe the following repeating pattern that should go inside the body of a loop:
```
num= quo;
quo= num / 10;
rem= num % 10;
```
What if we try to specify some unreasonable amount of digits, say 10 for the same example of 456789?
This is why the loop needs two stoping conditions (whichever occurs first), namely:
- when it reaches the specified number of digits (3 in the example);
- when quotient gets to ZERO (hence the `break;`).
The following `reverse()` method shows a `while()` loop, where all variables are properly initialised to avoid any surprises. Tha variable `digit` is the one that controls the number of iterations for the loop and is incremented at the end:
```
static int reverse( int number, int numDigits ){
int res= 0;
int quo= number / 10;
int rem= number % 10;
int digit= 1;
while( (digit <= numDigits) && (quo != 0) ){
res= 10*res + rem;
number= quo;
quo= number / 10;
rem= number % 10;
digit= digit + 1;
}
return res;
}
```
The above `reverse()` method can be called from `main()`:
```
public static void main( String args[] ){
// firstApproach();
// secondIteration();
// thirdIteration();
int result= reverse( 456789, 3 ); // reverses 456789, upto 3 digits
System.out.println( result );
}
``` |
779,898 | How can I pass a arbitrary number of arguments to the class constructor using the Object() function defined below?
```
<?php
/*
./index.php
*/
function Object($object)
{
static $instance = array();
if (is_file('./' . $object . '.php') === true)
{
$class = basename($object);
if (array_key_exists($class, $instance) === false)
{
if (class_exists($class, false) === false)
{
require('./' . $object . '.php');
}
/*
How can I pass custom arguments, using the
func_get_args() function to the class constructor?
$instance[$class] = new $class(func_get_arg(1), func_get_arg(2), ...);
*/
$instance[$class] = new $class();
}
return $instance[$class];
}
return false;
}
/*
How do I make this work?
*/
Object('libraries/DB', 'DATABASE', 'USERNAME', 'PASSWORD')->Query(/* Some Query */);
/*
./libraries/DB.php
*/
class DB
{
public function __construct($database, $username, $password, $host = 'localhost', $port = 3306)
{
// do stuff here
}
}
?>
``` | 2009/04/23 | [
"https://Stackoverflow.com/questions/779898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89771/"
] | Instead of your class taking separated parameters I'd have it take an array.
```
class DB
{
public function __construct(array $params)
{
// do stuff here
}
}
```
That way you can pass the direct result of the func\_get\_args into your constructor. The only problem now is being able to figure out the array key / values.
If anyone else has any ideas I'd also be delighted to know :) | I haven't tried this, but `call_user_func_array` sounds like you want.
```
$thing = call_user_func_array(array($classname, '__construct'), $args);
```
Have a look in the [PHP Documentation](http://www.php.net/manual/en/function.call-user-func-array.php). |
779,898 | How can I pass a arbitrary number of arguments to the class constructor using the Object() function defined below?
```
<?php
/*
./index.php
*/
function Object($object)
{
static $instance = array();
if (is_file('./' . $object . '.php') === true)
{
$class = basename($object);
if (array_key_exists($class, $instance) === false)
{
if (class_exists($class, false) === false)
{
require('./' . $object . '.php');
}
/*
How can I pass custom arguments, using the
func_get_args() function to the class constructor?
$instance[$class] = new $class(func_get_arg(1), func_get_arg(2), ...);
*/
$instance[$class] = new $class();
}
return $instance[$class];
}
return false;
}
/*
How do I make this work?
*/
Object('libraries/DB', 'DATABASE', 'USERNAME', 'PASSWORD')->Query(/* Some Query */);
/*
./libraries/DB.php
*/
class DB
{
public function __construct($database, $username, $password, $host = 'localhost', $port = 3306)
{
// do stuff here
}
}
?>
``` | 2009/04/23 | [
"https://Stackoverflow.com/questions/779898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89771/"
] | ```
$klass = new ReflectionClass($classname);
$thing = $klass->newInstanceArgs($args);
```
Although the need to use reflection suggests that you are overcomplicating something in your design. Why do you want to write this function in the first place? | Instead of your class taking separated parameters I'd have it take an array.
```
class DB
{
public function __construct(array $params)
{
// do stuff here
}
}
```
That way you can pass the direct result of the func\_get\_args into your constructor. The only problem now is being able to figure out the array key / values.
If anyone else has any ideas I'd also be delighted to know :) |
779,898 | How can I pass a arbitrary number of arguments to the class constructor using the Object() function defined below?
```
<?php
/*
./index.php
*/
function Object($object)
{
static $instance = array();
if (is_file('./' . $object . '.php') === true)
{
$class = basename($object);
if (array_key_exists($class, $instance) === false)
{
if (class_exists($class, false) === false)
{
require('./' . $object . '.php');
}
/*
How can I pass custom arguments, using the
func_get_args() function to the class constructor?
$instance[$class] = new $class(func_get_arg(1), func_get_arg(2), ...);
*/
$instance[$class] = new $class();
}
return $instance[$class];
}
return false;
}
/*
How do I make this work?
*/
Object('libraries/DB', 'DATABASE', 'USERNAME', 'PASSWORD')->Query(/* Some Query */);
/*
./libraries/DB.php
*/
class DB
{
public function __construct($database, $username, $password, $host = 'localhost', $port = 3306)
{
// do stuff here
}
}
?>
``` | 2009/04/23 | [
"https://Stackoverflow.com/questions/779898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89771/"
] | Instead of your class taking separated parameters I'd have it take an array.
```
class DB
{
public function __construct(array $params)
{
// do stuff here
}
}
```
That way you can pass the direct result of the func\_get\_args into your constructor. The only problem now is being able to figure out the array key / values.
If anyone else has any ideas I'd also be delighted to know :) | An alternative for the reflection method, would be evaluate your code.
```
eval('$instance = new className('.implode(', ', $args).');');
``` |
779,898 | How can I pass a arbitrary number of arguments to the class constructor using the Object() function defined below?
```
<?php
/*
./index.php
*/
function Object($object)
{
static $instance = array();
if (is_file('./' . $object . '.php') === true)
{
$class = basename($object);
if (array_key_exists($class, $instance) === false)
{
if (class_exists($class, false) === false)
{
require('./' . $object . '.php');
}
/*
How can I pass custom arguments, using the
func_get_args() function to the class constructor?
$instance[$class] = new $class(func_get_arg(1), func_get_arg(2), ...);
*/
$instance[$class] = new $class();
}
return $instance[$class];
}
return false;
}
/*
How do I make this work?
*/
Object('libraries/DB', 'DATABASE', 'USERNAME', 'PASSWORD')->Query(/* Some Query */);
/*
./libraries/DB.php
*/
class DB
{
public function __construct($database, $username, $password, $host = 'localhost', $port = 3306)
{
// do stuff here
}
}
?>
``` | 2009/04/23 | [
"https://Stackoverflow.com/questions/779898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89771/"
] | ```
$klass = new ReflectionClass($classname);
$thing = $klass->newInstanceArgs($args);
```
Although the need to use reflection suggests that you are overcomplicating something in your design. Why do you want to write this function in the first place? | I haven't tried this, but `call_user_func_array` sounds like you want.
```
$thing = call_user_func_array(array($classname, '__construct'), $args);
```
Have a look in the [PHP Documentation](http://www.php.net/manual/en/function.call-user-func-array.php). |
779,898 | How can I pass a arbitrary number of arguments to the class constructor using the Object() function defined below?
```
<?php
/*
./index.php
*/
function Object($object)
{
static $instance = array();
if (is_file('./' . $object . '.php') === true)
{
$class = basename($object);
if (array_key_exists($class, $instance) === false)
{
if (class_exists($class, false) === false)
{
require('./' . $object . '.php');
}
/*
How can I pass custom arguments, using the
func_get_args() function to the class constructor?
$instance[$class] = new $class(func_get_arg(1), func_get_arg(2), ...);
*/
$instance[$class] = new $class();
}
return $instance[$class];
}
return false;
}
/*
How do I make this work?
*/
Object('libraries/DB', 'DATABASE', 'USERNAME', 'PASSWORD')->Query(/* Some Query */);
/*
./libraries/DB.php
*/
class DB
{
public function __construct($database, $username, $password, $host = 'localhost', $port = 3306)
{
// do stuff here
}
}
?>
``` | 2009/04/23 | [
"https://Stackoverflow.com/questions/779898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89771/"
] | ```
$klass = new ReflectionClass($classname);
$thing = $klass->newInstanceArgs($args);
```
Although the need to use reflection suggests that you are overcomplicating something in your design. Why do you want to write this function in the first place? | An alternative for the reflection method, would be evaluate your code.
```
eval('$instance = new className('.implode(', ', $args).');');
``` |
14,063,072 | So I would like to do a select from an SQL database, using Java, subject to a conditional statement (less than or equal to something) subject to some loop in Java. In other words, something like the following:
```
for (int i=0; i< 195; i++) {
// Get the results of the SQL query
resultSet = statement.executeQuery(
"SELECT max( millisFromMid ) FROM stockInfo1 WHERE ( millisFromMid <= 34200000 + (120000)*i ) GROUP BY stockID"
);
```
Now Java is returning an exception here, because it doesn't want me to use "i" in this condition; however, without being able to use it here, I'm not sure how I can change this condition. The problem is this: I'm looking to retrieve data from one database, with the intent of doing some manipulation and putting the results into a new database. These manipulations depend on taking the most recent data available, which is why I'm wanting to increase the number bounding millisFromMid. Does that make sense?
Does anyone have a suggestion on how someone might do something like this? This seems like a fundamental skill to have when using Java and SQL together, so I'd very much like to know it. | 2012/12/28 | [
"https://Stackoverflow.com/questions/14063072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1849003/"
] | The SQL statement is parsed and run in a different environment than your Java code - different language, different scope, and unless you use SQLite they run in different processes or even different machines. Because of that, you can't just refer to the Java variable `i` from your SQL code - you have to either inject it or use special API.
The first option - injection - is to simply put the value of i inside the string:
```
"SELECT max( millisFromMid ) FROM stockInfo1 WHERE ( millisFromMid <= 34200000 + (120000)*"+i+" ) GROUP BY stockID"
```
Personally, I prefer to do it using `String.format` - but that's just me.
```
String.format("SELECT max( millisFromMid ) FROM stockInfo1 WHERE ( millisFromMid <= 34200000 + (120000)*%d ) GROUP BY stockID",i)
```
The second option - via API - is more complex but also faster(especially if you combine it with transactions) - using SQL parameters. You need to create a prepared statement:
```
PreparedStatement preparedStatement = connection.prepareStatement("SELECT max( millisFromMid ) FROM stockInfo1 WHERE ( millisFromMid <= 34200000 + (120000)*? ) GROUP BY stockID")
```
Notice the `?` that is replacing the `i` - this is your parameter. You create `prepareStatement` **once** - before the loop, and inside the loop you set the parameter every time and execute it:
```
for (int i=0; i< 195; i++) {
preparedStatement.setInt(1,i); //Set the paramater to the current value of i.
resultSet = preparedStatement.executeQuery(); //Execute the statement - each time with different value of the parameter.
}
``` | The problem os that the database is not told about the value of i. Instead make Java put the value into the string and then submit it to the database.
string sql = "select \* from foo where bar=" + i;
You need to remember at all times that the database only knows what you explicitly tell it, and that you are essentially writing code at runtime that will execute on another host. |
14,063,072 | So I would like to do a select from an SQL database, using Java, subject to a conditional statement (less than or equal to something) subject to some loop in Java. In other words, something like the following:
```
for (int i=0; i< 195; i++) {
// Get the results of the SQL query
resultSet = statement.executeQuery(
"SELECT max( millisFromMid ) FROM stockInfo1 WHERE ( millisFromMid <= 34200000 + (120000)*i ) GROUP BY stockID"
);
```
Now Java is returning an exception here, because it doesn't want me to use "i" in this condition; however, without being able to use it here, I'm not sure how I can change this condition. The problem is this: I'm looking to retrieve data from one database, with the intent of doing some manipulation and putting the results into a new database. These manipulations depend on taking the most recent data available, which is why I'm wanting to increase the number bounding millisFromMid. Does that make sense?
Does anyone have a suggestion on how someone might do something like this? This seems like a fundamental skill to have when using Java and SQL together, so I'd very much like to know it. | 2012/12/28 | [
"https://Stackoverflow.com/questions/14063072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1849003/"
] | The problem os that the database is not told about the value of i. Instead make Java put the value into the string and then submit it to the database.
string sql = "select \* from foo where bar=" + i;
You need to remember at all times that the database only knows what you explicitly tell it, and that you are essentially writing code at runtime that will execute on another host. | You can generate an sql string and call it via jdbc, using bind variable is more correct from performance, security. It also saves you from escaping any special characters.
Since you are learning about using sql with jdbc, please read about bind variables. An example is [here](http://steveracanovic.blogspot.in/2008/03/performance-using-bind-variables-in.html) |
14,063,072 | So I would like to do a select from an SQL database, using Java, subject to a conditional statement (less than or equal to something) subject to some loop in Java. In other words, something like the following:
```
for (int i=0; i< 195; i++) {
// Get the results of the SQL query
resultSet = statement.executeQuery(
"SELECT max( millisFromMid ) FROM stockInfo1 WHERE ( millisFromMid <= 34200000 + (120000)*i ) GROUP BY stockID"
);
```
Now Java is returning an exception here, because it doesn't want me to use "i" in this condition; however, without being able to use it here, I'm not sure how I can change this condition. The problem is this: I'm looking to retrieve data from one database, with the intent of doing some manipulation and putting the results into a new database. These manipulations depend on taking the most recent data available, which is why I'm wanting to increase the number bounding millisFromMid. Does that make sense?
Does anyone have a suggestion on how someone might do something like this? This seems like a fundamental skill to have when using Java and SQL together, so I'd very much like to know it. | 2012/12/28 | [
"https://Stackoverflow.com/questions/14063072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1849003/"
] | The SQL statement is parsed and run in a different environment than your Java code - different language, different scope, and unless you use SQLite they run in different processes or even different machines. Because of that, you can't just refer to the Java variable `i` from your SQL code - you have to either inject it or use special API.
The first option - injection - is to simply put the value of i inside the string:
```
"SELECT max( millisFromMid ) FROM stockInfo1 WHERE ( millisFromMid <= 34200000 + (120000)*"+i+" ) GROUP BY stockID"
```
Personally, I prefer to do it using `String.format` - but that's just me.
```
String.format("SELECT max( millisFromMid ) FROM stockInfo1 WHERE ( millisFromMid <= 34200000 + (120000)*%d ) GROUP BY stockID",i)
```
The second option - via API - is more complex but also faster(especially if you combine it with transactions) - using SQL parameters. You need to create a prepared statement:
```
PreparedStatement preparedStatement = connection.prepareStatement("SELECT max( millisFromMid ) FROM stockInfo1 WHERE ( millisFromMid <= 34200000 + (120000)*? ) GROUP BY stockID")
```
Notice the `?` that is replacing the `i` - this is your parameter. You create `prepareStatement` **once** - before the loop, and inside the loop you set the parameter every time and execute it:
```
for (int i=0; i< 195; i++) {
preparedStatement.setInt(1,i); //Set the paramater to the current value of i.
resultSet = preparedStatement.executeQuery(); //Execute the statement - each time with different value of the parameter.
}
``` | You can generate an sql string and call it via jdbc, using bind variable is more correct from performance, security. It also saves you from escaping any special characters.
Since you are learning about using sql with jdbc, please read about bind variables. An example is [here](http://steveracanovic.blogspot.in/2008/03/performance-using-bind-variables-in.html) |
9,287,960 | I currently have this code that parses imdbAPI http returns:
```
text = 'unicode: {"Title":"The Fountain","Year":"2006","Rated":"R","Released":"22 Nov 2006","Genre":"Drama, Romance, Sci-Fi","Director":"Darren Aronofsky","Writer":"Darren Aronofsky, Darren Aronofsky","Actors":"Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn","Plot":"Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg","Runtime":"1 hr 36 mins","Rating":"7.4","Votes":"100139","ID":"tt0414993","Response":"True"}'
def stripData(tag="Title"):
tag_start = text.find(tag)
data_start = tag_start + len(tag)+3
data_end = text.find('"',data_start)
data = text[data_start:data_end]
return tag, data
```
I'm wondering: is there a better way to do this I am missing? | 2012/02/15 | [
"https://Stackoverflow.com/questions/9287960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1176502/"
] | ```
>>> ast.literal_eval(text.split(' ', 1)[1])
{'Plot': 'Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.', 'Votes': '100139', 'Rated': 'R', 'Response': 'True', 'Title': 'The Fountain', 'Poster': 'http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg', 'Writer': 'Darren Aronofsky, Darren Aronofsky', 'ID': 'tt0414993', 'Director': 'Darren Aronofsky', 'Released': '22 Nov 2006', 'Actors': 'Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn', 'Year': '2006', 'Genre': 'Drama, Romance, Sci-Fi', 'Runtime': '1 hr 36 mins', 'Rating': '7.4'}
>>> json.loads(text.split(' ', 1)[1])
{u'Plot': u'Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.', u'Votes': u'100139', u'Rated': u'R', u'Response': u'True', u'Title': u'The Fountain', u'Poster': u'http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg', u'Writer': u'Darren Aronofsky, Darren Aronofsky', u'ID': u'tt0414993', u'Director': u'Darren Aronofsky', u'Released': u'22 Nov 2006', u'Actors': u'Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn', u'Year': u'2006', u'Genre': u'Drama, Romance, Sci-Fi', u'Runtime': u'1 hr 36 mins', u'Rating': u'7.4'}
``` | You can try casting all the data into a dict after removing all the unnecessary head and tail chars.
```
import re
line = 'unicode: {"Title":"The Fountain","Year":"2006","Rated":"R","Released":"22 Nov 2006","Genre":"Drama, Romance, Sci-Fi","Director":"Darren Aronofsky","Writer":"Darren Aronofsky, Darren Aronofsky","Actors":"Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn","Plot":"Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg","Runtime":"1 hr 36 mins","Rating":"7.4","Votes":"100139","ID":"tt0414993","Response":"True"}'
def parser(text):
match = re.search(r'\{\"([^}]+)\"\}', text)
if match:
return dict(x.split('":"') for x in match.group(1).split('","'))
newdict = parser(line)
for k, v in newdict.items():
print k, v
```
I employ regex, but it's just as easily substituted with any method that removes up to {" and after }" in the retrieved string. |
9,287,960 | I currently have this code that parses imdbAPI http returns:
```
text = 'unicode: {"Title":"The Fountain","Year":"2006","Rated":"R","Released":"22 Nov 2006","Genre":"Drama, Romance, Sci-Fi","Director":"Darren Aronofsky","Writer":"Darren Aronofsky, Darren Aronofsky","Actors":"Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn","Plot":"Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg","Runtime":"1 hr 36 mins","Rating":"7.4","Votes":"100139","ID":"tt0414993","Response":"True"}'
def stripData(tag="Title"):
tag_start = text.find(tag)
data_start = tag_start + len(tag)+3
data_end = text.find('"',data_start)
data = text[data_start:data_end]
return tag, data
```
I'm wondering: is there a better way to do this I am missing? | 2012/02/15 | [
"https://Stackoverflow.com/questions/9287960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1176502/"
] | ```
>>> ast.literal_eval(text.split(' ', 1)[1])
{'Plot': 'Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.', 'Votes': '100139', 'Rated': 'R', 'Response': 'True', 'Title': 'The Fountain', 'Poster': 'http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg', 'Writer': 'Darren Aronofsky, Darren Aronofsky', 'ID': 'tt0414993', 'Director': 'Darren Aronofsky', 'Released': '22 Nov 2006', 'Actors': 'Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn', 'Year': '2006', 'Genre': 'Drama, Romance, Sci-Fi', 'Runtime': '1 hr 36 mins', 'Rating': '7.4'}
>>> json.loads(text.split(' ', 1)[1])
{u'Plot': u'Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.', u'Votes': u'100139', u'Rated': u'R', u'Response': u'True', u'Title': u'The Fountain', u'Poster': u'http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg', u'Writer': u'Darren Aronofsky, Darren Aronofsky', u'ID': u'tt0414993', u'Director': u'Darren Aronofsky', u'Released': u'22 Nov 2006', u'Actors': u'Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn', u'Year': u'2006', u'Genre': u'Drama, Romance, Sci-Fi', u'Runtime': u'1 hr 36 mins', u'Rating': u'7.4'}
``` | Seems to me that everyone is working way too hard... if you really have
```
line = 'unicode: {"key1":"Value1", "key2","value2", etc...}'
```
Which looks like a *string*...
then you strip "unicode:" off the front of the string
```
newline = line[9:]
```
then eval the result directly into a dict
```
data_dict=eval(newline)
```
then you access the data by key
```
print(data_dict['Title'])
```
You have perfect formatting to create a Python dict and can access the values directly from that container. |
52,466,555 | I want to find (or make) a python script that reads a different python script line by line and prints the commands executed and the output right there after.
Suppose you have a python script, `testfile.py` as such:
```
print("Hello world")
for i in range(3):
print(f"i is: {i}")
```
Now, I want a different python script that parses the `testfile.py` and outputs the following:
```
print("Hello world")
## Hello world
for i in range(3):
print(f"i is: {i}")
## i is: 0
## i is: 1
## i is: 2
```
Any suggestions on existing software or new code on how to achieve this is greatly appreciated!
---
Attempts / concept code:
========================
### Running `ipython` from python:
One of the first thoughts were to run ipython from python using `subprocess`:
```
import subprocess
import re
try:
proc = subprocess.Popen(args=["ipython", "-i"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
# Delimiter to know when to stop reading
OUTPUT_DELIMITER = ":::EOL:::"
# Variable to contain the entire interaction:
output_string = ""
# Open testfile.py
with open("testfile.py") as file_:
for line in file_:
# Read command
cmd = line.rstrip()
# Add the command to the output string
output_string += cmd + "\n"
proc.stdin.write(f"{cmd}\n")
# Print the delimiter so we know when to end:
proc.stdin.write('print("{}")\n'.format(OUTPUT_DELIMITER))
proc.stdin.flush()
# Start reading output from ipython
while True:
thisoutput = proc.stdout.readline()
thisoutput = thisoutput.rstrip()
# Now check if it's the delimiter
if thisoutput.find(OUTPUT_DELIMITER) >= 0:
break
output_string += thisoutput + "\n"
except Exception as e:
proc.stdout.close()
proc.stdin.close()
raise
proc.stdout.close()
proc.stdin.close()
print("-" * 4 + "START OUTPUT" + "-" * 4)
print(output_string)
print("-" * 4 + "END OUTPUT" + "-" * 4)
```
In this approach, the problem becomes indented blocks, like the `for` loop.
Ideally something like this would work using just plain `python` (and not `ipython`). | 2018/09/23 | [
"https://Stackoverflow.com/questions/52466555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997253/"
] | [`code.InteractiveConsole.interact`](https://docs.python.org/3/library/code.html#code.InteractiveConsole.interact) does exactly what is asked. | This is not *exactly* what you wanted, but it's close. `trace` module does something very similar.
`so.py:`
```py
print("Hello world")
for i in range(3):
print(f"i is: {i}")
```
```
python -m trace --trace so.py
--- modulename: so, funcname: <module>
so.py(1): print("Hello world")
Hello world
so.py(3): for i in range(3):
so.py(4): print(f"i is: {i}")
i is: 0
so.py(3): for i in range(3):
so.py(4): print(f"i is: {i}")
i is: 1
so.py(3): for i in range(3):
so.py(4): print(f"i is: {i}")
i is: 2
so.py(3): for i in range(3):
``` |
30,205,906 | I have been using oauth 2.0 with Linkedin as the provider. Now as of today suddenly the authentication is no longer working. Looked on Linkedin its API profile page and figured that they have been updating their program.
The error that I am getting is the following:
>
> No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<http://localhost:3000>' is therefore not allowed access.
>
>
>
This is in JS in the Console. I am wondering if this is the actual error or if there is another error.
I am using Rails on the back-end | 2015/05/13 | [
"https://Stackoverflow.com/questions/30205906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2164689/"
] | LinkedIn February 12th 2015 update effects LinkedIn applications between May 12th - May 19th, 2015. Maybe, your application affected today.
I'm getting error after updating. Your application has not been authorized for the scope "r\_fullprofile". The update affected somethings.
<https://developer.linkedin.com/support/developer-program-transition> | Figured it out! Not only on linkedin side, but also in your initializers you have to be careful with what you are asking for. So r\_fullprofile is not longer part of Linkedin API (you have to ask linkedin to be able to make it work). There are also other API things that no longer work (e.g. r\_connections), so be really careful as Linkedin has changed this policy.
In addition, you should not forget to reset the server to reinitialize the initializers. |
50,886,900 | I'm trying to make a test for some of my students where they need to type in missing words from a paragraph (see picture). The key problem I'm hitting is trying to embed input boxes into a text paragraph, so that when there is a gap, tkinter can make an entry box for the student to type in.
Sketch of desired Output:
[Target](https://i.stack.imgur.com/wP42t.png)
---------------------------------------------
Code attempt:
```
import tkinter as tk
root = tk.Tk()
tk.Label(root, font=("Comic Sans MS",24,"bold"),\
text="The largest bone in the human body is the").grid(row=0,column=0)
ent1 = tk.Entry(root)
ent1.grid(row=0,column=1)
tk.Label(root, font=("Comic Sans MS",24,"bold"),\
text="which is found in the").grid(row=0,column=2)
ent2 = tk.Entry(root)
ent2.grid(row=0,column=3)
tk.mainloop()
```
Thank you for reading, and any help is very much appreciated. | 2018/06/16 | [
"https://Stackoverflow.com/questions/50886900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9181800/"
] | You can add widgets to a text widget with the `window_create` method.
Here's a quick example to show how you can use it to embed widgets into a block of text. The code inserts a string that contains `{}` wherever you want an entry widget. The code then searches for that pattern in the widget, deletes it, and inserts an entry widget.
```
import Tkinter as tk
quiz = (
"The largest bone in the human body is the {} "
"which is found in the {}. It is mainly made "
"of the element {}, and is just below the {}."
)
root = tk.Tk()
text = tk.Text(root, wrap="word")
text.pack(fill="both", expand=True)
text.insert("end", quiz)
entries = []
while True:
index = text.search('{}', "1.0")
if not index:
break
text.delete(index, "%s+2c"%index)
entry = tk.Entry(text, width=10)
entries.append(entry)
text.window_create(index, window=entry)
root.mainloop()
``` | You can insert entries in a text widget, example below.
```
import tkinter as tk
root = tk.Tk()
text = tk.Text(root)
text.pack()
text.insert('end', 'The largest ')
question = tk.Entry(text, width=10)
text.window_create('end', window=question)
text.insert('end', ' in the human body is...')
root.mainloop()
``` |
14,527,237 | We have a website running and my boss wanted to use a WordPress website as a cover.
I am trying to create a log in in WordPress using our existing user database. So that when the user log in in WordPress, they will be redirect to our current website.
Any suggestions on how should I approach this?
I tried using jQuery `$.post` but it didn't work out well for external links. | 2013/01/25 | [
"https://Stackoverflow.com/questions/14527237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011844/"
] | Thanks, I've found the problem.
My resource identifier `R.id.listItem_date` is declared as `@+id/listItem.date` in my resource xml file.
Android seems to convert the "." in the name to an "\_" in the generated R file. This works fine when compiling and running the code but apparently robolectric has problems with this.
When I change the dot in my resource name to an underscore, my robolectric code works fine.
Now that I know what to look for, I've found that there is an open bug ticket for this:
<https://github.com/pivotal/robolectric/issues/265> | Please see the following changes
```
LayoutInflater inflater = (LayoutInflater)**"ContextOnject"**.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.timeline_list_item, null);
``` |
29,252,113 | I am using [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx) to build reusable expressions as return values of objects. For example:
```
public interface ISurveyEligibilityCriteria
{
Expression<Func<Client, bool>> GetEligibilityExpression();
}
```
I want to have automated tests that determine whether a particular expression is translateable into T-SQL by Entity Framework (ie that it doesn't throw a `NotSupportedException` while "executing"). I can't find anything on the internet - is this possible (seems like it should be)? | 2015/03/25 | [
"https://Stackoverflow.com/questions/29252113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1860652/"
] | You can create a LINQ statement containing the expression and then check whether it can be translated without actually executing it:
```
var connString = @"server=x;database=x";
using(var db = new MyContext(connString))
{
// ToString() shows the generated SQL string.
var sql = db.Entities.Where(generatedExpression).ToString();
Assert.IsTrue(sql.StartsWith("SELECT");
}
```
In the `Assert` you can test anything you'd expect to be part of the generated SQL string, but of course if the expression can't be translated, the test will fail because e.g. a `NotSupportedException` is thrown.
---
You can wrap this up into a handy extension method:
```
public static class EntityFrameworkExtensions
{
public static void CompilePredicate<T>(this DbContext context, Expression<Func<T, bool>> predicate)
where T : class
{
context.Set<T>().Where(predicate).ToString();
}
}
```
Then in your test:
```
// act
Action act = () => context.CompilePredicate(predicate);
// assert
act.ShouldNotThrow();
``` | A very simple solution is executing it:
```
using (var context = ...)
{
// The query will return null, but will be executed.
context.Clients.Where(GetEligibilityExpression())
.Where(() => false)
.SingleOrDefault();
}
```
In older versions of EF (or using `ObjectContext`) you could have tried "manually" compiling the query with `CompiledQuery.Compile`, but this isn't supported with `DbContext`. |
35,828,328 | I am using Swashbuckle (swagger for C#) with my Web API. I have several GET End-Points that return lists and I allow the user to add a perpage and page params into the QueryString
Example: <http://myapi.com/endpoint/?page=5&perpage=10>
I see that swagger does support parameter in 'query' but how do I get Swashbuckle to do it?
---
I mention in one of the comments that I solved my issue by creating a custom attribute to allow me to do what I needed. Below is the code for my solution:
```
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class SwaggerParameterAttribute : Attribute
{
public SwaggerParameterAttribute(string name, string description)
{
Name = name;
Description = description;
}
public string Name { get; private set; }
public Type DataType { get; set; }
public string ParameterType { get; set; }
public string Description { get; private set; }
public bool Required { get; set; } = false;
}
```
Register the Attribute with the Swagger Config:
```
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.OperationFilter<SwaggerParametersAttributeHandler>();
});
```
Then add this attribute to your methods:
```
[SwaggerParameter("page", "Page number to display", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
[SwaggerParameter("perpage","Items to display per page", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
``` | 2016/03/06 | [
"https://Stackoverflow.com/questions/35828328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4202984/"
] | You can achieve that quite easily. Suppose you have an `ItemsController` with an action like this:
```
[Route("/api/items/{id}")]
public IHttpActionResult Get(int id, int? page = null, int? perpage = null)
{
// some relevant code
return Ok();
}
```
Swashbuckle will generate this specification (only showing relevant part):
```
"paths":{
"/api/items/{id}":{
"get":{
"parameters":[
{
"name":"id",
"in":"path",
"required":true,
"type":"integer",
"format":"int32"
},
{
"name":"page",
"in":"query",
"required":false,
"type":"integer",
"format":"int32"
},
{
"name":"limit",
"in":"query",
"required":false,
"type":"integer",
"format":"int32"
}
]
}
}
```
When you want `page` and `perpage` to be required, just make the parameters not nullable. | There's some comments here regarding missing information on the SwaggerParametersAttributeHandler. It is an operation filter to help you determine what to do to your attributes.
Here's an example handler I used that allows me to override nullable parameters' required fields using the SwaggerParameterAttribute.
```
public class RequiredParameterOverrideOperationFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
// Get all SwaggerParameterAttributes on the method
var attributes = apiDescription.ActionDescriptor.GetCustomAttributes<SwaggerParameterAttribute>();
if (operation.parameters == null)
{
operation.parameters = new List<Parameter>();
}
// For each attribute found, find the operation parameter (this is where Swagger looks to generate the Swagger doc)
// Override the required fields based on the attribute's required field
foreach (var attribute in attributes)
{
var referencingOperationParameter = operation.parameters.FirstOrDefault(p => p.name == attribute.Name);
if (referencingOperationParameter != null)
{
referencingOperationParameter.required = attribute.Required;
}
}
}
}
``` |
35,828,328 | I am using Swashbuckle (swagger for C#) with my Web API. I have several GET End-Points that return lists and I allow the user to add a perpage and page params into the QueryString
Example: <http://myapi.com/endpoint/?page=5&perpage=10>
I see that swagger does support parameter in 'query' but how do I get Swashbuckle to do it?
---
I mention in one of the comments that I solved my issue by creating a custom attribute to allow me to do what I needed. Below is the code for my solution:
```
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class SwaggerParameterAttribute : Attribute
{
public SwaggerParameterAttribute(string name, string description)
{
Name = name;
Description = description;
}
public string Name { get; private set; }
public Type DataType { get; set; }
public string ParameterType { get; set; }
public string Description { get; private set; }
public bool Required { get; set; } = false;
}
```
Register the Attribute with the Swagger Config:
```
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.OperationFilter<SwaggerParametersAttributeHandler>();
});
```
Then add this attribute to your methods:
```
[SwaggerParameter("page", "Page number to display", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
[SwaggerParameter("perpage","Items to display per page", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
``` | 2016/03/06 | [
"https://Stackoverflow.com/questions/35828328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4202984/"
] | You can achieve that quite easily. Suppose you have an `ItemsController` with an action like this:
```
[Route("/api/items/{id}")]
public IHttpActionResult Get(int id, int? page = null, int? perpage = null)
{
// some relevant code
return Ok();
}
```
Swashbuckle will generate this specification (only showing relevant part):
```
"paths":{
"/api/items/{id}":{
"get":{
"parameters":[
{
"name":"id",
"in":"path",
"required":true,
"type":"integer",
"format":"int32"
},
{
"name":"page",
"in":"query",
"required":false,
"type":"integer",
"format":"int32"
},
{
"name":"limit",
"in":"query",
"required":false,
"type":"integer",
"format":"int32"
}
]
}
}
```
When you want `page` and `perpage` to be required, just make the parameters not nullable. | Here is a summary of the steps required (ASP.Net Core 2.1, Swashbuckle.AspNetCore v4.0.1) for the Attribute method. I needed a parameter starting with "$" so optional parameters were not an option!
SwaggerParameterAttribute.cs
```
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class SwaggerParameterAttribute : Attribute
{
public SwaggerParameterAttribute(string name, string description)
{
Name = name;
Description = description;
}
public string Name { get; private set; }
public string DataType { get; set; }
public string ParameterType { get; set; }
public string Description { get; private set; }
public bool Required { get; set; } = false;
}
```
SwaggerParameterAttributeFilter.cs
```
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Linq;
public class SwaggerParameterAttributeFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
var attributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
.Union(context.MethodInfo.GetCustomAttributes(true))
.OfType<SwaggerParameterAttribute>();
foreach (var attribute in attributes)
operation.Parameters.Add(new NonBodyParameter
{
Name = attribute.Name,
Description = attribute.Description,
In = attribute.ParameterType,
Required = attribute.Required,
Type = attribute.DataType
});
}
}
```
add this in Startup.ConfigureServices
```
using Swashbuckle.AspNetCore.Swagger;
services.AddSwaggerGen(c =>
{
c.OperationFilter<SwaggerParameterAttributeFilter>();
c.SwaggerDoc("v1.0", new Info { Title = "My API", Version = "v1.0" });
});
```
and use like this:
```
[SwaggerParameter("$top", "Odata Top parameter", DataType = "integer", ParameterType ="query")]
```
DataTypes can be: integer, string, boolean
ParameterTypes: can be path, body, query |
35,828,328 | I am using Swashbuckle (swagger for C#) with my Web API. I have several GET End-Points that return lists and I allow the user to add a perpage and page params into the QueryString
Example: <http://myapi.com/endpoint/?page=5&perpage=10>
I see that swagger does support parameter in 'query' but how do I get Swashbuckle to do it?
---
I mention in one of the comments that I solved my issue by creating a custom attribute to allow me to do what I needed. Below is the code for my solution:
```
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class SwaggerParameterAttribute : Attribute
{
public SwaggerParameterAttribute(string name, string description)
{
Name = name;
Description = description;
}
public string Name { get; private set; }
public Type DataType { get; set; }
public string ParameterType { get; set; }
public string Description { get; private set; }
public bool Required { get; set; } = false;
}
```
Register the Attribute with the Swagger Config:
```
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.OperationFilter<SwaggerParametersAttributeHandler>();
});
```
Then add this attribute to your methods:
```
[SwaggerParameter("page", "Page number to display", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
[SwaggerParameter("perpage","Items to display per page", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
``` | 2016/03/06 | [
"https://Stackoverflow.com/questions/35828328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4202984/"
] | You can achieve that quite easily. Suppose you have an `ItemsController` with an action like this:
```
[Route("/api/items/{id}")]
public IHttpActionResult Get(int id, int? page = null, int? perpage = null)
{
// some relevant code
return Ok();
}
```
Swashbuckle will generate this specification (only showing relevant part):
```
"paths":{
"/api/items/{id}":{
"get":{
"parameters":[
{
"name":"id",
"in":"path",
"required":true,
"type":"integer",
"format":"int32"
},
{
"name":"page",
"in":"query",
"required":false,
"type":"integer",
"format":"int32"
},
{
"name":"limit",
"in":"query",
"required":false,
"type":"integer",
"format":"int32"
}
]
}
}
```
When you want `page` and `perpage` to be required, just make the parameters not nullable. | I know this is old and all but I spent some time looking for the easier method and found it. So for anyone who also stumbles onto this old thread, here it is:
```
public async Task<IActionResult> Foo([FromQuery]YourDtoType dto)
``` |
35,828,328 | I am using Swashbuckle (swagger for C#) with my Web API. I have several GET End-Points that return lists and I allow the user to add a perpage and page params into the QueryString
Example: <http://myapi.com/endpoint/?page=5&perpage=10>
I see that swagger does support parameter in 'query' but how do I get Swashbuckle to do it?
---
I mention in one of the comments that I solved my issue by creating a custom attribute to allow me to do what I needed. Below is the code for my solution:
```
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class SwaggerParameterAttribute : Attribute
{
public SwaggerParameterAttribute(string name, string description)
{
Name = name;
Description = description;
}
public string Name { get; private set; }
public Type DataType { get; set; }
public string ParameterType { get; set; }
public string Description { get; private set; }
public bool Required { get; set; } = false;
}
```
Register the Attribute with the Swagger Config:
```
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.OperationFilter<SwaggerParametersAttributeHandler>();
});
```
Then add this attribute to your methods:
```
[SwaggerParameter("page", "Page number to display", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
[SwaggerParameter("perpage","Items to display per page", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
``` | 2016/03/06 | [
"https://Stackoverflow.com/questions/35828328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4202984/"
] | Here is a summary of the steps required (ASP.Net Core 2.1, Swashbuckle.AspNetCore v4.0.1) for the Attribute method. I needed a parameter starting with "$" so optional parameters were not an option!
SwaggerParameterAttribute.cs
```
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class SwaggerParameterAttribute : Attribute
{
public SwaggerParameterAttribute(string name, string description)
{
Name = name;
Description = description;
}
public string Name { get; private set; }
public string DataType { get; set; }
public string ParameterType { get; set; }
public string Description { get; private set; }
public bool Required { get; set; } = false;
}
```
SwaggerParameterAttributeFilter.cs
```
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Linq;
public class SwaggerParameterAttributeFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
var attributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
.Union(context.MethodInfo.GetCustomAttributes(true))
.OfType<SwaggerParameterAttribute>();
foreach (var attribute in attributes)
operation.Parameters.Add(new NonBodyParameter
{
Name = attribute.Name,
Description = attribute.Description,
In = attribute.ParameterType,
Required = attribute.Required,
Type = attribute.DataType
});
}
}
```
add this in Startup.ConfigureServices
```
using Swashbuckle.AspNetCore.Swagger;
services.AddSwaggerGen(c =>
{
c.OperationFilter<SwaggerParameterAttributeFilter>();
c.SwaggerDoc("v1.0", new Info { Title = "My API", Version = "v1.0" });
});
```
and use like this:
```
[SwaggerParameter("$top", "Odata Top parameter", DataType = "integer", ParameterType ="query")]
```
DataTypes can be: integer, string, boolean
ParameterTypes: can be path, body, query | There's some comments here regarding missing information on the SwaggerParametersAttributeHandler. It is an operation filter to help you determine what to do to your attributes.
Here's an example handler I used that allows me to override nullable parameters' required fields using the SwaggerParameterAttribute.
```
public class RequiredParameterOverrideOperationFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
// Get all SwaggerParameterAttributes on the method
var attributes = apiDescription.ActionDescriptor.GetCustomAttributes<SwaggerParameterAttribute>();
if (operation.parameters == null)
{
operation.parameters = new List<Parameter>();
}
// For each attribute found, find the operation parameter (this is where Swagger looks to generate the Swagger doc)
// Override the required fields based on the attribute's required field
foreach (var attribute in attributes)
{
var referencingOperationParameter = operation.parameters.FirstOrDefault(p => p.name == attribute.Name);
if (referencingOperationParameter != null)
{
referencingOperationParameter.required = attribute.Required;
}
}
}
}
``` |
35,828,328 | I am using Swashbuckle (swagger for C#) with my Web API. I have several GET End-Points that return lists and I allow the user to add a perpage and page params into the QueryString
Example: <http://myapi.com/endpoint/?page=5&perpage=10>
I see that swagger does support parameter in 'query' but how do I get Swashbuckle to do it?
---
I mention in one of the comments that I solved my issue by creating a custom attribute to allow me to do what I needed. Below is the code for my solution:
```
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class SwaggerParameterAttribute : Attribute
{
public SwaggerParameterAttribute(string name, string description)
{
Name = name;
Description = description;
}
public string Name { get; private set; }
public Type DataType { get; set; }
public string ParameterType { get; set; }
public string Description { get; private set; }
public bool Required { get; set; } = false;
}
```
Register the Attribute with the Swagger Config:
```
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.OperationFilter<SwaggerParametersAttributeHandler>();
});
```
Then add this attribute to your methods:
```
[SwaggerParameter("page", "Page number to display", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
[SwaggerParameter("perpage","Items to display per page", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
``` | 2016/03/06 | [
"https://Stackoverflow.com/questions/35828328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4202984/"
] | Here is a summary of the steps required (ASP.Net Core 2.1, Swashbuckle.AspNetCore v4.0.1) for the Attribute method. I needed a parameter starting with "$" so optional parameters were not an option!
SwaggerParameterAttribute.cs
```
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class SwaggerParameterAttribute : Attribute
{
public SwaggerParameterAttribute(string name, string description)
{
Name = name;
Description = description;
}
public string Name { get; private set; }
public string DataType { get; set; }
public string ParameterType { get; set; }
public string Description { get; private set; }
public bool Required { get; set; } = false;
}
```
SwaggerParameterAttributeFilter.cs
```
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Linq;
public class SwaggerParameterAttributeFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
var attributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
.Union(context.MethodInfo.GetCustomAttributes(true))
.OfType<SwaggerParameterAttribute>();
foreach (var attribute in attributes)
operation.Parameters.Add(new NonBodyParameter
{
Name = attribute.Name,
Description = attribute.Description,
In = attribute.ParameterType,
Required = attribute.Required,
Type = attribute.DataType
});
}
}
```
add this in Startup.ConfigureServices
```
using Swashbuckle.AspNetCore.Swagger;
services.AddSwaggerGen(c =>
{
c.OperationFilter<SwaggerParameterAttributeFilter>();
c.SwaggerDoc("v1.0", new Info { Title = "My API", Version = "v1.0" });
});
```
and use like this:
```
[SwaggerParameter("$top", "Odata Top parameter", DataType = "integer", ParameterType ="query")]
```
DataTypes can be: integer, string, boolean
ParameterTypes: can be path, body, query | I know this is old and all but I spent some time looking for the easier method and found it. So for anyone who also stumbles onto this old thread, here it is:
```
public async Task<IActionResult> Foo([FromQuery]YourDtoType dto)
``` |
34,870 | My pro tools version is HD 10.3.7.
When I arm and start recording, everything is working, the meters going up, wave form is bulit.
And when I stop it, the wave form (aka. region) immediately disappears. This happens only to short recordings. (As far as my test goes, it happens to recordings under 4 seconds).
However, the disappeared recording is saved in audio files. It's not just there anymore on pro tools edit view.
???? | 2015/04/05 | [
"https://sound.stackexchange.com/questions/34870",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/11447/"
] | Try this:
click off pre-roll on transport window (CMND + 1) | PT has a pre-record period whereby it will display the waveform but not record until this period is over. Logic Pro also has this function and you can disable it in preferences. |
14,809,861 | I'm having trouble with reverse navigation on one of my entities.
I have the following two objects:
```
public class Candidate
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long CandidateId { get; set; }
....
// Reverse navigation
public virtual CandidateData Data { get; set; }
...
// Foreign keys
....
}
public class CandidateData
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long CandidateDataId { get; set; }
[Required]
public long CandidateId { get; set; }
// Foreign keys
[ForeignKey("CandidateId")]
public virtual Candidate Candidate { get; set; }
}
```
Now my foreign key navigation on the CandidateData object works fine. I am having trouble getting the reverse navigation for the candidate object to work (if that's even possible).
This is my OnModelCreating function:
```
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Candidate>()
.HasOptional(obj => obj.Data)
.WithOptionalPrincipal();
base.OnModelCreating(modelBuilder);
}
```
It's close to working except in the database I get two columns that link to the CandidateId. I get the one I from the POCO object the I get another column Candidate\_CandidateId I assume was created by the modelBuilder.
I am quiet lost at the moment. Can someone please shed some light on what's going on? | 2013/02/11 | [
"https://Stackoverflow.com/questions/14809861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056149/"
] | The One to One problem....
The issue is EF and CODE First, when 1:1 , for the dependent to have a Primary key that refers to the principal. ALthough you can define a DB otherwise and indeed with a DB you can even have OPTIONAL FK on the Primary. EF makes this restriction in Code first. Fair Enough I think...
TRy this instead: IS have added a few **opinions** on the way which you may **ignore** if you disagree:-)
```
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace EF_DEMO
{
class FK121
{
public static void ENTRYfk121(string[] args)
{
var ctx = new Context121();
ctx.Database.Create();
System.Console.ReadKey();
}
}
public class Candidate
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]// best in Fluent API, In my opinion..
public long CandidateId { get; set; }
// public long CandidateDataId { get; set; }// DONT TRY THIS... Although DB will support EF cant deal with 1:1 and both as FKs
public virtual CandidateData Data { get; set; } // Reverse navigation
}
public class CandidateData
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] // best in Fluent API as it is EF/DB related
public long CandidateDataId { get; set; } // is also a Foreign with EF and 1:1 when this is dependent
// [Required]
// public long CandidateId { get; set; } // dont need this... PK is the FK to Principal in 1:1
public virtual Candidate Candidate { get; set; } // yes we need this
}
public class Context121 : DbContext
{
static Context121()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<Context121>());
}
public Context121()
: base("Name=Demo") { }
public DbSet<Candidate> Candidates { get; set; }
public DbSet<CandidateData> CandidateDatas { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Candidate>();
modelBuilder.Entity<CandidateData>()
.HasRequired(q => q.Candidate)
.WithOptional(p=>p.Data) // this would be blank if reverse validation wasnt used, but here it is used
.Map(t => t.MapKey("CandidateId")); // Only use MAP when the Foreign Key Attributes NOT annotated as attributes
}
}
```
} | I think that the foreign key should be created as:
.Map(t => t.MapKey("CandidateDataId")) because thsi foreign key will be placed in Candidate table...
Waht do you think? |
19,615,784 | I'm trying to run a simple batch file.
```
for /f %%a IN ('dir /b /s "%~dp0\EnsembleIndependant\*.mis"') DO (ECHO %%a >> ResultatVorace.txt & CALL vorace.exe -f %%a >> ResultatVorace.txt)
```
this only works if there is no space in the path of the batch file.
the batch is in:
C:\Users\Rafael\Documents\Visual Studio 2012\Projects\vorace\Release\vorace.exe
the files I want to loop through are in:
C:\Users\Rafael\Documents\Visual Studio 2012\Projects\vorace\Release\EnsembleIndependant
can anyone help me.
thanks.
thank you guys for the suggestions.
for /f "delims=" solved my problem. | 2013/10/27 | [
"https://Stackoverflow.com/questions/19615784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2453139/"
] | ```
for /f "delims=" %%a IN ('dir /b /s "%~dp0EnsembleIndependant\*.mis"') DO (ECHO %%a >> ResultatVorace.txt & CALL vorace.exe -f %%a >> ResultatVorace.txt)
```
`%~dp0` has already a backspace at the end. | ```
for /f "delims=" %%a IN ('dir /b /s "%~dp0\EnsembleIndependant\*.mis"') DO (ECHO %%a >> ResultatVorace.txt & CALL vorace.exe -f %%a >> ResultatVorace.txt)
```
space is a standard delimiter in batch for loops as well as `<tab>` and with `"delims="` you deactivate it. |
19,615,784 | I'm trying to run a simple batch file.
```
for /f %%a IN ('dir /b /s "%~dp0\EnsembleIndependant\*.mis"') DO (ECHO %%a >> ResultatVorace.txt & CALL vorace.exe -f %%a >> ResultatVorace.txt)
```
this only works if there is no space in the path of the batch file.
the batch is in:
C:\Users\Rafael\Documents\Visual Studio 2012\Projects\vorace\Release\vorace.exe
the files I want to loop through are in:
C:\Users\Rafael\Documents\Visual Studio 2012\Projects\vorace\Release\EnsembleIndependant
can anyone help me.
thanks.
thank you guys for the suggestions.
for /f "delims=" solved my problem. | 2013/10/27 | [
"https://Stackoverflow.com/questions/19615784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2453139/"
] | ```
for /f "delims=" %%a IN ('dir /b /s "%~dp0EnsembleIndependant\*.mis"') DO (ECHO %%a >> ResultatVorace.txt & CALL vorace.exe -f %%a >> ResultatVorace.txt)
```
`%~dp0` has already a backspace at the end. | FOR /F uses as standard delimiters `space` and `tab`, to avoid this you need to add the options.
```
for /f "delims=" %%a IN ('dir /b /s "%~dp0\EnsembleIndependant\*.mis"') DO (ECHO %%a >> ResultatVorace.txt & CALL vorace.exe -f %%a >> ResultatVorace.txt)
``` |
4,764,553 | I want to create computer for the word-game [Ghost](http://en.wikipedia.org/wiki/Ghost_%28game%29). However, I'm having problems thinking of a good way to deal with accessing the huge word list. Here's my current implementation (which doesn't work):
```
import os, random, sys, math, string
def main():
#Contains a huge wordlist-- opened up for reading
dictionary = open("wordlist.txt", "r")
wordlist = []
win= 0
turn= 0
firstrun = 0
word = ""
#while nobody has won the game
while win==0:
if turn == 0:
#get first letter from input
foo = raw_input("Choose a letter: ")[0]
word+=foo
print "**Current word**: "+ word
#Computer's turn
turn = 1
if turn == 1:
#During the first run the program gets all definitively
#winning words (words that have odd-number lengths)
#from the "dictionary" file and puts them in a list
if firstrun== 0:
for line in dictionary:
#if the line in the dictionary starts with the current
#word and has an odd-number of letters
if str(line).startswith(word) and len(line)%2 == 0:
wordlist.append(line[0: len(line)-1])
print "first run complete... size = "+str(len(wordlist))
firstrun = 1
else: #This is run after the second computer move
for line in wordlist:
#THIS DOES NOT WORK-- THIS IS THE PROBLEM.
#I want it to remove from the list every single
#word that does not conform to the current limitations
#of the "word" variable.
if not line.startswith(word):
wordlist.remove(line)
print "removal complete... size = "+str(len(wordlist))
turn = 0
if __name__ == "__main__":
main()
```
I have demarcated the problem area in the code. I have no idea why it doesn't work. What should happen: Imagine the list is populated with all words that start with 'a.' The user then picks the letter 'b.' The target word then must have the starting letters 'ab.' What should happen is that all 'a' words that are in the list that are not directly followed with a 'b' should be removed.
I also would appreciate it if somebody could let me know a more efficient way of doing this then making a huge initial list. | 2011/01/21 | [
"https://Stackoverflow.com/questions/4764553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372526/"
] | I would suggest not deleting words from your list. It will be extremely slow because deleting in the middle of a list is O(N).
It is better to just make a new list. One possible way to do this is to replace the lines
```
for line in wordlist:
if not line.startswith(word):
wordlist.remove(line)
```
with
```
wordlist = [w for w in wordlist if w.startswith(word)]
``` | Peter Norvig has a great discussion on autocorrect here:
<http://norvig.com/spell-correct.html>
The large-list comprehension and context matching seem relevant - and at 21 lines it's a quick read (with good explanation following). Also check out the "Charming python" 3-part on functional programming with python (IBM). You can do all the setup with a few list comprehensions. |
4,764,553 | I want to create computer for the word-game [Ghost](http://en.wikipedia.org/wiki/Ghost_%28game%29). However, I'm having problems thinking of a good way to deal with accessing the huge word list. Here's my current implementation (which doesn't work):
```
import os, random, sys, math, string
def main():
#Contains a huge wordlist-- opened up for reading
dictionary = open("wordlist.txt", "r")
wordlist = []
win= 0
turn= 0
firstrun = 0
word = ""
#while nobody has won the game
while win==0:
if turn == 0:
#get first letter from input
foo = raw_input("Choose a letter: ")[0]
word+=foo
print "**Current word**: "+ word
#Computer's turn
turn = 1
if turn == 1:
#During the first run the program gets all definitively
#winning words (words that have odd-number lengths)
#from the "dictionary" file and puts them in a list
if firstrun== 0:
for line in dictionary:
#if the line in the dictionary starts with the current
#word and has an odd-number of letters
if str(line).startswith(word) and len(line)%2 == 0:
wordlist.append(line[0: len(line)-1])
print "first run complete... size = "+str(len(wordlist))
firstrun = 1
else: #This is run after the second computer move
for line in wordlist:
#THIS DOES NOT WORK-- THIS IS THE PROBLEM.
#I want it to remove from the list every single
#word that does not conform to the current limitations
#of the "word" variable.
if not line.startswith(word):
wordlist.remove(line)
print "removal complete... size = "+str(len(wordlist))
turn = 0
if __name__ == "__main__":
main()
```
I have demarcated the problem area in the code. I have no idea why it doesn't work. What should happen: Imagine the list is populated with all words that start with 'a.' The user then picks the letter 'b.' The target word then must have the starting letters 'ab.' What should happen is that all 'a' words that are in the list that are not directly followed with a 'b' should be removed.
I also would appreciate it if somebody could let me know a more efficient way of doing this then making a huge initial list. | 2011/01/21 | [
"https://Stackoverflow.com/questions/4764553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372526/"
] | Peter Norvig has a great discussion on autocorrect here:
<http://norvig.com/spell-correct.html>
The large-list comprehension and context matching seem relevant - and at 21 lines it's a quick read (with good explanation following). Also check out the "Charming python" 3-part on functional programming with python (IBM). You can do all the setup with a few list comprehensions. | If you want to work for ITA you'd be better off writing this in clisp... or clojure. |
4,764,553 | I want to create computer for the word-game [Ghost](http://en.wikipedia.org/wiki/Ghost_%28game%29). However, I'm having problems thinking of a good way to deal with accessing the huge word list. Here's my current implementation (which doesn't work):
```
import os, random, sys, math, string
def main():
#Contains a huge wordlist-- opened up for reading
dictionary = open("wordlist.txt", "r")
wordlist = []
win= 0
turn= 0
firstrun = 0
word = ""
#while nobody has won the game
while win==0:
if turn == 0:
#get first letter from input
foo = raw_input("Choose a letter: ")[0]
word+=foo
print "**Current word**: "+ word
#Computer's turn
turn = 1
if turn == 1:
#During the first run the program gets all definitively
#winning words (words that have odd-number lengths)
#from the "dictionary" file and puts them in a list
if firstrun== 0:
for line in dictionary:
#if the line in the dictionary starts with the current
#word and has an odd-number of letters
if str(line).startswith(word) and len(line)%2 == 0:
wordlist.append(line[0: len(line)-1])
print "first run complete... size = "+str(len(wordlist))
firstrun = 1
else: #This is run after the second computer move
for line in wordlist:
#THIS DOES NOT WORK-- THIS IS THE PROBLEM.
#I want it to remove from the list every single
#word that does not conform to the current limitations
#of the "word" variable.
if not line.startswith(word):
wordlist.remove(line)
print "removal complete... size = "+str(len(wordlist))
turn = 0
if __name__ == "__main__":
main()
```
I have demarcated the problem area in the code. I have no idea why it doesn't work. What should happen: Imagine the list is populated with all words that start with 'a.' The user then picks the letter 'b.' The target word then must have the starting letters 'ab.' What should happen is that all 'a' words that are in the list that are not directly followed with a 'b' should be removed.
I also would appreciate it if somebody could let me know a more efficient way of doing this then making a huge initial list. | 2011/01/21 | [
"https://Stackoverflow.com/questions/4764553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372526/"
] | I would suggest not deleting words from your list. It will be extremely slow because deleting in the middle of a list is O(N).
It is better to just make a new list. One possible way to do this is to replace the lines
```
for line in wordlist:
if not line.startswith(word):
wordlist.remove(line)
```
with
```
wordlist = [w for w in wordlist if w.startswith(word)]
``` | If you want to work for ITA you'd be better off writing this in clisp... or clojure. |
62,465,566 | I am trying to first upload images to firebase then retrieving in in an activity(gallery) but getting a code error.
```
@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
ImageUploaderAdapter uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.get().load(mContext).into(imageView)
.load(uploadCurrent.getImageUrl())
.fit()
.centerCrop()
.into(holder.imageView);
```
Error in code `Picasso.get().load(mContext).into(imageView)`
getting error
```
error: method get in class Picasso cannot be applied to given types;
Picasso.get(mContext)
``` | 2020/06/19 | [
"https://Stackoverflow.com/questions/62465566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13607439/"
] | matchTemplate wont work well in this case, as they need exact size and viewpoint match.
Opencv Feature based method might work. You can try SIFT based method first. But the general assumption is that the rotation, translation, perspective changes are bounded. It means that for adjacent iamge pair, it can not be 1 taken from 20m and other picture taken from 10km away. Assumptions are made so that the feature can be associated.
[](https://i.stack.imgur.com/WgfIQ.png)
Deep learning-based method might work well given enough datasets. take POSEnet for reference. It can matches same building from different geometry view point and associate them correctly.
[](https://i.stack.imgur.com/sr0c2.png)
Each method has pros and cons. You have to decide which method you can afford to use
Regards
Dr. Yuan Shenghai | For pixel-wise similarity, you may use `res = cv2.matchTemplate(img1, img2, cv2.TM_CCOEFF_NORMED) \\ similarity = res[0][0]`, which adopts standard corralation coefficient to evaluate simlarity (first assure two inputted image is in the same size).
For chromatic similarity, you may calculate histogram of each image by `cv2.calHist`, then measure the similarity between each histogram by metric of your choice.
For intuitive similarity, I'm afraid you have to use some machine learning or deep learning method since "similar" is a rather vague concept here. |
15,795,748 | I am hosting an ASP.NET MVC 4 site on AppHarbor (which uses Amazon EC2), and I'm using CloudFlare for Flexible SSL. I'm having a problem with redirect loops (310) when trying to use RequireHttps. The problem is that, like EC2, CloudFlare terminates the SSL before forwarding the request onto the server. However, whereas Amazon sets the X-Forwarded-Proto header so that you can handle the request with a custom filter, CloudFlare does not appear to. Or if they do, I don't know how they are doing it, since I can't intercept traffic at that level. I've tried the solutions for Amazon EC2, but they don't seem to help with CloudFlare.
Has anyone experienced this issue, or know enough about CloudFlare to help? | 2013/04/03 | [
"https://Stackoverflow.com/questions/15795748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1141679/"
] | The `X-Forwarded-Proto` header is intentionally overridden by AppHarbor's load balancers to the actual scheme of the request.
Note that while CloudFlare's flexible SSL option may add slightly more security, there is still unencrypted traffic travelling over the public internet from CloudFlare to AppHarbor. This arguably defies the purpose of SSL for anything else than appearances and reducing the number of attack vectors (like packet sniffing on the user's local network) - i.e. it may look "professional" to your users, but it actually is still insecure.
That's less than ideal particularly since AppHarbor supports both installing your own certificates and includes piggyback SSL out of the box. CloudFlare also recommends using "Full SSL" for scenarios where the origin servers/service support SSL. So you have a couple of options:
* Continue to use the insecure "Flexible SSL" option, but instead of inspecting the `X-Forwarded-Proto` header in your custom `RequireHttps` filter, you should inspect the `scheme` attribute of the `CF-Visitor` header. There are more details in [this discussion](https://support.cloudflare.com/entries/22088068-How-do-I-redirect-HTTPS-traffic-with-Flexible-SSL-and-Apache-).
* Use "Full SSL" and point CloudFlare to your `*.apphb.com` hostname. This way you can use the complimentary piggyback SSL that is enabled by default with your AppHarbor app. You'll have to override the `Host` header on CloudFlare to make this work and [here's a blog post on how to do that](http://blog.cloudflare.com/ssl-on-custom-domains-for-appengine-and-other). This will of course make requests to your app appear like they were made to your `*.apphb.com` domain - so if for instance you automatically redirect requests to a "canonical" URL or generate absolute URLs you'll likely have to take this into consideration.
* Upload your certificate and add a custom hostname to AppHarbor. Then turn on "Full SSL" on CloudFlare. This way the host header will remain the same and your application will continue to work without any modifications. You can read more about the SSL options offered by AppHarbor in [this knowledge base article](http://support.appharbor.com/kb/tips-and-tricks/ssl-and-certificates). | This is interesting.
Just I recently had a discussion with one of our clients, who asked me about "flexible" SSL and suggested that we (Incapsula) also offer such option.
After some discussion we both came to the conclusion that such a feature would be misleading, since it will provide the end-user with a false sense of security while also exposing the site owner to liability claims.
Simply put, the visitor on one of "flexible" SSL connection may feel absolutely safe behind the encryption and will be willing provide sensitive data, not knowing that the 'server to cloud' route is not encrypted at all and can be intercepted (i.e. by backdoor shells).
It was interesting to visit here and see others reach the same conclusion. +1
Please know that as website owner you may be liable for any unwanted exposure such setup may cause.
My suggestion is to do the responsible thing and to invest in SSL certificate or even create a self signed one (to use for encryption of 'cloud to server' route). |
15,795,748 | I am hosting an ASP.NET MVC 4 site on AppHarbor (which uses Amazon EC2), and I'm using CloudFlare for Flexible SSL. I'm having a problem with redirect loops (310) when trying to use RequireHttps. The problem is that, like EC2, CloudFlare terminates the SSL before forwarding the request onto the server. However, whereas Amazon sets the X-Forwarded-Proto header so that you can handle the request with a custom filter, CloudFlare does not appear to. Or if they do, I don't know how they are doing it, since I can't intercept traffic at that level. I've tried the solutions for Amazon EC2, but they don't seem to help with CloudFlare.
Has anyone experienced this issue, or know enough about CloudFlare to help? | 2013/04/03 | [
"https://Stackoverflow.com/questions/15795748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1141679/"
] | The `X-Forwarded-Proto` header is intentionally overridden by AppHarbor's load balancers to the actual scheme of the request.
Note that while CloudFlare's flexible SSL option may add slightly more security, there is still unencrypted traffic travelling over the public internet from CloudFlare to AppHarbor. This arguably defies the purpose of SSL for anything else than appearances and reducing the number of attack vectors (like packet sniffing on the user's local network) - i.e. it may look "professional" to your users, but it actually is still insecure.
That's less than ideal particularly since AppHarbor supports both installing your own certificates and includes piggyback SSL out of the box. CloudFlare also recommends using "Full SSL" for scenarios where the origin servers/service support SSL. So you have a couple of options:
* Continue to use the insecure "Flexible SSL" option, but instead of inspecting the `X-Forwarded-Proto` header in your custom `RequireHttps` filter, you should inspect the `scheme` attribute of the `CF-Visitor` header. There are more details in [this discussion](https://support.cloudflare.com/entries/22088068-How-do-I-redirect-HTTPS-traffic-with-Flexible-SSL-and-Apache-).
* Use "Full SSL" and point CloudFlare to your `*.apphb.com` hostname. This way you can use the complimentary piggyback SSL that is enabled by default with your AppHarbor app. You'll have to override the `Host` header on CloudFlare to make this work and [here's a blog post on how to do that](http://blog.cloudflare.com/ssl-on-custom-domains-for-appengine-and-other). This will of course make requests to your app appear like they were made to your `*.apphb.com` domain - so if for instance you automatically redirect requests to a "canonical" URL or generate absolute URLs you'll likely have to take this into consideration.
* Upload your certificate and add a custom hostname to AppHarbor. Then turn on "Full SSL" on CloudFlare. This way the host header will remain the same and your application will continue to work without any modifications. You can read more about the SSL options offered by AppHarbor in [this knowledge base article](http://support.appharbor.com/kb/tips-and-tricks/ssl-and-certificates). | Or you could just get a free one year SSL cert signed by StartCom and upload that to AppHarbor.
Then you can call it a day and pat yourself on the back! That is until future you one year from now has to purchase a cert =). |
27,343,087 | I am developing an application which requires the youtube api.
I am stuck at a point where i need the keywords of a youtube channel. I am getting all keywords in a string.
```
$string = 'php java "john smith" plugins';
```
I am trying to get the above keywords in an array. I can use `explode(' ',$string)` but the problem is `john smith` itself is a keyword. I am expecting my array to be like this:
```
array(
[0] => 'php',
[1] => 'java',
[2] => 'john smith',
[3] => 'plugins'
)
```
Any quick/dirty solution to achieve this ? | 2014/12/07 | [
"https://Stackoverflow.com/questions/27343087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1015448/"
] | ```
char *get_set(int size, char *set){// size : size of set as buffer size
char ch;
int i;
for(i = 0; i < size-1 && (ch=getchar()) != '\n'; ){
if(!isspace(ch))
set[i++] = ch;
}
set[i] = '\0';
return set;
}
``` | You can use [getchar](http://linux.die.net/man/3/getchar):
```
while (((ch = getchar()) != '\n')) {
if(!isspace(ch))
inset[i++] = ch;
}
```
getchar reads the next character from stdin and returns it as an unsigned char cast to an int, or EOF on end of file or error. |
27,343,087 | I am developing an application which requires the youtube api.
I am stuck at a point where i need the keywords of a youtube channel. I am getting all keywords in a string.
```
$string = 'php java "john smith" plugins';
```
I am trying to get the above keywords in an array. I can use `explode(' ',$string)` but the problem is `john smith` itself is a keyword. I am expecting my array to be like this:
```
array(
[0] => 'php',
[1] => 'java',
[2] => 'john smith',
[3] => 'plugins'
)
```
Any quick/dirty solution to achieve this ? | 2014/12/07 | [
"https://Stackoverflow.com/questions/27343087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1015448/"
] | ```
char *get_set(int size, char *set){// size : size of set as buffer size
char ch;
int i;
for(i = 0; i < size-1 && (ch=getchar()) != '\n'; ){
if(!isspace(ch))
set[i++] = ch;
}
set[i] = '\0';
return set;
}
``` | once try these,
char \*
```
get_set(char *set)
{
char inset[SETSIZ];
char ch = ' ';
int i = 0;
while(ch != '\n'){
if(ch!=32)// ASCII 32 for whitespaces
inset[i] = scanf(" %c", &ch);
i++;
}
set[strlen(inset)] = '\0';
return (set);
}
``` |
25,382,103 | I have created a Login page using MVC Razor. The page contains a User name & Password to be entered and two button Login and SignUp button.
I have applied required field validation for both textboxes. It works fine when i click Login button. For Signup button i want the page to be redirected to signup page. But when i click SignUp button, it throws error as UserName and Password are required.
How to check for validation when only login button is clicked.
View page:
```
<body>
@using (Html.BeginForm("CheckLogin", "Login"))
{
<div>
<div>
<img src="@Url.Content("../../Content/Images/Logo.png")" alt="logo" style="margin-top:17px;" />@*width="184" height="171"*@
</div>
<div class="LoginBg">
<h3 class="LoginHdng">
@Html.Label("lblLogin", "Login")
</h3>
<table style="width: 745px;">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td style="font-size: 20px; text-align: right; width: 250px">
@Html.LabelFor(model => model.FirstName, "User Name: ")
</td>
<td>
@Html.TextBoxFor(model => model.FirstName, new { @class = "txtBox" })
@Html.ValidationMessageFor(model => model.FirstName)
</td>
</tr>
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td style="font-size: 20px; text-align: right;">
@Html.LabelFor(model => model.Password, "Password: ")
</td>
<td>
@Html.PasswordFor(model => model.Password, new { @class = "txtBox" })
@Html.ValidationMessageFor(model => model.Password)
</td>
</tr>
<tr>
<td colspan="2" style="font-size: 16px; text-align: center; color: Red;">
<br />
@TempData["Error"]
</td>
</tr>
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" value="Login" name="Command" class="loginBtn" />
<input type="submit" value="SignUp" name="Command" class="loginBtn" />
</td>
</tr>
</table>
</div>
</div>
}
</body>
```
Controller:
```
[HttpPost]
public ActionResult CheckLogin(FormCollection coll)//, string command
{
if (coll["Command"] == "Login")
{
using (var db = new MVC_DBEntities())
{
if (db.tbl_UserDetails.ToList().Select(m => m.FirstName == coll["FirstName"] && m.Password == coll["Password"]).FirstOrDefault())
{
TempData["Error"] = "";
return this.RedirectToAction("Index", "Home");
}
else
{
TempData["Error"] = "Invalid UserName/Password";
return this.RedirectToAction("Login", "Login");
}
}
}
else if (coll["Command"] == "SignUp")
{
return this.RedirectToAction("SignUp", "SignUp");
}
else
{
return this.RedirectToAction("Login", "Login");
}
}
```
Thanks in Advance... | 2014/08/19 | [
"https://Stackoverflow.com/questions/25382103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3211705/"
] | Take `Signup` button as **input type button** not **input type submit** as shown :-
```
<input type="button" value="SignUp" name="Command" class="loginBtn" id="SignUpBtn" />
```
and use some **Jquery/Javascript** to go to `SignUp Page` as :-
```
$("#SignUpBtn").click(function(){
window.location.href="/SignUp/SignUp";
});
``` | There are several ways.
1. Can't you put "SignUp" as link and use css to appear like button.
2. wrap "SingUp" button around a separate form
```
<form action="/signup" method="get">
<input type="submit" />
</form>
```
1. Or As suggested use button with value property. u can use js to redirect or in controller u can look for value and redirect. |
25,382,103 | I have created a Login page using MVC Razor. The page contains a User name & Password to be entered and two button Login and SignUp button.
I have applied required field validation for both textboxes. It works fine when i click Login button. For Signup button i want the page to be redirected to signup page. But when i click SignUp button, it throws error as UserName and Password are required.
How to check for validation when only login button is clicked.
View page:
```
<body>
@using (Html.BeginForm("CheckLogin", "Login"))
{
<div>
<div>
<img src="@Url.Content("../../Content/Images/Logo.png")" alt="logo" style="margin-top:17px;" />@*width="184" height="171"*@
</div>
<div class="LoginBg">
<h3 class="LoginHdng">
@Html.Label("lblLogin", "Login")
</h3>
<table style="width: 745px;">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td style="font-size: 20px; text-align: right; width: 250px">
@Html.LabelFor(model => model.FirstName, "User Name: ")
</td>
<td>
@Html.TextBoxFor(model => model.FirstName, new { @class = "txtBox" })
@Html.ValidationMessageFor(model => model.FirstName)
</td>
</tr>
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td style="font-size: 20px; text-align: right;">
@Html.LabelFor(model => model.Password, "Password: ")
</td>
<td>
@Html.PasswordFor(model => model.Password, new { @class = "txtBox" })
@Html.ValidationMessageFor(model => model.Password)
</td>
</tr>
<tr>
<td colspan="2" style="font-size: 16px; text-align: center; color: Red;">
<br />
@TempData["Error"]
</td>
</tr>
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" value="Login" name="Command" class="loginBtn" />
<input type="submit" value="SignUp" name="Command" class="loginBtn" />
</td>
</tr>
</table>
</div>
</div>
}
</body>
```
Controller:
```
[HttpPost]
public ActionResult CheckLogin(FormCollection coll)//, string command
{
if (coll["Command"] == "Login")
{
using (var db = new MVC_DBEntities())
{
if (db.tbl_UserDetails.ToList().Select(m => m.FirstName == coll["FirstName"] && m.Password == coll["Password"]).FirstOrDefault())
{
TempData["Error"] = "";
return this.RedirectToAction("Index", "Home");
}
else
{
TempData["Error"] = "Invalid UserName/Password";
return this.RedirectToAction("Login", "Login");
}
}
}
else if (coll["Command"] == "SignUp")
{
return this.RedirectToAction("SignUp", "SignUp");
}
else
{
return this.RedirectToAction("Login", "Login");
}
}
```
Thanks in Advance... | 2014/08/19 | [
"https://Stackoverflow.com/questions/25382103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3211705/"
] | You can simply add a cancel class to the button that does not need the validation as follows:
```
<input type="submit" value="SignUp" name="Command" class="loginBtn cancel" />
```
This will circumvent validation, provided you are using the built in jQuery unobtrusive validation. | There are several ways.
1. Can't you put "SignUp" as link and use css to appear like button.
2. wrap "SingUp" button around a separate form
```
<form action="/signup" method="get">
<input type="submit" />
</form>
```
1. Or As suggested use button with value property. u can use js to redirect or in controller u can look for value and redirect. |
11,838 | My website can only be accessed by authenticated users. How can I automatically make the author's name the user's name without giving users the option to input anything else in the name field? | 2011/09/22 | [
"https://drupal.stackexchange.com/questions/11838",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/1273/"
] | Custom datepicker options are now supported (as of Date module version 7.x-2.6) by setting the necessary values with `#datepicker_options`. Alex's use case of a custom form element to display only future dates would look like this:
```
$form['date'] = array(
'#prefix'=>t('When do you want to start the featured campaign?'),
'#date_format' => 'Y-m-d',
'#date_year_range' => '0:+1',
'#type' => 'date_popup',
'#weight'=>0,
'#datepicker_options' => array('minDate' => 0),
);
``` | As far as I know by default you do not have such option. The easiest way would be just to check it in validate function, and return an error if selected date is not from future.
On the other hand, a quick Google search returned for example this question - [how to restrict the user to enter only today to future dates. using datepicker](http://drupal.org/node/927582) - however you would need to test for yourself if it really works... |
11,838 | My website can only be accessed by authenticated users. How can I automatically make the author's name the user's name without giving users the option to input anything else in the name field? | 2011/09/22 | [
"https://drupal.stackexchange.com/questions/11838",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/1273/"
] | Date use Jquery DatePicker:
<https://jqueryui.com/datepicker/#min-max>
Then, We must do that from javascript:
```
$(function () {
$("#myIdinputDatePicker").datepicker({ minDate: -0, maxDate: "+1M +10D" });
});
```
That's it, leaving the Drupal World. | As far as I know by default you do not have such option. The easiest way would be just to check it in validate function, and return an error if selected date is not from future.
On the other hand, a quick Google search returned for example this question - [how to restrict the user to enter only today to future dates. using datepicker](http://drupal.org/node/927582) - however you would need to test for yourself if it really works... |
11,838 | My website can only be accessed by authenticated users. How can I automatically make the author's name the user's name without giving users the option to input anything else in the name field? | 2011/09/22 | [
"https://drupal.stackexchange.com/questions/11838",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/1273/"
] | Custom datepicker options are now supported (as of Date module version 7.x-2.6) by setting the necessary values with `#datepicker_options`. Alex's use case of a custom form element to display only future dates would look like this:
```
$form['date'] = array(
'#prefix'=>t('When do you want to start the featured campaign?'),
'#date_format' => 'Y-m-d',
'#date_year_range' => '0:+1',
'#type' => 'date_popup',
'#weight'=>0,
'#datepicker_options' => array('minDate' => 0),
);
``` | Date use Jquery DatePicker:
<https://jqueryui.com/datepicker/#min-max>
Then, We must do that from javascript:
```
$(function () {
$("#myIdinputDatePicker").datepicker({ minDate: -0, maxDate: "+1M +10D" });
});
```
That's it, leaving the Drupal World. |
2,646,463 | I have a XMLDocument like:
```
<Folder name="test">
<Folder name="test2">
<File>TestFile</File>
</Folder>
</Folder>
```
I want only the folder´s, not the files. So, how to delete / manipulate the XML Document in c# to delete / remove ALL elements in the document?
Thanks! | 2010/04/15 | [
"https://Stackoverflow.com/questions/2646463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/298926/"
] | If you can use `XDocument` and LINQ, you can do
```
XDocument doc = XDocument.Load(filename) // or XDocument.Parse(string)
doc.Root.Descendants().Where(e => e.Name == "File").Remove();
```
-- edited out an error | To remove a node from an `XMLDocument` (see Jens' answer for remove node form `XDocument`)
```
XmlDocument doc = XmlDocument.Load(filename); // or XmlDocument.LoadXml(string)
XmlNodeList nodes = doc.SelectNodes("//file");
foreach(XmlNode node in nodes) {
node.ParentNode.RemoveChild(node);
}
```
Watch for the possible null exception if node.ParentNode is null. |
45,041,702 | My Application wants to Request for Wifi Permission on the start.So far I have managed to give permission through **Setting**.But I don't want to Do that anymore.So far I have seen this previous [Question](https://stackoverflow.com/questions/40301628/how-to-request-permissions-during-run-time-when-using-gluon-mobile-environment/40370076?noredirect=1#comment77053866_40370076).I could understand a bit.but it's not Enough. I created a ***.class*** that that manages Wifi Activity like turning ON/OFF , checking wifi state.It works well if Wifi permission is *granted*.but if not it does'nt work.
Here's the **WifiController.class** that I have created.
```
import android.content.Context;
import android.net.wifi.WifiManager;
import javafxports.android.FXActivity;
public class WifiController implements WifiInterface
{
WifiManager wifiManager=null;
WifiController()
{
wifiManager = (WifiManager)FXActivity.getInstance().getSystemService(Context.WIFI_SERVICE);
}
WifiManager getWifimanager()
{
return wifiManager;
}
public boolean isTurnedOn()
{
return wifiManager.isWifiEnabled();
}
public boolean turnOn()
{
wifiManager.setWifiEnabled(true);
return true;
}
public boolean turnOff()
{
wifiManager.setWifiEnabled(false);
return true;
}
}
```
So, Please Enlighten Me. Thanks in Advance. | 2017/07/11 | [
"https://Stackoverflow.com/questions/45041702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7315145/"
] | The Android Developers Website has a great walkthrough example on how runtime permissions work here:
<https://developer.android.com/training/permissions/requesting.html>
Also don't forget to add the permissions into your manifest as well. | Heavily based on this [answer](https://stackoverflow.com/questions/40301628/how-to-request-permissions-during-run-time-when-using-gluon-mobile-environment/40370076?noredirect=1#comment77053866_40370076), I created the following class to request permissions on the app start when android version >= Marshmallow:
```
public class AndroidPlatform {
private static final String KEY_PERMISSIONS = "permissions";
private static final String KEY_REQUEST_CODE = "requestCode";
private static final int REQUEST_CODE_ASK_PERMISSIONS = 246;
private static final int REQUEST_CODE = 123;
private final FXActivity activity;
public AndroidPlatform() {
activity = FXActivity.getInstance();
}
public void checkPermissions() {
if (Build.VERSION.SDK_INT >= MARSHMALLOW) {
List<String> requiredPermissions = new ArrayList<>();
addPermission(activity, requiredPermissions , Manifest.permission.ACCESS_COARSE_LOCATION);
// additional required permissions
if (!requiredPermissions.isEmpty()) {
Intent permIntent = new Intent(activity, PermissionRequestActivity.class);
permIntent.putExtra(KEY_PERMISSIONS, requiredPermissions.toArray(new String[requiredPermissions .size()]));
permIntent.putExtra(KEY_REQUEST_CODE, REQUEST_CODE);
activity.startActivityForResult(permIntent, REQUEST_CODE_ASK_PERMISSIONS);
}
}
}
private void addPermission(Activity activity, List<String> permissionsList, String permission) {
if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
}
}
public static class PermissionRequestActivity extends Activity {
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
FXActivity.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
finish();
}
@Override
protected void onStart() {
super.onStart();
String[] permissions = this.getIntent().getStringArrayExtra(KEY_PERMISSIONS);
int requestCode = this.getIntent().getIntExtra(KEY_REQUEST_CODE, 0);
ActivityCompat.requestPermissions(this, permissions, requestCode);
}
}
}
```
In your AndroidManifest.xml you have to add the corresponding activity:
```
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<activity android:name="yourpackage.AndroidPlatform$PermissionRequestActivity" />
```
Also you have to add the android-support-library to your build.gradle:
```
dependencies {
androidCompile files('libs/android-support-v4.jar')
compileNoRetrolambda files('libs/android-support-v4.jar')
}
```
For further information regarding wifiManager / permissions see [link](http://www.intentfilter.com/2016/08/programatically-connecting-to-wifi.html) |
45,041,702 | My Application wants to Request for Wifi Permission on the start.So far I have managed to give permission through **Setting**.But I don't want to Do that anymore.So far I have seen this previous [Question](https://stackoverflow.com/questions/40301628/how-to-request-permissions-during-run-time-when-using-gluon-mobile-environment/40370076?noredirect=1#comment77053866_40370076).I could understand a bit.but it's not Enough. I created a ***.class*** that that manages Wifi Activity like turning ON/OFF , checking wifi state.It works well if Wifi permission is *granted*.but if not it does'nt work.
Here's the **WifiController.class** that I have created.
```
import android.content.Context;
import android.net.wifi.WifiManager;
import javafxports.android.FXActivity;
public class WifiController implements WifiInterface
{
WifiManager wifiManager=null;
WifiController()
{
wifiManager = (WifiManager)FXActivity.getInstance().getSystemService(Context.WIFI_SERVICE);
}
WifiManager getWifimanager()
{
return wifiManager;
}
public boolean isTurnedOn()
{
return wifiManager.isWifiEnabled();
}
public boolean turnOn()
{
wifiManager.setWifiEnabled(true);
return true;
}
public boolean turnOff()
{
wifiManager.setWifiEnabled(false);
return true;
}
}
```
So, Please Enlighten Me. Thanks in Advance. | 2017/07/11 | [
"https://Stackoverflow.com/questions/45041702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7315145/"
] | You have ask for the permission at run time:
```
if (ContextCompat.checkSelfPermission(thisActivity,Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSION);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
```
and than do what ever you want (if the user grand the permission):
```
@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
} else {
// User refused to grant permission.
}
}
}
```
You can read more here:
<https://developer.android.com/training/permissions/requesting.html> | Heavily based on this [answer](https://stackoverflow.com/questions/40301628/how-to-request-permissions-during-run-time-when-using-gluon-mobile-environment/40370076?noredirect=1#comment77053866_40370076), I created the following class to request permissions on the app start when android version >= Marshmallow:
```
public class AndroidPlatform {
private static final String KEY_PERMISSIONS = "permissions";
private static final String KEY_REQUEST_CODE = "requestCode";
private static final int REQUEST_CODE_ASK_PERMISSIONS = 246;
private static final int REQUEST_CODE = 123;
private final FXActivity activity;
public AndroidPlatform() {
activity = FXActivity.getInstance();
}
public void checkPermissions() {
if (Build.VERSION.SDK_INT >= MARSHMALLOW) {
List<String> requiredPermissions = new ArrayList<>();
addPermission(activity, requiredPermissions , Manifest.permission.ACCESS_COARSE_LOCATION);
// additional required permissions
if (!requiredPermissions.isEmpty()) {
Intent permIntent = new Intent(activity, PermissionRequestActivity.class);
permIntent.putExtra(KEY_PERMISSIONS, requiredPermissions.toArray(new String[requiredPermissions .size()]));
permIntent.putExtra(KEY_REQUEST_CODE, REQUEST_CODE);
activity.startActivityForResult(permIntent, REQUEST_CODE_ASK_PERMISSIONS);
}
}
}
private void addPermission(Activity activity, List<String> permissionsList, String permission) {
if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
}
}
public static class PermissionRequestActivity extends Activity {
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
FXActivity.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
finish();
}
@Override
protected void onStart() {
super.onStart();
String[] permissions = this.getIntent().getStringArrayExtra(KEY_PERMISSIONS);
int requestCode = this.getIntent().getIntExtra(KEY_REQUEST_CODE, 0);
ActivityCompat.requestPermissions(this, permissions, requestCode);
}
}
}
```
In your AndroidManifest.xml you have to add the corresponding activity:
```
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<activity android:name="yourpackage.AndroidPlatform$PermissionRequestActivity" />
```
Also you have to add the android-support-library to your build.gradle:
```
dependencies {
androidCompile files('libs/android-support-v4.jar')
compileNoRetrolambda files('libs/android-support-v4.jar')
}
```
For further information regarding wifiManager / permissions see [link](http://www.intentfilter.com/2016/08/programatically-connecting-to-wifi.html) |
45,062,106 | So i have two different queries as follows:
```
Query1
CPT Resource 1 2 3 4 5
2017-06-12 RM1 5.00 5.00 4.00 4.00 2.00
2017-06-12 RM2 3.00 6.00 4.00 7.00 4.00
2017-06-12 RM3 3.00 4.00 6.00 8.00 6.00
2017-06-13 RM1 3.00 7.00 5.00 3.00 5.00
2017-06-13 RM2 4.00 5.00 4.00 2.00 4.00
2017-06-13 RM3 2.00 4.00 5.00 2.00 7.00
2017-06-14 RM1 2.00 4.00 6.00 4.00 2.00
2017-06-14 RM2 6.00 5.00 4.00 5.00 2.00
2017-06-14 RM3 5.00 3.00 7.00 4.00 5.00
```
and
```
Query2
CPT Resource 1 2 3 4 5
2017-06-12 RM1 0.00 -2.00 0.00 0.00 -2.00
2017-06-12 RM2 -3.00 -3.00 0.00 0.00 0.00
2017-06-12 RM3 -1.00 -3.00 0.00 0.00 0.00
2017-06-13 RM1 0.00 -1.00 0.00 0.00 0.00
2017-06-13 RM2 0.00 -1.00 -1.00 -2.00 -2.00
2017-06-13 RM3 -2.00 -3.00 -1.00 0.00 0.00
2017-06-14 RM1 0.00 0.00 0.00 0.00 0.00
2017-06-14 RM2 0.00 -4.00 -3.00 -2.00 0.00
2017-06-14 RM3 0.00 -3.00 -1.00 0.00 -2.00
```
With these two queries how would I go about creating a new query that multiplies data from query1 with the corresponding number in query 2 that is in the same position based on that date, resource, and the hour (which are the headings 1, 2, 3, 4, and 5). I also want only positive numbers so the new data should be multiplied by -1.
If I do this by hand the new table should look like this:
```
Query3
CPT Resource 1 2 3 4 5
2017-06-12 RM1 0.00 10.00 0.00 0.00 4.00
2017-06-12 RM2 9.00 18.00 0.00 0.00 0.00
2017-06-12 RM3 3.00 12.00 0.00 0.00 0.00
2017-06-13 RM1 0.00 7.00 0.00 0.00 0.00
2017-06-13 RM2 0.00 5.00 4.00 4.00 8.00
2017-06-13 RM3 4.00 12.00 5.00 0.00 0.00
2017-06-14 RM1 0.00 0.00 0.00 0.00 0.00
2017-06-14 RM2 0.00 20.00 12.00 10.00 0.00
2017-06-14 RM3 0.00 9.00 7.00 0.00 10.00
``` | 2017/07/12 | [
"https://Stackoverflow.com/questions/45062106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8249331/"
] | Just join for the key field and use `ABS()` to return a positive result.
```
SELECT Q1.CPT,
Q1.Resource,
ABS(Q1.[1] * Q2.[1]) as [1],
ABS(Q1.[2] * Q2.[2]) as [2],
ABS(Q1.[3] * Q2.[3]) as [3],
ABS(Q1.[4] * Q2.[4]) as [4],
ABS(Q1.[5] * Q2.[5]) as [5]
FROM Query1 Q1
JOIN Query2 Q2
ON Q1.CPT = Q2.CPT
AND Q1.Resourece = Q2.Resource
``` | You need to join on CPT and Resource, returning table1.1 \* table2.1 as 1, like so:
```
SELECT t1.1 * t2.1 as 1 from t1 join t2 on t1.CPT = t2.CPT and t1.Resource = t2.Resource
``` |
45,062,106 | So i have two different queries as follows:
```
Query1
CPT Resource 1 2 3 4 5
2017-06-12 RM1 5.00 5.00 4.00 4.00 2.00
2017-06-12 RM2 3.00 6.00 4.00 7.00 4.00
2017-06-12 RM3 3.00 4.00 6.00 8.00 6.00
2017-06-13 RM1 3.00 7.00 5.00 3.00 5.00
2017-06-13 RM2 4.00 5.00 4.00 2.00 4.00
2017-06-13 RM3 2.00 4.00 5.00 2.00 7.00
2017-06-14 RM1 2.00 4.00 6.00 4.00 2.00
2017-06-14 RM2 6.00 5.00 4.00 5.00 2.00
2017-06-14 RM3 5.00 3.00 7.00 4.00 5.00
```
and
```
Query2
CPT Resource 1 2 3 4 5
2017-06-12 RM1 0.00 -2.00 0.00 0.00 -2.00
2017-06-12 RM2 -3.00 -3.00 0.00 0.00 0.00
2017-06-12 RM3 -1.00 -3.00 0.00 0.00 0.00
2017-06-13 RM1 0.00 -1.00 0.00 0.00 0.00
2017-06-13 RM2 0.00 -1.00 -1.00 -2.00 -2.00
2017-06-13 RM3 -2.00 -3.00 -1.00 0.00 0.00
2017-06-14 RM1 0.00 0.00 0.00 0.00 0.00
2017-06-14 RM2 0.00 -4.00 -3.00 -2.00 0.00
2017-06-14 RM3 0.00 -3.00 -1.00 0.00 -2.00
```
With these two queries how would I go about creating a new query that multiplies data from query1 with the corresponding number in query 2 that is in the same position based on that date, resource, and the hour (which are the headings 1, 2, 3, 4, and 5). I also want only positive numbers so the new data should be multiplied by -1.
If I do this by hand the new table should look like this:
```
Query3
CPT Resource 1 2 3 4 5
2017-06-12 RM1 0.00 10.00 0.00 0.00 4.00
2017-06-12 RM2 9.00 18.00 0.00 0.00 0.00
2017-06-12 RM3 3.00 12.00 0.00 0.00 0.00
2017-06-13 RM1 0.00 7.00 0.00 0.00 0.00
2017-06-13 RM2 0.00 5.00 4.00 4.00 8.00
2017-06-13 RM3 4.00 12.00 5.00 0.00 0.00
2017-06-14 RM1 0.00 0.00 0.00 0.00 0.00
2017-06-14 RM2 0.00 20.00 12.00 10.00 0.00
2017-06-14 RM3 0.00 9.00 7.00 0.00 10.00
``` | 2017/07/12 | [
"https://Stackoverflow.com/questions/45062106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8249331/"
] | Just join for the key field and use `ABS()` to return a positive result.
```
SELECT Q1.CPT,
Q1.Resource,
ABS(Q1.[1] * Q2.[1]) as [1],
ABS(Q1.[2] * Q2.[2]) as [2],
ABS(Q1.[3] * Q2.[3]) as [3],
ABS(Q1.[4] * Q2.[4]) as [4],
ABS(Q1.[5] * Q2.[5]) as [5]
FROM Query1 Q1
JOIN Query2 Q2
ON Q1.CPT = Q2.CPT
AND Q1.Resourece = Q2.Resource
``` | you can use simple join as below
```
Select q1.CPT, q1.[Resource]
, [1] = abs(q1.[1]*q2.[1])
, [2] = abs(q1.[2]*q2.[2])
, [3] = abs(q1.[3]*q2.[3])
, [4] = abs(q1.[4]*q2.[4])
, [5] = abs(q1.[5]*q2.[5])
from Query1 q1
join Query2 q2
on q1.CPT = q2.CPT
and q1.[Resource] = q2.[Resource]
```
replace query1 and 2 with your sub query if required |
45,062,106 | So i have two different queries as follows:
```
Query1
CPT Resource 1 2 3 4 5
2017-06-12 RM1 5.00 5.00 4.00 4.00 2.00
2017-06-12 RM2 3.00 6.00 4.00 7.00 4.00
2017-06-12 RM3 3.00 4.00 6.00 8.00 6.00
2017-06-13 RM1 3.00 7.00 5.00 3.00 5.00
2017-06-13 RM2 4.00 5.00 4.00 2.00 4.00
2017-06-13 RM3 2.00 4.00 5.00 2.00 7.00
2017-06-14 RM1 2.00 4.00 6.00 4.00 2.00
2017-06-14 RM2 6.00 5.00 4.00 5.00 2.00
2017-06-14 RM3 5.00 3.00 7.00 4.00 5.00
```
and
```
Query2
CPT Resource 1 2 3 4 5
2017-06-12 RM1 0.00 -2.00 0.00 0.00 -2.00
2017-06-12 RM2 -3.00 -3.00 0.00 0.00 0.00
2017-06-12 RM3 -1.00 -3.00 0.00 0.00 0.00
2017-06-13 RM1 0.00 -1.00 0.00 0.00 0.00
2017-06-13 RM2 0.00 -1.00 -1.00 -2.00 -2.00
2017-06-13 RM3 -2.00 -3.00 -1.00 0.00 0.00
2017-06-14 RM1 0.00 0.00 0.00 0.00 0.00
2017-06-14 RM2 0.00 -4.00 -3.00 -2.00 0.00
2017-06-14 RM3 0.00 -3.00 -1.00 0.00 -2.00
```
With these two queries how would I go about creating a new query that multiplies data from query1 with the corresponding number in query 2 that is in the same position based on that date, resource, and the hour (which are the headings 1, 2, 3, 4, and 5). I also want only positive numbers so the new data should be multiplied by -1.
If I do this by hand the new table should look like this:
```
Query3
CPT Resource 1 2 3 4 5
2017-06-12 RM1 0.00 10.00 0.00 0.00 4.00
2017-06-12 RM2 9.00 18.00 0.00 0.00 0.00
2017-06-12 RM3 3.00 12.00 0.00 0.00 0.00
2017-06-13 RM1 0.00 7.00 0.00 0.00 0.00
2017-06-13 RM2 0.00 5.00 4.00 4.00 8.00
2017-06-13 RM3 4.00 12.00 5.00 0.00 0.00
2017-06-14 RM1 0.00 0.00 0.00 0.00 0.00
2017-06-14 RM2 0.00 20.00 12.00 10.00 0.00
2017-06-14 RM3 0.00 9.00 7.00 0.00 10.00
``` | 2017/07/12 | [
"https://Stackoverflow.com/questions/45062106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8249331/"
] | Just join for the key field and use `ABS()` to return a positive result.
```
SELECT Q1.CPT,
Q1.Resource,
ABS(Q1.[1] * Q2.[1]) as [1],
ABS(Q1.[2] * Q2.[2]) as [2],
ABS(Q1.[3] * Q2.[3]) as [3],
ABS(Q1.[4] * Q2.[4]) as [4],
ABS(Q1.[5] * Q2.[5]) as [5]
FROM Query1 Q1
JOIN Query2 Q2
ON Q1.CPT = Q2.CPT
AND Q1.Resourece = Q2.Resource
``` | Assuming that you have two tables in question as t1 and t2 then your query should be
```
select
t1.CPT,
t1.resource,
ABS(t1.[1]*t2.[1]) as [1],
ABS(t1.[2]*t2.[2]) as [2],
ABS(t1.[3]*t2.[3]) as [3],
ABS(t1.[4]*t2.[4]) as [4],
ABS(t1.[5]*t2.[5]) as [5]
from
t1 join t2
on t1.CPT=t2.CPt
and t1.resource=t2.resource
```
In case you don't have tables t1 and t2 and these are your query results; please encapsulate your queries as subquery with alias of t1 and t2
```
select
t1.CPT,
t1.resource,
ABS(t1.[1]*t2.[1]) as [1],
ABS(t1.[2]*t2.[2]) as [2],
ABS(t1.[3]*t2.[3]) as [3],
ABS(t1.[4]*t2.[4]) as [4],
ABS(t1.[5]*t2.[5]) as [5]
from
--( your query 1)
t1 join
--( your query 2)
t2
on t1.CPT=t2.CPt
and t1.resource=t2.resource
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.