text:
Q: Get next value of array depending on current one I've got this code :
$array1 = array("2018-02-01" => "10", "2018-03-01" => "20");
$array2 = array("2018-01-01" => "random", "2018-02-01" => "random", "2018-03-01" => "random", "2018-04-01" => "random");

$end_array = array();

$v = 0;
foreach($array2 as $key => $value) {

    if($array1[$key]) {
        $v = intval($array1[$key]);
        $end_array[] = $v;
    } else {
        $end_array[] = $v;
    }
}

var_dump($end_array);

Which is giving me this output :
array(4) { [0]=> int(0) [1]=> int(10) [2]=> int(20) [3]=> int(20) }

But I want to get this output :
array(4) { [0]=> int(10) [1]=> int(20) [2]=> int(20) [3]=> int(20) }

In other words, I want to assign the value of the current array to the previous one.
I tried looking for ways to check if the key of the next array is a key in my array1 but it still didn't give me the right output (or rather I don't think I correctly checked, I can't seem to find the right algorithm). I hope it's clear what I'm trying to do.

A: EDIT: i did not understand in a first place.
Basically you can just handle your id and just change the last element if it exist in the first array
$end_array = array();
$id = 0;
$v = 0;
foreach($array2 as $key => $value) {
    if(isset($array1[$key])) {
        $v = intval($array1[$key]);
        $end_array[$id] = $v;
        if(isset($end_array[$id-1]))
        {
            $end_array[$id-1] = $v;
        }
    } else {
        $end_array[$id] = $v;
    }
$id++;
}

A: I'm not really sure what you are trying to do but you can check if the key exists with the array_key_exists() function. More info


text:
Q: Array strings come out as undefined So i've got an array of 9 strings, predefined, and when i try to call them out in a function they come out as undefined, i don't really know what am i doing wrong :/
function checkAns(){
    var nr_pytania = (document.getElementById("q_id").value)-1;
    var odpowiedz = document.getElementById("answer").value;
    var odpowiedzi = ["Mazury", "Korfanty", "Paderewski", "Wersalski", "Zaolzie", "Orlęta", "Wisła", "Haller", "Gdańsk"];

        console.log(odpowiedzi[0].charAt[0]);
        if(odpowiedz == odpowiedzi[nr_pytania])
        {
            document.getElementById("answer").value = "POPRAWNE!";
                for(var i=0; i<odpowiedzi[nr_pytania].length; i++)
                {
                    document.getElementById("letter"+nr_pytania+i).innerHTML = odpowiedzi[nr_pytania].charAt[i];
                }
        }
        else
        {
            document.getElementById("answer").value = "Odpowiedź błędna!";
        }

}
So, the part that is the most important to me is:
    var odpowiedzi = ["Mazury", "Korfanty", "Paderewski", "Wersalski", "Zaolzie", "Orlęta", "Wisła", "Haller", "Gdańsk"];

    console.log(odpowiedzi[0].charAt[0]);

Because the console returns undefined, and im not really sure why :(

A:

var odpowiedzi = ["Mazury", "Korfanty", "Paderewski", "Wersalski", "Zaolzie", "Orlęta", "Wisła", "Haller", "Gdańsk"];

console.log(odpowiedzi[0].charAt(0));

You need to change it from charAt[0] to charAt(0).
Additional reading for String.prototype.charAt().

A: You could simply use odpowiedzi[0][0] - no need to use charAt() :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using imagejpeg() in Laravel I am migrating my existing PHP program to Laravel. I know the upload should be $request->files->store('images'); but this doesn't compress the images beforehand.
I have found Intervention Image plugin for Laravel but I don't want to use it because I want it to be pure PHP only.
My working code from pure PHP was:
$info = getimagesize($tmpFilename);
if ($info['mime'] == 'image/jpeg') {
    $image = imagecreatefromjpeg($tmpFilename);
} else if ($info['mime'] == 'image/gif') {
    $image = imagecreatefromgif($tmpFilename);
} else if ($info['mime'] == 'image/png') {
    $image = imagecreatefrompng($tmpFilename);
}

imagejpeg($image, $path, 60);

I know the images get saved at /storage/app/public/ so I used that path for imagejpeg as well. This is my laravel code:
$tmp_file = $inner->getPathName();
imagejpeg($tmp_file, '/storage/app/public/images/hehe.jpg', 60);

But it doesn't work. It only says
imagejpeg(/storage/app/public/images/hehe.jpg): failed to open stream: No such file or directory
Any help would be appreciated


text:
Q: how to display results from search box in masterpage in asp.net i have a search-box in masterpage, in asp.net project and i dont know two things:
1) how to transfer the results to a new page (because its in master page)
2) how to display the results?
for the first question i tried creating a Session with the DataTable of the answers and in new page (which is built on the master page) on the pageload function check if the Session !=null but it doesn't work well becuase the pageload function is before the masterpage function.
for the second question i tried this:
users += "
";
users += "
" + dt.Rows[0][0].ToString() + "
";
users += "
" + dt.Rows[0][1].ToString() + "
";
users += "
";

but is there a better way to show the results?

A: You don't need to transfer results you just need to send search string to the page, try this
On search button click in master page
protected void SearchButton1_Click(object sender, EventArgs e)
{
  Response.Redirect("~/SearchPage.aspx?searchTerm="+txtSearchter.Text);
}

On the page load of the results page
protected void Page_Load(object sender, EventArgs e)
{
  if(!IsPostBack)
   {
     string SearchTerm = Request.QueryString["searchTerm"];
     //Do database search and bind to a gridview
   }
}

A: On the master page you can put a control to display the results.

    <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>

<%# Eval("columnName") %>

        </ItemTemplate>
    </asp:Repeater>

And then on the aspx of the page that is using the Mater, use FindControl to locate the control on the master page and bind the data to it.
protected void SearchButton1_Click(object sender, EventArgs e)
{
    Repeater rep = this.Master.FindControl("Repeater1") as Repeater;
    rep.DataSource = DataTable;
    rep.DataBind();
}

A: It is better to show the result in Dialog(Popup) instead of Transfering it to new page
<GridView>
<Columns>
    <asp:BoundField DataField="FirstName" HeaderText="First Name" ReadOnly="True" Visible="True" />
//other Boundfields
    <asp:TemplateField HeaderText="Search">
    <ItemTemplate>
       <asp:Button Id="Searchbtn" runat="server" Text="Search" onClick="Searchbtn_Onclick"/>
    </ItemTemplate>
   </asp:TemplateField>
</columns>
</GridView>

Code Behind
protected void Searchbtn_Onclick(object sender, EventArgs e)
{
    //bind the gridview
    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "javascript:ShowDialog(" + "'Result " + "');", true);
}

then in Script
script type="text/javascript">
    function ShowDialog() {
       $("#dialog").dialog({
            autoOpen: false,
            hide: "puff",
            show: "slide",
            width: "70%",
            modal: true,
            close: function(event, ui) {
                $("#dialog").find("form").remove();
                $("#dialog").dialog('destroy');

            }
        });
        $("#dialog").dialog("open");

    }


text:
Q: Ember calling delete action for object in each loop behaves strangely In ember calling an action to delete from model in a #each always deletes the last object.
{{#each itm in content}}
  <li>
      {{itm.firstName}} {{itm.lastName}}
      <button {{action delete itm}}>delete</button>
  </li>
{{/each}}

App.IndexController = Ember.Controller.extend({
actions:{
    delete: function(itm){
        alert("deleting " + itm.firstName + " " + itm.lastName)
        this.content.popObject(itm);
    }
}
});

it seems like when I delete the object ember gets lost in his action references and always deletes the last item!
but the alert box gives me the right data.
here is a fiddle cause I find this hard to explain: http://jsfiddle.net/jmorvan/ap4qD/
Am I doing something terribly wrong?

A: You can use this.content.removeObject(itm); Worked in the jsfiddle you provided.


text:
Q: Getting background-color of display block to fill only behind text I ran into a situation where I have a link that is set as a display:block. I'm trying to fill the background-color property with a color, but only behind the text; instead, it's filling the entire background of that row, which is logical, but not what I want. How can I fill only the background of the text without being an inline element? Or is this not possible?
HTML:
mylink

CSS:
a {
    display:block;
    background-color:blue;
}

A: If you need to keep the link as a block, you can wrap the text in a  and apply the background colour to that.

A: Simple code would be something like this:

 Hellobluelink

You can then add padding and other style to the span tag.
You can add a ID tag to the span if its a special once off thing for specific styling.


text:
Q: How can i add menu items to the context menu of a NSTextField I tried to overwrite the simple NSView method:
- (NSMenu *)menuForEvent:(NSEvent *)event {
   NSMenu* result = [super menuForEvent: event];
   NSMenuItem* mi = [[NSMenuItem alloc] initWithTitle: @"Foobar" action: @selector(foobar) keyEquivalent: @""];
   [result addItem: mi];
   return result;
}

but it does not work. It is never called.

A: Try to use the NSTextViewDelegate Protocol
- (NSMenu *)textView:(NSTextView *)view menu:(NSMenu *)menu forEvent:(NSEvent *)event atIndex:(NSUInteger)charIndex

The window's field editor will then ask your NSTextField for the menu

A: If the text field has focus, I believe the menu you're getting is actually that of the Field Editor. Maybe ask it for its menu.

A: Thanks for others pointing the way. I haven't been able to get the window's default field editor to use any delegate methods. Finally I put the following in my window delegate's -windowDidLoad method
NSTextView* defaultFieldEditor = [self.window fieldEditor:YES forObject:nil];
//  defaultEditor.delegate = self; didn't help
NSMenu *mu = defaultEditor.menu;
[mu insertItem:[NSMenuItem separatorItem] atIndex:0];
[mu insertItemWithTitle:@"Insert Line"
                 action:@selector(acnInsertLine:)
          keyEquivalent:@"" atIndex:0];
 [mu insertItemWithTitle:@"Delete Line"
                  action:@selector(acnDeleteLine:)
           keyEquivalent:@"" atIndex:0];

This is supposed to put the items at the beginning (so reverse order). You could use addItem: instead. Both suffer from the problem that the contents of the menu vary and your items are likely to up somewhere in the middle.
Note that the field editor is a NSTextView even if the control it covers is a NSTextField. This has caused me some perplexity.


text:
Q: MySQL query for top documents based on associated tags There is  a list of documents. Multiple  users can tag document. Now for  given tags (more tha, list of  documents is required where more than 30% of users have chosen  that tag.

mapping:
---------------------------
user_id | document_id | tag
    1   |     34      | 26
    2   |     34      | 26
    3   |     36      | 25
    4   |     34      | 27

A helper table is also there with total tag_count for given document.

counters:
---------------------------
document_id | tag_count
    34      | 12
    36      | 26

I am able to write query for single tag like

select * from mapping m
join (select document_id,count(*) as req_tag_count
from mapping
group by document_id) as s on s.document_id = m.document_id
join counters c on c.document_id = m.document_id and req_tag_count / c.tag_count > .3
where m.tag = 26

But not able to write query for multiple tags like return documents with both tags A and B fulfilling the above condition of 30%.

A: Maybe this is what you need:
SELECT t.document_id
FROM (SELECT m.document_id
    FROM mapping m
    WHERE m.tag = 26         # Specify the first tag
    GROUP BY m.document_id
    HAVING COUNT(m.document_id) /
    (SELECT count(document_id)
        FROM mapping i
        WHERE i.document_id = m.document_id
        GROUP BY i.document_id) > 0.3
    UNION SELECT n.document_id
    FROM mapping n
    WHERE n.tag = 27         # Specify the second tag
    GROUP BY n.document_id
    HAVING COUNT(n.document_id) /
    (SELECT count(document_id)
        FROM mapping i
        WHERE i.document_id = n.document_id
        GROUP BY i.document_id) > 0.3)
AS t
GROUP BY t.document_id
HAVING COUNT(t.document_id) = 2    # One per tag

It worked when I tested it. You can adapt this for 3 tags as well.


text:
Q: Does Apache spark 2.2 supports user-defined type (UDT)? From this JIRA ticket Hide UserDefinedType in Spark 2.0
, seems that spark hide the UDT API from version 2.0.
Is there exists an alternative function or API we can use in version 2.2,  so that we could define UserDefinedType? I wish to use a custom type in dataframe or structured streaming.

A: There is no alternative API and UDT remains private (https://issues.apache.org/jira/browse/SPARK-7768).
Generic Encoders (org.apache.spark.sql.Encoders.kryo and org.apache.spark.sql.Encoders.javaSerialization) serve similar purpose in Dataset, but there are not direct replacement:

*

*How to store custom objects in Dataset?

* Questions about the future of UDTs and Encoders


text:
Q: ASP .NET CORE 2.2 JWT & Claims identity Authentication for Website I have an .net core 2.2 api which generates (on a successful login) a JWT token which contains a claims identity that passes along information such as the username, permissions and roles of the authenticated user.
In my .net core 2.2. web app I have a login mechanism which retrieves the JWT token via the user of a controller.
My question is.
How can I expand the token from within my login controller and set up my web app to include the use of the authentication mechanisms like User.Identity.IsAuthenticated, User.IsInRole("Admin") and controller actions like [Authorize] and [Authorize(Roles="Admin")]
I've been directed towards looking at the source code behind external authentication providers such as facebook/google but to no avail.
Thanks in advance.

A: First step is to use cookie authentication in Startup.cs :
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

In the Configure method, use the UseAuthentication method to invoke the Authentication Middleware that sets the HttpContext.User property. Call the UseAuthentication method before calling UseMvcWithDefaultRoute or UseMvc:
app.UseAuthentication();

Then in your auth controller , after getting token and decode to get the claims , you should create new ClaimsIdentity , add your claims and sign-in user :
if (!User.Identity.IsAuthenticated)
{
    var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, YourName));
    identity.AddClaim(new Claim(ClaimTypes.Name, YourName));
    identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));

    //Add your custom claims

    var principal = new ClaimsPrincipal(identity);
    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });

}

After that , you can useUser.Identity.IsAuthenticated, User.IsInRole("Admin") and [Authorize(Roles="Admin")]:
[Authorize(Roles = "Admin")]
public IActionResult About()
{
    var result = User.IsInRole("Admin");
    return View();
}


text:
Q: SAS date variable I have a SAS data set A and one of the column is date. 31AUG2010. when I do the following code:
data b;
set a;
newdate=date;
run;

The newdate becomes numeric and 31AUG2010 becomes 18505. How do I solve it?

A: Apply a format.
See the example below with two different formats applied.
data b;
set a;
newdate=date;
newdate2 = date;

format newdate date9. newdate2 ddmmyy10.;
run;

A: Dates are just the number of days from 01JAN1960.  You need to apply a format.  A format doesn't change how the number is stored, just how it is presented to you.
Data a;
set a;
format newdate date9.;
newdate=date;
run;

A: You have to assign a date format to the new field. Since Date is a numeric field in SAS; SAS assigns the default format which is numeric.
You can assign the format by adding a format statement
data test;
format newdate date9.;
date='31AUG2010'd;
newdate=date;
run;

date has no format assigned but newdate has date9. format assigned.
Output:
newdate=31AUG2010 date=18505


text:
Q: write array starting from specific column to new workbook using xlwt I am trying to write an array (data = [][]) to a worksheet I will create using xlwt.
My question is can I specify a column to start from?  I am planning to use a for loop to iterate through the array retrieving the values row by row starting a new line with each row ex: first row starts at C1, next row starts at C2 etc...  I have read the documentation and examples but cannot find a clear way to do this.  Any help would be greatly appreciated!

A: Something like:
wb = xlwt.Workbook()
ws = wb.add_sheet('Sheet1')
for r, row in enumerate(data):
    for c, col in enumerate(row):
        ws.write(r, 2 + c, label=col)


text:
Q: Expected value of the sample median from a folded normal distribution Suppose $X_1, \ldots, X_n \sim N(0,\sigma^2)$ are iid. Find the expected value of $M$, the median of $\vert X_1 \vert, \ldots \vert X_n \vert$
What I have so far:
The density of $\vert X_i \vert$ is given by:
$$f_{\vert X \vert}(x) = \frac{2}{\sqrt{2\pi \sigma^2}}\exp\left(-\frac{x^2}{2\sigma^2}\right)$$
If $n = 2m - 1$, the median $M$ is the $m^{th}$ order statistic of $\vert X_1 \vert, \ldots, \vert X_n \vert$. This has density
$$f_{\vert X \vert_{(m)}} (x) = \frac{n!}{(m-1)!(n-m)!} f_{\vert X \vert}(x) (F_{\vert X \vert})^{m-1}(1 - F_{\vert X \vert})^{n-m}$$
where $F_{\vert X \vert}(x) = F_X(x) - F_X(-x)$ is the cdf of $\vert X \vert$. So the expected value of the median is
$$\mathbb E M = \int_0^\infty x  f_{\vert X \vert_{(m)}} (x) dx$$
Is there a better way to approach this, rather than having to compute this integral?


text:
Q: weird problem with select count from multiple tables (with joins) I'm having an odd problem with the following query, it works all correct,
the count part in it gets me the number of comments on a given 'hintout'
I'm trying to add a similar count that gets the number of 'votes' for each hintout, the below is the query:
SELECT h.*
  , h.permalink AS hintout_permalink
  , hi.hinter_name
  , hi.permalink
  , hf.user_id AS followed_hid
  , ci.city_id, ci.city_name, co.country_id, co.country_name, ht.thank_id
  , COUNT(hc.comment_id) AS commentsCount
FROM hintouts AS h
INNER JOIN hinter_follows AS hf ON h.hinter_id = hf.hinter_id
INNER JOIN hinters AS hi ON h.hinter_id = hi.hinter_id
LEFT JOIN cities AS ci ON h.city_id = ci.city_id
LEFT JOIN countries as co ON h.country_id = co.country_id
LEFT JOIN hintout_thanks AS ht ON (h.hintout_id = ht.hintout_id
  AND ht.thanker_user_id = 1)
LEFT JOIN hintout_comments AS hc ON hc.hintout_id = h.hintout_id
WHERE hf.user_id = 1
GROUP BY h.hintout_id

I tried to add the following to the select part:
COUNT(ht2.thanks_id) AS thanksCount

and the following on the join:
LEFT JOIN hintout_thanks AS ht2 ON h.hintout_id = ht2.hintout_id

but the weird thing happening, to which I could not find any answers or solutions,
is that the moment I add this addtiional part, the count for comments get ruined (I get wrong and weird numbers), and I get the same number for the thanks -
I couldn't understand why or how to fix it...and I'm avoiding using nested queries
so any help or pointers would be greatly appreciated!
ps: this might have been posted twice, but I can't find the previous post

A: When you add
LEFT JOIN hintout_thanks AS ht2 ON h.hintout_id = ht2.hintout_id

The number of rows increases, you get duplicate rows for table hc, which get counted double in COUNT(hc.comment_id).
You can replace
COUNT(hc.comment_id) <<-- counts duplicated
/*with*/
COUNT(DISTINCT(hc.comment_id))  <<-- only counts unique ids

To only count unique appearances on an id.
On values that are not unique, like co.county_name the count(distinct will not work because it will only list the distinct countries (if all your results are in the USA, the count will be 1).
Quassnoi
Has solved the whole count problem by putting the counts in a sub-select so that the extra rows caused by all those joins do not influence those counts.

A: SELECT  h.*, h.permalink AS hintout_permalink, hi.hinter_name,
        hi.permalink, hf.user_id AS followed_hid,
        ci.city_id, ci.city_name, co.country_id, co.country_name,
        ht.thank_id,
        COALESCE(
        (
        SELECT  COUNT(*)
        FROM    hintout_comments hci
        WHERE   hc.hintout_id = h.hintout_id
        ), 0) AS commentsCount,
        COALESCE(
        (
        SELECT  COUNT(*)
        FROM    hintout_comments hti
        WHERE   hti.hintout_id = h.hintout_id
        ), 0) AS thanksCount
FROM    hintouts AS h
JOIN    hinter_follows AS hf
ON      hf.hinter_id = h.hinter_id
JOIN    hinters AS hi
ON      hi.hinter_id = h.hinter_id
LEFT JOIN
        cities AS ci
ON      ci.city_id = h.city_id
LEFT JOIN
        countries as co
ON      co.country_id = h.country_id
LEFT JOIN
        hintout_thanks AS ht
ON      ht.hintout_id = h.hintout_id
        AND ht.thanker_user_id=1
WHERE   hf.user_id = 1


text:
Q: Can I get scuba gear for a mosquito? I'm trying to venture under the sea, but I've been told that my familiar (a mosquito) wouldn't be able to breathe! Do I have to leave him on the surface, or is there some way to kit him up for aquatic adventures?

A: When you first meet the Old Man, he should give you a little bitty bathysphere, which allows you take non-water breathing familiars underwater at the cost of -20 pounds. After retrieving the Old Man's boot, you have the option of receiving the das boot familiar equipment, which also allows non-water breathing familiars to adventure underwater with a reduced cost of -10 pounds.
Another way to adventure with your familiar underwater without a penalty to familiar weight is to use willyweed, which is an item that your penpal can send to you. This, however, is a limited-turn item effect unlike the familiar equipment.


text:
Q: can anyone tell me how to store geocoder address in android database using android studio? I am able to see the address(for on click listener) fetching from the GeoCoder code and i am able to display in log file but i am not able to store that address in my local DataBase.
can any one please help me in this issue.
thanks in advance.
package com.example.raghotham.androidgeocodelocation;

import java.util.List;

public class MainActivity extends Activity {

Button btnGPSShowLocation;
Button btnShowAddress;
TextView tvAddress;
final DatabaseHandler1 db = new DatabaseHandler1(this);

AppLocationService appLocationService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvAddress = (TextView) findViewById(R.id.tvAddress);
    appLocationService = new AppLocationService(
            MainActivity.this);

    btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
    btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            Location gpsLocation = appLocationService
                    .getLocation(LocationManager.GPS_PROVIDER);
            if (gpsLocation != null) {
                double latitude = gpsLocation.getLatitude();
                double longitude = gpsLocation.getLongitude();
                String result = "Latitude: " + gpsLocation.getLatitude() +
                        " Longitude: " + gpsLocation.getLongitude();

                tvAddress.setText(result);

            } else {
                showSettingsAlert();
            }
        }
    });

    btnShowAddress = (Button) findViewById(R.id.btnShowAddress);
    btnShowAddress.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Location location = appLocationService
                    .getLocation(LocationManager.GPS_PROVIDER);

            if (location != null) {
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();

                LocationAddress locationAddress = new LocationAddress();

                locationAddress.getAddressFromLocation(latitude, longitude,
                        getApplicationContext(), new GeocoderHandler());

            } else {
                showSettingsAlert();
            }

        }
    });

}

public void showSettingsAlert() {
       AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            MainActivity.this);
         alertDialog.setTitle("SETTINGS");
    alertDialog.setMessage("Enable Location Provider! Go to settings menu?");
    alertDialog.setPositiveButton("Settings",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    MainActivity.this.startActivity(intent);
                }
            });
    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    alertDialog.show();
}

private class GeocoderHandler extends Handler {

    @Override
    public void handleMessage(Message message) {

        String locationAddress;
        switch (message.what) {
            case 1:
                Bundle bundle = message.getData();
                locationAddress = bundle.getString("address");

                Log.d("testing: ", locationAddress);
                break;
            default:
                locationAddress = null;

        }
        tvAddress.setText(locationAddress);
    }
   }
}

I am able to store the latitude and longitude but not the address part.

A: Simply return your address as String and store it in your local db using SQlite. It is easy to store a string in SQLite. Below is the code to get address.
 public static String getAddressFromLocation(Context context,
                double latitude, double longitude) {
            String address = "";
            Geocoder geocoder;
            List<Address> listAddresses;

            try {
                geocoder = new Geocoder(context, Locale.getDefault());
                if (isNetworkAvailable(context)) {
                    listAddresses = geocoder
                            .getFromLocation(latitude, longitude, 1);
                    for (Address addrss : listAddresses) {
                        String adminArea = addrss.getAdminArea();
                        Logging(SHOW_LOG, TAG, "adminArea = " + adminArea);

                        String locality = addrss.getLocality();
                        Logging(SHOW_LOG, TAG, "locality = " + locality);

                        String postalCode = addrss.getPostalCode();
                        Logging(SHOW_LOG, TAG, "postalCode = " + postalCode);

                        String address1 = addrss.getAddressLine(0);
                        Logging(SHOW_LOG, TAG, "address1 = " + address1);

                        String cityState = addrss.getAddressLine(1);
                        Logging(SHOW_LOG, TAG, "cityState = " + cityState);

                        String countryName = addrss.getCountryName();
                        Logging(SHOW_LOG, TAG, "countryName = " + countryName);

                    }
                    address = listAddresses.get(0).getAddressLine(0) + " "
                            + listAddresses.get(0).getAddressLine(1) + " "
                            + listAddresses.get(0).getCountryName();
                } else {
                    address = "";
                }
            } catch (Exception e) {
                address = "";
            }

            Log.i(TAG, "address : " + address);
            return address;
        }


text:
Q: Cannot create instance of 'ProductListingUserControl' defined in assembly ProductListing Hi I am getting following error:

Cannot create instance of 'ProductListingUserControl' defined in assembly 'ProductListing, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Exception has been thrown by the target of an invocation.  Error at object 'System.Windows.Controls.Grid' in markup file 'ProductListing;component/views/productlistingcshostedcontrol.xaml' Line 22 Position 10.

I have a user control which I am using in another class.In another class I have defined  an event ProductSelectionChangedEvent which is giving me above error whenever I am creating the instance of my User control.
I am creating following event for my user control:
Window w = Window.GetWindow(productServiceFunction);
w.LocationChanged += new EventHandler(ProductListingUserControl_LocationChanged);
this.SizeChanged += new SizeChangedEventHandler(ProductListingUserControl_SizeChanged);


text:
Q: Upgrade angular-meteor project (v1.2.1) to Meteor 1.3 Meteor 1.3 was released today (yay). As it has builtin npm support and other goodies, I'd like to upgrade my angular-meteor project (the app is on Meteor 1.2.1).
I run
meteor update

and then (in response to instructions given in the meteor output on first run)
meteor npm install --save underscore jsondiffpatch angular clipboard

Following that, there were no errors on the server side (except for [BABEL] Note: The code generator has deoptimised ...
When loading the client I bumped into:
angular_angular.js?hash=... Uncaught Error: [$injector:nomod] Module 'angular-meteor' is not available!

Which I can't seem to circumvent.
I tried running:
meteor npm install --save angular-meteor

which completed successfully (confimed in package.json) yet angualr still can't find it.
So, what am I doing wrong? What's your advice regarding such an upgrade?

A: I've released 1.3.9_1 that should solve that issue now.


text:
Q: composer update doesn't update files I have a local git repo and project where I want to use it.
composer.json in project folder:

"repositories": [
    {
        "type":"package",
        "package":{
            "name":"api",
            "version":"0.1.0",
            "source":{
                "type":"git",
                "url":"/var/www/modules/api",
                "reference":"master"
            }
        }
    }
],
"require": {
    "api": "*"
}

composer install get source from the repo. Then I commited changes in the repository and make git tag "0.1.1"
In composer.json I changed version to "0.1.1"
run composer update:
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 1 update, 0 removals
  - Updating api (0.1.0 => 0.1.1) Checking out master
Writing lock file
Generating autoload files

But files was not updated.

A: Don't use package as the repository type. You'd have to manually change all information inside if something changes.
package really only is for the situation where you have code that you cannot add a composer.json for, or that is not hosted in version control.
For all other situations, i.e. you have the code in version control, and you can add composer.json to it, use "type" = "vcs" with the repository URL. Composer then works so much better.
See the documentation:

package: If you depend on a project that does not have any support for composer whatsoever you can define the package inline using a package repository. You basically just inline the composer.json object.

See the documentation:

Note: This repository type has a few limitations and should be avoided whenever possible:

*

*Composer will not update the package unless you change the version field.

*Composer will not update the commit references, so if you use master as reference you will have to delete the package to force an update, and will have to deal with an unstable lock file.


text:
Q: How can I use a string to call a method in Node JS I have a function that returns a string of a method I want to call.
For example:
I call the function and it returns the string "price". I then want to use the word price to call another method ( contractObject.price() )
Is there any way to accomplish this in Node JS?

A: Yes, you can use square brackets:
let methodName = "price";

contractObject[methodName]();

contractObject["price"] is equivalent to contractObject.price.

A: This will work.
const functionToCall = yourFunction(); // this returns "price"
// call the price function like this
contractObject[functionToCall]();

A: Ended up figuring out the answer. If I make the whole function a string and then use eval(  ) it calls the method I wanted


text:
Q: Python list delete My program, I want to delete some item from a list:
num_str = input('Enter a number: ')
num_num = int(num_str)

fac_list = list(range(1, num_num + 1))
print("BEFORE: ", fac_list)

for item in fac_list:
    if num_num % item == 0:
        fac_list.remove(item)

print("AFTER: ",fac_list)

output:
Enter a number: 8
BEFORE:  [1, 2, 3, 4, 5, 6, 7, 8]
AFTER:  [2, 3, 5, 6, 7]

It should be:
[3, 5, 6, 7]

What's wrong with it?

A: You are iterating over the list and deleting it, that does not work how you want it to. This is because when you are iterating over the list, the for loop keeps track of the index you are currently at, but when you delete an item from the list, the index gets changed and hence you can end up skipping iterating over some elements.
You can just create a new list, with the values that you need (instead of deleting from old list) , and this can be done using list comprehension -
fac_list[:] = [x for x in fac_list if num_num % x != 0:]

The slice notation on left side is to make this inplace, so that fac_list is changed inplace.
If you want to delete (and not create a new list) , you should iterate over its copy , Example -
for item in fac_list[:]:
    if num_num % item == 0:
        fac_list.remove(item)

A: I haven't tried Anand S Kumar's solution, but instead of generating a new list you can just iterate through it backwards, so as you are deleting items it doesn't affect the index you will be iterating through.
num_str = input('Enter a number: ')
num_num = int(num_str)

fac_list = list(range(1, num_num + 1))
print("BEFORE: ", fac_list)

for i in range(len(fac_list)-1, -1, -1): # Iterate backwards instead
    item = fac_list[i]
    if num_num % item == 0:
        fac_list.remove(item)

print("AFTER: ",fac_list)

Output:

('AFTER: ', [3, 5, 6, 7])


text:
Q: Interactive Powershell using Intellij Run Configuration? I have a python script foo which uses getpass to prompt for a password.  This python script works at the windows powershell command line:
PS D:\Users\me\projects> foo
Password:

I am calling this python script within a powershell script bar.ps1 and everything still works fine at the command line:
PS D:\Users\me\projects> .\bar.ps1 -bar_argument 42
bar_argument is: 42
calling foo
Password:

The above works when I run the script in the Intellij Terminal but when I setup a powershell run configuration using the Intellij powershell plugin the "Password:" prompt never appears and the powershell script just hangs:

C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -File D:\Users\me\projects\bar.ps1 -bar_argument 42
bar_argument is: 42
calling foo

How can I run a powershell script using the Intellij run configuration and have the script work interactively (similar to the command line behavior)?
Thank you in advance for your consideration and response.

A: Your python script needs to run non-interactively, since it's called as such by the PowerShell script. Move the interactive part to the PowerShell script an pass the value as an argument to the python script.

A: Although it is not the powershell terminal the following worked for me with

*

*win10

*IDEA 2019.1

*phyton 3.7.4 (installed: py launcher and associate files with phyton)

In IDEA windows Terminal execute the following command

*

*path

and make sure the path to phyton.exe is set
execute the script with py. It should work:


text:
Q: how do i make a form select option php mysql loop and have the correct option selected in 3 different scenarios? so let's say i have this dropdown box loop which is populated via database table.  by the way this is on an edit/update form page, not the initial create/insert form page.
<select name="company" id="company">
<option value="">-select-</option>
<?php
$selectedvendor = $row['company'];
while($row1 = mysql_fetch_array($result1)) { ?>
<option value="<?php echo $row1['company'] ?>"
<?php
if (count($_POST)>0) {
    if ($row1['company'] == $_POST["company"]) {
        echo " selected='selected'";
    }
} else {
    if ($row1['company'] == $selectedvendor) {
        echo " selected='selected'";
    }
}
?>
><?php echo $row1['company'] ?></option>
<?php } ?>
</select>

i am trying to make it so that the correct option is selected in 3 different scenarios.
scenario 1: on initial page load
scenario 2: form was submitted but validation of some fields failed
scenario 3: form was submitted and there were no validation errors and form submitted successfully
right now, with the above code, scenario 1 and 2 work.  i need to know how to make scenario 3 work.
whichever option was selected which saved to the database, that is the one that should be selected.


text:
Q: Trying to get a css transparent background on an li tag working in IE Have the follow code which works if I put the 'filter' on the ul or any other element but when I place it on the li tag it's not working. I've tried adding display:block but no joy. What could be stopping it working? Here's my css code:
.argh li{
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#4cdddddd, endColorstr=#4cdddddd);
  margin:0 -10px; padding:0.6em 20px; }

PS Css named argh because I've been pulling my hair out with this for a couple of hours now. :)

A: From the Microsoft gradient filter documentation:

The object that the filter is applied to must have layout before the filter effect will display. You can give the object layout by setting the height or width property, setting the position property to absolute, setting the writingMode property to tb-rl, or setting the contentEditable property to true.


text:
Q: How to Backup and Restore SQL server database files? I am using EF Core in .Net 6 App,
The Project is almost Complete,
But Now I want to code for Backup and Restore?
Here is code for EF, But it is not work for EF Core.
code.

A: Backing up a database is not within the scope of an ORM.  The code you linked to does not rely on Entity Framework it uses SQL Server Management Object (SMO).  SMO requires .NET Framework 4.0 or .NET Core 2.0 to run.  You can install the package from Nuget.


text:
Q: Is there any way to fetch the recycle bin items of share point office365 using graph API? Is there any way to fetch the share point O365 site's recycle bin items using graph API?
I am looking for option using IGraphServiceClient c# interface.

A: As you said there is no such Graph API call that can get data from the recycle bin. There is also a feature request already raised by some users in the Microsoft Graph Feedback Forum. Please upvote this feature so that the product team can implement it in the future.


text:
Q: Using [midway] to label a curved path at its centre I am trying to label two curved paths connecting two nodes with labels placed at their centres using the node[midway] option. This is something that should be very simple but I have not been able to come up with something that works. Here is my MWE with my question as two comments:
\documentclass[crop,border=0]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[>=latex]
    \node [draw,rectangle] (Start) {Start};
    \node [draw,rectangle] (Finish) [right=2cm] {Finish};
    \draw [->,out=90,in=90,looseness=0.75] (Start.north) to (Finish.north);
    % I want to label this path using [midway,below] as {forward}
    \draw [->,out=-90,in=-90,looseness=0.75] (Finish.south) to (Start.south);
    % I want to label this path using [midway,above] as {reverse}
\end{tikzpicture}
\end{document}

Can someone please point me in the right direction.
I also appreciate comments to improve code elegance or simplicity.
Thank you.

A: You must put the node direct after to
\documentclass[crop,border=0]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture} [>=latex]
    \node [draw,rectangle] (Start) {Start};
    \node [draw,rectangle] (Finish) [right=2cm] {Finish};
    \draw [->,out=90,in=90,looseness=0.75] (Start.north) to node[above]{above}  (Finish.north);
    \draw [->,out=-90,in=-90,looseness=0.75] (Finish.south) to node[below]{below} (Start.south)
      ;
\end{tikzpicture}
\end{document


text:
Q: Is this iteration necessary? Hi my usage of get_serving_url is serverside now I wonder if this can be done in template instead of iterating serverside?
class Ad(GeoModel,search.SearchableModel):
    .......

class Image(db.Model):   #migrate to blobstore
    reference = db.ReferenceProperty(Ad, collection_name='matched_images', verbose_name="Title")
    primary_image = blobstore.BlobReferenceProperty()
    .........

    class AdHandler(I18NHandler):
        def get(self, id):
            ad = Ad.get_by_id(long(id))
            image = ad.matched_images.get()
            url = ''
            if image:
                url = images.get_serving_url(str(image.primary_image.key()))
            if not ad:
                self.error(404)
                return
            imv = []
            L = {}
            table = ''
            for i in ad.matched_images:
                if i.primary_image:
                    i1 = images.get_serving_url(str(i.primary_image.key()))
                    imv.append(i1)
            self.render_template("imageinfo.html",
                                 {'url':url, 'imv':imv, 'ad':ad, 'image': image,
                                  'logout_url': users.create_logout_url('/'),}
                                 )

A: I´d suggest you store the image url in the database. This url´s are static, and whenever you do a get_serving_url theres a lot of CPU time involved. I saw a drastic improvement in my own app when I did this. Also, by doing so, your initial problem will be solved immediately.


text:
Q: External Firebase communication to Elm via Ports? I have custom Firebase auth processes (Auth0 => Firebase), so I run all my login logic using TypeScript with Svelte, once I have a successful JWT token, either from sessionStorage or from a fresh login, I boot off my Elm app, sending it some JWT and profile info via a flag. It's a SPA, with a routeing and pages, all componentized and working fine.
My only real problem now is, when it comes to firebase, sure, ElmFire exists, but how do I just give it an active auth token etc. And without loading Firebase for JS and also ElmFire for Elm, it just seems like way too many Kb's.
Is there a nice and efficient way to let Elm port out a "hey listen to this ref", with a "hey Elm, I have some new data for you for this ref". Ports to tell JS to listen, and subscriptions to tell Elm about new data. Without having a port for every listener, and a subscription for every data callback.
Ideally, I'd like my update, to send off a CMD that accepts a callback Msg, to update the function to call and a ref. So that way I can store that in a List of some sort, and when I get a new data payload from JS, I can loop through my List to find the item that matches the ref, execute the update, send in the Msg with the string value, so decoding happens on the pages' update.

Someone feel free to abstract this question into something more general. Feel like this question is something more people might have.

A: The problem is that port/sub must be typed in Elm.
So, a single port / sub with one argument could listen to multiple refs as long as they all have the same type.
If not, you could define the port / sub with multiple arguments, one for each type of data you want to exchange, and pass any particular data in the proper argument.  The other arguments would be null.


text:
Q: При разворачивании-сворачивании QVideoWidget срывает с окна приложения в угол монитора Имеется программа, в окне которой находится виджет QVideoWidget (включен в layout). В этот виджет установлен eventFilter который сворачивает/разворачивает его на полный экран по двойному клику мышки:
bool mywidget::eventFilter(QObject *watched, QEvent *event)
{
if(event->type() == QEvent::MouseButtonDblClick) {
    QVideoWidget * v = reinterpret_cast<QVideoWidget*>(watched);
    if(v->isFullScreen()) v->setFullScreen(false);
    else v->setFullScreen(true);
}
return false;
}

. Но возникла такая проблема: после сворачиванию QVideoWidget оказывается в углу монитора как отдельный виджет (его, например можно закрыть нажав на кнопку), а в консоли высвечивается:
QWidget::paintEngine: Should no longer be called

При этом проблема не возникает под виндоусом... Почему так и как это исправить?


text:
Q: SQL Query to count IDs with exactly 91 duplicates I've got a mySQL database of survey responses.  Each one has a userID, a questionID and the actual answer.  Now I'm trying to write a report that will tell me how many people actually completed the survey as opposed to stopped halfway through.  So I'm trying to figure out how to write a query that will count all of the userIDs that are duplicated exactly 91 times.
Be gentle, this is my first stackoverflow question.

A: You have to group by having count(*) = 91
select userId from myTable group by userId having count(*) = 91

http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html

A: I don't have data to test this, but this may help:
SELECT COUNT(*) AS userCount, userId
FROM tbl
GROUP BY userId
HAVING userCount = 91

A: If the questions are ordered, then you could check for the last question ID:
SELECT COUNT(*) FROM SurveyResponses WHERE QuestionId= [last_question_id]


text:
Q: Como realocar a caixa de paleta de cor do input(color)? O html, tem um tipo de input que ao click abre uma paleta de cor para o usuário escolher uma cor:

<input type='color'>

Eu queria saber se tem alguma forma de editar essa caixa que aparece, estou interessado principalmente em como reposicionar ela. Pode ser por meio do css ou javascript (se for possível).

A: Inicialmente, creio que não.
Como visto na MDN, que traduzi (elementarmente) abaixo, a informação é de que o componente é estilizado e exibido pelo navegador, e não conseguimos alterá-los. Não obstante, cada navegador exibe conforme seus próprios padrões de interface.

A apresentação do elemento pode variar substancialmente de um navegador e/ou plataforma para outra — Este pode ser um simples
'input' textual que automaticamente valida a informação de cor para
garantir que está em formato adequado, ou um seletor de cor no padrão
da plataforma, ou algum tipo de janela de seletor de cor.

Caso sua situação exija que o seletor seja personalizado recomendo que use algo já pronto, como por exemplo: Spectrum, Pick-a-color,Tiny Colorpicker


text:
Q: Change upstream response from 302 to 301 in nginx I have a Django app as an upstream using Gunicorn in nginx, and that app sometimes sent me back a 302 with a Location. And that it's perfectly fine.
We can't touch Django's code but colleagues need the 302 to be 301.
So I would like to modify that 302 to 301, but I haven't found a way to do it without using LUA.
I have tried combinations of "error_page" statement, eg. error_page 302 =301 @redirect; with the "proxy_intercept_errors on;", named location, etc. but haven't had any luck.
Is there any quick way to achieve it? Thanks.
Edit1: Here below my pretty simple upstream:
upstream test {
  server unix:/webapps/test/gunicorn.sock fail_timeout=0;
}

A: You can change the 3xx status code by using proxy_intercept_errors and error_page as you suggest.
You will need to use the value from $upstream_http_location to reconstruct the Location header in the replacement response.
In its simplest form, you could use:
proxy_intercept_errors on;
error_page 302 = @redirect;
location @redirect {
    return 301 $upstream_http_location;
}

In this case, $upstream_http_location is the original value for the Location header in the response from the upstream server before being transformed by proxy_redirect - equivalent to using proxy_redirect off;.
This may be sufficient for your needs.

However, if you need to rewrite the Location response header - for example, if you are using proxy_redirect default; - you may need to modify the response using a map.
For example:
map $upstream_http_location $location {
        ~^https?://[^/]+(.*)$    $1;
        default                  /oops;
}

server {
    ...
    proxy_intercept_errors on;
    error_page 302 = @redirect;
    location @redirect {
        return 301 $location;
    }
}


text:
Q: C++ factorial function not working Can someone please help me understand why this code isn't working properly? I know it's very close and I think that I'm just overlooking something. Any help is appreciated. Here is what I have so far:
 #include <iostream>
    #define TEST_ARRAY_SIZE 4

    long int factorial(int num);

    long int factorial(int num){
        for(unsigned int i = 1; i <= num; i++) {
        num *= i;
        }
            return num;
    }

    int main() {
        int test[TEST_ARRAY_SIZE] = {1, 2, 5, 7};
        for (unsigned int i = 0; i < TEST_ARRAY_SIZE; i++) {
            std::cout << "Factorial of " << test[i] << " is " << factorial(test[i]) << std::endl;
        }
        return 0;
    }

A: You should move return num; outside the loop. As it is now, control always return after the first number is multiplied.
-- the correct code --
long int factorial(int num){
    long int res = 1;
    for(unsigned int i = 1; i <= num; i++) {
    res *= i;
    }
return res;
}

A: The body of the factorial function is not correct. You can use a recursive method to compute the factorial of a specific number. The corrected program of your version is below:
    #include <iostream>
    #define TEST_ARRAY_SIZE 4

    long int factorial(int num);

    int main() {

       int test[TEST_ARRAY_SIZE] = {1, 2, 5, 7};

       for (unsigned int i = 0; i < TEST_ARRAY_SIZE; i++) {
           std::cout << "Factorial of " << test[i] << " is " << factorial(test[i]) << std::endl;
       }

       return 0;
    }

    long int factorial(int num){
       if (num == 1)
          return num;
       else
          return num * factorial(num-1);
    }

A: That's only part of the problem; it's a case in which proper indentation would make the bug apparent in an instant.
In addition to that, why are you using num inside the loop? You should leave it as-is and declare a new variable to compound and return the result.
long int factorial(unsigned int num) {
   int x = 1;

   for(unsigned int i = 1; i <= num; i++) {
      x *= i;
   }

   return x;
}

Other things to note:

*

*You shouldn't be using a #define; you should declare a const instead.

*You're comparing an unsigned against a signed in the factorial() for loop.


text:
Q: How can I automate build of multiple swfs from Flash Builder 4? I'm working on a project that has a Main.fla and a Preload.fla. I am doing all the coding in Flash Builder 4. Each time I want to test I have to go to Flash CS5, publish Main.swf and then run Preload.swf. Is there a way to automate this process so I can just press the "Run Main" button inside Flash Builder 4 and all that is done automatically?

A: Use a JSFL script to compile all your fla's.  Then set up the JSFL as an external tool in Flash Builder.


text:
Q: Copy dependencies excluding some configuration Suppose a project layout like this:
allprojects {
    apply plugin: "java"

    configurations {
        provided
        compile.extendsFrom(provided)
    }
}

project("a") {
    dependencies {
        compile("foo:bar:1.0")
        ...
        provided("bar:baz:3.14")
        ...
    }
}

project("b") {
    dependencies {
        compile("abc:def:1.0")
        ...
        provided("xyz:foo:3.14")
        ...
    }
}

dependencies {
    compile(project(":a"))
    compile(project(":b"))
}

Now, I need a task that will copy all the dependencies of root project (transitively) to some directory, but excluding the provided configuration. How can I do this?

A: To copy only compile dependencies (that is not in the provided dependencies set) to a directory, this should work:
task copyDependencies(type:Copy) {
    from (configurations.compile - configurations.provided)
    into 'build/dependencies'
}

Hope this helps.

A: Was a little obsessed with this and tried to figure out how to do it. I got it to work with the following gradle file. Note the configurations part and where I copy the dependencies.
allprojects {
    apply plugin: "java"

    configurations {
        provided
    }

    sourceSets {
        main {
            compileClasspath += configurations.provided
        }
    }

    repositories {
        mavenCentral()
    }
}

project("a") {
    dependencies {
        compile("jdom:jdom:1.0")
        provided("javax.servlet:servlet-api:2.5")
    }
}

project("b") {
    dependencies {
        compile("javax.jcr:jcr:2.0")
        provided("commons-logging:commons-logging:1.0")
    }
}

dependencies {
    compile(project(":a"))
    compile(project(":b"))
}

task copyDependencies(type:Copy) {
    from configurations.compile
    into 'build/dependencies'
}

I think it's a simpler solution to this problem, but did not figure it out. But this one works. The only thing is that you have to add provided configuration to idea/eclipse classpath too to make the ide integration work as espected.

A: Take a look also at providedCompile without war plugin question.
There is notion of SpringSource propdeps Gradle plugin featuring provided configuration support.


text:
Q: Create django groups programmatically I want to create groups in django programmatically, but not in a view, but rather in something like model (for example using migrations). How to do it? There's no information about it in google and docs (at least not here: https://docs.djangoproject.com/en/1.7/topics/auth/default/#groups)

A: Groups are just like any other Django model. You can create them as you would anything else.
my_group = Group.objects.create(name='group1')

A: Okay, it seems you're using Django 1.7's new migrations system. This is similar to but not exactly like South.
A migration that involves altering the data in the tables is a data migration, and you typically need to write Python code to do the migration.
From the Django docs, there's this example:
# -*- coding: utf-8 -*-
from django.db import models, migrations

def combine_names(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Person = apps.get_model("yourappname", "Person")
    for person in Person.objects.all():
        person.name = "%s %s" % (person.first_name, person.last_name)
        person.save()

class Migration(migrations.Migration):

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(combine_names),
    ]

Note that the code to run during the migration is in the combine_names function, which is called by the migrations.RunPython(combine_names) entry in the operations list of the migration. Your migration should do its group creation in a function like that, along with whatever other data migration is needed.
You should probably use a line like
Group = apps.get_model("auth", "Group")
my_group, created = Group.objects.get_or_create(name='group1')

to create your groups, in case there is already a group of that name in the table.
Don't put code to run during a migration into the root level of the Python file; if you do so, it will be run every time that migration is imported, for example, every time you run ./manage.py runserver.
P.S. You need to put your migrations.RunPython entry at the right point in the operations list; it won't work if you put it after an operation that deletes a table it needs, for example.


text:
Q: Cypress.io page objects cause 'cy.click() failed because it requires a DOM element.' error New to cypress, but did a couple projects in Protractor and TestCafe.
I'm aware of the controversy using PO's in cypress, but due to the complexity / nature of our app, we're going with it.
Refactoring the test to remove PO's and include the app ID's works.   With the page objects, we get the 'requires a DOM element' error.
// myPo.js
class LoginPage {
    loginPageCon() {
      return cy.get('#page-login');
    }
    forgotPasswordLnk() {
      return cy.get('#forgotPassword');
    }
    emailTxt() {
      return cy.get('#email');
    }
    forgotPasswordCon() {
      return cy.get('#page-forgot-password');
   }
  }
  export default LoginPage;

// myTest.spec.js
import loginPage from '../pageObjects/myPo.js';
const loginPage = new LoginPage();

describe('Authorization', () => {
  it('can direct to the azure instance', () => {
    cy.visitHome();
    cy.get(loginPage.loginPageCon);
  });

describe('Forgot Password', () => {
  it('clicking forgot password sends you to the correct screen', () => {
      cy.get(loginPage.forgotPasswordLnk).click();
      cy.get(loginPage.forgotPasswordCon);
    });
  });
});

A: You are returning a function reference to cy.get() when you call cy.get(loginPage.forgotPasswordLink).
Change It to:
loginPage.forgotPasswordLink().click()

Your page object is already returning a chainable of cy.get()


text:
Q: PostgreSQL 9.4 pg_restore is not working recently i'm trying to restore a table in local DB or production DB and whatever i do, seems like pg_restore can't connect to the local or remote DB.
It is just exiting with code 0 or just exiting without any errors or result code.
No data inserted or table schema updated
example command :
pg_restore.exe --host localhost --port 5432 --username "postgres" --dbname "homemarket" --no-password  --data-only --table test_table --schema public --verbose "D:\folder\backup\21.06.2016.backup"

tried with options --password, tried to specify the connection String, tried different DB's, different tables and schemes, different option. Nothing help. Completely can't understand why it's not working :(
Example string just executing and exiting without errors or any result code.
ADD the log of backup file creation:
C:/Program Files/PostgreSQL/9.4/bin\pg_dump.exe --host localhost --port 5432 --username "postgres" --no-password  --format custom --verbose --file "D:\folder\backup\21.06.2016.backup" --table "public.condos" "homemarket"
pg_dump: reading schemas
pg_dump: reading user-defined tables
pg_dump: reading extensions
pg_dump: reading user-defined functions
pg_dump: reading user-defined types
pg_dump: reading procedural languages
pg_dump: reading user-defined aggregate functions
pg_dump: reading user-defined operators
pg_dump: reading user-defined operator classes
pg_dump: reading user-defined operator families
pg_dump: reading user-defined text search parsers
pg_dump: reading user-defined text search templates
pg_dump: reading user-defined text search dictionaries
pg_dump: reading user-defined text search configurations
pg_dump: reading user-defined foreign-data wrappers
pg_dump: reading user-defined foreign servers
pg_dump: reading default privileges
pg_dump: reading user-defined collations
pg_dump: reading user-defined conversions
pg_dump: reading type casts
pg_dump: reading table inheritance information
pg_dump: reading event triggers
pg_dump: finding extension members
pg_dump: finding inheritance relationships
pg_dump: reading column info for interesting tables
pg_dump: finding the columns and types of table "condos"
pg_dump: finding default expressions of table "condos"
pg_dump: flagging inherited columns in subtables
pg_dump: reading indexes
pg_dump: reading indexes for table "condos"
pg_dump: reading constraints
pg_dump: reading foreign key constraints for table "condos"
pg_dump: reading triggers
pg_dump: reading triggers for table "condos"
pg_dump: reading rewrite rules
pg_dump: reading dependency data
pg_dump: saving encoding = UTF8
pg_dump: saving standard_conforming_strings = on
pg_dump: dumping contents of table condos

Process returned exit code 0.


text:
Q: OpenGL context recreation with GLFW I'm currently thinking about handling the OpenGL context recreation.
But for now there is some bugs. Some of my objects fails to be reloaded and sometimes the engine simply crash.
I use GLFW library for OpenGL context creation and GL3W for the extensions loader.
My question is quite simple: should I consider to call gl3wInit() again when I'm rebuilding the context ?

A: Yes, you might need to call it again.
I heard that at least on Windows, GL function pointers could be context-specific. If you make a new context, you need to obtain new function pointers (which is what gl3wInit() does).


text:
Q: Trouble sorting JSON results with django rest framework and dynamic rest I am trying to sort my results by either date or primary key, newer entries in the database first.
models.py
class Notifications(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateTimeField('date transacted')
    read = models.BooleanField(default=False)
    message = models.CharField(max_length=300)

views.py
class getnotifications(viewsets.ModelViewSet):
    # Database model
    queryset = User.objects.all()
    # Serializer - this performs the actions on the queried database entry
    serializer_class = NotificationsSerializer
    # What field in database model will be used to search
    lookup_field = 'username'

serializers.py
class NotificationsSerializer(DynamicModelSerializer):
    notifications_set = DynamicRelationField('ListNotificationsSerializer', many=True, embed=True)
    class Meta:
        model = User
        fields = ['notifications_set']

class ListNotificationsSerializer(DynamicModelSerializer):
    class Meta:
        model=Notifications
        name='notifications_set'
        fields=['pk','date','read','message']

URL accessing request
http://localhost:8000/pm/getnotifications/<omitted>/?sort[]=-notifications_set.pk

JSON results
{
    "notifications_set": [
        {
            "pk": 1,
            "date": "2022-10-10T17:11:33.821757Z",
            "read": false,
            "message": "A user with the phone <omitted> has submitted a restock request for 5 of airpods"
        },
        {
            "pk": 2,
            "date": "2022-10-10T00:00:00Z",
            "read": false,
            "message": "A user with the phone <omitted> has submitted a restock request for 5 of airpods"
        },
        {
            "pk": 3,
            "date": "2022-10-10T17:25:11.824385Z",
            "read": false,
            "message": "A user with the phone <omitted> has submitted a restock request for 5 of airpods"
        }
    ],
    "links": {
        "notifications_set": "notifications_set/"
    }
}

Whether I use -notification_set.pk or notification_set.pk it displays the results in Postman the same way, with no changed order
Using this plugin: https://github.com/AltSchool/dynamic-rest
for sorting
This plugin was linked in the rest framework docs


text:
Q: $L$ $U$ Decomposition Not Working (not Sure what I'm doing wrong: Matlab)
I'm given this question 14a.  The question gives me the pseudocode and I'm supposed to code it up on the algorithm or procedure in Matlab. I use this matrix for my A in my Matlab code:

I run my Matlab code but yet I keep getting incorrect results.  My L*U ends up not being equal to A.  I'm really confused as I follow the pseudocode pretty much exactly.
Here's my Matlab code:
A=[1 4 0 0; 3 4 1 0; 0 2 3 4; 0 0 1 3];
$n=4$;
$L=zeros(n,n)$;
$U=zeros(n,n)$;
$L(1,1)=A(1,1)$;
for $i=2:4$
$L(i,i-1)=A(i,i-1)$;
$U(i-1,i)=A(i-1,i)/L(i-1,i-1)$;
$L(i,i)=A(i,i)-(L(i,i-1)*U(i-1,i))$;
end
$Z=L*U$;
If someone could help me debug my code, I would really appreciate it as my L*U (which I store as Z) ends up not being equal to A and I have no idea what I'm doing wrong).

A: ReplaceU=zeros(n,n);    by
    U=eye(n);
$U$ is an upper bidiagonal matrix, we know that the diagonal entries are $1$.


text:
Q: how to hide state param from url in angularjs with asp.net MVC5? .state('Wizard', {
 url: '/Wizard/:Email',
 templateUrl: '/Common/_Wizard',
 controller: 'Common_Wizard',

}
We are seeing email address in our url like
localhost:15646/Home/Index#/Wizard/sda@adal.com/Loan/Loan
sda@adal.com this is an email address.and this email address is used in different controller and views.
how we can hide this and access on other controller and views.
we dont want to use any local storage or service.
Thanks in Advance

A: You could create service factory class:
angular.module('YourApp').factory('UserContext', function() {
   this.getUserEmail = function() {...}
});

to encapsulate user (email,...) data and inject it in every controller:
angular.module('YourApp').controller('FooBar', function($scope, UserContext) {
   $scope.email = UserContext.getUserEmail();
});

You could also just put the data into the $rootScope, but this is for sure not the best idea.


text:
Q: Using parameters from S3 object keys in AWS Athena My objects are structured as follows:
year=X/month=Y/day=Z/hour=I/minute=J/something.gz

Can I somehow contain these parameters in Athena query like:
... WHERE year=2022

or do I have do do regexp_like on a $path?

A: As of @luk2302 comment - look for "partition" keyword


text:
Q: Inheriting from a template with a member class of the inheriting class as a template parameter I would like to inherit from a class template, but pass a member class of the inheriting class as a template parameter to the base. Is this even possible? Here's a minimal example.
template<typename T>
class Base { /* stuff involving T */ };

template <typename U>
class Derived : Base<typename Derived<U>::Member> {
public:
    class Member { /* stuff involving U */};
    /* stuff involving Member, Base<Member> and U */
};

This compiles fine until I try to create an instance of Derived (eg. Derived<int>) at which point g++ (7.2.0) tells me that I'm using an incomplete type.
In instantiation of 'class Derived<int>':
 error: invalid use of incomplete type 'class Derived<int>'
 class Derived : Base<typename Derived<U>::Member> {
       ^~~~~~~

I can kind of see the problem: the instantiation of Base requires knowledge of Derived::Member, which hasn't yet been defined, but is there any way around this?
As an alternative, I could have Member outside Derived, but then I lose the advantages of having it as a member class (access to private and protected members of Derived, encapsulation of Member, etc...). I also considered making Member a member of Base instead, but logically, the contents of Member are specific to Derived and don't belong in the more general Base.

A: After some investigation, I've decided this is not possible. The closest thing that works is the Curiously Recurring Template Pattern (CRTP) described here: What is the curiously recurring template pattern (CRTP)?
As noted here Why this CRTP does not compile? and elsewhere, Derived is an incomplete type at the moment of the template instantiation of Base. Therefore Member is not known to exist, causing the error.
The closest to a solution I found was to move the functionality of Member into a separate, non-member, class (NonMemebr) and have Member inherit from that. That way everyone outside Base<NonMember> doesn't need to know that NonMember exists.
template<typename T>
class Base { /* Instance of T. */ };

namespace detail {
    class NotMember { /* Functionality I'd like to have in Member. */ };
}

template <typename U>
class Derived : Base<detail::NotMember> {
public:
    class Member : public detail::NotMember { /* Appropriate constructors. */ };
    /* Stuff involving U, Base<NotMember> and Member. */
};

This may not be the prettiest, but it does do what I want.


text: Q: Web Service - using OAuth for private website I have a private website and I want to write an app for it in order to learn how to create an app. Is it recommended that I use OAuth to authenticate my app with the service, even when the API will never be for public use? How should I write web services for fully private sites? I just want to offer the functions of the website as an app, but I do not want to make the web service publicly available.


text:
Q: Grails Spring Security ui plugin with ldap authorities? I have the Grails Spring Security ldap plugin working and connecting to my Active Directory. Now I am trying to add the Spring Security UI plugin to manage my AD users and roles. Is this possible?
It appears that the spring security ui plugin controllers only handle database user/role crud.

A: Right, there's no support for managing LDAP in the UI plugin. I'm not sure how well-maintained it is, but the http://grails.org/plugin/ldap can manage LDAP.


text:
Q: What changes need to be done to get HTTP Status code of domain using Scrapy? I have this code available from my previous experiment.
import scrapy

class BlogSpider(scrapy.Spider):
    name = 'blogspider'
    start_urls = ['http://example.com/']

    def parse(self, response):
        for title in response.css('h2'):
            yield {'Agent-name': title.css('a ::text').extract_first()}

        next_page = response.css('li.col-md-3 ln-t > div.cs-team team-grid > figure > a ::attr(href)').extract_first()
        if next_page:
            yield scrapy.Request(response.urljoin(next_page), callback=self.parse)

I am not understanding how to modify this code to take input as a list of URL from a text file (May be 200+ domains) and check the HTTP status of the domains and store it in a file. I am trying this to check whether the domains are live or not.
What I am expecting to have output is:
example.com,200
example1.com,300
example2.com,503

I want to give file as an input to scrapy script and it should give me the above output. I have tried to look at the questions: How to detect HTTP response status code and set a proxy accordingly in scrapy? and Scrapy and response status code: how to check against it?
But find no luck. Hence, I am thinking to modify my code and get it done. How I can do that? Please help me.

A: For each response object you could be able to get the url and status code thx to response object properties. So for each link you send request to, you can get the status code using response.status.
Does it work as you want like that ?
def parse(self, response):
       #file choosen to get output (appending mode):
        file.write(u"%s : %s\n" % (response.url, response.status))
       #if response.status in [400, ...]: do smthg
        for title in response.css('h2'):
            yield {'Agent-name': title.css('a ::text').extract_first()}
        next_page = response.css('li.col-md-3 ln-t > div.cs-team team-grid > figure > a ::attr(href)').extract_first()
        if next_page:
            yield scrapy.Request(response.urljoin(next_page), callback=self.parse)


text:
Q: php reach functions from a extended class through the parent class I've been searching around the net for answers but couldn't find anything relevant, so I thought about asking it here.
How can I reach functions from a extended class through it's parent class?
Base (parent class)
require_once('FirstChild.class.php');

require_once('SecondChild.class.php');

class Base {

public $first;

public $second;

function __construct() {

$this->first = new FirstChild();

$this->second = new SecondChild();

}

}

First (child class)
class FirstChild extends Base {

public $firstVar;

function __construct() {

$this->firstVar = 'Hello';

}

public function getSecondVar() {

echo parent::$second->getVar();//doesnt work!!?

}

}

Second (child class)
class SecondChild extends Base {

public $secondVar;

function __construct() {

$this->secondVar = 'World';

}

public function getVar() {

return $this->secondVar;

}

}

How can the "getSecondVar" function be reached inside "FirstChild"?
Thanks!

A: Don't use the parent:: method. Instead use $this->second->getVar(); and make sure the parent constructor is called as well, e.g. with parent::__construct(); (alternatively, populate $this->second in your FirstChild constructor)
E.g.
class FirstChild extends Base {
    public function __construct() {
        // your code
        $this->second = new SecondChild();
        $this->firstVar = 'Hello';
    }
    public function getSecondVar() {
        echo $this->second->getVar();
    }
}

EDIT:
Also the way you've set it up, $second would never be set as by adding the constructor method to FirstChild, you are overriding Base::__construct(). You'll either need to recall parent::__construct() and make sure it doesn't create a new instance of FirstChild() or you need to do the same code within FirstChild's constructor.
Anyway, it's usually not best practice to be calling child classes from a parent class.

A: You read about how to reach a parents class function and it works with the parent keyword like so:
parent::__construct();

For the property $second you can just access with $this as it is public:
$this->second;

And that's already all. Take care you call the parent's constructor and keep in mind that public members are public (and you will never be able to reach private members).


text:
Q: Can we assign a keyboard shortcut to a particular window in Mac? I have so many apps to work with, and each has som many windows. Is thre a way to assign key windows with a keyboard shortcut (not apps). So Window 1 of Excel with F1 for example.
OR
Is there a program that can manage this. For eg. I can tag, out of 30 windows on my computer, 3 key ones that I use very frequently, more so than the rest. Then instead of Cmd+Tab to go one by one to the app in question, and then after that still go thru window by window to the approrpaite one, can I just have, when I press say F1, the program appearing showing the 3 windows I have marked as important, choose the approrpiate one, and voila.

A: There are two programs that could help you: Witch and Optimal layout.
Also, you can choose a keyboard shortcut in the system preferences to activate application windows: Cmd+Tab to switch apps, then Ctrl+↓ (down arrow) (for me) to switch between windows.
And if you don't mind using Expose, you may check the "Group windows by applications" checkbox in the Mission control panel of the system preferences.


text:
Q: Unable to save/write tree data that plotBS() results I have aligned sequences in class of phyDat. Here is a minimal example:
library(seqinr)
seqs <- DNAMultipleAlignment( c(a1 = "------ATGTTCATTAACCGCTGACTATTCTCAACCA",
                                a2 = "------ATGTTCACCGACCGCTGACTATTCTCTACAA",
                                a3 = "---GTGACCTTCATCAACCGATGATTATTCTCAA---",
                                a4 = "---TCAGTCGTCACCAGGCGTTG-CAGGACCCGAC--",
                                a5 = "ATGGGGGTCTTCCTCA-TCGCCGTCGCCGCGT-----"))

library(phangorn)
phyDat_seqs <- as.phyDat(seqs)

I followed the manual of phangorn package to construct a phylogenic tree. (Below, I wrote a simplified code. You don't need to check manual, you can run the code directly.)
dm <- dist.ml(phyDat_seqs)
treeNJ <- NJ(dm)

fit <- pml(treeNJ, data=phyDat_seqs)
fitGTR <- optim.pml(fit, model="GTR")

bs <- bootstrap.pml(fitGTR, bs=5, optNni=TRUE)

And I can simply plot this tree with plotBS :
plotBS(fitGTR$tree, bs, type="p")

There is no problem so far. My question starts from this point.
I want to customize this tree by using ggtree package but I couldn't figure out how to do that. When I use ggtree(fitGTR$tree), it gives me a different tree.
plotBS somehow uses bs values to change tree branching. If you compare plot(fitGTR$tree, type="p") and plotBS(fitGTR$tree, bs, type="p") difference can easily be seen. ggtree() and  plot() construct the same trees, but not the tree that I want to customize.
I've tried different approaches such as saving tree with write.tree or write.nexus functions and calling the file again with ggtree package functions but I can't save the plotBS version of the tree. How can I get an output of plotBS tree?
Thank you in advance.

A: Problem was occuring because I misread the documentation. I did a mistake in this line:
plotBS(fitGTR$tree, bs, type="p")

Tree must be constructed through midpoint() function. Therefore, when I changed the line as this:
plotBS(midpoint(fitGTR$tree), bs, type="p")

no problem occurs. I can use ggtree and I can save/write the tree data without a problem.
Even if I can't figure out what midpoint() function does to tree actually (you can comment about this), problem is solved.


text:
Q: Potentiometer for two 12V/1.1A fans in parallel I recently bought a potentiometer to regulate the speed of two 12V/1.1A DC fans in parallel, powered by a 12V source. Its specifications are the following:
Resistance= 10k Ohm, MaxPower = 0.2W.
Can I connect the fans, the potentiometer and the power source in series, or do I need additional circuitry to avoid circuit damage? I feel like the potentiometer's maximum power is too low, but I may be wrong.

A: In today's world electronic controls for this kind of work are the only way to go. And thanks to cheap products on Ebay, there is a solution. I'm sure this is cheaper than a pot that would work. And, it is way more efficient.
Ebay Product to do the job

A: If you have a 10 kohm pot rated at 0.2 watts then, end-to-end you could apply 44.7 volts across it - that would take a current of 4.47 mA. Reason: -
Power = Voltage\$^2\$/Resistance hence voltage = \$\sqrt{P\cdot R}\$ = 44.7 volts.
That's the maximum current the pot can be used for.
Even if you only used one-tenth the range of the pot (1 kohm) i.e. you used it like a rheostat, the power is also reduced by one-tenth to 20 mW and the maximum voltage across one tenth is 4.47 volts. Guess what... the current is still 4.47 mA.
4.47 mA is the maximum current you can pass through a 10 kohm 200 mW pot.


text:
Q: Finding vector that minimizes ratio of two covariances I have a problem where I need to solve for vector $w$ using
$\min \frac{{w}'\Sigma_{1}w}{{w}'\Sigma_{2}w}$
$s.t.$
${w}'e = 1$
where $e$ is a vector of ones, $\Sigma_{1}$, and $\Sigma_{2}$ both have the characteristics of co-variance matrices and positive definite.
I am struggling to find an answer.

Here is what I have done so far:
Step 1:
Rewrite the problem as
$\min {w}'\Sigma_{1}w$
$s.t.$
${{w}'\Sigma_{2}w} = r^2$
${w}'e = 1$
where I can minimize the solution over a range of $r^2$.
Step 2:
Minimize the Langrangian of the modified problem in Step 1
$\min {w}'\Sigma_{1}w - \lambda ({w}'\Sigma_{1}w - r) - 2\mu({w}'e = 1)$
which gives:
$(\Sigma_{1} - \lambda \Sigma_{2})w = \mu e$
or, $w = \mu (\Sigma_{1} - \lambda \Sigma_{2})^{-1} e$
Substituting into ${w}'e = 1$ gives $\mu = \frac{1}{e(\Sigma_{1} - \lambda \Sigma_{2})^{-1} e}$ and $w = \frac{(\Sigma_{1} - \lambda \Sigma_{2})^{-1} e}{e(\Sigma_{1} - \lambda \Sigma_{2})^{-1} e}$.
Substituting $w$ into ${{w}'\Sigma_{2}w} = r^2$ gives:
$\frac{{e}'(\Sigma_{1} - \lambda \Sigma_{2})^{-1}\Sigma_{2}(\Sigma_{1} - \lambda \Sigma_{2})^{-1} e}{(e(\Sigma_{1} - \lambda \Sigma_{2})^{-1} e)^2} = r^2$
and I am lost after this, because I'm not sure I can easily solve for $\lambda$ in terms of $r$.

A: For typing convenience, define the matrices
$$\eqalign{
A = \Sigma_1,\quad B = \Sigma_2,\quad M = B^{-1}A \\
}$$
and the scalar functions
$$\eqalign{
\alpha &= w^TAw \implies
\frac{\partial \alpha}{\partial w} &= 2Aw \\
\beta &= w^TBw \implies
\frac{\partial \beta}{\partial w} &= 2Bw \\
}$$
Write the cost function in terms of these new variables.
Then calculate its differential and gradient.
$$\eqalign{
\lambda &= \beta^{-1}\alpha \\
d\lambda
 &= \beta^{-2}\big(\beta\,d\alpha-\alpha\,d\beta\big) \\
\frac{\partial \lambda}{\partial w}
 &= 2\beta^{-1}\big(Aw-\lambda Bw\big) \\
}$$
Setting the gradient leads to an eigenvalue problem.
$$\eqalign{
Aw &= \lambda Bw\quad &({\rm generalized\,EV\,problem}) \\
Mw &= \lambda w\quad &({\rm standard\,EV\,problem}) \\
}$$
Thus the min/max of the cost function equals the minimum/maximum eigenvalue of the $M$-matrix, and the $w$-vectors are the corresponding eigenvectors.
If $B^{-1}$ does not exist, then you must solve the generalized eigenvalue problem instead.
Note that the given normalization condition has no effect on eigenvalue equation or the cost function. For example, scale the vector by a factor of a hundred and substitute it into the cost function.
$$\eqalign{
\frac{(100\,w)^TA(100\,w)}{(100\,w)^TB(100\,w)}
 = \frac{w^TAw}{w^TBw}
 = \lambda
}$$
That being said, after finding an eigenvector, you can certainly scale it to any length that is required.


text:
Q: Random number generator C I can't seem to figure out why this is not working. I am trying to get these two void functions to generate randoms numbers when called in the main. I think the problem has to do with srand(time(NULL)); in the void function's. I think that when it gets called in the main and runs in the for loop, srand(time(NULL)); is not updated so it prints out the same number x times. numGen_10 should generate 1-10 and numGen_4 should generate 1-4 based on a variable.
What can I do to get the functions to output different random numbers each time the function is called?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void numGen_10(int xOry, int* xRey);
void numGen_4(int num, int choice, int *choiceRe);

int main()
{
    int x;
    int num = 5;

    for (int i = 0; i < 3; i++)
    {
        numGen_10(x, &x);
        printf("val : %d \n", x);
    }

    printf("------------------------\n");

    for (int i = 0; i < 4; i++)
    {
        numGen_4(4, x, &x);
        printf("val2 : %d \n", x);
    }
    return 0;
}

void numGen_10(int xOry, int *xRey)
{
        srand(time(NULL));
        int r = rand() % 10 + 1;
        xOry = r;
        *xRey = xOry;
    return;
}

void numGen_4(int num, int choice, int *choiceRe)
{
    srand(time(NULL));
    choice = rand() % num + 1;
    *choiceRe = choice;
    return;
}

A: The random number generator is completely deterministic; it will always output the same sequence of numbers for any given seed.  srand() seeds the random number generator.  So by calling srand() with the time immediately before each call to rand(), and since your loops will take less than a second to execute, you'll always get the same random number (or maybe two if the time happens to change in the middle).
Try calling srand() once before entering the loops.

A: Just for fun , add a delay of 1 second before each srand call when calling srand multiple times :
    sleep(1);
    /* or delay(1001); or usleep(500000);usleep(500000); based on availability */
    srand(time(NULL));

A: Additional to what others said about solving problem of srand I would like to add a remark about how you use pointers, calling your functions with x and &x is pointless, you can just call either with pointer only or with variable only:
calling with pointer :
void numGen_10(int* xRey); // prototype
void numGen_10(int *xRey) // function's body
{
    int r = rand() % 10 + 1;
    *xRey = r;
    return;
}
numGen_4(4, &x); // use from the main function

calling with variable :
int numGen_10(int xRey); // prototype
int numGen_10(int xRey) //function's body
{
    int r = rand() % 10 + 1;
    return r;
}
int y = numGen_4(4, x);  // use from the main function


text:
Q: BST Insertion issue My code for BST insertion is getting passed for 3 test cases and is failing for other 3 test cases, as the test case are hidden I can't figure out where I'm going wrong with my logic. Please check and advise me what other different test case my logic will not pass.
here's code:
/*
Node is defined as

typedef struct node
{
   int data;
   node * left;
   node * right;
}node;

*/

node * insert(node * root, int value)
{ node* n;
 n=root;
 if(n!=NULL)
 {while (true )
   { if(n->data > value && n->left!=NULL){n=n->left;}
      else if(n->data < value && n->right!=NULL){n=root->right;}
      else
            {  node* a=new node();
             a->data=value;
           if(n->data > value ){ n->left=a;break; }
           else{ n->right=a;break; }
            }
   }
 }
 else
 {node* a=new node();
  a->data=value;
  root=a;
 }
return root;

}

A: I write it like
node*  insert(node * root, int value)
    { node* n=  root;
       node* a=new node();
      if( a == NULL )
    { cout<<" no memory  \n " ; exit(0); }
       a->data=value;
       a->left=a->right=NULL;
     if(n!=NULL)
     {while (true )
       { if(n->data > value  )
             {   if( n->left!=NULL )
                              {n=n->left;}
                 else
                     {
                          n->left=a;
                          return root;
                      }
               }
          else if(n->data < value  )
              {  if (  n->right!=NULL )
                           {n=n->right;}
                 else
                      {
                         n->right = a;
                         return root;
                        }
              }

       }
     }
     else
     {
    return  a;
     }
    }


text:
Q: How can I save array of object and reuse with same values once I opened my app again. #Swift func applicationDidFinishLaunching(_ application: UIApplication) {
   let defaults = UserDefaults.standard
   defaults.set(memes, forKey: "HI")

}

var memes = [ViewController.Meme]()

I wrote this code in my AppDelegate and reload the values in the tableview using this code.
override func viewDidLoad() {
   let defaults = UserDefaults.standard
   let token = defaults.array(forKey: "HI")?.count
   print(token ?? -1)
}

But I can't see the array is filling with anything I'm using it wrong?

A: You seem to have the ordering wrong. In your applicationDidFinishLaunching(_:) you first need to add items to your array and then store it as follows:
var memes = [ViewController.Meme]()
let defaults = UserDefaults.standard
defaults.set(memes, forKeyL "HI")

And then you can read it as you currently are in your view controller

A: It looks like you saved an empty array.
AppDelegate.swift:
//  if (by whether your array is full)
let defaults = UserDefaults.standard
private let memesKey = "memesHI"
defaults.set(memes, forKey: memesKey)

viewDidLoad():
var memes = [ViewController.Meme]()
let defaults = UserDefaults.standard
private let memesViewKey = "memesHI"
let memesArray = [Any]()
memesArray = memes
let token = defaults.array(memesArray, forKey:memesViewKey)?.count


text:
Q: c++ auto type signed to/from unsigned conversion I want to write a function that performs bit-wise operations on a parameter that is auto type.

*

*The type passed in might be unsigned int or int type (with differing widths).

*I only want to perform bit-wise operations on unsigned types.

I need an operator that returns the unsigned version of the original data type. In the function example below the "operator" unsigned_type would give me the data type that value has but insure it is unsigned.

*

*int -> unsigned int

*int16_t -> uint16_t

*uint16_t -> uint16_t
Function example:
auto bit_shifting_and_mask(auto value) -> decltype(value)
{
    unsigned_type(value) unsigned_value = static_cast<unsigned_type(value)>(value);

    unsigned_value >>= 8u;       // Contrived bit manipulation
    unsigned_value &= 0xABCDu;   // here ...

    return static_cast<decltype(value)>(unsigned_value);
}

Is there some means to perform the operation unsigned_type against a data type obtained from decltype?
Thanks.

A: C++11 has a std::make_unsigned utility in <type_traits>:
auto bit_shifting_and_mask(auto value) -> decltype(value)
{
    auto unsigned_value = static_cast<std::make_unsigned<decltype(value)>::type>(value);

    unsigned_value >>= 8u;       // Contrived bit manipulation
    unsigned_value &= 0xABCDu;   // here ...

    return static_cast<decltype(value)>(unsigned_value);
}

With C++14, you can simplify further by using std::make_unsigned_t instead of std::make_unsigned::type.

A: make_unsigned, as Jarod42 said.
auto bit_shifting_and_mask(auto value) -> decltype(value)

This is not the way you want to make this function type-dependent. Use template, unless this function is lambda.

A: This does not require features not (yet) in the standard. It compiles under VS 2017 with VC++17 enabled.
#include <type_traits>
template<typename T>
auto bit_shifting_and_mask(T value) {
    static_assert(std::is_integral_v<T>,
        "bit_shifting_and_mask(value): value is not integral type");
    using unsgn =std::make_unsigned_t<T>;
    auto unsigned_value = static_cast<unsgn>(value);

    unsigned_value >>= 8u;       // Contrived bit manipulation
    unsigned_value &= 0xABCDu;   // here ...

    return unsigned_value;
}


text:
Q: Insert nested objects into KieSession I have the following scenario in Drools:
package test;

public class A {
   public ArrayList<B> b = new ArrayList<B>();
}

public class B {
   public ArrayList<C> c = new ArrayList<C>();
   public ArrayList<D> d = new ArrayList<D>();
}

public class C {
   some attributes
}

public class D {
   some attributes
}

When I'm going to insert those facts into the KieSession, in order to make them available straight into the working memory, I have to iterate through all over the object, i.e:
for( int i=0; i< a.getB().size(); i++ ){
    ksession.insert(a.getB().get(i));
    for( int j=0; j< a.getB().get(i).getC().size; j++ ){
         ksession.insert(a.getB().get(i).getC().get(j));
         etc...
    }
}

In my understanding you have to do this if you don't want to access to one object through its parent, i.e.:
rule "Do something with B"
    when
        B()
    then
        ....
end

Instead of
rule "Do something with B"
    when
       A.b()
then
       ....
end

My question is: is there any way to load all the nested facts in a faster way than loads of nested FOR LOOP?
I hope my question makes sense.
Thank you for you feedback.

A: Written using slicker Java statements it doesn't look so bad:
for( B b: a.getB() ){
     for( C c: b.getC() ) ksession.insert( c );
     for( D d: b.getD() ) ksession.insert( d );
     ksession.insert( b );
}

Drools will not "flatten" a recursive set of collections - how could any SW read your mind when you want the List of Cs expanded but not the List of Ds?
It may not be necessary to do this for all lists or down to the last level. The from clause may be the better option in some cases when writing rules that need to refer to child objects in a collection.
Also, review your object model. It may not be the best decision to have these lists collecting child objects. There are many ways to represent a graph, and some are closer to some Normal Form by avoiding repetitive fields, and this will also help when writing rules.


text:
Q: How to use my local API in a javascript file? I have a file api.js which contains something along the lines of this:
exports.showAll = function(req, res) {
    Obj.find(function(err, Objs) {
        res.send(Objs);
    });
}

My server has the line:
app.get('/all', api.showAll);

When I load /all in the browser, I get the JSON, but I want to get this JSON into a client-side JS file, so I can display the JSON data beautifully on a webpage.
How do I use my server-side API in a client-side JS file?

A: To make a call to a server and work with the result, you need to use AJAX. AJAX stands for Asynchronous JavaScript and XML but the reality is that you can make these kinds of call through other languages and without retrieving XML. Here's a simple example of how to make a request to your server:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  // Verify that the request is done and completed successfully
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      var json = xhr.responseText;
      var data = JSON.parse(json); // Parse the JSON into an actual object/array
      console.log(data);
    } else {
      console.log('Something went wrong');
    }
  }
};
xhr.open('GET', '/all');
xhr.send();


text:
Q: Questions to be reviewed based on reviewer's expertise Most probably, our SO moderators will be little upset to see this question. Apology in advance. There is a considerable amount of reviews/edits to be done daily. However when reviewing a question, in terms of English we may notice if it's out of topic. That to say the question is obviously ambiguous/talking totally something else than the title/body -vise versa.. But in terms of technology domain, only a person familiar with a particular technology is able to correctly mark a question as "off topic" or "not constructive".
But often, it seems that when one marks a question off topic/non-constructive, some follows the norm blindly and mark it without much consideration.
Thus is it possible to let users to review and mark questions based on their expertise/specialized tags/questions/answers? This could improve the quality of question reviewing.


text:
Q: ansible expect module respond to password prompt I have read the documentation related expect module on here
I'm trying to add a CentOS7 to 2012 AD Domain controller, here is my playbook,
  - name: Attempt to join the server to AS
    expect:
      command: realm join --user=admin@mydomain.local mydomain.local
      responses:
        (?i)Password for admin@mydomain.local: abc123

Ansible playbook fails, saying the password is incorrect, is this the correct way of using expect?

A: Have you try to incapsulate the password in quotes like so?
(?i)Password for admin@mydomain.local: "abc123"


text:
Q: Stream a database recordset to multiple thread workers I have a process which requires streaming data from a database and passing the records off to an external server for processing before returning the results to store back in the database.
Get database row from table A
Hand off to external server
Receive result
insert database row into table B

Currently this is a single-threaded operation, and the bottleneck is the external server process and so I would like to improve performance by using other instances of the external server process to handle requests.
Get 100 database rows from table A
  For each row
    Hand off to external server 1
    Receive Result
    insert database row into table B
In parallel get 100 database rows from table A
  For each row
    Hand off to external server 2
    Receive Result
    insert database row into table B

Problem 1
I have been investigating Java thread pools, and dispatching records to the external servers this way, however I'm not sure how to fetch records from the database as quickly as possible without the workers rejecting new tasks. Can this be done with thread pools? What architecture should be used to achieve this?
Problem 2
At present I have optimised the database inserts by using batch statements and only executing once 2000 records have been processed. Would it be possible to adopt a similar approach within the workers?
Any help in structuring a solution to this problem would be greatly appreciated.

A: Based on your comments, I think the key point is controlling the count of pending tasks. You have several options:

*

*Do an estimate on the number of records in your data set. Then, decide on a batch size that will produce a reasonable number of tasks. For example, if you want to limit pending task count to 100. Then if you have 100K records, you can have a batch size of 1K. If you have 1Mil records, then set batch size to 10K.

*Supply your own bounded BlockingQueue to the threadpool. If you haven't done it before, you probably should study the java.util.concurrent package carefully before doing this.

*Or you can use a java.util.concurrent.Semaphore, which is a simpler facility than a user supplied queue:

*

*Declare a semaphore with your pending task count limit

Semaphore mySemaphore = new Semaphore(max_pending_task_count);

*

*Since your task generation is fast, you can use a single thread to generate all tasks. In your task generating thread:

    while(hasMoreTasks()) {
        // this will block if you've reached the count limit
        mySemaphore.acquire();
        // generate a new task only after acquire
        // The new task must have a reference to the Semaphore
        Task task = new Task(..., mySemaphore);
        threadpool.submit(task);
    }
    // now that you've generated all tasks,
    // time to wait for them to finish.
    // you may have a better way to detect that, however
    while(mySemaphore.availablePermits() < max_pending_task_count) {
        Thread.sleep(some_time);
    }
    // now, go ahead dealing with the results

*

*In your Task thread:

    public void run() {
        ...
        // when finished, do a release which increases the permit
        // by 1 and inform your task generator thread to produce 1 more task
        mySemaphore.release();
    }


text:
Q: mod_rewrites in nested .htaccess causing strange 404 I have an apache HTTP server with a directory structure as such:
/
---- api/
---- ---- index.php
---- ---- .htaccess
---- index.php
---- .htaccess

/.htaccess:
DirectorySlash Off
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*[^/])$ $1/

/api/.htaccess
RewriteEngine On

My objective was to display the index.php of a directory when it was called without a trailing backslash. However, calling http://domain.com/api results in a 404. Commmenting out the one line in /api/.htaccess causes everything to work as expected.
I'm having a hard time understanding this behavior as the doc for RewriteEngine On says nothing about it. Could someone shed some light on mod_rewrite's workings here?
Note: This question was originally posted on SO here but received no response. I will close it if this one solves the issue.
EDIT: As per @Jonah B's suggestion that a new rewrite context might be created, I tried changing the rules of /api/.htaccess to the following:
RewriteEngine On
RewriteRule ^ index.php

but the result remains the same - it still 404s.

A: If you only need to tell apache that a request to route
/api

should look for an index.php file in the directory /api maps to, use
DirectoryIndex index.php

Don't bother with the rewrite engine.
See:
http://httpd.apache.org/docs/current/mod/mod_dir.html#directoryindex
http://www.htaccess-guide.com/directoryindex-uses/
https://stackoverflow.com/questions/2384423/index-php-not-loading-by-default