text:
Q: How redirect user with all variables coming with POST I have a html form with action="script1.php"
In script1 I need write all data to the database and redirect to
script2.php, but I need all parameters posted to script1 to be sent to script2.
mod_rewrite is on
How I can redirect using PHP with all data come through POST ?
if i do like that this disgusting practice but
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
function Search(){
wpc_form.submit();
}
// -->
</script>
</HEAD>
<BODY onload='Search()'>
 <form name=wpc_form  method="post" action="/script2/">
 <?php
foreach($_REQUEST as $name => $value)
echo '<input type="hidden" name="'.$name.'" value="'.$value.'">'
 ?>

 </form>

A: Impossible.
But you don't need it. Because you have all this data already. Just read it from the database in script2.php

A: A redirect doesn't allow you to do this unless you have custom client-side code running in the browser to extract state from the response message body in order to populate your form fields. This is advanced usage and probably not what you really want to do.
If you really do need to transmit state between your forms then you can use the session to do this. The form in the browser won't have access to the data, but your PHP script running on the server can store values between requests. Here's a link to a tutorial on sessions in PHP which might be of use to you. This approach is often used for maintaining application state between requests and redirects to third-party services such as OpenID providers etc.

A: You can use the cURL library (or similar) to send a separate POST request from your local script to the external service.
// assemble data from your post here:
$data = array('formfield' => 'data', 'otherfield' => 'otherdata');

// and then send it off somewhere else
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://somewhere.else');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);


text:
Q: Play Framework WebSocket disconnecting IE clients I've asked on the Play Framework forums, but figured I'd ask here as well for the additional coverage:
Using Play Framework 2.3, I have a WebSocket handled with an actor that I'm using to push "StatusUpdate" messages to connected clients:
def updateSocket = WebSocket.tryAcceptWithActor[StatusUpdate, StatusUpdate] {
  implicit request =>
    authorized(Set.empty[SecurityRole]).map {
      case Right(user) =>
         Right({upstream => DashboardListener.props(upstream, user.dblocations)})
      case Left(_) =>
         Left(Forbidden)
    }
 }

Everything is working wonderfully, except...
When a user connects via Internet Explorer, and the IE window loses focus, within 20 or so seconds the WebSocket forcibly closes. Firefox, so far, seems not to exhibit this behavior. I used Fiddler to inspect the WebSocket traffic, and it looks like IE is sending a "pong" message after it loses focus:
{"doneTime": "02:08:39.462","messageType": "Pong","messageID": "Client.2",
"wsSession":"WSSession-1","payload": "", "requestPartCount": "1"}

Immediately, the server sends:
{"doneTime": "02:08:39.462","messageType": "Close","messageID": "Server.3",
 "wsSession": "WSSession-1","payload": "03-EB-54-68-69-73-20-57-65-62-53-6F-
 63-6B-65-74-20-64-6F-65-73-20-6E-6F-74-20-68-61-6E-64-6C-65-20-66-72-61-6D-
 65-73-20-6F-66-20-74-68-61-74-20-74-79-70-65", "requestPartCount": "1"}

I'm assuming that this is because my WebSocket doesn't know how to handle pongs (since I've declared incoming and outgoing traffic to be of the StatusUpdate type). Moreover, the client receives a closeEvent with code 1003 (The connection is being terminated because the endpoint received data of a type it cannot accept). I've done some research, and it seems that this ping/pong is supposed to keep the connection alive, but not be exposed to the API. Has anyone run into this before or know of a potential solution?
If it matters, the clients only receive StatusUpdates via this socket -- at no point is any sort of message ever explicitly sent on it. The StatusUpdate messages originate from elsewhere in my Actor system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mismatching versions-error when trying to install unlocked package I created a new version of my unlocked package and tried to install it into a scratch org. Unfortunately I get the error Mismatching versions..
From what I know this error comes up, when one tries to install higher api-version sources into a lower api-version org.
How is the api version of unlocked packages set? Is it in the sfdx-package.json? I did not change anything there, it is still "sourceApiVersion": "43.0" as it was before. Furthermore is the scratch org is API version 44, so it should not be a problem, right?
Or am I missing something? Thanks

A: Usually this means your devhub has a different version of Salesforce compared to the scratch org you want to install the package on.
The version of you Salesforce org you can check on this website: https://status.salesforce.com/


text:
Q: Case when duplicate add one more letter For example: I have a table with these records below
1  A
2  A
3  B
4  C

...
and I need to migrate these record in to another table
1  AA
2  AB
3  B
4  C
...

Meaning if the record is duplicate, it will automatically add one more letter alphabetically.

A: Just a slightly different approach
Example
Declare @YourTable Table (ID int,[SomeCol] varchar(50))
Insert Into @YourTable Values
 (1,'A')
,(2,'A')
,(3,'B')
,(4,'C')

Select *
       ,NewVal = concat(SomeCol,IIF(sum(1) over (partition by SomeCol)=1,'',char(64+row_number() over ( partition by SomeCol order by ID ))) )
 From @YourTable

Returns
ID  SomeCol NewVal
1   A       AA
2   A       AB
3   B       B
4   C       C

EDIT - Requested UPDATE
Declare @YourTable Table (ID int,[SomeCol] varchar(50))
Insert Into @YourTable Values
 (1,'A')
,(2,'A')
,(3,'B')
,(4,'C')

Select *
       ,NewVal = concat(SomeCol,IIF(sum(1) over (partition by SomeCol)=1,'',replace(char(63+row_number() over ( partition by SomeCol order by ID )),'@','')) )
 From @YourTable

Returns
ID  SomeCol NewVal
1   A       A
2   A       AA
3   B       B
4   C       C

A: We might be able to handle this requirement with the help of a calendar table mapping secondary letters to duplicate sequence counts:
WITH letters AS (
    SELECT 1 AS seq, 'A' AS let UNION ALL
    SELECT 2, 'B' UNION ALL
    SELECT 3, 'C' UNION ALL
    ...
    SELECT 26, 'Z' UNION ALL
    ...
),
cte AS (
    SELECT id, let, ROW_NUMBER() OVER (PARTITION BY let ORDER BY id) rn,
           COUNT(*) OVER (PARTITION BY let) cnt
    FROM yourTable
)

SELECT t1.id, t1.let + CASE WHEN t1.cnt > 1 THEN t2.let ELSE '' END AS let
FROM cte t1
LEFT JOIN letters t2
    ON t1.id = t2.seq
ORDER BY t1.id;

Demo


text:
Q: how to write program for area for circle and square Write a program that asks the user to enter two values: an integer choice and a real number x. If choice is 1, compute and display the area of a circle of radius x. If choice is 2, compute and display the are of a square with sides of length x. If choice is neither 1, nor 2, will display the text Invalid choice.
so im guessing this is broken into 2 parts? all i can think of so far is having a choice(input) function and defining what pi and area and so on are. but i keep getting errors. what am i doing wrong?
choice = input ('Enter Choice:')
choice_1 = int (choice)
if (choice_1==1): radius = (int)
print('Enter x:',radius)
pi = 3.14159
area = ( radius ** 2 ) * pi
print ( 'The Area is=' , area )
choice_2= (choice)
if (choice_2==2): side= (int)
print('enter X:' side*side)

A: While you've got the actual calculations right, there are some problems with how you're receiving input. You start out well:
choice = input ('Enter Choice:')

But then do this:
choice_1 = int (choice)

That's not wrong, but there's no need for a new variable name. You could just as well do choice = int(choice).
You then go on:
if (choice_1==1): radius = (int)

The if statement is okay (although the parentheses are not necessary), but the body of it is a bit strange. I don't know what you're trying to achieve there, but it's almost certainly not doing what you want. What you'll probably want to do is remove the current body of the if statement and indent a bunch of the following code.
print('Enter x:',radius)

This will print out Enter x: followed by radius, which you just set to the int function (probably not what you want. Instead, you probably want to prompt the user and receive their input:
radius = input('Enter x: ')

And then convert it to a float:
radius = float(radius)

Back to your code. pi = 3.14159 is valid and correct, but there is no need to assign pi in your own code; just import it from math:
from math import pi

Then you've got these two lines:
area = ( radius ** 2 ) * pi
print ( 'The Area is=' , area )

You've got no problem there; those should work fine. Your code continues:
choice_2= (choice)

This is not useful. Just use choice; you don't need a new variable.
if (choice_2==2): side= (int)

The if statement, here, too, is correct, but its body, too, is senseless. Again, you probably want to prompt the user to enter something and then convert it to a float.
At the end, you've got:
print('enter X:' side*side)

First of all, you're missing a comma. Second of all, you're outputting the area after enter X:, which doesn't make that much sense. That said, you did get the calculation right.

A: There are a number of issues with the code. Here is a working example of what I believe you want to accomplish:
#!/usr/bin/python
pi = 3.14159265

choice = input('Enter Choice [1 or 2]:')
choice = int (choice)

if choice == 1:
  radius = input('Enter x:')
  area = ( radius ** 2 ) * pi
  print 'The Area is=', area

if choice == 2:
  side = input('Enter x:')
  area = side ** 2
  print 'The Area is=', area

There are a number of problems with the code you've presented: indentation, variables, inputs, and outputs. There are a number of improvements that can be made as well (such as removing duplicate statements). The code I've given above will accomplish what you want to do. So let's go through the errors to get a deeper understanding.
Indentation
First, Python programs should be indented properly. This means that lines following a conditional logic (such as an if statement) should be tabbed. The indentation is called a "block" statement. Only those lines that are indented will be evaluated (executed) if the given condition is met (e.g., the user supplied 1 or 2 as a value).
Variables
The choice_1 and choice_2 variables are not necessary. Logistically, you want to tell the reader of your source code that the user's input should be rounded to a whole integer. The extra variables are superfluous -- you can reuse the choice variable.
Inputs
The input function is used to assign the value of whatever the user typed to the variable on the left-hand-side of the expression. Examples:
choice = input ('Enter choice:')
radius = input( 'Enter x:' )
side = input( 'Enter x:' )

These input statements appear on the screen. The user types in a number and the value of that number is put inside the corresponding variable.
Outputs
The print statement is used to display a value on the screen. In your code, you had combined a text string ('Enter x') with a print statement. The computer cannot "know" that 'Enter x' means that the user must type in a value. Just like the computer does not know that 'Barney' is the name of a purple dinosaur.

A: radius = (int)
This seems to be the main problem.

A: A few things.
If that is how your script is indented, it's not going to work, period. Indenting is core to python, and you need to understand that before you'll get anything substantial working.
If the input is an integer, it will be automatically converted using input(). You're only asking for input once, so don't both creating two variables.
choice = input('Enter choice: ')

If should be using an if-elif-else statement here. Use control structures to your advantage:
if choice == 1:
  radius = input('Enter radius: ')
  print('Area of circle is ', (radius ** 2) * 3.14159)
elif choice == 2:
  side = input('Enter side length: ')
  print('Areas of square is ', side*side)

That's simplified, what you're trying to acheive.
Other than that, you shouldn't do side= (int) or radius = (int). You're assigning a type of int to the variable, when you should be getting a value from input. You'll find very quickly that there are no operators that support multiplication of type and type.


text:
Q: SaveChanges problem in N-Tier Architecture Normally, with MVC I use  db.savechanges() method after I do some processes. But check the below code when I use N-Tier Architecture in everyloop its gonna insert in this way but I dont want it. I have to check all the items first. If there is no problem then I have to insert it all together.
              foreach (var item in mOrderList)
                {
                    MOrder mOrder = new MOrder();
                    mOrder.StatusAdmin = false;
                    mOrder.Date = DateTime.Now;
                    mOrder.StatusMVendor = "Sipariş alındı.";
                    mOrder.HowMany = item.HowMany;
                    mOrder.MBasketId = item.MBasketId;
                    mOrder.MProductId = item.MProductId;
                    mOrder.MVendorId = item.MVendorId;
                    mOrder.WInvestorId = item.WInvestorId;

                    MProduct mprostock = _imProductService.GetMProductById(item.MProductId);
                    if (mprostock.Stock<=0)
                    {
                        return ReturnErrorAndSuccess(HttpStatusCode.NotFound, "MProduct", mprostock.Name + " ürününde stok kalmadığı için işlem tamamlanamadı.");
                    }
                    _imOrderService.InsertMOrder(mOrder);
                }

A: all you have to do is:

*

*first you should define a method that get list of mProductId and then return list of MProduct.

*after that you should check if there is any record with Stock<=0 then return your error.
-also for your insert you should define a method that get list of MOrder and return appropriate datatype for example Boolean.
public List<MProduct> GetMProductByIds(List<MProductId> mProductId)
{
  //getting record code
}

public bool AddMOrder(List<MOrder> mOrder)
{
  //inserting record code
}


text:
Q: unresolved external symbol when using unordered_map I'm trying to create a basic Python interpreter using cpp and I'm facing an unresolved external symbol problem with the container of the _variables: an unordered_map
here is the declaration:
private:
    static std::unordered_map<std::string, Type*> _variables;//type is a base class for all the types of variables

and here is the relevant code using the container:
bool Parser::makeAssignment(std::string str)
{
    char ch = '=';
    int count = 0;
    Type* newVar;
    for(int i = 0; (i = str.find(ch, i)) != std::string::npos; i++)
    {
        count++;
    }
    if (count != 1)
    {
        return false;
    }

    std::string::size_type pos = str.find('=');
    std::string varName = str.substr(0, pos);
    std::string varVal = str.substr(pos + 1, str.size());
    Helper::trim(varName);
    Helper::trim(varVal);
    if (!isLegalVarName(varName))
    {
        throw SyntaxException();
    }
    if (getType(varVal) != NULL)
    {
        newVar = getType(varVal);
    }
    else
    {
        throw SyntaxException();
    }//checks if the declaration written is valid

    auto it = _variables.find(varName);
    if (it != _variables.end())
    {
        it->second = newVar;
    }
    else
    {
        _variables.insert({ varName, newVar });
    }
    return true;
}

Type* Parser::getVariableValue(std::string str)
{
    auto it = _variables.find(str);
    if (it != _variables.end())
    {
        return it->second;
    }
    return NULL;
}

void Parser::cleanMemory()
{
    _variables.clear();
}

I would also appreciate an explanation for this problem in general (LNK2001) because I have encountered it several times before.

A: This issue has to do with the difference between a declaration and a definition.
A declaration such as
class Parser {
...
    static std::unordered_map<std::string, Type*> _variables;
...
};

tells the compiler that a symbol Parser::_variables will be available with the given type.
All code modules (.cpp files) which use that symbol will include the header file with the declaration to make the symbol known to that module.
In one place (only), the symbol needs to be defined, i.e. instantiated such that it is actually present in the final binary. Hence one .cpp file should have a definition like this:
std::unordered_map<std::string, Type*> Parser::_variables;

Building of a program is, put shortly, a two-step process: compilation and linking.
During compilation, the binary translation of each code module is generated except for unresolved "external" references to symbols (functions and variables) that are used (declared), but not defined in that module.
During the linking step, all the modules are put together and unresolved references in each module are resolved by pointing to the module where they are defined. If it turns out that there is a symbol which is used, but not defined anywhere, then that reference remains unresolved and the final binary cannot be generated. Thus, the linker reports the observed error "unresolved external symbol".


text:
Q: java.lang.RuntimeException: Camera.setParameters i know that the question was asked before, and i did read all the solutions, but my case is kinda strange, i keep getting on Crash report on developer account the following:

java.lang.RuntimeException:    at
  android.hardware.Camera.native_setParameters(Native Method:0)   at
  android.hardware.Camera.setParameters(Camera.java:2080)   at
  com.xxxxxxxxxx.core.xxxxxxxx.xxxxxxx.surfaceCreated(BackgroundVideoRecorder.java:119)
  at android.view.SurfaceView.updateWindow(SurfaceView.java:675)   at
  android.view.SurfaceView$3.onPreDraw(SurfaceView.java:185)   at
  android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:944)
  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2050)
  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1117)   at
  android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6175)
  at
  android.view.Choreographer$CallbackRecord.run(Choreographer.java:773)
  at android.view.Choreographer.doCallbacks(Choreographer.java:586)   at
  android.view.Choreographer.doFrame(Choreographer.java:556)   at
  android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:759)
  at android.os.Handler.handleCallback(Handler.java:739)   at
  android.os.Handler.dispatchMessage(Handler.java:95)   at
  android.os.Looper.loop(Looper.java:135)   at
  android.app.ActivityThread.main(ActivityThread.java:5421)   at
  java.lang.reflect.Method.invoke(Native Method:0)   at
  java.lang.reflect.Method.invoke(Method.java:372)   at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)

Removed the application name for the sake of advertising, i tried the application on multiple devices and i cannot arrive to reproduce the error, even tho the devices that i tried it are available in the crash report, and in my parameter generation process i made sure to check if every parameter is supported, by checking the camera params here the code bellow:
   if (front) {
            params = camera.getParameters();
            params.setRotation(90);
            List<String> focusModes = params.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
                Log.w("VideoTakerFront","Continuous Video Supported");
            }
        } else {
            params = camera.getParameters();
            params.setRotation(270);
            List<String> focusModes = params.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
                Log.w("VideoTakerBack","Continuous Video Supported");
            }
        }
        camera.setParameters(params);
                if (android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.JELLY_BEAN_MR1){
                    camera.enableShutterSound(false);
                }
                else{
                    AudioManager audio= (AudioManager)this.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                    audio.setStreamVolume(AudioManager.STREAM_SYSTEM, 0,   AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                }
        Log.w("VideoTaker", "Open Camera");

Thank you for the help!

A: i found the problem... The users that reported the issue was using an older version of the application, i did not pay attention for the version, this problem used to happen in an older version, before I didn't use to get supported focus mode and check if it is available, thank you!


text:
Q: Error with the Python Fuel SDK I am trying to return all the data extensions within my org, and within the same script return a list from all the columns by looping through the results of from step 1.
Here is a sample of my code:
import ET_Client

try:
    debug = False
    stubObj = ET_Client.ET_Client(False, debug)

    # Get all of the DataExtensions in an Account - This works
    print('>>> Get all of the DataExtensions in an Account')
    de = ET_Client.ET_DataExtension()
    de.auth_stub = stubObj
    de.props = ["CustomerKey"]
    de.search_filter = {'Property' : 'IsSendable','SimpleOperator' : 'equals','Value' : 'True'}
    getResponse = de.get()
    #de.search_filter = {'Property' : 'IsSendable','SimpleOperator' : 'equals','Value' : 'True'}

    extract = getResponse.results

    list2 = []

    for item in extract:
        list2.append(item[2])

    print(list2)

    # list2 now has all my customers keys , which I pass to a Second API Call
    for x in list2:
        de_columns = ET_Client.ET_DataExtension_Column()
        de_columns.props = ["CustomerKey"]
        de_columns.search_filter = {'Property' : 'CustomerKey','SimpleOperator' : 'equals','Value' : x}
        getResponse2 = de_columns.get()
        print(getResponse2.results)

except Exception as e:
    print('Caught exception: ' + str(e.message))
    print(e)

It works until I try looping the results of the second API and I get this error:

File "GetAllDEs.py", line 45, in
      getResponse2 = de_columns.get()   File "/anaconda/lib/python3.6/site-packages/FuelSDK/objects.py", line 234,
  in get
      obj = ET_Get(self.auth_stub, self.obj, self.props, self.search_filter)                         File
  "/anaconda/lib/python3.6/site-packages/FuelSDK/rest.py", line 145, in
  init
      auth_stub.refresh_token() AttributeError: 'NoneType' object has no attribute 'refresh_token'

Not sure where to go from here. I will appreciate any pointers on this.

A: Here's Django management command script that queries data extensions and their columns.  You can remove the Django parts.  Perhaps your column search filter should use the 'like' operator instead of 'equals'.
from django.core.management.base import BaseCommand
from FuelSDK import ET_Client, ET_DataExtension, ET_DataExtension_Column

class Command(BaseCommand):
    help = 'Queries data extensions (including columns) per Business Unit from Marketing Cloud'
    client_id = 'xxxx'
    clientsecret = 'xxxxx'

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):
        try:
            stub_obj = ET_Client(False, False, params={'clientid': client_id,
                                                   'clientsecret': client_secret})
            de = ET_DataExtension()
            de.auth_stub = stub_obj
            de.props = ["CustomerKey","Name"]
            de.search_filter = {'Property': 'Name', 'SimpleOperator': 'like', 'Value': 'test'}
            de_res = de.get()

            de_list = []
            for ext in de_res.results:
                de_list.append(ext.CustomerKey)

            # query for the columns
            for x in de_list:
                stub_obj = ET_Client(False, False, params={
                                     'clientid': client_id,
                                     'clientsecret': client_secret})
                de_col_req = ET_DataExtension_Column()
                de_col_req.auth_stub = stub_obj
                de_col_req.props = ["CustomerKey"]
                de_col_req.search_filter = {'Property': 'CustomerKey',
                                        'SimpleOperator': 'like',
                                        'Value': x}
                de_col_res = de_col_req.get()
                de_cols_added = []
                for res_item in de_col_res.results:
                    print(res_item)

        except Exception as e:
            print(str(e.message))
            print(e)


text:
Q: Assessing GLM fit for categorical data I am looking for advice on how to model categorical data, in particular whether or not a generalized linear model is appropriate for my situation and, if so, how to test for fit. My ultimate goal is to compare a set of models using AIC. I have a complex dataset with 15k records, which I've simplified for some of the examples in this question.
The variables I am analyzing are all categorical. See snippet below for an example, where uniqueness is my response variable with three levels (unique_county, unique_locality, unique_time) and my predictor variables are sizeClass (2 levels: large or small), status (4 levels: S1, S2, native, introduced), and state (8 levels: AR, CA, CO, FL, GA, MI, TN, WV).
> example_rawData
# A tibble: 6 x 5
  index sizeClass status     state uniqueness
  <dbl> <chr>     <chr>      <chr> <chr>
1   823 large     introduced AR    unique_locality
2  1994 large     introduced FL    unique_time
3   902 large     S1         FL    unique_county
4  1205 small     S2         FL    unique_time
5  1962 small     introduced CA    unique_locality
6  2088 small     native     GA    unique_time

I do not have much experience modeling, and so a colleague recommended using a generalized linear model with bimodal distribution to do a multiple logistic regression. I interpreted this as using the glm function in R, a la a global model of uniqueness ~ sizeClass + status + state. To run this I dummy coded my variables into a glm-friendly df:
> example_dummyCoded
# A tibble: 6 x 18
  index unique_county unique_locality unique_time large small introduced native    S1    S2    AR    CA    CO    FL    GA    MI    TN    WV
  <dbl>         <dbl>           <dbl>       <dbl> <dbl> <dbl>      <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1   823             0               1           0     1     0          1      0     0     0     1     0     0     0     0     0     0     0
2  1994             0               0           1     1     0          1      0     0     0     0     0     0     1     0     0     0     0
3   902             1               0           0     1     0          0      0     1     0     0     0     0     1     0     0     0     0
4  1205             0               0           1     0     1          0      0     0     1     0     0     0     1     0     0     0     0
5  1962             0               1           0     0     1          1      0     0     0     0     1     0     0     0     0     0     0
6  2088             0               0           1     0     1          0      1     0     0     0     0     0     0     1     0     0     0

With the dummy coded data I can generate a model using glm(unique_county ~ small + native + S1 + S2 + AR + CA + CO + FL + GA + MI + TN, data = example_dummyCoded, family = binomial(link="logit")). Does creating models for my data this way (using a glm and dummy coding the variables) make sense? I would expect to end up with three sets of models, one set for each of the levels in my response variable: unique_county ~ ..., unique_locality ~ ... and unique_time ~ ....
If that does make sense then my next problem is that I'm not sure how to test for model fit. Here is the summary of my actual global model (not the example here but using the same steps on the full dataset):
> summary(mGLOBAL)

Call:
glm(formula = unique_county ~ small + native + S1 + S2 + AR + CA
+ CO + FL + GA + MI + TN, family = binomial(link = "logit"), data = modelData)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.0626  -0.5720  -0.3861  -0.2283   2.9369

Coefficients:
                Estimate   Std. Error z value             Pr(>|z|)
(Intercept) -0.276137007  0.089746361  -3.077              0.00209 **
small       -0.612519559  0.057460515 -10.660 < 0.0000000000000002 ***
native      -0.428259979  0.055192949  -7.759  0.00000000000000854 ***
S1          -0.375853505  0.129017440  -2.913              0.00358 **
S2          -0.080792234  0.087646391  -0.922              0.35663
CA          -2.982253831  0.135104856 -22.074 < 0.0000000000000002 ***
CO          -1.854740655  0.120353139 -15.411 < 0.0000000000000002 ***
FL          -2.000331482  0.117071808 -17.086 < 0.0000000000000002 ***
GA          -0.000004545  0.096040410   0.000              0.99996
MI          -1.451191711  0.096645269 -15.016 < 0.0000000000000002 ***
TN          -0.933275348  0.093412187  -9.991 < 0.0000000000000002 ***
WV          -0.328605823  0.105405432  -3.118              0.00182 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 12381  on 15790  degrees of freedom
Residual deviance: 10901  on 15779  degrees of freedom
AIC: 10925

Number of Fisher Scoring iterations: 6

I can test for correlation in the predictor variables using variance inflation factor, the values of which all seem low enough to be fine:
car::vif(mGLOBAL)
   small   native       S1       S2       CA       CO       FL       GA       MI       TN       WV
1.085822 1.227785 1.069836 1.140127 1.445937 1.542216 1.716258 2.245607 2.163657 2.311633 2.058554

I can also plot my mGLOBAL, but when I plot the residuals using qqnorm(rstandard(mGLOBAL)) I don't know how to interpret this distribution:

Likewise not sure how to interpret plot(fitted(mGLOBAL),rstandard(mGLOBAL)):

Or my Cook's distance plot(mGLOBAL,4):

Are these even appropriate tests to validate my model...? Thank you very much for any thoughts/advice!

A: You can see from your diagnostic plots that you have two separate groups, which presumably correspond to the response variables unique_locality and unique_time.  This occurs because you have fit a logistic regression using a binary response outcome, rather than using a multiple logistic regression that can handle the three-category outcome you actually have.  I recommend that you follow your colleague's advice to use a multiple logistic regression (in the first instance), so that you have a model that allows for the three-category outcome in your data.
You can fit a multiple logistic regression model in R using the multinom function in the nnet package (documentation here and here).  The multiple logistic regression model is a type of "log-linear model", which can be extended to more complex models if required.  My advice would be to fit to the multiple logistic regression model in the first instance, and then see if the model diagnostics warrant any change to the model.


text:
Q: Why this code isn't causing endless recurssion I found this code online and I have some doubts regarding its syntax.
https://github.com/playframework/play-mailer/blob/master/play-mailer/src/main/scala/play/api/libs/mailer/MailerClient.scala
Question 1 - In line import play.libs.mailer.{ Email => JEmail, MailerClient => JMailerClient }
, I suppose this is import rename and play.libs.mailer.Email will be referred as JEmail and play.libs.mailer.MailerClient is being referred as JMailerClient. Why is the import been renamed?
Question 2 - In line trait MailerClient extends JMailerClient, the code uses both MailerClient and JMailerClient but isn't MailerClient same as JMailerClient
Question 3 - In the following code, send is undefined, then it is overriden and then in the overridden function, send is called again! How is it working?
def send(data: Email): String

  override def send(data: JEmail): String = {
    val email = convert(data)
    send(email)
  }

A: *

*If play.libs.mailer.Email were imported as Email, that would hide the Email class from this package. By importing the former as JEmail, the latter can still be referred to as Email. Similarly if MailerClient were imported without the "J", the MailerClient defined in this very file would just shadow it. Plus line 7 would turn into trait MailerClient extends MailerClient, which is obviously a problem because it now looks like the trait is trying to extend itself.

*No. This definition defines a trait named MailerClient. That trait extends JMailerClient (a.k.a. play.libs.mailer.MailerClient). MailerClient is the trait being defined right here and JMailerClient is the interface that is being extended.

*As you can see later in the file, convert returns an Email object. So the call send(email) does not recursively call the second send method (which takes a JEmail), but rather calls the overload for Email objects that's defined (as an abstract method) on line 15.


text:
Q: VueJS and Image CDNs: How to check when image is done being optimized through the Image CDN? I might be over thinking this, but I got a an avatarprofile component that lets a user update their avatar image. I am using Google Cloud storage as the image hosting and then I am using an image CDN (imagekit) to handle the image optimization/caching. All works good...however, I do have a minor annoyance that I was wondering if someone could help me with:
First, here's my code (will help explain what I am having issue with):
    async avatarChangeHandler(e) {
      this.overlayShow = true //<-- show a loading indicator
      try {
        if (e.target.files.length) {
          this.image = await new Promise((resolve) => {
            const reader = new FileReader()
            reader.onload = (e) => {
              resolve(e.target.result)
            }
            reader.readAsDataURL(e.target.files[0])
          })
          await this.photoUpload() //<-- upload image to Google storage and return new image URL
          await this.updateAvatar() //<-- update user's profile in the database with new URL
          await this.$store.dispatch('getUserProfile', this.currentUser) //<-- grab updated profile
          console.log('updating...done')
          this.overlayShow = false //<-- terminate the loading indicator

The problem is that the user profile is updated with the new image URL and fetched faster than the image CDN...and so that means the overlayShow is already set to false and still shows the old image for a second or so (depending on level of optimization needed).
What can I do to make sure the overlayShow is not set to false until the image CDN is done with the new image? Thanks and I realize this may not be  feasible, but looking for advice or suggestions on approach. Thanks!


text:
Q: Cross fade background-image with jQuery so I have some images and I would like to show them as a slideshow in the background. However, I want the image to cross-fade between the current image and the next image. So far, I have only been able to switch between the images:
$(document).ready(function () {

    var images = ["landing_background_1.jpg", "landing_background_2.jpg", "landing_background_3.jpg", "landing_background_4.jpg"];

    var currentImage = 0;

    function changeBackgroundImage() {

        $("html").fadeIn().css({

            "background-image": "url('img/backgrounds/" + images[++currentImage] + "')",

        });

        if (currentImage >= images.length - 1) {

            //set it back to the begining
            currentImage -= images.length;

        }

    }

    setInterval(changeBackgroundImage, 1500);

});

Any help would be much appreciated! :)

A: What you have to do is layer two element on top of each other.  Then have one fadeout and the other fadein.
Here is how I would go about doing it ...
css ...
#background-images {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1;
    }

#bImg1 {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 3;
    background: url(starting-img1.jpg) no-repeat;
    background-size: contain;
    }

#bImg2 {
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 2;
    background: url(starting-img2.jpg) no-repeat;
    background-size: contain;
    }

.container {
    width: 960px;
    height: 900px;
    background: rgba(255,255,255,.7);
    margin: auto;
    position: relative;
    z-index: 10;
}

The html ...

        Content Here

The script ...
var imageSet1 = ["image1.jpg", "image2.jpg", "image3.jpg"];
var currentImageSet1 = 0;

var imageSet2 = ["image4.jpg", "image5.jpg", "image6.jpg"];
var currentImageSet2 = 0;

function changeBackgroundImages() {
    img1Fade();
    setTimeout(img2Fade, 2000);

}

function img1Fade(){

    $('#bImg1').fadeOut('slow', function(){$('#bImg1').css({background: 'url(' + imageSet1[++currentImageSet1] + ')'})});
    $('#bImg2').fadeIn('slow');
    if (currentImageSet1 >= imageSet1.length - 1) {

            currentImageSet1 -= imageSet1.length;
        };
}

function img2Fade(){

    $('#bImg2').fadeOut('slow', function(){$('#bImg2').css({background: 'url(' + imageSet2[++currentImageSet2] + ')'})});
    $('#bImg1').fadeIn('slow');
    if (currentImageSet2 >= imageSet2.length - 1) {

            currentImageSet2 -= imageSet2.length;
        };
}

$(document).ready(function(){

    setInterval(changeBackgroundImages, 5000);
});

You will need to mess with the timing to get it to look good.  Make sure to set your urls to the images in the image array or when the sting in the css is built.

A: I've spent a lot of time to find the most clean and easy way.
This finally works:

var i=0;
var imghead=[
 "url(http://yoururl.com/picture0.jpg)",
 "url(http://yoururl.com/picture1.jpg)"
 ];//add as many images as you like

function slideimg() {
    setTimeout(function () {
        jQuery('#element').css('background-image', imghead[i]);
        i++;
        if(i==imghead.length) i=0;
        slideimg();
    }, 6000);
}
slideimg();
#element{
 height: 100%;
 overflow: hidden;
 opacity: 1.0;
 -webkit-transition: background-image 1.5s linear;
 -moz-transition: background-image 1.5s linear;
 -o-transition: background-image 1.5s linear;
 -ms-transition: background-image 1.5s linear;
 transition: background-image 1.5s linear;
}

A: Easier:
var current = 1;
function anim() {
   if(current == 4) {current = 1;   }
   $('#bImg'+ current).fadeOut(3000);
   ++current;
   $('#bImg'+ current).fadeIn(3000);
   setTimeout(anim, 8000);
}
anim();

html:

css:
.inside {
 background:url(top_01.jpg) no-repeat center top ;
}

#bImg2 {
position: absolute;
top: 0px;
width: 100%;
background:url(top_02.jpg) no-repeat center top ;
 display: none;
}

  #bImg3 {
position: absolute;
top: 0px;
width: 100%;
background:url(top_03.jpg) no-repeat center top ;
 display: none;
}


text:
Q: Como executar um loop até as linhas de um determinado arquivo.txt acabar Gostaria de fazer um sisteminha basico com loop por exemplo, abria o arquivo que o usuario digitou depois usava um if para enquanto tiver linhas no arquivo executar um loop com outros codigos

A: Em Python, o próprio objeto que representa um arquivo aberto é feito para funcionar direto com um loop como você fala.
Por exemplo, um programa para imprimir cada linha de um arquivo é simplesmente:
nome = input("Digite o nome do arquivo: ")
with open(nome) as arq:
    for linha in arq:
        print(linha)

Em outras palavras: você usa o arquivo direto no comando for do Python - quando o arquivo acabar ele sai do for. (E nesse caso, como temos o with, ele saí do with também e já fecha o arquivo).
Isso acontece simplesmente por que o objeto arquivo implementa o "iterator protocol" - com os métodos __iter__ e  __next__. Qualquer objeto que tenha esses métodos (implementdos da forma correta) pode funcionar direto no comando for.

A: Eu não gosto de pedir interactivamente nomes de ficheiros;
prefiro a criação de scripts que recebem parâmetros via linha
de comando. Nesso sentido recomendo o módulo fileinput:
#!/usr/bin/python
# -*- coding=utf-8 -*-

import fileinput
for linha in fileinput.input():
   linha=linha.strip()
   #processa linha

Deste modo a script funciona como um comando normal Unix, e na linha de
comando podemos dar zero (stdin, pipes) ou mais ficheiros a processar.
Ver também as sempre úteis funções fileinput.filename() close() isfirstline() lineno() filelineno() nextfile()


text:
Q: pandas rolling max min mean being new to pandas I am lost in the zillions of smooth random data generation examples.
What I have been trying to achieve is to create graphs using bokeh with rolling time window. I want x-axis to be (resampled or whatever) timestamp and 3 lines displaying max, min and mean values for let's say rolling 15 second time window for the duration field.
The joy stops before starting... I have tried to apply quite many examples without making progress or learning much.
The code below
d2 = pd.read_csv(input_file, delimiter=",")
d2["ts_send"] = pd.to_datetime(d2["ts_send"], \
format="%Y-%m-%d %H:%M:%S.%f", exact=True, utc=True)

print (d2.head())
print (d2.rolling("15s", min_periods=1).mean().head())
print (d2.rolling("15s", min_periods=1).std().head())
print (d2.rolling("15s", min_periods=1).min().head())
print (d2.rolling("15s", min_periods=1).max().head())

produces an exception:

ValueError: window must be an integer

If I could get the rolling stuff work, I'd probably could manage the bokeh side.
Any pointers supporting to make this happen are highly appreciated!
I have this data in csv:

ts_send,endpoint,duration,
2017-01-19 09:03:28.600,/api/sig,1.0
2017-01-19 09:03:29.760,/api/sig,0.5
2017-01-19 09:04:51.210,/api/sig,0.508
2017-01-19 09:04:52.410,/api/sig,0.574
2017-01-19 09:09:32.854,/api/sig,1.0
2017-01-19 09:09:36.776,/api/sig,0.637
2017-01-19 09:14:14.207,/api/sig,0.672
2017-01-19 09:14:16.906,/api/sig,0.533
2017-01-19 11:49:34.939,/api/sig,1.0
2017-01-19 11:49:38.709,/api/sig,0.529
2017-01-19 12:19:01.668,/api/sig,1.0
2017-01-19 12:19:05.559,/api/item,0.169
2017-01-19 12:19:05.559,/api/item,0.102
2017-01-19 12:19:05.559,/api/item,0.44
2017-01-19 12:19:05.585,/api/item,0.173
2017-01-19 12:19:06.633,/api/sig,0.564
2017-01-19 12:27:05.712,/api/sig,0.574
2017-01-19 12:27:08.370,/api/sig,0.497
2017-01-19 12:27:43.319,/api/sig,0.561
2017-01-19 12:27:45.873,/api/sig,0.508
2017-01-19 12:46:15.454,/api/sig,1.0
2017-01-19 12:46:20.409,/api/item,0.173
2017-01-19 12:46:20.427,/api/item,0.163
2017-01-19 12:46:20.457,/api/item,0.169
2017-01-19 12:46:20.474,/api/item,0.162
2017-01-19 12:46:20.618,/api/item,0.209
2017-01-19 12:46:20.642,/api/item,0.172
2017-01-19 12:46:20.695,/api/item,0.26
2017-01-19 12:46:20.698,/api/item,0.193
2017-01-19 12:46:20.788,/api/item,0.193
2017-01-19 12:46:20.822,/api/item,0.232
2017-01-19 12:46:20.873,/api/item,0.164
2017-01-19 12:46:20.875,/api/item,0.142
2017-01-19 12:46:20.905,/api/item,0.356
2017-01-19 12:46:20.998,/api/item,0.199

The timestamp ts_send is millisecond precission. There are times when no events are recorded and there are times when there multiple events on a single millisecond.

A: This will work if your time series is the index. Add this before you run your code:
d2.set_index('ts_send', inplace=True)

A: Thanks to kind members Boud and Goyo I was able to move forward.
The code produces what I needed:
d2 = pd.read_csv(input_file, delimiter=",")
d2["ts_send"] = pd.to_datetime(d2["ts_send"], format="%Y-%m-%d %H:%M:%S.%f", exact=True, utc=True)
d2.index = pd.DatetimeIndex(d2.ts_send, inplace=True)
d3 = d2.sort_index()
d3.drop(d3.columns[0],axis=1,inplace=True)

print (d3.index.is_monotonic_increasing)
print (d3.head())

print (d3.rolling("5s", min_periods=1).mean())
print (d3.rolling("5s", min_periods=1).std())
print (d3.rolling("5s", min_periods=1).min())
print (d3.rolling("5s", min_periods=1).max())


text:
Q: How to turn off cell brackets programmatically? From the documentation, it appears that executing
SetOptions[EvaluationNotebook[], ShowCellBracket -> False];
in the current notebook, should immediately hide the cell brackets in the current notebook.
But nothing happens. Where am I going wrong?


text:
Q: export sql in php UTF-8 I want to export all of tables of my db in sql file using php with encoding UTF-8
whats the best way! whats the code!
thank you

A: Start your query after this:
$db = new MySQLi("host", "username", "password", "db");

if(!$db)
{
    die("your_error_msg" . mysqli_error($db));
}

$db->set_charset("utf8");'

EDIT
<?php
    //ENTER THE RELEVANT INFO BELOW
    $mysqlDatabaseName ='xxxxxx';
    $mysqlUserName ='xxxxxxx';
    $mysqlPassword ='myPassword';
    $mysqlHostName ='xxxxxxxx.net';
    $mysqlExportPath ='chooseFilenameForBackup.sql';

    //DO NOT EDIT BELOW THIS LINE
    //Export the database and output the status to the page
    $command='mysqldump --opt -h' .$mysqlHostName .' -u' .$mysqlUserName .' -p' .$mysqlPassword .' --default-character-set=utf8 ' .$mysqlDatabaseName .' > ~/' .$mysqlExportPath;
    exec($command);
 ?>

From: export database using php code in .sql Extension?, but I added the --default-character-set=utf8 part


text:
Q: How to specify object value type depending on object key? I have an object with 2 arrays which contain different types of functions.
Also I have a function that pushes callbacks into arrays of this object.

type StringCallbackType = (str: string) => void
type BoolCallbackType = (bool: boolean) => void

type ObjType = {
  first: Array<StringCallbackType>,
  second: Array<BoolCallbackType>
}

const obj: ObjType = {
  first: [],
  second: []
}

function pushCallback(objKey: keyof ObjType, callback: StringCallbackType | BoolCallbackType) {
  obj[objKey].push(callback)
}

I see this message when I try to push a callback into an array - "Argument of type 'StringCallbackType | BoolCallbackType' is not assignable to parameter of type 'StringCallbackType & BoolCallbackType'."
I found a solution when values of object are not arrays. But I couldn't find a solution for this case...
I couldn't find anything helpful in typescript documentation...


text:
Q: Xamarin.Forms popup "New Version Available" I am working on Xamarin.forms Android Project, I am searching away to display a pop up for user:

New Version Available

when user try to open an Application and a new update is available on play-store .

A: I think the easiest thing would be to have a web service on your own server that returns the current version number, unfortunately you would need to update this version number any time you update the app in the store.

A: Create a text file with the latest version number in a GitHub Gist account.
Get the raw URL
string url = "https://gist.githubusercontent.com/YOUR_ACCOUNT_NAME/0df1fa45aa11753de0a85893448b22de/raw/UpdateInfo.txt";
private static async Task<string> GetLatestVersion(string URL)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(URL));
        request.ContentType = "application/json"; //i am using a json file
        request.Method = "GET";
        request.Timeout = 20000;
        // Send the request to the server and wait for the response:
        try
        {
            using (WebResponse response = await request.GetResponseAsync())
            {
                // Get a stream representation of the HTTP web response:
                using (Stream stream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(stream);
                    return reader.ReadToEnd();
                }
            }
        }
        catch (Exception ex)
        {
            return string.Empty;
        }
    }

which will returns the latest version of your app. and check with the existing app version in activity
var versionName = Application.Context.ApplicationContext.PackageManager.GetPackageInfo(Application.Context.ApplicationContext.PackageName, 0).VersionName;
        var currentVer = double.Parse(versionName);

but you have to update this version number any time you update the app in the play store.

A: private class GetVersionCode extends AsyncTask<Void, String, String> {
    @Override
    protected String doInBackground(Void... voids) {

        String newVersion = null;
        try {
            newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + SplashActivity.this.getPackageName() + "&hl=it")
                    .timeout(30000)
                    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                    .referrer("http://www.google.com")
                    .get()
                    .select("div[itemprop=softwareVersion]")
                    .first()
                    .ownText();
             return newVersion;
        } catch (Exception e) {
            return newVersion;
        }
    }

    @Override
    protected void onPostExecute(String onlineVersion) {
        super.onPostExecute(onlineVersion);
        String currentVersion = null;
        try {
            currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (onlineVersion != null && !onlineVersion.isEmpty()) {
            if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) {

                    final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SplashActivity.this);
                    alertDialogBuilder.setTitle("Product Update");
                    alertDialogBuilder.setMessage("A new version is available. Would you like to Upgrade now? (Current: "+currentVersion+" Latest: "+onlineVersion+")");
                    alertDialogBuilder.setPositiveButton("ok",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+SplashActivity.this.getPackageName())));
                                }
                            });

                    alertDialogBuilder.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            alertDialogBuilder.setCancelable(true);
                            finish();
                            loginUserCheck();
                        }
                    });

                    AlertDialog alertDialog = alertDialogBuilder.create();
                    alertDialog.show();
             }


text:
Q: Подключение и работа с Web-Service Добрый день!
Передо мной стоит задача:

*

*Подключиться к веб-сервису по имени.

*Получить список методов на сервисе и количество параметров каждого.

*Иметь возможность вызвать каждый из методов и задавать параметры выбранного метода.

Единственное, что у меня пока получилось, - это подключиться к веб-сервису соседнего проекта и вывести у себя на странице HelloWorld().
Мне кажется, что тут нужно копать в сторону HttpWebRequest, но как именно, непонятно. Подскажите, пожалуйста, в какую сторону копать, может, статьи где полезные есть, сам я не нашел еще. Буду очень благодарен за любую помощь. Спасибо.
Обновление
Ошибка, точнее проблема в том, что я не знаю, как получить список методов веб-сервиса. По ходу дела  нужно использовать wdsl, но как именно, ума не приложу. Вот в этом проблема. Т.е. по адресу сервиса получить список его методов. Спасибо!
A: При поиске в гугле по запросу "работа с веб службами c#" ссылка на эту страничку выдается первой в списке или одной из первых, а ответа здесь толком нет, есть ссылка только на сторонний ресурс (на сколько он надежен? на сколько удачен и применим тот пример?) и отсылка обратно в гугл, поэтому я напишу этот ответ (возможно для себя самого в будущем).
Я создал пустой проект по шаблону Console App в Visual Studio. Добавим ссылку на веб-службу: правый клик в Solution Explorer по References, выбрать Add Service Reference.... Нажать внизу слева кнопку Advanced..., в появившемся окне слева внизу нажать Add Web Reference.... В поле URL необходимо вставить ссылку на asmx-файл веб службы. Я вставил туда ссылку на веб службу всеми любимого ЦБРФ API: http://www.cbr.ru/DailyInfoWebServ/DailyInfo.asmx. Нажать Enter или кнопку со стрелочкой. После загрузки прописать в Web reference name удобное имя, оно будет использоваться как пространство имен для этой службы, я написал Cbrf. Нажать Add Reference...
Всё. В Solution Explorer в вашем проекте появится папка Web Refereces и элемент Cbrf в ней. Теперь можно подключиться:
using System;
using System.Xml;
using TestWebService.Cbrf;

namespace TestWebService
{
    class Program
    {
        static void Main(string[] args)
        {
            var di = new DailyInfo();
            var curs = di.GetCursOnDateXML(DateTime.Today);
            foreach (XmlNode node in curs.ChildNodes)
                Console.WriteLine(node["Vnom"].InnerText + " "
                                + node["Vname"].InnerText.Trim() + " = "
                                + node["Vcurs"].InnerText + " руб.");
            Console.ReadLine();
        }
    }
}

PS. Вопросы актуальности использования таких веб служб, а также удобства использования пространства имен System.Xml я не затрагиваю. Хотя в этом конкретном примере я бы предпочел не использовать веб службу, а воспользоваться XML-сервисом получения данных в связке с XmlSerializer или XDocument

A: Предпочитаю для таких вещей использовать более подходящий язык программирования. Но раз предпочитаете C#, то вот небольшой пример:
http://www.ibm.com/developerworks/ru/library/l-Mono_11/
А еще погуглите на предмет получения курсов валют с сайта Центробанка. Найдете много примеров на C#.


text:
Q: how do you subset a data frame that has multiple duplicate values in R I have this data frame called data1:
dput(data1)
structure(list(Time = structure(c(1421561100, 1421561100, 1421564700,
1421564700, 1421568300, 1421568300, 1421571900), class = c("POSIXct",
"POSIXt"), tzone = "America/New_York"), Server1 = c(0.75, 1,
0.82, 1, 0.75, 1.08, 0.92)), .Names = c("Time", "Server1"), row.names = c(1L,
13L, 2L, 14L, 3L, 15L, 4L), class = "data.frame")

As you can see for the same time period, I have multiple data points. I need to modify this data frame and only include the max value for the same time period.
For example, for time period ("2015-01-18 01:05:00"), I see 0.75 and 1.00, I need to only include 1.00 for that time period in. Any ideas how could do this, remove duplicate times and only include the max value?

A: > require(dplyr)
> data1 %>% group_by(Time) %>% filter(Server1 == max(Server1))
Source: local data frame [4 x 2]
Groups: Time

                 Time Server1
1 2015-01-18 01:05:00    1.00
2 2015-01-18 02:05:00    1.00
3 2015-01-18 03:05:00    1.08
4 2015-01-18 04:05:00    0.92


text:
Q: Regex. Escape group? Is there any way to make something.+()[]* matching literally 'something.+()[]*'? I'm using regex builder so manual escaping is not allowed. Sure, i can add hardcoded checks if (char === '+') return '\+' but i'm looking for native solution or better way
UPD
I'm sorry. I forgot to add that matching should be in given order with moving forward but not back. So [+.] will not fit my requirements because it will match both +. and .+. I need only first case (In definition order)

A: You don't need to escape them if within square brackets.. I just tested and works for me, but maybe not what you are looking for?
something[.+()[]]


text:
Q: Django: How do I allow views and methods with AllowAny permission to bypass authentication with HttpOnly JWT token cookies? I have applied JWT authentication with HttpOnly cookies using a custom middleware. Now, the middleware checks for the presence of access and refresh tokens as HttpOnly cookies in every request. Everything works well.
But, it retuns 'KeyError': 'access' if I request for a page that does not require authentication, say, the homepage or bloglist or blogdetail page. How do I remove this need for access token in these views with permissions set to AllowAny and also in some views where only the GET method permission is set to AllowAny?
My view:
class TagView(viewsets.ModelViewSet):
    queryset = Tag.objects.all()
    serializer_class = TagSerializer

    def get_permissions(self):
        if self.request.method == 'PUT':
            self.permission_classes = [permissions.IsAuthenticated,]
        elif self.request.method == 'GET':
            self.permission_classes = [permissions.AllowAny,]
        elif self.request.method == 'POST':
            self.permission_classes = [permissions.IsAuthenticated,]
        return super(TagView, self).get_permissions()

If request method is GET, the middleware should pass the request even if no access cookie is found.
Now, it checks for the access cookie in every request. I added a line to skip asking for tokens if the request method is GET and if there is no cookie in the request, to mark it as AllowAny view, but I think it is unsafe.
My middleware:
class AuthorizationHeaderMiddleware:
    def __init__(self, get_response=None):
        self.get_response = get_response

    def process_view(self, request, view_func, view_args, view_kwargs):
        pass

    def __call__(self, request):
        if request.path == '/api/auth/login/':
            return self.get_response(request)

        # for AllowAny views, I am doing this, but I think it is unsafe
        elif request.method == 'GET' and request.COOKIES == {}: # no cookies present
            return self.get_response(request)

        else:
            try:
                access_token = request.COOKIES['access']
                key = settings.SECRET_KEY
                jwt.decode(access_token, key, algorithms=["HS256"])
                request.META['HTTP_AUTHORIZATION'] = f'Bearer {access_token}'
                return self.get_response(request)

            except jwt.ExpiredSignatureError:
                refresh_cookie = request.COOKIES['refresh']
                data = {"refresh": refresh_cookie}
                resp = requests.post('http://127.0.0.1:8000/api/auth/refresh/', data=data)
                access_token_string = json.loads(resp.text)["access"]
                request.META['HTTP_AUTHORIZATION'] = f'Bearer {access_token_string}'
                return self.get_response(request)

How do I allow selected AllowAny views and methods if they don't have HttpOnly JWT token cookies?


text:
Q: Installed Redmine, now phpmyadmin results in "Cannot start Ruby on Rails application" I recently installed Redmine on an Ubuntu 12.04 + Apache server, and it is working fine.
However, my phpmyadmin site is giving me a bizarre error when I go to https://phpmyadmin.example.com:

Here is the VirtualHost configuration bit for phpmyadmin:
<VirtualHost *:443>
    ServerName phpmyadmin.example.com
    DocumentRoot /usr/share/phpmyadmin

    SSLEngine on
    SSLCertificateFile    /etc/ssl/certs/ssl-cert-snakeoil.pem
    SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key

    <Directory /usr/share/phpmyadmin>
            Options FollowSymLinks
            DirectoryIndex index.php

            <IfModule mod_php5.c>
                    AddType application/x-httpd-php .php

                    php_flag magic_quotes_gpc Off
                    php_flag track_vars On
                    php_flag register_globals Off
                    php_admin_flag allow_url_fopen Off
                    php_value include_path .
                    php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp
                    php_admin_value open_basedir /usr/share/phpmyadmin/:/etc/phpmyadmin/:/var/lib/phpmyadmin/
            </IfModule>

    </Directory>
</VirtualHost>

I think it may have something to do with my recent installation of Redmine (a ruby on rails application), but I have been unable to find anything preventing phpmyadmin to load like a regular website.
I find it particularly odd that my default apache "It works!" site is still working at https://example.com.
Why is phpmyadmin being treated like a ruby on rails app?

UPDATE
I think I figured out why phpmyadmin is being treated like a ruby on rails app, but I still have not figured out how to fix it.
I have in /etc/apache2/mods-enabled a passenger.conf file which contains:
<IfModule mod_passenger.c>
    PassengerRoot /usr
    PassengerRuby /usr/bin/ruby
</IfModule>

I tried, modifying the value for PassengerRoot to my Redmine application, /usr/share/redmine/public.  That fixes phpmyadmin, but unfortunately, when I try to access my Redmine app, I get a 403 Forbidden error.
Any suggestions on how to fix this?

A: You'll need to disable Passenger for the VirtualHosts that don't use it.
Inside the phpmyadmin.example.com block add:
PassengerEnabled off

to prevent it from trying to take over all of the requests.


text:
Q: TEMP Environment variable expansion for C++ (Windows) I need to get a %TEMP% environmental variable value string in Windows platform.
If I try to use any methods(C / C++) (getenv(), …) to get this environmental variable, it returns with "~" in that string.
For Example: C:\DOCUME~1\pkp\LOCALS~1\Temp.
But I need to get full string for some reasons, as below:
C:\Documents and Settings\pkp\Local Settings\Temp
If anyone knows any methodology to obtain this, please let me know.

A: Call GetLongPathName() on the short name.

A: DOCUME~1 is not an environment variable. It is a legacy naming convention from DOS still supported by windows for backward compatibility. Hence there is nothing to 'expand' in the environment variable sense.

A: You can use GetTempPath it obliges you to include "windows.h" but I assume you how to do that anyway since you're writing a windows app.


text:
Q: UEFA/FIFA scores API Does anybody know if UEFA or FIFA provide a scores api for football matches, official team players list, transfers, etc?
I found footytube api but not sure ofits stability and completeness..

A: UEFA or FIFA don't seem to provide any API to get the information you want. However, there are some third-party services which support that:

*

*OPTA - Both commercial and free. They have incredible database about matches. Whoscored.com currently uses it.

*Others: livescoreboards, xmlsoccer, ...

A: http://api.football-data.org/index is free and useful.
The API is in active development, stable and recently the first versioned release called alpha was put online. Check the blog section to follow updates and changes.

A: UEFA internally provides their own LIVEX Api for their Broadcasting Partners. That one is perfect enough to develop the Applications by their partners for themselves.

A: You can find stats-dot-com - personally I think their are better than opta. ESPN seems don't provide data in full and do not provide live data feeds (unfortunatelly).
We've been seeking for official data feed providing for our fantasy games (solutionsforfantasysport.com) and still staying with stats-com mainly (used opta, datafactory as well)


text:
Q: Error compiling gold in binutils I am trying to compile the project KernelGen (http://hpcforge.org/plugins/mediawiki/wiki/kernelgen/index.php/Compiling) for some research project I am doing , the build script is using rpmbuild and it looks like it has a dependency on gold from binutils. Build keeps failing when trying to compile gold with the following error:
/bin/sh ./../ylwrap yyscript.y y.tab.c yyscript.c y.tab.h yyscript.h y.output yyscript.output -- byacc  -d
byacc: e - line 42 of "/home/xxx/rpmbuild/BUILD/binutils-2.23.2/gold/yyscript.y", syntax error
%pure-parser
^

The file yyscript.c looks like this:
/* We need to use a pure parser because we might be multi-threaded.
   We pass some arguments through the parser to the lexer.  */

%pure-parser
%parse-param {void* closure}
%lex-param {void* closure}

/* Since we require bison anyhow, we take advantage of it.  */
%error-verbose

/* The values associated with tokens.  */

It looks like it is some kind of grammar file that fails to parse. Things is this file is from the binutils package itself and I can't find a reason why it is failing to parse.
Any ideas ?

A: Your version of byacc doesn't properly support %pure-parser, which I believe was originally a bison extension.  Use bison instead.


text:
Q: Design JSON in Java I have an API which returns JSON in below format. Need to design Java class for the same. These values will be varying. So can't create a java class with fixed properties.
JSON as:
 {
        "jan": {
            "2020-01-01": {
                "A": 348,
                "B": 408
            },
            "2020-01-02": {
                "A": 348,
                "B": 408
            }
        },
        "feb": {
            "2020-02-01": {
                "A": 348,
                "B": 408
            },
            "2020-02-02": {
                "A": 348,
                "B": 408
            }

        }
    }

How to design Object in Spring Boot/Java for this?

A: I understand that you are looking for a java class to use to deserialize the JSON structure that you are sharing. This looks to me like
Map<String, Map<String, Data>>

Where
class Data {
   private int A;
   private int B;
}

Now if you want to deserialize it using for example jackson, you can use
new ObjectMapper().readValue(myJson, new TypeReference<Map<String, Map<String, Data>>>() {});


text:
Q: Crear Ventana con Barra de menu Python Pyqt5 Estoy creando una ventana la cual tenga una barra menú, pero cuando corro el programa con sólo una de las opciones en la barra de menú aparece este error:

mainMenu = self.menuBar()
AttributeError: 'VentanaC' object has no attribute 'menuBar'

El código es el siguiente:
class VentanaC(QDialog):
    def __init__(self, parent=None):
        super(VentanaC, self).__init__()

        self.title = "Observaciones - INICM"
        self.top = 200
        self.left = 500
        self.width = 680
        self.height = 480
        self.setWindowIcon(QtGui.QIcon("icono.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.CreateMenu()

    def CreateMenu(self):

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('File')

if __name__ == '__main__':

    aplicacion = QApplication(sys.argv)

    ventana = VentanaC()
    ventana.show()

    sys.exit(aplicacion.exec_())

No sé por que sucede esto. Otra pregunta que me surge es si el error se presenta por el tipo de ventana, ya que la puse como QDialog, la verdad aún no entiendo muy bien cuando debe ser QDialog, Qwidgets, etc...

A: En ningún momento has añadido el QMenuBar.
En ventanas más completas como QMainWindow las traen por defecto, una menubar y una statusbar, y algunos controles más. Pero en otros tipos de ventanas no es así.
1: La manera más sencilla de solucionarlo es convertir tu ventana en una QMainWindow
2: Una manera alternativa sería añadir explicitamente el nuevo elemento (En este caso una QMenuBar) a tu ventana QDialog. Realmente no sé si será posible, pero yo haría algo así.
def CreateMenu(self):
    mainMenu = QMenuBar(self)
    self.layout().setMenuBar(mainMenu)
    fileMenu = mainMenu.addMenu('File')

Nota: No lo he testeado (No puedo ahora, desde mi telefono) pero debería funcionar.
Actualizacion tras los comentarios:
Puedes crear una ventana pasandole parametros, en este caso lo llamo ejemplo.
class VentanaPrincipal(QMainWindow):
    ventanac = QDialog(ejemplo=self)  # Se pasa una referencia de la clase VentanaPrincipal (self) a la ventanaC

class VentanaC(QDialog):
    def __init__(self, parent=None, ejemplo):
        self.ventanaprincipal = ejemplo  # Se añade la referencia a esta clase

Con ese código ahora puedes, desde cualquier lado de tu QDialog, pedirle cosas a la ventana principal, ya que has creado una referencia dentro de la clase. Por ejemplo:
self.ventanaprincipal.menuBar()
self.ventanaprincipal.statusBar.showMessage("ejemplo")


text:
Q: Where are the different event status values documented? In eventbrite, the event object has many fields, one of which is "status" ...

*

*status string: One of canceled, live, started, ended, completed
But where are the meanings of those different status values documented? Particularly, how is ended different from completed? And why are some events marked as live even though they occurred last month?

A: The status string is directly related to what state your event is in.

*

*Canceled: the event was canceled and is no longer taking place.

*Live: the event is on the Eventbrite platform and tickets are available for
purchase.

*Started: The event has started.

*Ended: The event has ended.

*Complete: (This status is specific to the event organizer.) The payout has been sent from Eventbrite to the event organizer.

I am not sure about the last question... I'm guessing it has to do with series/repeating events.


text:
Q: What's the domain of $f(x) = \sqrt{x^2 - 4x - 5}$? What's the domain of the function $f(x) = \sqrt{x^2 - 4x - 5}$ ?
Thanks in advance.

A: The function $x\mapsto\sqrt x$ is defined on the interval $[0,+\infty)$ so the given function $f$ is defined for $x$ such that $x^2-4x-5\ge0$.
The reduced discriminant $\Delta'=9$ hence the roots are: $x_1=-1$ and $x_2=5$ and then $f$ is defined on $(-\infty,-1]\cup[5,+\infty)$.

A: $f(x) = \sqrt{x^2 - 4x - 5}$
Since the square root of a negative number is imaginary, the condition is that :
$$x^2 - 4x - 5 \geq 0$$
$$ (x-2)^2 - 9 \geq 0$$
$$ (x-2) \geq 3$$ or
$$ (x-2) \leq -3$$
Therefore the domain of the function $f(x)$ would be:
$$(-\infty, -1] \cup [5, +\infty)$$
Hope the answer is clear ! And wish you a happy new year !

A: The domain is $\text{domain}(f)\geq 0$, because since you are dealing with the reals, it cannot be negative inside the square root.
To determine domain, solve: $x^2-4x-5=0$:
$(x-5)(x+1)=0 \implies x=5,-1$ These are the roots, so the domain is: $(-\infty,-1] \cup [5,\infty)$.

A: The domain is $D =\{ x \in \mathbb{R} | x^{2}-4x-5 \geq 0 \}$.
The roots of $x^{2}-4x-5$ are $-1$ and $5$ so $D =(-\infty, -1] \cup [5, +\infty)$.

A: For the function $f$ you gave to be undefined, the input to the square root must be negative. First, notice that
$$
x^2-4x-5=(x+1)(x-5)
$$
So for this to be negative one of the terms must be negative and the other must be positive. So what numbers satisfy $x+1>0$ and $x-5<0$ or $x+1<0$ and $x-5>0$?


text:
Q: Set height of right hand side using height of left hand side I am using semanti-UI-react. The Ui I want to achieve is a modal which is divided vertically in 2 parts. The left side shows a video and the right shows timestamps and descriptions of indices of the video. My right side with the indices should be scrollable.
            <Grid>
              <Grid.Row>
                <Grid.Column style={{margin: '0', padding: '0'}} computer={10} mobile={16} table={16} >
                  <Segment raised inverted style={{ padding: '2.5rem 0'}}>
                    <ReactPlayer style={{margin: '0 auto'}} ref={this.ref} url={this.state.url} controls={true} playing={true}/>
                  </Segment>
                </Grid.Column>
                <Grid.Column style={{margin: '0', padding: '0'}} computer={6} mobile={16} table={16}>
                  <Segment basic style={{overflowX: 'hidden', margin: '0 auto', height: '450px'}}>
                    <List relaxed>
                      {_.keys(this.props.videoMeta.timestamps).map(ts => (
                        <List.Item className='clickable' onClick={() => this.forward(this.props.videoMeta.timestamps[ts])}>
                          <List.Icon name='video' size='fullscreen' verticalAlign='middle'/>
                          <List.Content>
                            <List.Header style={{textTransform: 'capitalize'}}>{ts}</List.Header>
                            <List.Description>{this.props.videoMeta.timestamps[ts]}</List.Description>
                          </List.Content>
                        </List.Item>
                      ))}
                    </List>
                  </Segment>
                </Grid.Column>
              </Grid.Row>
            </Grid>

This achieves the above mentioned UI. But I had to set a hardcoded height value to my right hand side grid column. If I dont set it, its not scrollable. I tried percentage values but that makes my right hand side a different height from left hand side height.
Instead of hardcoding, how do I set the height to my left hand side grid column ?
A screenshot of my UI right now:

Edit:
Adding to the answer below. I had previosly tried the same display flex idea but it did not work. One thing I added from the answer below was the css position property that fixed the display flex.
My code looks like this now -
             <Grid>
              <Grid.Row style={{display: 'flex'}}>
                <Grid.Column style={{margin: '0', padding: '0'}} computer={10} mobile={16} table={16}>
                  <Segment raised inverted style={{padding: '2.5rem 0'}}>
                    <ReactPlayer style={{margin: '0 auto'}} ref={this.ref} url={this.state.videoMeta.link} controls={true} playing={true}/>
                  </Segment>
                </Grid.Column>
                <Grid.Column style={{margin: '0', padding: '0', overflowX: 'hidden', position: 'relative', flexGrow: 1}} computer={6} mobile={16} table={16}>
                  <Segment basic>
                    Timestamps:
                    <List relaxed style={{position: 'absolute'}}>
                      {_.keys(this.state.videoMeta.timestamps).map(ts => (
                        <List.Item className='clickable' onClick={() => this.forward(this.state.videoMeta.timestamps[ts])}>
                          <List.Icon name='video' size='fullscreen' verticalAlign='middle'/>
                          <List.Content>
                            <List.Header style={{textTransform: 'capitalize'}}>{ts}</List.Header>
                            <List.Description>{this.state.videoMeta.timestamps[ts]}</List.Description>
                          </List.Content>
                        </List.Item>
                      ))}
                    </List>
                  </Segment>
                </Grid.Column>
              </Grid.Row>
            </Grid>

Note the css properties of position relative for the container tag and the postion absolute for the inner element  on the right hand side. Without the position property the display flex did not work.

A: I don't have experience with react or semantic-ui, but you can do this in css using flexbox and some clever positioning. Here is a simple example that you should hopefully be able to adapt to your own code. The content in the left column is a fixed size, and the right column will be the same height, scrolling if it's too tall.

.container {
  display: flex;
}

.right-col {
  overflow-y: auto;
  flex-grow: 1;
  position: relative;
}

.right-col ul {
  position: absolute;
}

/* -- The following css is just for demo purposes: -- */
.content {
  height: 100px;
  width: 200px;
  background-color: purple;
}
.container {
  border: 2px solid black;
}
.left-col {
  border: 2px solid blue;
}
.right-col {
  border: 2px solid green;
}

Item

Item

Item

Item

Item

Item

Item


text:
Q: How to see in MSDN only the properties/methods added by a .NET class, and not those inherited? For example, the ContextMenu WPF class documentation (either offline or online) has pages and pages of properties and methods. Can I filter them somehow and only see the ones added by ContextMenu, like StaysOpen?

A: In the tree structure on the left of that page, click on  ContextMenu Properties , you then get another page full of properties, but if you look to the left again you see just the properties belonging to the ContextMenu class.


text:
Q: How to invoke another servlet in a servlet? As title metioned, How to invoke another servlet in a servlet and get the invoked servlet response?

A: Use RequestDispatcher instance which is available through the HttpServletRequest instance.
However, if you're looking at getting hold of the single instance held by the servlet container [like using the getServlet method in the ServletContext instance], it's an entirely different story. The servlet specs have purposefully deprecated the operation which might allow such an option. But, if you really want to invoke one servlet while executing the other one, use the include method of the RequestDispatcher instead of the forward method.

A: See here:
getServletContext().getNamedRequestDispatcher("servletName")
    .forward(request, response);

However I'd assume there are better options. For example move the code you need to a helper class / utility method, and invoke it.
As I come to think of it, you may want another thing: call a servlet separately. For that you need:
InputStream is = new URL(urlOfTheServlet).openStream();
IOUtils.copy(is, response.getOutputStream());

(this is using apache commons-io to copy the input stream to the output stream of the current request)

A: Use ServletContext or current request to get RequestDispatcher, and then use RequestDispatcher forward() or include().
Can use Spring MockHttpServletRequest and MockHttpServletResponse to create new request and response instead of use current request.
Example:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
RequestDispatcher dispatcher = request.getRequestDispatcher(url);

MockHttpServletRequest servletRequest = new MockHttpServletRequest();
servletRequest.setServerName(request.getServerName() );
servletRequest.setServerPort(request.getServerPort() );
servletRequest.setSession(request.getSession() );
servletRequest.setMethod(HttpMethod.GET.name() );

servletRequest.setRequestURI(url);
servletRequest.setParameters(parameters);

MockHttpServletResponse servletResponse = new MockHttpServletResponse();
servletResponse.setCharacterEncoding("UTF-8");
// Use include() instead of forward(). Similar as client HttpClient GET
dispatcher.include(servletRequest, servletResponse);
String content = servletResponse.getContentAsString();

A: String destinationBlockAccount  ="./BlockAccount";
response.sendRedirect(response.encodeRedirectURL(destinationBlockAccount));

Furthermore you can sending a parameter like directly from JSP:
response.sendRedirect(response.encodeRedirectURL("./GetAccount?accountID="+accountID));


text:
Q: How can I get the monthly balance and overall balance using the daily balance from the child of a data in Firebase? I have a Firebase Realtime Database that stores the public transport vehicle driver's total balance, monthly balance, and daily balance as shown below:

As you can see, I got the computations wrong. But I want to know how can I be able to add the daily balance of the driver for each day, add it to the monthly balance, then to the total balance of the driver because I'm really at lost right now on what to do.
Thank you in advance for your help!


text:
Q: button position placement problem in multiple browser I am working on this site- sheraspace  .I want to my chat and phone  button in the bottom position.But the button works differently in different browser.It also exceeds the screen in some cases.I also want it to adjust accordingly during zoom in and zoom out.What can i do to keep it constant in multiple browser. This is what i tried for the chat button so far:

     <button onClick={() => this.handleClickOutside()} style={{

                                }}>
     <FontAwesomeIcon icon={faPhone} style={{color:'#fff' ,
             marginRight:'8px'}} />
      Call us on
+880 1738174440

         </button>

}


text:
Q: Mysql Multiple Subquery Limit I have a table with the following columns:
playlistid
trackname
playstatus
likes
dislikes
created

playstatus can have the following values:0, 1, 2 and 4.
The sql query that Im using now is:
 SELECT * from playlist
 WHERE playlistid=$myplaylistid && playstatus=0
 ORDER BY (likes-dislikes) DESC, created ASC

Its worth to mention that there at all times only will be one row with playstatus = 1, one row with playlistid=3, but there will be multiple rows with playstatus = 0 and 2.
I want to change the query above so that I get 1 row from where playstatus=3, 1 row from where playstatus=1, and 3 rows from where playstatus=0 in one single query. All these have to be chosen based on the same orderby that you see in the query above.
All help is appreciated! Thank you for your time!

A: Try this
SELECT * from playlist WHERE playlistid=$myplaylistid && playstatus=3
union
SELECT * from playlist WHERE playlistid=$myplaylistid && playstatus=1
union
SELECT * from playlist WHERE playlistid=$myplaylistid && playstatus=0
ORDER BY (likes-dislikes) DESC, created ASC

A: Try this query
SELECT * from playlist WHERE playlistid=$myplaylistid && playstatus=1
ORDER BY (likes-dislikes) DESC, created ASC limit 1
union
SELECT * from playlist WHERE playlistid=$myplaylistid && playstatus=3
ORDER BY (likes-dislikes) DESC, created ASC limit 1
union
SELECT * from playlist WHERE playlistid=$myplaylistid && playstatus=0
ORDER BY (likes-dislikes) DESC, created ASC limit 3


text:
Q: How to modify tags of an already existing svg object with data from json file I have this code snippet:
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="d3.min.js"></script>
</head>
<body>
    <svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000" stroke="#000" stroke-linecap="round" stroke-linejoin="round" fill="none" fill-rule="evenodd">
         <path d="M377.4528 264.0669q3.7795-113.3858 151.1811-113.3858m0 0q0 11.3386 0 11.3386 0 139.8425-41.5748 139.8425m3.7795 0q-37.7953 0-37.7953 0 56.6929 0 56.6929 113.3858-132.2835 0-132.2835-79.3701"/>
         <path d="M377.4528 335.878q0 79.3701-132.2835 79.37-3.7795-113.3857 56.6929-113.3857-75.5905 0-75.5905-151.1812 151.1811 0 151.1811 113.3859"/>
         <ellipse cx="377.4528" cy="284.8543" rx="3mm" ry="16.5mm"/>
    </svg>
    <script type="text/javascript">

         d3.json("./data.json").then(function(data){
             var svg = d3.select("body")
                         .selectAll("svg")
                         .... something here
               })
    </script>
</body>

I cannot update, with values from data.json file, for example cx, cy, rx etc... and most of all values contained in path string. Someone can help me? Thanks to all.

A: In the example below I'm using a mock API to simulate your d3.json() request and then making up a new value for rx and ry for the ellipse. I've used timeout just for demonstration purposes so that you can see the ellipse changes - you wouldn't need to do that in your code.
So, once you have the new data, you can use a selection e.g. d3.select("svg ellipse") so you can then update the attributes of the selection.
If your new data has new d attributes for the path elements, then you can use the same  approach e.g. path.attr("d", newD). If you want to change datapoints within the path definition, it would depend on your incoming data and better asked as a separate question.

// mock api to make this snippet work
const url = "https://jsonplaceholder.typicode.com/todos/1";

// wait for 1.5s and apply new attributes to ellipse
setTimeout(function() {
  // get the new data
  d3.json(url).then(function(data) {
    // mock up some data
    data = [{rx: "5mm", ry: "20mm"}];
    changeEllipse(data[0]);
  });
}, 1500);

function changeEllipse(data) {
  // select the ellipse with a selector
  const ellipse = d3.select("svg ellipse");
  // change attributes
  ellipse
    .attr("rx", data.rx)
    .attr("ry", data.ry);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script>
<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000" stroke="#000" stroke- linecap="round" stroke-linejoin="round" fill="none" fill-rule="evenodd">
  <path d="M377.4528 264.0669q3.7795-113.3858 151.1811-113.3858m0 0q0 11.3386 0 11.3386 0 139.8425-41.5748 139.8425m3.7795 0q-37.7953 0-37.7953 0 56.6929 0 56.6929 113.3858-132.2835 0-132.2835-79.3701"/>
  <path d="M377.4528 335.878q0 79.3701-132.2835 79.37-3.7795-113.3857 56.6929-113.3857-75.5905 0-75.5905-151.1812 151.1811 0 151.1811 113.3859"/>
  <ellipse cx="377.4528" cy="284.8543" rx="3mm" ry="16.5mm"/>
</svg>


text:
Q: Choosing values from pandas column with the lowest value I'm reading a df from csv that has 2 columns showing the prices of various items. In some cases the price is a single int/float, but other cases it could be a range of spaces seperated int/floats or mixture of int/floats with strings.
example df:
  item            prices
 ------ ---------------------------
  a      2
  b      3.5
  c      5
  d      0.04
  e      1 8 3 4 2
  f      0.04 0.04 0.01
  g      Normal: 4.56Premium: 4.75

What I'm looking is a nice pythonic way to get the prices column to display the lowest possible int/float value for every item. e.g.
  item   prices
 ------ --------
  a           2
  b         3.5
  c           5
  d        0.04
  e           1
  f        0.01
  g        4.56

The only way I could think of solving this problem for items e and f would be to split the value by using str.split(" ") and mapping the output to int or float, but this seems like it would be messy as not all values are the same types. And I don't even know how I would get the lowest value for item g.
any help would be appreciated

A: Use Series.str.extractall for get integers or floats, convert to floats and get minimal values:
df['prices'] = (df['prices'].str.extractall('(\d+\.\d+|\d+)')[0]
                            .astype(float)
                            .groupby(level=0)
                            .min())
print (df)

  item  prices
0    a    2.00
1    b    3.50
2    c    5.00
3    d    0.04
4    e    1.00
5    f    0.01
6    g    4.56


text:
Q: How many / how long are stashes saved by git? I'm very new to git and have some question about stashing. If I've worked on a branch but was not able to get to a position where I can commit the branch, stashing is the right thing to use. My questions regarding stashing are:

*

*How many stashes are saved?

*How long are these stashes saved?

*Do they just temporarily save the work such that the changes are lost when you reboot your computer?

If someone could quickly help clarifying these would be really appreciated.

A:
1 - How many stashes are saved?

Stashes don't appear out of thin air; only if you create them, using
git stash

or, equivalently,
git stash save

So how many are saved? As many as you create.

2 - How long are these stashes saved?

This question looks innocent, but the answer is actually quite subtle. There are two aspects to consider here: 1) the stash reflog, and 2) the repository's object database.
When you create a stash, Git

*

*adds an entry to the stash reflog,

*creates two (three if you use the --include-untracked flag) commit objects in the repository's database: one that corresponds to the WIP (work in progress) in your working tree, and another that corresponds to the state of your staging area (a.k.a. index).

Edit: those commit objects are bona fide commits, as can be verified by running git cat-file -t on them. They just happen to not be reachable from any branch; see torek's comment.
By default, Git's garbage collection will automatically delete reflog entries that are older than 90 days; you can specify a different "lifetime" for stash reflog entries, by running
git config gc.refs/stash.reflogexpire <lifetime>

However, as torek notes, Git handles stashes specially – even though old reflog entries are normally deleted automatically, Git will never delete reflog entries for refs/stash unless you explicitly tell it to.
In other words, Git will not delete stashes on its own; a stash will remain in your local repository as long as you don't voluntarily

*

*drop it, using
git stash drop <stash-reference>

which deletes the specified stash entry from the stash reflog;

*pop it, using
git stash pop <stash-reference>

which applies the specified stash and then deletes the corresponding entry from the stash reflog; or

*run
git stash clear

which deletes all entries of the stash reflog (be careful with that one).
However, be aware that those three actions only affect the stash reflog. In particular, they do not immediately cause the associated "WIP" and "index" objects to be deleted from your repository's database; they merely make those objects unreachable. The latter will remain in "repository limbo" for a while, until they eventually get garbage-collected and die a "true death".
That's a useful thing to know: if you accidentally drop a stash, you might still be able to retrieve it from the entrails of your repo, if you can remember or identify the SHAs of its two objects (WIP and index).

3 - Do they just temporarily save the work such that the changes are lost when you reboot your computer?

No. Stashes are no different from any other commit objects; a reboot has no effect on them.

A: Git stashes are saved until your hard disk dies (unlike commits, which are usually transmitted to some other computer via git push so will outlive a hard disk failure).
You can have as many stashes as you want.  Get rid of old ones when you feel  like it by running git stash drop or git stash clear (read the docs for those).


text:
Q: Proving that every poset has a maximal well ordered subset This has been given as an guided exercise in Pinter's set theory textbook. I'm unable to complete the problem.

Let $(A, \le )$ be a partially ordered set and let $\mathcal{A}$ be the set of all well ordered subsets of $A$. For $C \in \mathcal{A}$ and $D \in \mathcal{A}$, define $C \preccurlyeq D$ iff $C$ is a section of $D$. (Here's the definition of section: Let $A$ be a partially ordered set. A subset $B$ of $A$ is called a section if for all $x \in A$ and all $b \in B$, if $x\le b$ then $x\in B$.)

*

*Show that $\mathcal{A}, \preccurlyeq$ is a partially ordered set.

*Show that every chain in $\mathcal{A}$ has a upperbound in $\mathcal{A}$.

*Show by Zorn's Lemma that $A$ has a maximal well ordered set.

I see how parts 1 through 3 work. Let $\mathcal{C}$ be a chain of $\mathcal{A}$. I did manage to show that $\bigcup \mathcal{C}$ is totally ordered and that it is an upperbound for $\mathcal{C}$. I'm unable to show that $\bigcup \mathcal{C}$ is well ordered. Any hints would be appreciated.
Here's my attempt: Let $D$ be nonempty subset of $\bigcup \mathcal{C}$. If $\mathcal{C}$ has a greatest element $C$, then $\bigcup \mathcal{C} = C$ and we are done. Suppose it does not. So for all $C \in \mathcal{C}$, there must be $C' \in \mathcal{C}$ such that $C \prec C'$ and it would follow that $C=\{ x \in C' \, : \, x < c' \}$ for some $c' \in C'$. Now for each $d \in D$, there is a $C_d \in \mathcal{C}$ such $d\in C_d$. So, we obtain $\{ C_d : d \in D \}$.If I could find a $C' \in \mathcal{C}$ such that $C_d \subseteq C'$ for all $d\in D$. We'll be done. But I'm not sure how to finish this.

A: If $D$ is a non-empty subset of $\bigcup\cal C$, then take $d\in D$ to be some arbitrary point, and consider $C\in\cal C$ such that $d\in C$. Consider now $D\cap C$, it is non-empty. So it has a minimal element, $m$.
Now, argue that every $C'\in\cal C$ such that $C\subseteq C'$, we have that $D\cap C$ is an initial segment of $D\cap C'$, and therefore $m$ is still minimal there. Finally, use this to conclude that $m$ is in fact the minimal element of $D$ in $\bigcup\cal C$.