text:
Q: Calling Parent to open settings I'm new to react and this is my current structure using material UI
<Setting/>
  <Paper className={paperHeight}>
      <Title>Settings</Title>
         <SettingTable />
  </Paper>

The setting component returns a button that will open a modal on click. Inside my settingstable component I have an edit button on each row that I would like to simulate the onclick of the Setting component so that the modal opens.
Inside the setting component I have the following to open my modal
const [open, setOpen] = React.useState(false);

 const handleClickOpen = () => {
    setOpen(true);
 };

I don't know what to search to get the answer. I've tried
"Sending props to parent" etc.. but cannot figure out what or how to do it.
If anyone can point me in the right direction,
Thank you

A: *

*As per my understanding, that "Setting" component is rendering "Setting Table" and "Button"(that opens modal).

*"Setting Table" also have button, that opens same modal. Hence you can use "handleClickOpen" for both scenarios.
    <Setting>
        <Paper className={paperHeight}>
            <Title>Settings</Title>
            <SettingTable modalHandler={handleClickOpen}/>
        </Paper>
    </Setting>

*You can have modalHandler function and pass it as a prop to the child. Link received modalHandler prop to Onclick(edit button) in SettingTable.
    <SettingTable>
        <Button onclick={props.modalHandler}>Edit</Button>
    </SettingTable>

*If "SettingTable" is not rendered by "Setting" component and modalHandler is defined in "Setting" component, I would request you to move modalHandler to the parent, so that it can be shared by its child components.


text:
Q: Spring ACL & Inheritance I'm currently evaluating spring ACL for a web project. The domain model (JPA) of the project consists basically of a hierarchy starting with Company -> Client -> Product and so on. Users (which are members of a company) of the app are only allowed to see Products which belong to their Company.
I don't see any other way than assigning each Company it's own Role (e.g. ROLE_COMPANY_A, ROLE_COMPANY_B, etc), which is persisted more or less hardcoded in the ACL-tables (This is most probably not the best design; open for suggestions...)
While I was able to hook up the Spring ACL with the JPA Layer (Aspect on the various Repository's save()-Methods), I have troubles finding the proper parent ACL Object when inserting a new Entity. To find out to which Company an Entity belongs I must traverse the Object-hierarchy to find the proper Role (i.e. ROLE_COMPANY_A) within the Aspect (which is even worse, since an Aspect should not contain any app-knowledge).
So the question is, if anyone has used spring ACL in a scenario like this one? Since we are not bound to spring ACL, another solution/framework may also be considered. Bascially I really want to avoid the traversal of the object hierarchy to find out the proper Role.
tnx & regards

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sizing and alignment issues with CSS grid I am working on a messaging app, but I am having trouble making the conversation float properly. Right now I am using a section HTML tag to hold the contents of each message, which contains the image of the sender, the message, the date, and sometimes the reference link.
The issue I am running into is twofold:

*

*Messages that float to the right
, are not floating to the right of the .messages box as I would like them to. I have narrowed this down to being an issue with the grid-template-columns on line 145, but I am not sure a different alternative.

*Messages that are short, such as "hi", should not have a long message box. I figure I'll need to do a minmax, but I'm not exactly sure how I would go about doing this.
Any advice, along with an explanation, would be greatly appreciated. If you are a more visual person, I've attached a screenshot of what I'm trying to accomplish.

body {margin: 0}

nav {
  position: fixed;
    top: 0; left: 0;
    width: 100vw; height: 65px;
    padding: 0px 20px;
    box-sizing: border-box;
    font-size: 20px;
    font-family: 'Noto Sans JP', sans-serif;
    color: #5F6368;
    background-color: white;
    border-bottom: 1px solid lightgray}

#content {
  display: grid;
  position: fixed;
  top: 60px; left: 0;
  width: 100vw;
  padding: 14px;
  box-sizing: border-box;
  height: calc(100vh - 60px);
  grid-column-gap: 14px;
  grid-row-gap: 30px;
  grid-template-columns: 1fr 3fr;
  grid-template-rows: 220px 1fr;
  grid-template-areas:
    "whochat convo"
    "previews convo";}
/* -------- [WHO CHAT] -------- */
#whochat {
  grid-area: whochat;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  border-radius: 6px;
  border: 1px solid lightgray;}

#whochat img {
  width: 90px;
  clip-path: circle();}

#whochat .title {
  color: #484848;
  font-weight: 800;}

#whochat .lastseen {
  margin-top: 6px;
  color: gray;
  font-size: 14px;
  font-style: italic;}

/* --------[PREVIEWS]-------- */
#previews {
  grid-area: previews;
  border-radius: 6px;
  overflow-y: auto;
  overflow-x: hidden}

#previews .title {
  z-index: 1;
  position: sticky;
  top: 0; left: 0;
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 10px;
  background-color: white}

#previews ul {
  margin: 0;
  padding: 0;
  list-style: none;}

#previews li {
  display: flex;
  align-items: center;
  margin-bottom: 6px}
  #previews li:hover{
    transform: scale(1.007);
    border-radius: 6px;
    background-color: #E9DCF9}

#previews img {
  width: 30px;
  margin: 0px 10px;
  clip-path: circle();}

#previews .name {
  font-size: 18px;}

/* -------- [CONVO] -------- */
#convo {
  grid-area: convo;
  border-radius: 14px;
  background-color: #FCFCFC;
  display: grid;
  grid-template-rows: 1fr 60px;
  grid-template-areas:
    "messages"
    "compose";}

#convo .compose {
  grid-area: compose;
  display: flex;
  align-items: center;
  margin: 6px;}

.compose textarea {
  max-height: 100%;
  padding: 8px 24px;
  margin-right: 8px;
  border-radius: 6px;
  border: 1px solid darkgray;
  flex: 100%;
  box-sizing: border-box;}

.compose .button {
  padding: 8px 24px;
  margin-right: 8px;
  font-size: 18px;
  border-radius: 26px}

#convo .messages {
  grid-area: messages;
  overflow: auto;
  padding: 10px;
  box-sizing: content-box;}

.messages section {
  width: 100%;
  margin-bottom: 20px;}

.messages section.left{
  display: grid;
  grid-template-columns: 45px 60%;
  grid-row-gap: 8px;
  grid-template-areas:
    "img msg"
    "img reference"}

.messages section.right{
  display: grid;
  grid-template-columns: 60% 45px;
  grid-row-gap: 8px;
  grid-template-areas:
    "msg img"
    "reference img"}

.messages section .pic {
  display: flex;
  justify-content: center;
  align-items: flex-end;}

.messages section img {
  grid-area: img;
  width: 30px;
  clip-path: circle();}

.messages section .msg {
  grid-area: msg;
  border-radius: 6px;
  padding: 8px;
  font-size: 18px;
  box-shadow: 1px 1.5px #CECECE}
  .messages section.left .msg {background-color: white;}
  .messages section.right .msg {background-color: #B488E7;}

.messages section .reference {
  grid-area: reference;
  color: gray;
  font-size: 12px;}

.messages section.right .reference {
  display: flex;
  flex-direction: row-reverse}

.messages section .link {
  margin: 0px 16px;
  font-style: italic;}
<link rel="stylesheet" href="https://classcolonies.com/resources/style.css">

John Doe

Last Seen: Mon, Aug 14 at 2:00 pm

Conversations:

        Elon Musk

        Chris Pratt

        This is an example of a message that would take up multiple lines because of the length. Notice that the image appears on the bottom of the message, which is the desired end result.

          1h ago
          Referencing Roanoke Cloze Passage

        This is an example reply. This reply should be floating all the way to the right of the .messages container.

          10m ago
          Referencing Roanoke Cloze Passage

        This response does not have a link attached.

          1h ago

      <textarea></textarea>
      <button class='button purple-btn'>Send</button>

Image of desired end result:

A: Recommendation to question 2
How about max-content? I would not force a big message size on the user. Actually, I'd just make it fit the content. Only set a max-width so that it does not break things.
Edit:
I have added this here:
.messages section .msg {
  [...]
  display: flex;
  justify-self: right;
  [...]
}

Solution to question 1
Did you try justify-content: right; on the righthand section?
Snippet for q1 & q2:

body {
  margin: 0
}

nav {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 65px;
  padding: 0px 20px;
  box-sizing: border-box;
  font-size: 20px;
  font-family: 'Noto Sans JP', sans-serif;
  color: #5F6368;
  background-color: white;
  border-bottom: 1px solid lightgray
}

#content {
  display: grid;
  position: fixed;
  top: 60px;
  left: 0;
  width: 100vw;
  padding: 14px;
  box-sizing: border-box;
  height: calc(100vh - 60px);
  grid-column-gap: 14px;
  grid-row-gap: 30px;
  grid-template-columns: 1fr 3fr;
  grid-template-rows: 220px 1fr;
  grid-template-areas: "whochat convo" "previews convo";
}

/* -------- [WHO CHAT] -------- */

#whochat {
  grid-area: whochat;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  border-radius: 6px;
  border: 1px solid lightgray;
}

#whochat img {
  width: 90px;
  clip-path: circle();
}

#whochat .title {
  color: #484848;
  font-weight: 800;
}

#whochat .lastseen {
  margin-top: 6px;
  color: gray;
  font-size: 14px;
  font-style: italic;
}

/* --------[PREVIEWS]-------- */

#previews {
  grid-area: previews;
  border-radius: 6px;
  overflow-y: auto;
  overflow-x: hidden
}

#previews .title {
  z-index: 1;
  position: sticky;
  top: 0;
  left: 0;
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 10px;
  background-color: white
}

#previews ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

#previews li {
  display: flex;
  align-items: center;
  margin-bottom: 6px
}

#previews li:hover {
  transform: scale(1.007);
  border-radius: 6px;
  background-color: #E9DCF9
}

#previews img {
  width: 30px;
  margin: 0px 10px;
  clip-path: circle();
}

#previews .name {
  font-size: 18px;
}

/* -------- [CONVO] -------- */

#convo {
  grid-area: convo;
  border-radius: 14px;
  background-color: #FCFCFC;
  display: grid;
  grid-template-rows: 1fr 60px;
  grid-template-areas: "messages" "compose";
}

#convo .compose {
  grid-area: compose;
  display: flex;
  align-items: center;
  margin: 6px;
}

.compose textarea {
  max-height: 100%;
  padding: 8px 24px;
  margin-right: 8px;
  border-radius: 6px;
  border: 1px solid darkgray;
  flex: 100%;
  box-sizing: border-box;
}

.compose .button {
  padding: 8px 24px;
  margin-right: 8px;
  font-size: 18px;
  border-radius: 26px
}

#convo .messages {
  grid-area: messages;
  overflow: auto;
  padding: 10px;
  box-sizing: content-box;
}

.messages section {
  width: 100%;
  margin-bottom: 20px;
}

.messages section.left {
  display: grid;
  grid-template-columns: 45px 60%;
  grid-row-gap: 8px;
  grid-template-areas: "img msg" "img reference"
}

.messages section.right {
  display: grid;
  grid-template-columns: 60% 45px;
  grid-row-gap: 8px;
  grid-template-areas: "msg img" "reference img";
  justify-content: right;
}

.messages section .pic {
  display: flex;
  justify-content: center;
  align-items: flex-end;
}

.messages section img {
  grid-area: img;
  width: 30px;
  clip-path: circle();
}

.messages section .msg {
  grid-area: msg;
  display: flex;
  justify-self: right;
  border-radius: 6px;
  padding: 8px;
  font-size: 18px;
  box-shadow: 1px 1.5px #CECECE
}

.messages section.left .msg {
  background-color: white;
}

.messages section.right .msg {
  background-color: #B488E7;
}

.messages section .reference {
  grid-area: reference;
  color: gray;
  font-size: 12px;
}

.messages section.right .reference {
  display: flex;
  flex-direction: row-reverse
}

.messages section .link {
  margin: 0px 16px;
  font-style: italic;
}
<link rel="stylesheet" href="https://classcolonies.com/resources/style.css">

John Doe

Last Seen: Mon, Aug 14 at 2:00 pm

Conversations:

        Elon Musk

        Chris Pratt

        This is an example of a message that would take up multiple lines because of the length. Notice that the image appears on the bottom of the message, which is the desired end result.

          1h ago
          Referencing Roanoke Cloze Passage

        This is an example reply. This reply should be floating all the way to the right of the .messages container.

          10m ago
          Referencing Roanoke Cloze Passage

        Hi.

          10m ago
          Referencing Roanoke Cloze Passage

        This response does not have a link attached.

          1h ago

      <textarea></textarea>
      <button class='button purple-btn'>Send</button>


text:
Q: How to implement UIUserNotificationActionBehavior.TextInput from iOS 9 in iOS 8? I registered UIMutableUserNotificationAction:
let responseTextAction = UIMutableUserNotificationAction()
responseTextAction.identifier = "text"
responseTextAction.title = "New text"
if #available(iOS 9.0, *) {
    responseTextAction.behavior = UIUserNotificationActionBehavior.TextInput
} else {
    // Fallback on earlier versions
}

This is screenshot from iOS 9:

and from iOS 8:

How can I implement text input for iOS 8 also.

A: Text Input for Notifications is only available in iOS 9+. Previous versions will default to a standard notification as you have seen.


text:
Q: What is wrong with my tax calculator program? def taxcalc (tax):

    income = float(raw_input('Welcome to the PAYG Tax calculator,please enter your gross income, and your net income will be displayed.\n'))

    if income <= 18200:
        print income

    elif income >= 18201 and income <= 37000:
        beforetax1 = income * 0.19
        tax = income - beforetax1

    elif income >= 37001 and income <= 80000:
        beforetax2 = income - 3572
        secondtax = beforetax2 * 0.325
        tax = income - secondtax

    elif income >= 80001 and income <= 180000:
        beforetax3 = income - 17547
        thirdtax = beforetax3 * 0.37
        tax = income - thirdtax

    elif income >= 180001:
        beforetax4 = income - 54547
        fourthtax = beforetax4 * 0.45
        tax = income - fourthtax

print 'Your net pay is $',tax

print 'The amount of tax paid is $',beforetax

It does not print anything except for tax.
(EDIT)
def taxcalc ():

    income = decimal.Decimal(raw_input('Welcome to the PAYG Tax calculator, please enter your gross income, and your net income will be displayed.\n'))

    if income <= 18200:
        net = income

    elif income > 18200 and income <= 37000:
        tax = income * 0.19
        net = income - tax

    elif income > 37000 and income <= 80000:
        tax = income - 3572
        tax = tax * 0.325
        net = income - tax

    elif income > 80000 and income <= 180000:
        tax = income - 17547
        tax = tax * 0.37
        net = income - tax

    elif income > 180000:
        tax = income - 54547
        tax = tax * 0.45
        net = income - tax

    print "Your net income is $",net

taxcalc()

A: You have a whole slew of problems here, and you have to fix all of them, including at least the following:

*

*Your taxcalc function sometimes prints a value, sometimes calculates some temporary values and then forgets them and does nothing; the one thing it never does is actually return its values to the caller, e.g., return tax, beforetax1.

*Your taxcalc function takes a tax parameter that it doesn't use. It shouldn't.

*You define a taxcalc function, but never call it anywhere, so it isn't doing any good. You need something like tax, beforetax = taxcalc().

*Your variable names are misleading. You have something named tax which is the net pay rather than the tax, and something named beforetax which is the amount of tax paid rather than the before-tax income. Similarly, beforetax1 is actually the tax, not the before-tax income, while beforetax2 is the before-tax income, secondtax is the tax, and tax is the after-tax income.

*Your elif bounds all have gaps. For example, if someone makes $18200.50, that's not <= 18200, nor is it >= 18201. You don't actually need the lower half of each test; just do elif income <= 37000 (if it was <= 18200, it would already have been handled in the if, so it won't get to this test).

*Your first case, for people under the minimum taxable income, needs to do the same thing as the others: calculate and return a tax cost and a before-tax income (in this case, that's just return 0, income). You can't just do nothing, or you're going to get some kind of exception somewhere when someone wants those values and they don't exist. Also, just printing the income doesn't do anything useful.

There are also things that aren't actually broken, but should be improved:

*

*It's probably better to move the raw_input outside the function, then pass the income in as a parameter.

*There's no reason to name a variable beforetax2 in one block and beforetax3 in another. If they both mean the same thing, and there's no way they're going to get in each other's way, just call them both beforetax.

*You probably want to round to even cents—or maybe use decimal.Decimal instead of float (see the moneyd` recipes in the docs).*

* I don't know about Australia, but in the US, if the IRS screws up and sends you a tax bill for $17.3811713, you're in big trouble. Pay $17.38, and that's underpaying and they'll issue penalties; pay $17.39 without explicitly specifying that you're overpaying and they'll return your check uncashed and then fine you for not paying on time. Call them and they'll tell you it's not a problem, and then three months later they've garnished your wages for $288 for not paying that 0.11713 cents, and they tell you "the information we give you isn't actually guaranteed to be correct, and doesn't count legally as advise".


text:
Q: WooCommerce get product type after save Can you please tell me how can I get product type after product save?
add_action( 'save_post_product', 'nd_update_group_product_attributes_func', 1001, 3 );

function nd_update_group_product_attributes_func($post_ID, $post, $update)
{

    if($post->post_type == 'product'){

        $childrens   = $post->get_children();
        $product_type = $post->get_type();  /* this will return simple for all product type*/

    }

}

Even I have "grouped" product type.
$product_type = $post->get_type(); on save_post_product hook will return the "simple" when we first create the product and later on update will return "grouped".

A: Get the WooCommerce product object using the function wc_get_product
add_action('woocommerce_after_product_object_save', 'nd_update_group_product_attributes_func', 10, 2);

function nd_update_group_product_attributes_func($product, $data_store) {

    $product_type = $product->get_type();
    if ($product->is_type('grouped')) {

        $child_product_ids = $product->get_children();
        $all_child_bed_attributes = array();

        foreach ($child_product_ids as $child_product_id) {

            $child_product = wc_get_product($child_product_id);
            $pa_bedrooms = $child_product->get_attribute('pa_bedrooms');
            $all_child_bed_attributes = array_unique(array_merge($all_child_bed_attributes, $pa_bedrooms));
        }
        if ($all_child_bed_attributes) {

            foreach ($all_child_bed_attributes as $bed) {
                wp_set_object_terms($post_ID, $bed, 'pa_bedrooms', true);
            }
        }
    }
}

The hook woocommerce_after_product_object_save can be used here

A: if( $_product->is_type( 'simple' ) )
$product->is_type( 'variable' )


text:
Q: display selected image from String[] imageurl in another activity I am having image slider which are containing images through image url.So,when I select any particular image that image on button click should go to another activity.I am getting image url but its not displaying image on another activity.So please help me.Thanks in advance.
I am having String[] imageUrl in Main
String[] imageUrl={"http://l.yimg.com/a/i/us/we/52/21.gif","https://devimages.apple.com.edgekey.net/contact/images/technical-icon.png","https://devimages.apple.com.edgekey.net/contact/images/technical-icon.png"};

On button click I am sending these url to another activity
Main.java
 String[] imageUrl={"http://l.yimg.com/a/i/us/we/52/21.gif","https://devimages.apple.com.edgekey.net/contact/images/technical-icon.png","https://devimages.apple.com.edgekey.net/contact/images/technical-icon.png"};

        Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
        btnNextScreen.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent intent = new Intent(Main.this, OpenImage.class);
                        intent.putExtra("some_key", imageUrl);
                        startActivity(intent);

                    }
                });

In another activity I am getting these url but not a image
OpenImage.java
 public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.screen2);
            String[] data = getIntent().getExtras().getStringArray("some_key");
            for(String x:data) {
                Log.i(TAG, "x="+x);
                Toast.makeText(OpenImage.this, x, Toast.LENGTH_SHORT).show();
                }

        }

A: In this code you only get urls. You are not displaying any image.
As you have an url, maybe you should try to display them in a webview
Example:
webView = (WebView) findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://l.yimg.com/a/i/us/we/52/21.gif");

A: Here is my code. It is working. Please change your minsdkversion in Androidmanifest to 9.
StrictPolicy require minimum sdk version to be 9
mainactivity.java
    package com.example.test;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.widget.ImageView;

public class MainActivity extends Activity {
    ImageView image1,image2;
    Bitmap bitmap;
    final static String imageLocation="http://www.codeincloud.tk/play.png"; //Use any image location.
    String[] imageUrl={"http://l.yimg.com/a/i/us/we/52/21.gif","https://devimages.apple.com.edgekey.net/contact/images/technical-icon.png","https://devimages.apple.com.edgekey.net/contact/images/technical-icon.png"};

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        image1 = (ImageView)findViewById(R.id.imageView1);
        image2 = (ImageView)findViewById(R.id.imageView2);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        URL imageURL = null;

        try {
            for(int i=0;i<imageUrl.length;i++){
                imageURL = new URL(imageUrl[i]);

                HttpURLConnection connection= (HttpURLConnection)imageURL.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream inputStream = connection.getInputStream();

                bitmap = BitmapFactory.decodeStream(inputStream);//Convert to bitmap

                if(i == 0)
                    image1.setImageBitmap(bitmap);

                if(i == 1)
                    image2.setImageBitmap(bitmap);

            }
        }
        catch (IOException e) {

            e.printStackTrace();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="69dp"
        android:layout_marginTop="106dp"
        android:src="@drawable/ic_launcher" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignTop="@+id/imageView1"
        android:layout_marginLeft="183dp"
        android:layout_marginTop="45dp"
        android:layout_toRightOf="@+id/imageView1"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

A: Main.java
    String[] imageUrl={"https://devimages.apple.com.edgekey.net/contact/images/technical-icon.png","http://www.codeincloud.tk/play.png",
                             "https://devimages.apple.com.edgekey.net/contact/images/technical-icon.png"};

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }

            imgView = (ImageView)findViewById(R.id.ImageViewTops);
            imgView.setImageResource(Imgid[0]);

            Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
            btnNextScreen.setOnClickListener(new View.OnClickListener() {
              public void onClick(View v) {
                    String image_selected = imageUrl[selected_image];
                    sendMessage(image_selected);
                }

            });

            topsgallery = (Gallery) findViewById(R.id.gallery1);
            topsgallery.setAdapter(new AddImgAdp (this));

            topsgallery.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {

                    selected_image = position;
                    Log.d("Selected","Image url="+selected_image);
                    imgView = (ImageView)findViewById(R.id.ImageViewTops);
                }
             });

     }
public void sendMessage(String image_selected) {
        Intent intent = new Intent(this, SecondActivity.class);
        String image_url = imageUrl[selected_image];
        intent.putExtra(EXTRA_MESSAGE, image_url);
        startActivity(intent);
    }
}

SecondActivity
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen2);

        setupActionBar();
        Intent intent = getIntent();
        Context context = getApplicationContext();
        String image_url = intent.getStringExtra(Main.EXTRA_MESSAGE);
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, image_url, duration);
        toast.show();
        new DownloadImageTask((ImageView) findViewById(R.id.imageview))
        .execute(image_url);

    }
    private void setupActionBar() {
        // TODO Auto-generated method stub

    }
    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        @SuppressWarnings("unused")
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            //Log.i("url","urldisplay="+urldisplay);
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
                } catch (Exception e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            ImageView bmImage = (ImageView)findViewById(R.id.imageview);
            bmImage.setImageBitmap(result);
        }

    }
}


text:
Q: Rails routes /name instead of /users/:id I've completed Hartl's tutorial and am trying to create vanity URLs to my twitter clone in the same way twitter has, e.g. www.twitter.com/realDonaldTrump
I've managed to get my URLs to look like /users/:slug.
Wondering - how do I get it so it's just /:slug?
Here's what I've done so far:
1.In my User model, there's no column for 'username', so I used 'name' instead.
2.Generated new migration to add a slug column to User model DB.
3.Plugged into rails console to add slugs for all users by typing:
User.all.each do |user|
  user.slug = user.name.downcase.parameterize
  user.save
end

4.Configured UsersController show action to:
def show
  @user = User.find_by_slug(params[:id])
  @microposts = @user.microposts.paginate(page: params[:page])
  redirect_to root_url and return unless @user.activated?
end

Now that I've configured it so it shows /users/:slug, how do I change it so it's just /:slug?

A: Try this ......
edit app/models/user.rb
class User < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, use: :slugged
end

User.create! name: "Username"

Change User.find to User.friendly.find in your controller
User.friendly.find(params[:id])

rails server

http://localhost:3000/users/username

If you're adding FriendlyId to an existing app and need
to generate slugs for existing users, do this from the
console, runner, or add a Rake task:
User.find_each(&:save)

To get /username instead of /users/username try this ...
In your User model add
class User < ActiveRecord::Base
  ...
  def to_param
    name
  end
  ...
end

But make sure in your controller you then find users by their name.
In your controller add
class UsersController < ApplicationController
  ...
  def show
    @user = User.find_by(name: params[:id])
  end
end

As for routing your users to /username, you have several options:
get ':id', to: 'users#show', as: 'show'
resources 'users', path: '/'

Just make sure you put these routes at the end of your routes file.
Hope this will work for you.

A: change your root with
get '/:slug', to: 'users#show'

and on your UsersController
def show
  @user = User.find_by slug: params[:slug]
...
end

don't forget to remove the ':show' on
before_action :set_user, only: [:show, :edit, :update]
of your Controller as "set_user" use :id and not :slug to retrieve instance
beware that you must worry about the slug uniqueness in your model when saving
before_validation :set_slug
validates :slug, uniqueness: true

private

def set_slug
...
end

A: get '/:slug', to: 'users#show' make this the last route and check.
Since it is the named route we created it should be at the last, so that the other routes are not disturbed.
In your Users Controller
def show
  @user = User.find_by slug: params[:slug]
end


text:
Q: Convert SQL to Linq - how to? Is it possible to convert this SQL to LINQ?
SqlCommand cmd = new SqlCommand(@"
WITH new AS (
   SELECT [UserSessionSequenceID],
          [SessionGuid],
          SiteID,
          IP,
          UrlTitle,
          Url,
          Referer,
          BrowserWidth,
          BrowserHeight,
          [Timestamp],
          ROW_NUMBER() OVER (PARTITION BY [SessionGuid]
                                 ORDER BY UserSessionSequenceID DESC) AS sort
     FROM [tblSequence]
    WHERE SiteID = @siteID
      AND [Timestamp] > DATEADD(mi, -@minutes, GETDATE()))
  SELECT TOP(@resultCount)
         n.*
    FROM new n
   WHERE n.sort = 1
     AND NOT EXISTS (SELECT NULL
                     FROM tblSequence s
                    WHERE s.siteid = n.siteid
                      AND s.sessionguid = n.sessionguid
                      AND [TimeStamp] <= DATEADD(mi, -@minutes, GETDATE()))
ORDER BY n.usersessionsequenceid DESC
            ");
            cmd.Parameters.Add("@resultCount", SqlDbType.Int).Value = resultCount;
            cmd.Parameters.Add("@minutes", SqlDbType.Int).Value = minutes;
            cmd.Parameters.Add("@siteID", SqlDbType.Int).Value = siteID;

I have a class containing all the fields selected from the SQL called "SimpleSession". Thanks in advance for any help.

A: To be honest, I would rather create a View for this statement and use that simple view in Linq2Sql...

A: In fact, many times there isn't no reason to convert complex SQL to some LINQ equivalent (even in case of compatible statements).
LinqToSql needs to dynamically create the SQL commands when running any LINQ command. So, do why we would want to overhead if we already know which is the best SQL query to solve?
We can easily create LINQ methods that call some View or Stored Procedure and returns it as typed objects. Your program will continue to be all fully object oriented but without unecessary overheads.

A: for first query u can use this
from seq in tblSequence.AsEnumerable()
                         where seq.Field("SiteID") == siteID
                               && seq.Field("Timestamp") > DateTime.Now.AddMinutes(minutes)
                         select new
                         {
                             seq.UserSessionSequenceID,
                             seq.SessionGuid,
                             seq.SiteID,
                             seq.IP,
                             seq.UrlTitle,
                             seq.Url,
                             seq.Referer,
                             seq.BrowserWidth,
                             seq.BrowserHeight,
                             seq.Timestamp
                         };
for row_number refer this How To Project a Line Number Into Linq Query Results


text:
Q: Verificar itens checados e aplicar a lógica Bom dia, estou estudando javascript e me deparei com um problema: Criei uma lógica onde disponibilizo dois botões, um para liberar acesso que quando clicado fica na tela apenas o ícone de check, e o bloquear que quando clicado fica apenas o ícone de bloqueado. O problema é que se podem ser mudado os ícones dos itens checados, porém, mesmo com os dois itens checados o único que muda o ícone é o primeiro. Estou mudando o ícone deixando seu display "none" e "initial" fiz dessa forma porque não conheço outra forma, se souberem algo com javascript agradeço, mas, a questão é como faço para a mudança de ícone acontecerem em todos itens checados e não apenas no primeiro ? Obrigado.
JS:
    function bloquearAcesso(){
    let inputs = document.querySelectorAll(".checar");

    for(let i = 0; i< inputs.length; i++){
        if(inputs[i].checked == true){

          document.getElementById("liberado").style.display = "none";
          document.getElementById("bloqueado").style.display = "initial";
      }
  };

    };

  function liberarAcesso(){
    let inputs = document.querySelectorAll(".checar");

        for(let i = 0; i < inputs.length; i++){
      if (inputs[i].checked == true){
      document.getElementById("bloqueado").style.display = "none";
      document.getElementById("liberado").style.display = "initial";
      };
  };
  }

HTML:

              Patio
              Acessar Desktop
              Criado em

              <input class="checar" type="checkbox">Patio1

              02/04/2018

                    <input class="checar" type="checkbox">Patio2

                    02/04/2018

        <button onclick="liberarAcesso()" type="button" class="btn btn-primary btn-xs btn-flat">Liberar acesso</button>
        <button onclick="bloquearAcesso()" type="button" class="btn btn-danger btn-xs btn-flat">Bloquear acesso</button>

A: Consegui, porém gerou outro problema, quando nenhum está selecionado ele funciona corretamente, porém quando eu seleciono apenas um ele aplica a lógica para todos.
function bloquearAcesso(){
    let inputs = document.querySelectorAll("#form1 [name=checar]");
    let liberado = document.querySelectorAll("#form1 [name=liberado]");
    let bloqueado =  document.querySelectorAll("#form1 [name=bloqueado]");

    for(let i = 0; i< inputs.length; i++){
        if(inputs[i].checked == true){

           for (var x = 0; x < liberado.length; x++){
    liberado[x].style.display = 'none';
    };
                for (var x = 0; x < bloqueado.length; x++){
                    bloqueado[x].style.display = 'initial';
                        };

    };
      }
  };

  function liberarAcesso(){
    let inputs = document.querySelectorAll("#form1 [name=checar]");
    let liberado = document.querySelectorAll("#form1 [name=liberado]");
    let bloqueado =  document.querySelectorAll("#form1 [name=bloqueado]");
    for(let i = 0; i < inputs.length; i++){
        if (inputs[i].checked == true){

            for (var x=0; x <bloqueado.length; x++){
                bloqueado[x].style.display = 'none';
            };

                for (var x = 0; x < liberado.length; x++){
                    liberado[x].style.display = "initial";
                };
            };

  };
}

A: Como dito nos comentários, repetir id's é errado e vai sempre pegar o primeiro elemento com a id. Transforme os id's em class e use document.querySelectorAll pegando os elementos pelo respectivo índice:

function bloquearAcesso(){
   let inputs = document.querySelectorAll(".checar");

   for(let i = 0; i < inputs.length; i++){
      if(inputs[i].checked){
          document.querySelectorAll(".liberado")[i].style.display = "none";
          document.querySelectorAll(".bloqueado")[i].style.display = "initial";
      }
   }

}

function liberarAcesso(){
   let inputs = document.querySelectorAll(".checar");

   for(let i = 0; i < inputs.length; i++){
      if (inputs[i].checked){
         document.querySelectorAll(".bloqueado")[i].style.display = "none";
         document.querySelectorAll(".liberado")[i].style.display = "initial";
      }
   }
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

            Patio
            Acessar Desktop
            Criado em

            <input class="checar" type="checkbox">Patio1

            02/04/2018

            <input class="checar" type="checkbox">Patio2

            02/04/2018

   <button onclick="liberarAcesso()" type="button" class="btn btn-primary btn-xs btn-flat">Liberar acesso</button>
   <button onclick="bloquearAcesso()" type="button" class="btn btn-danger btn-xs btn-flat">Bloquear acesso</button>

A: Resolvido! primeiro coloquei um for para varrer os inputs checados, dentro desse for tem mais dois fors, um para colocar o display none e outro no estado inicial, dentro de cada for exista mais uma verificação para garantir que a lógica será aplicada apenas aos inputs checados. Segue o código caso alguém tenha essa problema.
function bloquearAcesso(){
    let inputs = document.querySelectorAll("#form1 [name=checar]");
    let liberado = document.querySelectorAll("#form1 [name=liberado]");
    let bloqueado =  document.querySelectorAll("#form1 [name=bloqueado]");
    for(let i = 0; i< inputs.length; i++){
        if(inputs[i].checked == true){

           for (var x = 0; x < liberado.length; x++){
            let teste = " ";
            if(inputs[x].checked == true){

                teste = liberado[x].style.display = 'none';
    };
};
                for (var x = 0; x < bloqueado.length; x++){
                    if(inputs[x].checked == true){

                    let test = " ";

                    test = bloqueado[x].style.display = 'initial';
                        };

    };
};

      }

  };

  function liberarAcesso(){
    let inputs = document.querySelectorAll("#form1 [name=checar]");
    let liberado = document.querySelectorAll("#form1 [name=liberado]");
    let bloqueado =  document.querySelectorAll("#form1 [name=bloqueado]");
    for(let i = 0; i < inputs.length; i++){
        if (inputs[i].checked == true){

            for (var x=0; x <bloqueado.length; x++){
                if(inputs[x].checked == true){

                bloqueado[x].style.display = 'none';
            };

        };
                for (var x = 0; x < liberado.length; x++){
                    if(inputs[x].checked == true){

                    liberado[x].style.display = "initial";
                };
            };

  };
}
}


text:
Q: LINQ query is not retrieving saved data maybe I need to start over. Thx for the helpful links for the datagridview but I didn't really need to bring that up.
The essence of the problem is this: I use this method for 2 things:
- to get the necessary data out of the database when adding a new record
- to get the necessary data out of the database after I've updated a record
public void refreshReservationDetail()
{
    _oReservationDetail = (from rd in _oReservation.tblReservationDetails
                           where rd.ReservationID == _oReservationObject.ID
                           select rd).ToList();
}

When I add a new record the new data is saved and loaded into the datagridview. So this works fine.
When I update an existing record (that is already shown in the datagridview) the altered content is also being saved properly but the method above is not giving me the saved data but still the old data. How come?
Here I save my data
//frmReservationDetail
public event dRefresh SavedActivity;

private void btnOk_Click(object sender, EventArgs e)
{
    _oReservationDetail.ReservationDetailData.ReservationID = _oReservationDetail.ReservationObjectData.ID;
    _oReservationDetail.ReservationDetailData.StartTime = Convert.ToDateTime(_oReservationDetail.ReservationObjectData.StartTime.Value.ToString("dd/MM/yyyy") + " " + _oDateTime[cboStartTime.getSelectedID()]);
    _oReservationDetail.ReservationDetailData.EndTime = Convert.ToDateTime(_oReservationDetail.ReservationObjectData.StartTime.Value.ToString("dd/MM/yyyy") + " " + _oDateTime[cboEndTime.getSelectedID()]);
    if (this.cboLanguage.SelectedItem != null)
    {
        _oReservationDetail.ReservationDetailData.LanguageID = this.cboLanguage.getSelectedID();
    }
    else
        _oReservationDetail.ReservationDetailData.LanguageID = null;

    if (this.cboTargetgroup.SelectedItem != null)
    {
        _oReservationDetail.ReservationDetailData.TargetgroupID = this.cboTargetgroup.getSelectedID();
    }
    else
        _oReservationDetail.ReservationDetailData.TargetgroupID = null;

    if (this.cboExcursion.SelectedItem != null)
    {
        _oReservationDetail.ReservationDetailData.ExcursionID = this.cboExcursion.getSelectedID();
    }
    else
        _oReservationDetail.ReservationDetailData.ExcursionID = null;

    _oReservationDetail.ReservationDetailData.Participants = int.Parse(this.txtParticipants.Text);
    _oReservationDetail.ReservationDetailData.Leaders = int.Parse(this.txtLeaders.Text);
    _oReservationDetail.ReservationDetailData.Remarks = this.txtRemarks.Text;
    _oReservationDetail.save();

    if(SavedActivity != null)
        SavedActivity();

    this.Close();
    }

//clsReservationDetail
public void save()
{
    int i = _oReservationDetail.ID;
    if (_oReservationDetail.ID == 0)
    {
            _oReservation.tblReservationDetails.InsertOnSubmit(_oReservationDetail);
            _oReservation.SubmitChanges();
    }
    _oReservation.SubmitChanges();
}

A: It sounds like you aren't rebinding your datagridview. After you save/update you should be calling refreshReservationDetail() again, and then you'll need to once again set the datasource to that variable and rebind it. If you are doing this asynchronously with an update panel or some such, you'll have to call refreshReservationDetail() at the end of the event that is fired for saving/updating. If the page is posting back normally then just make sure your databinding to the gridview occurs regardless if it's a postback or not.

A: I have succeeded by calling this loop:
foreach (var oReservationDetail in
    _oReservationObject.ReservationData.tblReservationDetails)

I have used the setted relations in the database instead of querying again to get the data. It now works!


text:
Q: In Ruby on Rails, is there a clean way to get the URL but just the front part? (only up to the domain name) In Rails (version 3), request.url can show
http://www.foo.com/products/123

but what about just to get
http://www.foo.com

or
http://www.foo.com/

?  There are 2 apparent ways, one is using regular expression, which is not very clean, and the other is
"#{request.scheme}://#{request.host}"

and it is kind of ugly either.  Is there a cleaner to do it?

A: This will get you what request.url gets you, but without the path:
request.protocol + request.host_with_port

A: You should be able to do it with request.domain.

A: Should be stored in the request object. request.domain should get the info you need but use this command to retrieve all the information from the object and have a look at what is stored there
raise request.inspect

more info can be found at
http://rails.nuvvo.com/lesson/6377-action-controller-the-request-and-response-objects


text:
Q: IIS get real client IP Address when behind a AWS Elastic load balancer I have a IIS server behind a AWS Elastic load balancer. I want retrieve the real client ip address set into x-forwarded-for header from AWS Elastic load balancer.
I have found this setting for enable proxy mode, but IIS require the static IP address of the load balancer and the load balancer has only dynamic ip address.
<security>
  <ipSecurity allowUnlisted="false" enableProxyMode="true">
    <add ipAddress="XXX.XXX.XXX.XXX" allowed="true"/>
  </ipSecurity>
</security>

How to enable proxy mode with dynamic ip address?


text:
Q: Dynamically create graphql query based on criterias from javascript I am using GraphQl together with bigcommerce to grab products, and i need to find a sollution to make my query dynamic - its based on the length of an array of SKU's. Its no problem to make it work with one product.
let query = `
 query getProductBySku($sku: String) {
  site {
   product(sku: $sku) {
    id
    entityId
    name
    sku
    }
   }
  }
 `

And i figured out so far that i need to use something like aliases in graphql to be able to get several products in several response like this
 query productById {
  site {
   o1: product(entityId: 167) {
    id
    entityId
    sku
    name
   }
  o2: product(entityId: 168 ) {
   id
   entityId
   sku
   name
  }
 }
}

But i need to be able to make this alias query dynamic based on the lenght of the array. How would you approach to solve this problem? Is it possible to maybe create a loop that will write out the query before i will run it. Any help to let me in the right direction here would be highly appreciated! Thank you!
ps. im using javascript.

A: For anyone curious i ended up being able to use .map to dynamically loop out the query and the run it :)
let query = `
 query productBySku {
  site {
   ${sku
    .map(
      (product: any, idx: number) =>
       `pro${idx}: product(sku: "${product}") {
       id
       entityId
       sku
       name
      }
     `
    )
  .join('')}
 }
}

`


text:
Q: Python script does not work but gives no error message I am new to programming/scripting in general and just becoming to understand the basics of the workings of python2.7. Anyways, i have here a script i have been working on to randomly generate a password made up of letters, numbers and special characters.
import random

charset="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
charset+=charset.lower()   # adds lowercase a-z to charset
charset+="@&%_$#" # adds these special characters to the charset
charset+="1234567890" # adds digits 0-9 to charset

def generate_password(length):
  """generates random password"""
    password=[]
    for n in range(length):
        password.append(random.choice(charset))
        print password
    return password

def main():
    # test cases
    length = 4

  # boilerplate
if __name__ == '__main__':
    main()

Please excuse if this seems like a stupid question but i am new to this after all :(. When i run the above script i receive no output as well as no error message resulting in me not knowing what the heck im doing wrong!

A: It's because, your main() function doesn't do anything. Change it as following :
def main():
  # test cases
  length = 4
  #
  print generate_password(length)

  # boilerplate
if __name__ == '__main__':
  main()

A: import random

charset="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
charset+=charset.lower()   # adds lowercase a-z to charset
charset+="@&%_$#" # adds these special characters to the charset
charset+="1234567890" # adds digits 0-9 to charset

def generate_password(length):

    password=[]
    for n in range(length):
        password.append(random.choice(charset))

    print password
    return password

def main():
    length = 4
    generate_password(length)

if __name__ == '__main__':
    main()

first you did not have any indentation (that might have been a copy and paste issue). Then you never called generate_password so it would have never done anything but set length to 4.


text:
Q: How to place text on top of two table cells? Lets say we have this table:

    Text crossing two td´s

How can the text be on top of the two td´s and follow the size of the tr?
https://jsfiddle.net/roj7w1t4/
Is it possible?
EDIT
I need the borders to stay visible. Therefore i cannot use colspan!
Is it possible to create a span and put it over the td´s?
To make more sense what i am trying to do.. this is a small example of my application: What printable element is better to use than linear-gradient?
THE ELEMENT

105

A:

table {
  border: 1px solid black;
}

td {
  border: 1px solid red;
}

th {
  text-align:center;
}

    Monthly Savings

    This text should cross two td´s

You can include  the border will be visible.
All the best. For any query please comment.

A: How about changing your html layout? Try to use after pseudo element and position:absolute. This technique saves me in a lot of situation and it's very strong, I think.

div {
  border: 1px solid green;
  padding: 2px;
  position: relative;
  width: 150px;
}

div:after {
  background: green;
  bottom: 0;
  content: '';
  display: block;
  left: 50%;
  position: absolute;
  top: 0;
  transform: translateX(-50%);
  width: 1px;
}

This text should cross two td´s

A: The only way I can image doing this is placing an element outside the table and having a container around the table and the element. Then placing the element using position absolute on top of the table.

div {
  width: 200px;
  position: relative;
}
table {
  width: 200px;
}
td {
    border: 1px solid red;
    height: 40px;
}
span {
  position: absolute;
  padding: 2px;
  z-index: 99;
}

Lorem ipsum dolor sit amet


text:
Q: Lookup magnifier glass moves to the left When I just have the composition and define included on the page, the lookup magnifier glass moves to the left (ahead of the lookup text box), when I remove these tags, it restores to it's normal position. Has anyone seen this before? if so, how do I get the magnifier glass to get back to the normal position (right of lookup box). Code below.
<apex:page standardController="Account" showHeader="false">

 <apex:composition template="Template">
     <apex:define name="body" >

<apex:form>
    <apex:pageBlock mode="mainDetail">
        <apex:pageBlockSection>
                <apex:pageBlockSectionItem>
                    <apex:outputLabel value="Parent1 Account" />
                    <apex:outputPanel>
                     <apex:inputfield value="{!account.parentid}"/>
                        </apex:outputPanel>
            </apex:pageBlockSectionItem>

        </apex:pageBlockSection>

    </apex:pageBlock>

</apex:form>
</apex:define>
</apex:composition>
</apex:page>


text:
Q: How to plot a line representing a value from a dataframe with two geometry columns? I have the following data:
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point
import matplotlib.pyplot as plt

points = gpd.GeoDataFrame([['A', Point(1.5, 1.75), Point(2, 2), 16],
                          ['B', Point(3.0,2.0), Point(3, 4), 18],
                       ['C', Point(2.5,1.25), Point(1, 1), 19]],
                    columns=['id', 'geometry', 'geometry b', 'value'],
                    geometry='geometry')

the first geometry column represents the starting point, the second the ending point of a line which has a value corresponding to the value column.
I have tried to plot this with:
f, ax = plt.subplots(1, figsize = [12, 12])
points.plot(ax=ax, column = 'value')

However it just plots the first geometry column and colours the points corresponding to their value.
How do I produce a plot that draws the lines, colour coded to their value?

A: This working code and its output plot demonstrate how you can achieve what you need. See comments in the code for more details.
import geopandas as gpd
from shapely.geometry import Point, LineString
import matplotlib.pyplot as plt

# handle all points and create relating lines
pA1 = Point(1.5, 1.75)
pA2 = Point(2, 2)
line_A = LineString([[pA1.x, pA1.y], [pA2.x, pA2.y]])
pB1 = Point(3.0, 2.0)
pB2 = Point(3, 4)
line_B = LineString([[pB1.x, pB1.y], [pB2.x, pB2.y]])
pC1 = Point(2.5, 1.25)
pC2 = Point(1, 1)
line_C = LineString([[pC1.x, pC1.y], [pC2.x, pC2.y]])

# create a geodataframe,
# assigning the column containing `LineString` as its geometry
pts_and_lines = gpd.GeoDataFrame([['A', pA1, pA2, 16, line_A],
            ['B', pB1, pB2, 18, line_B],
            ['C', pC1, pC2, 19, line_C]],
            columns=['id', 'beg_pt', 'end_pt', 'value', 'LineString_obj'],
            geometry='LineString_obj')  # declare LineString (last column) as the `geometry`

# make a plot of the geodataframe obtained
f, ax = plt.subplots(1, figsize = [4, 4])
pts_and_lines.plot(ax=ax, column = 'value');
plt.show()

The output plot:

If you prefer to build a dataframe containing from_point and to_point first, then append new column containing LineString creating from the existing points, here is an alternative code.
import geopandas as gpd
from shapely.geometry import Point, LineString
import matplotlib.pyplot as plt

# this dataframe `points_df` contains from_point, to_point for creating `lineString`.
points_df = gpd.GeoDataFrame([['A', Point(1.5, 1.75), Point(2, 2), 16],
                          ['B', Point(3.0,2.0), Point(3, 4), 18],
                       ['C', Point(2.5,1.25), Point(1, 1), 19]],
                    columns=['id', 'geometry_a', 'geometry_b', 'value'])

# add new column, `line` to the dataframe,
# this column contains `LineString` geometry.
points_df['line'] = points_df.apply(lambda x: LineString([x['geometry_a'], x['geometry_b']]), axis=1)

# assign geometry to `points_df` using the column that has `LineString` geometry
# take the result as `target_gdf`
# `target_gdf` is now capable of plotting with matplotlib
target_gdf = gpd.GeoDataFrame(points_df, geometry=points_df['line'])

f, ax = plt.subplots(1, figsize = [4, 4])
target_gdf.plot(ax=ax, column = 'value');
plt.show()

Its output plot is the same as the previous one.


text:
Q: peewee select() return SQL query, not the actual data I'm trying sum up the values in two columns and truncate my date fields by the day. I've constructed the SQL query to do this(which works):
SELECT date_trunc('day', date) AS Day, SUM(fremont_bridge_nb) AS
Sum_NB, SUM(fremont_bridge_sb) AS Sum_SB FROM bike_count GROUP BY Day
ORDER BY Day;

But I then run into issues when I try to format this into peewee:
Bike_Count.select(fn.date_trunc('day', Bike_Count.date).alias('Day'),
fn.SUM(Bike_Count.fremont_bridge_nb).alias('Sum_NB'),
fn.SUM(Bike_Count.fremont_bridge_sb).alias('Sum_SB'))
.group_by('Day').order_by('Day')

I don't get any errors, but when I print out the variable I stored this in, it shows:
 <class 'models.Bike_Count'> SELECT date_trunc(%s, "t1"."date") AS
Day, SUM("t1"."fremont_bridge_nb") AS Sum_NB,
SUM("t1"."fremont_bridge_sb") AS Sum_SB FROM "bike_count" AS t1 ORDER
BY %s ['day', 'Day']

The only thing that I've written in Python to get data successfully is:
 Bike_Count.get(Bike_Count.id == 1).date

A: If you just stick a string into your group by / order by, Peewee will try to parameterize it as a value. This is to avoid SQL injection haxx.
To solve the problem, you can use SQL('Day') in place of 'Day' inside the group_by() and order_by() calls.
Another way is to just stick the function call into the GROUP BY and ORDER BY. Here's how you would do that:
day = fn.date_trunc('day', Bike_Count.date)
nb_sum = fn.SUM(Bike_Count.fremont_bridge_nb)
sb_sum = fn.SUM(Bike_Count.fremont_bridge_sb)

query = (Bike_Count
         .select(day.alias('Day'), nb_sum.alias('Sum_NB'), sb_sum.alias('Sum_SB'))
         .group_by(day)
         .order_by(day))

Or, if you prefer:
query = (Bike_Count
         .select(day.alias('Day'), nb_sum.alias('Sum_NB'), sb_sum.alias('Sum_SB'))
         .group_by(SQL('Day'))
         .order_by(SQL('Day')))


text:
Q: Copy first N files from source directory to "serialized" destination directory using powershell Either Powershell or batch script will work. I want to distribute every N number of files from directory A to directory B1, B2, B3, etc.
Example:
C:\a (has 9 .jpg files)
file1.jpg
file2.jpg
...
file9.jpg
then c:\b1, C:\b2, C:\b3 should have 3 files each. it should create directories C:\b* as well.
So far I came up with this code, works fine but copies ALL the files from directory A to directory B:
$sourceFolder = "C:\a"
$destinationFolder = "C:\b"
$maxItems = 9
Get-Childitem  $sourceFolder\*.jpg | ForEach-Object {Select-Object -First $maxItems | Robocopy $sourceFolder $destinationFolder /E /MOV}

A: This also works, will calculate how many new folders should be created.
$excludealreadycopieditems = @()
$sourcefolder = "C:\a"
$destinationFolder = "C:\b"
$maxitemsinfolder = 3
#Calculate how many folders should be created:
$folderstocreate = [math]::Ceiling((get-childitem $sourcefolder\*.jpg).count / $maxitemsinfolder)
#For loop for the proces
for ($i = 1; $i -lt $folderstocreate + 1; $i++)
     {
#Create the new folders:
New-Item -ItemType directory $destinationFolder$i
#Copy the items (if moving in stead of copy use Move-Item)
get-childitem $sourcefolder\*.jpg -Exclude $excludealreadycopieditems | sort-object name | select -First $maxitemsinfolder | Copy-Item -Destination $destinationFolder$i ;
#Exclude the already copied items:
$excludealreadycopieditems = $excludealreadycopieditems + (get-childitem $destinationFolder$i\*.jpg | select -ExpandProperty name)
     }

A: Something like this should do:
$cnt = 0
$i   = 1
Get-ChildItem "$sourceFolder\*.jpg" | % {
  if ($script:cnt -ge $maxItems) {
    $script:i++
    $script:cnt = 0
  }

  $dst = "$destinationFolder$script:i"
  if (-not (Test-Path -LiteralPath $dst)) {
    New-Item $dst -Type Directory | Out-Null
  }
  Copy-Item $_.FullName $dst

  $script:cnt++
}


text:
Q: Is there any difference between First Class Functions and Callback Functions in Javascript? Are there any differences between first class functions and callback functions in javascript? I thought that first class functions were functions that were treated as regular variables and can be passed as arguments. Aren't callback functions the same?

A: You are correct, all functions are first class in javascript and can be passed as objects. That's why callbacks are even possible. If you couldn't pass a function as an object there would be no way for another function (in a different scope) to use your passed function.
An example of using a first class function directly and as a callback.
function callsback(callbackFunc) {
    callbackFunc()
}

function firstClass() {
    console.log("I was called");
}

firstClass(); // "I was called"
callsback(firstClass); // "I was called"

A: A language is said to have first class function if they are treated as variables. So it means that we can return a function, we can pass a function as an argument and we can assign a function as a value to a variable.
Callback function is also a first class function going by this definition because it is also passed as an argument. But Callback functions are used to specifically handle asynchronous tasks in a synchronous single threaded language like JavaScript.


text:
Q: How to implement plugin manually for Cordova? I have this following script :
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />

         <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
         <link rel="stylesheet" type="text/css" href="css/index.css" />
         <meta name="msapplication-tap-highlight" content="no" />
         <title>Hello World</title>

Apache Cordova

Connecting to Device

Device is Ready

 Camera Position

        <input type="radio" name="deviceposition" id="deviceposition_back" value="Back" onclick="onChangeDevicePosition();"/>
        Back

        <input type="radio" name="deviceposition" id="deviceposition_front" value="Front" onclick="onChangeDevicePosition();"/>
        Front

 Flash Mode

        <input type="radio" name="flashmode" id="flashmode_off" value="Off" onclick="onChangeFlashMode();"/>
        Off

        <input type="radio" name="flashmode" id="flashmode_on" value="On" onclick="onChangeFlashMode();"/>
        On

        <input type="radio" name="flashmode" id="flashmode_auto" value="Auto" onclick="onChangeFlashMode();"/>
        Auto

        <input type="button" value="Take a picture" onclick="onTakePicture();" />

<!— camera preview canvas —>
    <canvas id="camera" width="352" height="288" style="border:2px"></canvas>

I have just tried this After installing the plugin with git here :- https://github.com/donaldp24/CanvasCameraPlugin. , this code is working and my problem can be explained by an error of installation of the plugin So, I am asking if somebody can help me to install the plugin because with this following steps from here:-https://github.com/donaldp24/CanvasCameraPlugin  doesn't work for me I don't understand why it is not the first time I try to install a plugin.
Thanks

A: If manual way don't work for you try out "Online Phonegap build services". It worked for me it may be helpful to you too.It will bind your plugins in your application and will build it for you.
Try out this Solution,4 Step Procedure:

*

*Create a Zip File of your project.(Build package->Zip)

*Update config.xml file with new plugins

*Build application using Phonegap build services

*Get .apk, .ipa, .xap i.e native applications

Source:https://www.devexpress.com/Support/Center/Question/Details/KA18816


text:
Q: Uploading files via network drive mapping I have already mapped a network drive and added my site as a trusted site on internet explore,but each time am trying to upload a file ,i get the error asking me to add my site as a trusted site.

A: To troubleshoot the issue, check things below:

*

*Delete and re-add the old site in trusted site in IE.

*Re-map network drive to the site with the issue.


text:
Q: Set margins for all children nodes in fxml I have a FXML layout file where the root element is a VBox. I want to set vertical margins/padding between each immediate child element within the VBox.
How do I accomplish this? Do I use a css, or is there XML tags I can use in the FXML file?
<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
  <HBox prefWidth="200.0">
        <Label text="Name:" />
        <TextField fx:id="nameTextField" />
  </HBox>
  <ChoiceBox fx:id="sampleEntryMode" />
  ...
</VBox>

A: You can use VBox.spacing to add some space between each direct child.


text:
Q: Interstitial Admob doesn't work : AFMA_ReceiveMessage is not defined I have two kind of ads : banner and interstitial. The first one works very well, but when I want to display an interstitial ad when I pressed the back button (but we don't care of the button), before closing my app. But my interstitial ad doesn't work and my app is closing with this error in log :
E/Ads(20984): JS: Uncaught ReferenceError: AFMA_ReceiveMessage is not defined (:1)

I don't know what this error means.
I browsed internet, and it may comes from my internet connection. My Wifi ?
Or it might comes from Admob aswell ?
Should I try in an other area with a better connexion ?
Thanks for helping me.

A: My code use to add InterstitialAdd:
public static void addInterstitialAd(final Activity context, final int id) {
    final InterstitialAd interstitial = new InterstitialAd(context);
    interstitial.setAdUnitId(context.getString(id));
    interstitial.loadAd(new AdRequest.Builder().build());
    interstitial.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            // Call displayInterstitial() function
            if (interstitial.isLoaded()) {
                interstitial.show();
            }
        }
    });
}

You can try it if not work, please separate to new thread:
 new Thread(new Runnable() {
        public void run() {
        final InterstitialAd interstitial = new InterstitialAd(context);
        interstitial.setAdUnitId(context.getString(id));
        interstitial.loadAd(new AdRequest.Builder().build());
        interstitial.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Call displayInterstitial() function
                if (interstitial.isLoaded()) {
                runOnUiThread(new Runnable() {
                public void run() {
                    interstitial.show();
                }
              });
             }
            }
        });
     }
    }).start();

If your want after click back -> Admod-> close admod -> apclose:
@Override
    public void onBackPressed() {
        final InterstitialAd interstitial = new InterstitialAd(getApplicationContext());
        interstitial.setAdUnitId(getApplicationContext().getString(id));
        interstitial.loadAd(new AdRequest.Builder().build());
        interstitial.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Call displayInterstitial() function
                if (interstitial.isLoaded()) {
                    interstitial.show();
                }
            }
            @Override
            public void onAdClosed(){
                finish();
            }
            @Override
            public void onAdFailedToLoad(int errorCode){
                //you can implement continue load or finish
            }

        });
    }

A: Do not place interstitial ads on app load and when exiting apps as interstitials should only be placed in between pages of app content.


text:
Q: Renaming pandas df column produces copy warning I am renaming a column in a pandas df, but get the error "A value is trying to be set on a copy of a slice from a DataFrame. See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy".
I am aware of this error message - a classic. I thought I had understood what causes this error. However, I am confused why this would pop up in this context. I do not see how I would (mistakenly) work on a copy... I am using the column rename function as follows:
match_stats_home_team.rename(columns={"Game Day ID":"Team Day ID"},inplace=True)

The column "Game Day ID" should be, and is, in fact, renamed into "Team Day ID". What am I doing wrong, and how would "good" code look like?


text:
Q: How does one set a background image in an OSX .pkg? I am creating a .pkg installer for my OSX application and I am having trouble figuring out how to set the background image.
I am creating my installer in my build script like this:
pkgbuild --root $APP_FOLDER --identifier "com.company.product" $FINAL_PKG

This works great but I have not been able to find any information about setting the background image in the man pages. I have seen package installers that have custom background images, how does one set it?
EDIT:
Here is a screenshot of a package installer with a custom background:

A: Ah ha! There is a resources flag that goes along with productbuild. Here is a stackoverflow question addressing the resources: How do I build an OS X installer package with a custom background with productbuild?
It mentions --resources /path/Resources
and an en.lproj subdirectory, and an XML resources file.  You can specify the background.jpg or modify an existing one.
Hope this points you in the right direction(s).

A: This was most likely done with a tool apple had for creating installers.
You might be able to find it if you search for it on the OS X developer site of Apple
EDIT:
See also

*

*installease

*Vise

*InstallBuilder
NOTE:
I don't think an installer is the best solution! Making your app in a way that frees you from an installer is not hard. License Agreement, Pre- and Post script functions can be coded in-app.


text:
Q: unity unitywebrequest 400 method not allowed error I am trying to send JSON to my python flask web server but when I run the code I got "method not allowed" for some reason
IEnumerator Upload()
{
    var something = new Data();
    //Debug.Log("something: " + something);

    var jsonString = JsonUtility.ToJson(something);
    //Debug.Log("jsonString: " + jsonString);

    using (var www = UnityWebRequest.Post("http://localhost:8000/test", jsonString))
    {
        www.SetRequestHeader("Content-Type", "application/json");

        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log("Form upload complete!");
        }

    }
}

this is the server side:
@app.route('/test', methods = ['POST'])
def testpost():
    if request.method == "POST":

        data = request.get_json()

        print(data)
        return jsonify(data)


text:
Q: Visual Studio hangs when IronPython code executes programmatically I have a question about executing IronPython code programmatically via C#. I use IronPython 2.7.6.3. My code looks like this:
ScriptEngine scriptEngine = IPython.CreateEngine();
ScriptScope scriptScope = Engine.CreateScope();

scriptScope.ImportModule("clr");

scriptEngine.Execute("import clr", scriptScope);
scriptEngine.Execute("import System", scriptScope);

scriptEngine.Execute("clr.AddReference('System.Core')", scriptScope);
scriptEngine.Execute("clr.ImportExtensions(System.Linq)", scriptScope);

scriptEngine.Execute("from System import *", scriptScope);

ScriptSource scriptSource = scriptEngine.CreateScriptSourceFromString(string_with_ironpython_code);

scriptSource.Execute(scriptScope);

My IronPython code contains usage of IEnumerable extension methods from System.Linq namespace, that's why I'm using System.Core and clr.ImportExtensions("") method. And when I run this code my Visual Studio hangs at this line:
scriptSource.Execute(scriptScope);

I've waited for 10 minutes and then just stopped the process. But if I remove adding reference to System.Core.dll and import extensions then I got error that I can't access to IEnumerable extension methods. By the way, when I execute another IronPython code, where there is no usage of IEnumerable extensions methods and I have no need write this lines:
scriptEngine.Execute("clr.AddReference('System.Core')", scriptScope);
scriptEngine.Execute("clr.ImportExtensions(System.Linq)", scriptScope);

everythings works fine.
So my questions is: Am I doing something wrong with adding reference and import extensions? Or why my Visual Studio hangs when I try execute scriptSource with adding this reference?
P.S. When I wrote IronPython code in Visual Studio and run this *.py file from Visual Studio - everything worked fine.


text:
Q: Is here a node missing when using the node voltage method? I am currently learning the Node voltage method to get a better know how about circuits. Let's say you have the following circuit:

This is the workout example with all the nodes. IMHO, I disagree, I think there is one node missing and the circuit should be as follows:

I thought that the definition of a branch was that it could only contain 1 and only 1 element (doesn't matter what element it is). When using the first circuit the current source I5 and the resistor R4 would be in the same branch, right?
Question: Then why is this the final answer? Am I missing something? Is it wrong to add N3?

A: There is actually no point adding node "n3", because node "n0" and node "n3" are short circuited. If you try to solve it like this, there is actually no problem if you keep in mind that they have the same potential (Vno = Vn3), but there is no reason to make things complicated. Try to avoid extra unknowns :)
Also, there is no element between those two nodes, hard wiring is not considered as an element, so that is not a branch.


text:
Q: Do we need to wrap app.get in async function I've come across this code
(async () => {
  app.get('/health', (req: Request, res: Response) => {
    res.send();
  });
  more endpoints here
  ....

})();

I don't get why we need to wrap app.get in async here, is that necessary?

A: Probably not, but we'd need more context to be sure. As shown, no, there's no point.
It may be that they were relying on information they only got asynchronously for setting up the routes and wanted to use await rather than .then/.catch when using that information, e.g.:
(async () => {
    try {
        app.get('/health', (req: Request, res: Response) => {
            res.send();
        });

        const moreRoutes = await getMoreRoutes();
        // −−−−−−−−−−−−−−−−^^^^^

        for (const route of moreRoutes) {
            // ...set up more routes
        }
    } catch (e) {
        // Handle/report error
    }
})();

If so, hopefully they have a try/catch around the entire body (as shown above) or a .catch at the end like this:
(async () => {
    app.get('/health', (req: Request, res: Response) => {
        res.send();
    });

    const moreRoutes = await getMoreRoutes();
    // −−−−−−−−−−−−−−−−^^^^^

    for (const route of moreRoutes) {
        // ...set up more routes
    }
})().catch(e =>  {
    // Handle/report error
});

async/await can make it much easier (IMHO) to read code. But the above can be done with .then/.catch as well:
app.get('/health', (req: Request, res: Response) => {
    res.send();
});

getMoreRoutes()
.then(moreRoutes => {
    // ...set up more routes
})
.catch(e =>  {
    // Handle/report error
});


text: Q: drawUnderTabBar property is not working I am using react-native-navigation and drawUnderTabBar property does not show my screen background behind the tabs. I have tried placing the prop in navigatorStyle, appStyle, and tabsStyle to no effect


text:
Q: Getting neighborhood from google maps or check if address is in neighborhood location I need to check if address is inside neighborhood using google geocode API, or get neighborhood by street address from google places API.
I'm trying to get neighborhood by street name and number in Latvia, Riga.
If request to geocoding API is made to get coordinates and all available data via this request:
https://maps.googleapis.com/maps/api/geocode/json?address=A+Deglava+iela+104&components=country:LV|postal_code:LV-1082
google does not return neighborhood address component, however if I manually use google maps to search for neighborhood name in google maps, it shows that neighborhood

It could be that google does not support neighborhood lookup by street name, but then how could I check that my street name and number is in location inside or outside of neighborhood.
Problem is that I can get viewport of that neighborhood, but google gives rectangle and that rectangle would cross with other neighborhoods
Example coordinates of "Purvciems" neighborhood
{
    "northeast": {
        "lat": 56.96616400000001,
        "lng": 24.2093959
    },
    "southwest": {
        "lat": 56.94633899999999,
        "lng": 24.1568988
    }
}
Also I have searched for containsLocation()
https://developers.google.com/maps/documentation/javascript/examples/poly-containsLocation
But it would return results only by your custom polygon.


text:
Q: FOR stopping before it should I have this code that get information inside a .xls file.
This is the end of the code as i think here I have a limit.
Its showing until the 50th line.
If I have more it is not working.
I dont know if you can help me just looking inside this code:
for (var cal = 0; cal < excelRows.length; cal++) {
  var lixo = excelRows[cal].CaseDate
  var lixo2 = excelRows[cal].Checkin

  lixoDate = new Date(lixo)
  var lixoc = Math.round(lixoDate / offset)

  lixo2Date = new Date(lixo2)
  var lixo2c = Math.round(lixo2Date / offset)

  var dif = lixo2c - lixoc

  if (dif >= 30) {
    var dataat = new Date(document.getElementById("today").value)
    var final = Math.abs(lixoDate - dataat.getTime())
    var final2 = Math.round(final / offset)
    dif = dif - 30 - final2
    divteste.innerHTML += ` ${dif}<br>`

  } else if (dif >= 15 && dif <= 30) {
    var dataat = new Date(document.getElementById("today").value)
    var final = Math.abs(lixoDate - dataat.getTime())
    var final2 = Math.round(final / offset)
    dif = dif - 15 - final2
    divteste.innerHTML += ` ${dif}<br>`

  } else if (dif >= 3 && dif <= 14) {
    var dataat = new Date(document.getElementById("today").value)
    var final = Math.abs(lixoDate - dataat.getTime())
    var final2 = Math.round(final / offset)
    dif = dif - 3 - final2
    divteste.innerHTML += ` ${dif}<br>`
  } else if (dif <= 2) {
    divteste.innetHTML += '0'
  }
}
}


text:
Q: Why can't Windows 7 find my BCDEdit store location? Quick backstory: I'm attempting to resolve "unknown errors" that come up trying to upgrade from Windows 7 to Windows 10. Whether or not this issue has anything to do with it doesn't matter, I just want it fixed regardless.
So, in trying to fix some Windows 7 errors, I discovered that msconfig.exe's boot tab is frozen and attempting to modify anything results in this error message:

Not only that, but going into Advanced System Settings > Startup and Recovery provides me with this dropdown that suggests
?
And if that wasn't weird enough, going to bcdedit revealed that apparently my boot configuration store (correct term?) is missing from the default location and is instead in c:\ESD\Windows\Boot\BCD for some reason.

Things to note:

*

*I am on Windows 7 Home (genuine)

*I only boot Windows 7 (always have)

*I have 4 disk drives (all SATA) and one other that USED to be my primary drive before I cloned it to my current primary drive (I suspect this to be where my problems started ;) )

*I currently cannot do a repair install as I have traced back this error from an error with attempting to do a repair install

So: How do I fix this? Can I modify something to look in the other path? Can I move the incorrect path somewhere else so it can be found? Am I missing the root of the issue entirely?
I would appreciate if someone could get back to me before July 29th in case it fixes my Windows 10 upgrade errors too!
Update 7-17-16:
I have tried several other suggestions (thanks, magicandre1981) but unfortunately none have fixed the issue:

*

*Booting from a Windows 7 iso and attempting an auto-repair (yields "the partition table does not have a valid system partition" and claims to fix it successfully, yet nothing changes despite running it multiple times)

*Booting from a Windows 7 iso and using "bootrec /fixmbr", "bootrec /fixboot", and "bootrec /rebuildbdc" (/fixmbr and /fixboot say "completed successfully" and /rebuildbcd identifies 1 OS, but when attempting to add it, it says "Element not found")

*Booting from a Windows 7 iso and executing "bootsect /nt60 all /mbr" (runs successfully, but nothing changes as far as I can tell)

A: Tl;dr: I had my drives plugged into the wrong SATA ports. I needed the SSD with Windows to show up as drive 0 (by physically plugging it into port #0).
Everything seems to work now.
Time to try that Windows 10 upgrade...
Why this works: Not 100% sure, but it appears that Windows 7 only checks the first drive it discovers in certain situations (such as msconfig's boot tab, running bcdedit in CMD, etc.) despite the fact that it can boot from an out-of-order drive just fine.


text:
Q: Multiple slidetoggles I have question about how I add another menu item in the following code. I would like to add a contact "menu" item. I found a lot of examples but they were all examples where the items was in a list, i want them to be displayed in a line. I would like that both of them can slide down and up independently and if its possible add a close link so the user can hit that and the slide. slides up again. I hope someone in here can help me. I'm new to jquery.
Javascript:
$(function() {
   $('#about').click(function() {
   $('.about').slideToggle('fast');
  return false;
  });

});

HTML:

About

blah blah

css:
#about {
margin-left: 325px;
}

.about {
display:none;
width: 100%;
background-color: #fff;
height: 351px;
padding-left: 325px;
}

.text {
padding-bottom: 35px;
padding-right: 35px;
font-family: 'HelveticaNeue-Light';
-moz-column-count: 3;
-moz-column-gap: 30px;

/* Safari and Chrome */
-webkit-column-count: 3;
-webkit-column-gap: 30px;

column-count: 3;
column-gap: 30px;
}

A: Try with this:
$('h2 a').click(function(e) {
  $('.'+this.id).slideToggle('fast');
  e.preventDefault();
});

its possible add a close link so the user can hit that and the slide. slides up again.
For this you can add a close link in each slides with a class like
Close
and then you can add this:
$('.close').click(function(e){
    $(this).closest('div').slideUp('fast');
});


text:
Q: Combine Rows MS Access (SQL) I need to combine rows to merge into one single row of the data for the following scenario. would really appreciate any help here. I'm trying this in MSAccess

I would like result as 1 row which has earliest INSTOREDATE  which is 21-Jan-19, total of TOTALBUY(10000+300+4000+2475=16,775). below is the result i am expecting

A: SELECT DISTINCT SEASON,
         PHASE,
         STYLEBR,
         COLOURCODE,
         INSTOREDATE,
         TICKETRETAIL,
         SUM(TOTALBUY) AS TOTAL
FROM YourTable

or
       SELECT SEASON,
        PHASE,
        STYLEBR,
        COLOURCODE,
        INSTOREDATE,
        TICKETRETAIL,
        SUM(TOTALBUY) AS TOTAL
FROM YourTable
GROUP BY  SEASON, PHASE, STYLEBR, COLOURCODE, INSTOREDATE, TICKETRETAIL


text:
Q: Converting object to an encodable object failed: Instance of '_CompactLinkedHashSet>' When I try to call the function below, flutter return this error: Converting object to an encodable object failed: Instance of '_CompactLinkedHashSet<List>'
Code:
 Future<void> signupVisitor() async {
    final _baseUrlToinu = 'https://api.toinu.com.br/api/v1/auth/signup';

    final response = await http.post(_baseUrlToinu,
        body: json.encode({
          "nameCountry": "Brazil",
          "states": [
            {
              "initials": "MG",
              "cities": {
                ["city 1", "city 2", "city 3"]
              }
            }
          ]
        }));

    final responseBody = json.decode(response.body);
    print(responseBody);

      }

A: Try to fix 'cities' value.
I think this {['city1', 'citi2'...]} code is wrong.
The 'cities' value is a object because you use '{}' but there is no key.
If you want 'cities' value as array [], you need to erase '{}'.
json.encode({
          "nameCountry": "Brazil",
          "states": [
            {
              "initials": "MG",
              "cities":
                ["city 1", "city 2", "city 3"]

            }
          ]
        })


text:
Q: Removing CSS property using jQuery
Possible Duplicate:
Is it possible to remove inline styles with jQuery?

I'm building a javascript application doing something with images.
At some point I'm having an element with inline style css-properties (width & height).
I want to remove these properties with javascript/jQuery.
I know you can set css-properties with .css() method.
Is there a way to remove the properties like you do with .removeAttr()? Potential other css-properties should not be removed.

A: From the documentation:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or  element.

So what you need, is just this:
$('element').css({width:'', height:''});

A: try this :
$('div').css({'width' : '', 'height' : ''});

or if there is a class, you remove it by:
$('div').removeClass('someClass');


text:
Q: javascript regex matches with g flag but not y flag I'm having trouble understanding why this is returning true
let str = '\\[\\]\\(\\)\\{\\}\\<\\>';

let reg = new RegExp(/\(/g);
reg.test(str);

yet
let str = '\\[\\]\\(\\)\\{\\}\\<\\>';

let reg = new RegExp(/\(/y);
reg.test(str);

is returning false.
Adding the global flag to the sticky flag doesn't help either.

A: Adding the global flag to the sticky flag doesn't help either.

A regular expression defined as both sticky and global ignores the
  global flag.
The "y" flag indicates that it matches only from the index indicated
  by the lastIndex

You must set the lastIndex property of the regex, it defaults to 0, and there isn't any ( at that index, that's why nothing is matched. The ( appears at index 5.
let str = '\\[\\]\\(\\)\\{\\}\\<\\>';

let reg = /\(/y; // No need for new RegExp

reg.lastIndex = str.indexOf('('); // 5
reg.test(str); // True

More on sticky flag here:

A: Sticky flag y starts matching at position 0 (reading from lastIndex property). There is no ( left at that position in str so your second match try fails.
Sticky flag from MDN:

matches only from the index indicated by the lastIndex property of
  this regular expression in the target string (and does not attempt to
  match from any later indexes)


text:
Q: vagrant, install chef/centos-6.6 My vagrant version is:
$ vagrant --version
Vagrant version 1.0.1

Following these instructions, vagrant init works:
$ vagrant init chef/centos-6.6
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

But vagrant up can't find the box:
$ vagrant up
There was a problem with the configuration of Vagrant. The error message(s)
are printed below:

vm:
* The box 'chef/centos-6.6' could not be found.

What is the way to configure vagrant, or the command line option, to use chef/centos-6.6?

A: Chef has removed all of their boxes from atlas. They have left a comment here https://atlas.hashicorp.com/chef/ saying:

If you are looking for Bento boxes they now have their own
  organization https://atlas.hashicorp.com/bento/

A: If you trigger a:
vagrant box add chef/centos-6.6

with the outdated source (chef) it will provide feedback leading to bento as the new source, something along the lines of:

Name: bento/centos-6.6
  Provider: virtualbox
  Version: 2.2.0

This eventually makes more concrete what is written on the site at the chef atlas link, that the command in your question shall now instead be:
$ vagrant init bento/centos-6.6

(replacing chef by bento)

A: Some time ago hashicorp moved their images to atlas. Boxes are now downloaded here:
https://atlas.hashicorp.com/boxes/search
Your box is here:
https://atlas.hashicorp.com/chef/boxes/centos-6.6
I can download the box with Vagrant 1.7.2. You are using 1.0.1.
So i think it's a version issue. You have to install a newer version.


text:
Q: proof/counterexample about local extrema of composite function Problem
Let $f\colon\mathbb{R}\to\mathbb{R}$ be a differentiable function.
If $f$ has local extrema at $x = a$, then $f(f(x))$ also has local extrema at $x=a$?

The original problem is :
Let $f, g\colon\mathbb{R}\to\mathbb{R}$ be a differentiable function.
If $g$ has local extrema at $x = a$, then $f(g(x))$ also at $x = a$?
This is false, for $f(x)=x^2\displaystyle\sin\left(\frac{1}{x}\right), \ f(0) = 0$ and $g(x)=x^2$
Because, $g$ has local extrema at $x=0$ but, $f(g(x))=f(x^2)$ contains $\displaystyle\sin\left(\frac{1}{x^2}\right)$ which switches its sign infinitely.
And this term makes $f(g(x))$ doesn't have a local extrema at $x=0$

Then how about $f(f(x))$, not $f(g(x))$?
'Infinitely changing sign' occurs this counterexample for $f(g(x))$ case,
But I think the same problem won't be happened for $f(f(x))$. (By the definition of local extrema)
How can I proof this? or is there any counterexample?

A: You can have the same kind of counterexample for $f \circ f$. Consider for example any differentiable function $f : \mathbb{R} \rightarrow \mathbb{R}$ satisfying
$$\forall x \in \left[-1,1 \right], \quad f(x) = x^2 \sin \left( \frac{1}{x}\right) \ \quad \quad \quad \text{and} \quad \quad \quad \forall x \in \left[2,4 \right], \quad f(x) = (x-3)^2 \ $$
Then such an $f$ has a local minimum at $x=3$, whose value is $f(3)=0$, but in a neighbourhood of $x=3$, you will have
$$f \circ f (x)= (x-3)^4 \sin \left( \frac{1}{(x-3)^2}\right)$$
which oscillates around $0$ and hence does not have an extremum at $x=3$.


text:
Q: Erlang code explained I am having a bit of trouble getting my head around the following erlang code
-module(threesix).
-export([quicksort/1]).

quicksort(Pivot, Left, Right, []=_Src) ->
     {Left, Pivot, Right};
quicksort(Pivot, Left, Right, [H|T]=_Src) when H < Pivot ->
     quicksort(Pivot, [H|Left], Right, T);
quicksort(Pivot, Left, Right, [H|T]=_Src) ->
     quicksort(Pivot, Left, [H|Right], T).

quicksort([]) ->
     [];
quicksort([H|T]=_List) ->
     {Left, Pivot, Right} = quicksort(H, [], [], T),
     quicksort(Left) ++ [Pivot] ++ quicksort(Right).

I am specifically talking about the use of _Src and _List in the parameters.
Are these simply for documentation as I cannot see why they are used?

A: Yes, they're only for documentation. They're not actually used (as signified by the leading underscore).


text:
Q: PHP parse error bracket expected When I run the following PHP code:
<?php

$start = "https://en.wikipedia.org";

function follow_links($url) {

    $doc = new DOMDocument();
    $doc->loadHTML(file_get_contents($url));

    $linklist = $doc->getElementsByTagName("a");

    foreach ($linklist = $link) {
        echo $link->getAttribute("href")."\n";
    }
}

follow_links($start);

Error:

Parse error: syntax error, unexpected ')' in C:\xampp\htdocs\test.php on line 12

What am I doing wrong, because I swear that I have closed all brackets correctly.

A: Change your foreach loop to this.  foreach reference
foreach ($linklist as $link) {
        echo $link->getAttribute("href")."\n";
    }

A: You need to change this
foreach ($linklist = $link) {

to this..
foreach ($linklist as $link) {


text:
Q: Installing Chef Solo on a windows Server I am new to Chef and cloud. I have to install chef on windows server 2008. I was going through the documentation here:
http://wiki.opscode.com/display/chef/Installing+Chef+Client+on+Windows
But few of the steps are not clear to me.
I have a very simple setup, its Chef solo so I have just one windows server where I am trying to install it and practice writing some cookbooks.
Please help me out with this.
The steps in the link above which is not clear to me is:
Step Name: Copy over the validation key
I do not understand which validation.pem it is talking about.
Thanks for your help in advance..

A: If you only want to use Chef Solo, then you don't need to do anything with "validation.pem", "'USERNAME'.pem", or "knife.rb".
Step 1: Install the Chef Windows MSI.
Step 2: Read the Chef Solo Documentation.
The paths on that page are specific to Unix, but you should be able to adapt them to the appropriate places for your Windows system.
Essentially to use Chef Solo, you need:

*

*A solo.rb configuration file. This should point to the location of the cookbooks you're using, e.g., "C:\chef\cookbooks"

*A JSON file that describes the node (like, create mynode.json), particularly the run list to use, e.g.:
{
    "run_list": ["recipe[windows]", "recipe[mycookbook_one"]]
}
Et cetera.

*

*The actual cookbooks in the location specified in the solo.rb. You can download several from the Chef Community Site that already work with Windows such as "windows", "iis", "sql_server" and many more.

*Run chef-solo specifying the config file and the JSON file. You'll probably want to do this as Administrator.
chef-solo -c solo.rb -j mynode.json
If you get stuck, the Chef Users Mailing List is a great place to ask questions.


text:
Q: How to change development port 3030 when I build and deploy to target server? I am facing a problem is dart editor using 3030 as default port.
My url always start from http:// 127.0.0.1:3030 /xxxx in my dart code.
So, I want to know any flexible can change my host/port setting in dart script when deploy it to different places?

A: I'm not sure if I understand your question correctly.
This is nothing you set in your Dart script unless your Dart script is the web server.
This is a configuration setting of the web server you are using.


text:
Q: Could not find rugged-0.24.0 in any of the sources I got an error when Installing gitlab on Centos 6.7 from source code.

My ruby version is 2.1.0 ,gem version is 2.2.5 .
How can I install rugged-0.24.0 ?
Thank you first.

A: You are using ruby.taobao.org as your gem source, it hasn't have rugged version yet. To install rugged v 0.24 you can do any of these:
a) Update ruby.taobao.org or ask whoever can update it
b) User official gem source, i.e. put: source 'https://rubygems.org' in your Gemfile

A: *

*reason:We can not visit https://rubygems.org

*Unfortunately , 'https://ruby.taobao.org' which had served serval years didn't update recently。

*https://gems.ruby-china.org now is on service.


text:
Q: Angular ng-style with a multiple conditional expression and multiple style attributes I want to add multiple style attribute for accordion group using ng-style with conditions as ng-class is not working with accordion.
Here is how i am trying:
ng-style="{ border: ivrMessageForm.ivr_messagetitle.$error.required && !isFormValid ? '2px solid' : 'none' }"

this is working fine. but want to add border-color too.
I tried this:
ng-style="{ border: ivrMessageForm.ivr_messagetitle.$error.required && !isFormValid ? '2px solid' : 'none', border-color: ivrMessageForm.ivr_messagetitle.$error.required && !isFormValid  ? 'red' : 'none'}"

but it gives me parse error.
i also tried this one but same parse error:
ng-style="ivrMessageForm.ivr_messagetitle.$error.required ? {border:'3px solid', border-color: 'red'} : {border:'none', border-color: 'none'}"

can anyone help me how to add multiple style attributes with multiple conditions using ng-style.

A: You should add single quotes to 'border-color'
ng-style="{ border: ivrMessageForm.ivr_messagetitle.$error.required && !isFormValid ? '2px solid' : 'none', 'border-color': ivrMessageForm.ivr_messagetitle.$error.required && !isFormValid  ? 'red' : 'none'}"

A:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
 $scope.styleobj = {};
  $scope.borderflag = true;
  $scope.widthflag = true;
  $scope.getStyle= function(){
     if($scope.borderflag){
    $scope.styleobj.border = '2px solid';
     }if($scope.widthflag){
       $scope.styleobj.width = '100%';
        $scope.styleobj.font = 'italic bold 12px/30px Georgia, serif';
     }
     console.log($scope.styleobj);
     return $scope.styleobj;
  }

    $scope.name = 'Arindam Banerjee';

}

  Hello, {{name}}!

   Hello, {{name}}!

##