text:
Q: How to return data from Backend to Frontend in Wix Corvid I'm trying to return few data from backend to frontend once the registration is complete. While testing I can see that the user gets registered successfully but for some reason, the data I return from the backend method to the frontend comes with "undefined".
Below is my Backend Code.
export function doRegistration(email, password, firstName, lastName) {
    wixUsersBackend.register(email, password, {
        "contactInfo": {
            "firstName": firstName,
            "lastName": lastName
        }
    }).then((result) => {
        if (result.status === "Pending") {
            wixUsersBackend.approveByToken(result.approvalToken)
                .then((token) => {
                    return {
                        "approved": true,
                        "userId": result.user.id,
                        "isEmailExist": false
                    }
                }).catch((err) => {
                    return {
                        "approved": false,
                        "isEmailExist": false,
                        "errorCode": err.errorCode,
                        "errorMessage": err.errorDescription
                    }
                });
        }
    }).catch((err) => {
        return {
            "approved": false,
            "isEmailExist": true
        }
    });
}

I tried reading the return value from frontend in both the ways as follow:
doRegistration($w('#txtLoginEmail').value, $w('#txtPassword').value, $w('#txtFirstName').value, $w('#txtLastName').value).then(result => {
                if (result.approved) { //.approved is undefined
}
});

Also,
let result = doRegistration($w('#txtLoginEmail').value, $w('#txtPassword').value, $w('#txtFirstName').value, $w('#txtLastName').value);
if (result.approved) {  //.approved is undefined
}

Any help on this will be greatly appreciated.
Thanks,
Jilu

A: I think its because you are not catering for a scenario where the result.status is not "Pending" Try the below
if (result.status === "Pending") {
      wixUsersBackend.approveByToken(result.approvalToken)
      .then((token) => {
           return {
              "approved": true,
              "userId": result.user.id,
              "isEmailExist": false
           }
           }).catch((err) => {
               return {
                  "approved": false,
                  "isEmailExist": false,
                  "errorCode": err.errorCode,
                  "errorMessage": err.errorDescription
               }
           });
} else {
      return {
         "approved": true,
         "userId": result.user.id,
         "isEmailExist": false
       }
}


text:
Q: Bubble Sort in Java - largest integer not showing up in final sort I am trying to create a bubble sort program for a small presentation that I am doing. The code runs fine but the largest integer in my array is never displayed. Output for the program as it stands is:
1
3
4
6
7
11

The 12 is missing!
Here is my code, excuse the comments - some of them might even be wrong.
public class BubbleSort {

public static void main(String[] args) {

    int number []={6,3,1,7,4,12,11};
                // 0,1,2,3,4

    //For temporarily storing a value that has to be swapped
    int temp;

    //Keeps the loop running until there is nothing left to sort.
    boolean fixed=false;

    while (fixed==false) {

    fixed=true;

    //If this IF statement is accessed it means something still has to be
    //swapped, so at the end of the statement fixed is reverted to false
    //again, so it can continue the loop.

    for(int i=0; i<number.length-1 ; i++){
        //This makes i start at 0 the first time it is run,
        //this is due to the array starting at 0, too.

        if(number[i] > number[i+1]) {
            //If 8   >   5

            temp = number[i+1];
            //Store 5 in temporary variable

            number[i+1]=number[i];
            //Swap array 1 with array 0/

            number[i]=temp;

            fixed=false;

        }

    }

    }

    for(int i=0; i<number.length-1 ; i++){
        System.out.println(number[i]);
    }

}

}

A: for(int i=0; i<number.length-1; i++){
    System.out.println(number[i]);
}

Should be
//                            no '-1'
//                              V
for(int i = 0; i < number.length; i++) {
    System.out.println(number[i]);
}

Why?
Let's see what happens if there are 5 elements in the array, then they are indexed as follows:
0, 1, 2, 3, 4

If we use i < 5-1 (or i < 4), once i becomes 4, before the next iteration of the loop runs, it will stop, skipping the last index.
In case the above doesn't explain it, note the order in which things happen in a for-loop:

*

*First the initialization occurs

*Then the following is repeated until the condition is false:

*

*The condition is checked

*A loop iteration is run

*The increment happens

The most applicable part here is that a loop iteration will never run if the condition is false.

A: The error is in your last loop showing numbers.
Your loop does not reach the last element because it stops in number.length-2. You have to add one more execution to your loop.
Try:
for(int i=0; i<number.length ; i++){
        System.out.println(number[i]);
    }

or
for(int i=0; i<=number.length-1 ; i++){
            System.out.println(number[i]);
        }

A: for(int i=0; i<number.length-1 ; i++){
    System.out.println(number[i]);

When you are printing your array, remove -1 only write number.length.

A: you are using wrong ending loop condition it should be
       for(int i=0;i<number.length;i++)

as array index starts from 0.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamics CRM: Create and bind Dialogs to on login event of a user I want to create a Dialog in CRM to show some sort of greeting message on user logon. But I didn't find out how to assign Dialogs and Workflows on events, how to make or bind event triggers on them?
Sultan

A: As far as I know, you can only implement dialogs on forms and I don't think it would be a great option for doing this.
The best bet for a greeting upon login is to modify the sitemap to load a custom web application as the default web page (or in 2011 add a iframe or html web resource to a dashboard).  On this page you could pull information from CRM to display a greeting.  Announcements is the typical place where these greetings are stored but you could create a custom entity to store them as well.


text:
Q: How do I download a YouTube playlist with over 100 videos? Pytube is able to generate a list of up to 100 links to download.  How do I download a YouTube playlist with up to 400 videos?
I am using github code by Mohit23x https://github.com/mohit23x/youtube-playlist-downloader/blob/master/ytdown.py


text:
Q: ul list items with different background sizes I'm trying to make the footer for my website. It's supposed to contain 5 lines of contact information, white text on a black background and white space between. So essentially it will look like 5 black strips on top of each other with white text on them.
The problem is that all the black strips turn out the same length, when I want them to be roughly the length of the text. I tried floating the list items instead of the
 and put line breaks after each one. The backgrounds were now the right size but I was unable to add the white space between them without messing it up.
HTML:

Company name

Adressadress 123444

023311 postal code

+358 12385495955

info@company.com

css:
ul {float:left;
li {
    list-style:none;
    background-color:black;
    color:white;
    text-transform:uppercase;
    font-weight:bold;
    margin-bottom:5px;
    padding-left:5px;
    padding-right:5px;
    }
    }

Any ideas?

A: Adding span tags around the text should solve your problem.

one

two

three

four

five

ul {
    margin:10px;
}

ul li {
    margin-bottom:15px;
}

ul li span {
    background:black;
    padding:5px;
    color:white;
}

http://jsfiddle.net/uwPcv/


text:
Q: Method [[UIDevice currentDevice] uniqueIdentifier] is not allowed any more, I need an alternative I'm using [[UIDevice currentDevice] uniqueIdentifier] in all of my apps, Apple is not allowing the use of uniqueIdentifier anymore.
I need something to use that replaces the uniqueIdentifier which I can use to recognize a user even when the user deletes the app and installs it again, (and also get my app approved by apple).
Thanks

A: Update for iOS 7 and prior:
+ (NSString *)uniqueDeviceIdentifier
{
    NSString *device_id = nil;

    if ([[self deviceModel] isEqualToString:@"Simulator iOS"]) {
        // static id for simulator
        device_id = @"== your random id ==";
    }
    else if (CurrentIOSVersion >= 6.f) {
        // iOS 6 and later
        device_id = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    }
    else {
        // iOS 5 and prior
        SEL udidSelector = NSSelectorFromString(@"uniqueIdentifier");
        if ([[UIDevice currentDevice] respondsToSelector:udidSelector]) {
            device_id = [[UIDevice currentDevice] performSelector:udidSelector];
        }
    }
    NSLog(@">>>>>> device_id: %@", device_id);
    return device_id;
}

Device model you can receive through:
+ (NSString*)deviceModel
{
    static NSString *device_model = nil;

    if (device_model != nil)
        return device_model;

    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *str = @(systemInfo.machine);

    return device_model;
}

A: The documentation recommends what to do in this section.

Special Considerations
  Do not use the uniqueIdentifier property. To create a unique identifier specific to your app, you can
  call the CFUUIDCreate function to create a UUID, and write it to the
  defaults database using the NSUserDefaults class.

To make sure that the unique identifier remains after you delete the app you should store it in the keychain rather than NSUserDefaults. Using the keychain you will also be able to share the same unique ID across all of your apps on the same device using keychain access groups. This approach will prevent you from incorrectly tracking users after the device is no longer theirs, and it will be available on any new iDevice they restore from backup.

A: with digipeople's hack.
Fix it to avoid app crash.
systemId = [[NSUUID UUID] UUIDstring];
http://developer.apple.com/library/mac/documentation/Foundation/Reference/NSUUID_Class/Reference/Reference.html#//apple_ref/occ/instm/NSUUID/UUIDString


text:
Q: How do you remove and return an item at the index of the queue for Python? How do you remove and return an item at the index of the queue for Python? I'm trying to do this problem.
When you send a file to be printed on a shared printer, it is put onto a print queue with other jobs. Anytime before your job prints, you can access the queue to remove it. Thus, some queues support a remove operation. The remove() method should expect an item as an argument. It should remove the given item in the queue or raise an exception if the item is not found.
class Queue:

    def __init__(self): # Constructor function
        self.items = []
    def isEmpty(self): # Returns True if the queue is empty or False otherwise
        return self.items == []
    def len(self): # Returns the number of items in the queue
        return len(self.items)
    def peek(self): # Returns the item at the front of the queue
        if len(self.items) == 0:
            return None
        else:
            return self.items[(len(self.items)-1)]
    def add(self, item): # Adds item to the rear of the queue
        return self.items.append(item)
    def pop(self): # Removes and returns the item at the front of the queue
        return self.items.pop()
    def remove(self):
         return.self.index.pop()

if __name__ == "__main__":
    queue = Queue()

A: To remove an item you can use:
def remove(self, item):
     return self.items.remove(item)

which will generate a ValueError if item is not in the items List. If required you could use a try: except:  block to handle the error in some other way.


text:
Q: Attaching a Drive file to an assignment with Google Classroom API Using Google Apps Script I have managed to create an assignment with the following code:
Classroom.Courses.CourseWork.create({
 "courseId": id,
 "title" : title,
 "description" : desc,
 "workType" : 'ASSIGNMENT',
 }, id)

This works fine, creating a draft assignment on Classroom. However, when I try to attach a Drive file like so:
  Classroom.Courses.CourseWork.create({
    "courseId": id,
    "title" : title,
    "description" : desc,
    "workType" : 'ASSIGNMENT',
    "materials" : [
      {
      "driveFile": {
        "id" : fileId,
        "title" : fileTitle,
        "alternateLink" : fileLink,
        "thumbnailUrl" : fileThumbnail,
      },
      "shareMode" : 'STUDENT_COPY',
    }
    ],
  }, id)

I receive these errors:
Execution failed: Invalid JSON payload received. Unknown name "share_mode" at 'course_work.materials[0]': Cannot find field.
Invalid JSON payload received. Unknown name "alternate_link" at 'course_work.materials[0].drive_file': Cannot find field.
Invalid JSON payload received. Unknown name "id" at 'course_work.materials[0].drive_file': Cannot find field.
Invalid JSON payload received. Unknown name "title" at 'course_work.materials[0].drive_file': Cannot find field.
Invalid JSON payload received. Unknown name "thumbnail_url" at 'course_work.materials[0].drive_file': Cannot find field. (line 61, file "Classroom") [1.187 seconds total runtime]
Any help will be appreciated, thank you

A: You may refer with this SO answer. This error might happen because of wrong formatting of the request.
Sample code:

function myFunction() {
  var ClassSource =  {
    title: "Test File",
    state: "DRAFT",
    materials: [
      {
        driveFile:{
        driveFile: {
          id: "fileID",
          title: "Sample Document"

        },
        shareMode: "STUDENT_COPY"
        }

      }
      ],
    workType: "ASSIGNMENT"
  };

  Classroom.Courses.CourseWork.create(ClassSource, COURSEID)
  //Logger.log(exec);
}

You may try this using Try this API.
Hope this helps!


text:
Q: Use PHP to execute system command with a long timeout period? We need to untar/unzip a very large archive file on a server that we don't have SSH access to. One of our alternative options is to execute a system command via PHP to unzip the file.
The problem is that its takes quite a while to unzip/untar the file. PHP ends up timing out before it completes.
Is there a way to make the untar command execute fully whether or not the PHP script times out or not? Like an Asynchronous execution?
Or how can you temporarily set the PHP timeout period to be extremely high so that it has enough time to finish untarring the file?

A: From the manual:

The set_time_limit() function and the configuration directive
  max_execution_time only affect the execution time of the script
  itself. Any time spent on activity that happens outside the execution
  of the script such as system calls using system(), stream operations,
  database queries, etc. is not included when determining the maximum
  time that the script has been running. This is not true on Windows
  where the measured time is real.

What may be happening is that your client (browser) is timing out. Such a disconnection may cause the script to abort. To prevent that, you can do:
ignore_user_abort(true);

You'll then want a second script that allows you to check the progress. One idea is to have the output of tar written to a file that your second script can check the end of to see if it's done. Another is to invoke a shell script that in turns runs tar. That shell script could either check the return code and touch a file with its results or it could create a rudimentary lock file while it is working.

A: This should do it if your server configuration doesn't prevent you from modifying these values:
set_time_limit( 0);
ini_set( 'max_execution_time', 0);

See set_time_limit and max_execution_time.

A: If the server runs on a *nix system, the nohup command might be available. ie
nohup tar ... >outfile.txt

You could then have the PHP script scan the outfile.txt until operation ends


text:
Q: How can I perform a regex/text search on a SUPER type? What I'm doing now:

*

*I have a table with one field that is a json value that is stored as a super type in my staging schema.

*the field containing the json is called elements

*In my clean table, I typecast this field to VARCHAR in order to search it and use string functions

*I want to search for the string net within that json in order to determine the key/value that I want to use for my filter

*I tried the following:

select
    elements
    , elements_raw
from clean.events
where 1=1
  and lower(elements) like '%net%'
  or strpos(elements,'net')

My output

*

*When running the above query, I keep getting an empty set returned.

My issue

*

*I tried running the above code and using the elements_raw value instead but I got an issue :ERROR: function strpos(super, "unknown") does not exist Hint: No function matches the given name and argument types. You may need to add explicit type casts.

*I checked the redshift super page and it doesn't list any specifics on searching strings within super types

Desired result:

*

*Perform string operations on super field

*Cast super field to a string type

A: There are some super related idiosyncrasies that are being run into here:

*

*You cannot change the type of a super field via :: or cast()

*String functions like and strpos do not work on super types

To address both of these issues, you can use the function json_serialize to return your super as a string.


text:
Q: open fragment under parent activity I want to open a fragment in activity but under objects of Activity.
in my code RelativeLayout is parent and LinearLayout is child
but when open fragment on relativelayout I lose linearlayout :(
this is my code:
Main Activity Java:
    public class MainActivity extends AppCompatActivity  implements View.OnClickListener{
private Context context;
private Button  fragment1 , fragment2;
private RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context = getApplicationContext();

    fragment1 = this.findViewById(R.id.fragment1);
    fragment2 = this.findViewById(R.id.fragment2);
    relativeLayout = this.findViewById(R.id.relativeLayout);

    fragment1.setOnClickListener(this);
    fragment2.setOnClickListener(this);
  }

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.fragment1:
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.relativeLayout , new fragment1());
            ft.commit();
            break;

        case R.id.fragment2:
            FragmentManager fm2 = getSupportFragmentManager();
            FragmentTransaction ft2 = fm2.beginTransaction();
            ft2.replace(R.id.relativeLayout , new fragment2());
            ft2.commit();
            break;
           }
    }
}

Main Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity"
  android:id="@+id/relativeLayout">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:id="@+id/layout"
    android:background="#F00"
    android:orientation="horizontal">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fragment 1"
        android:id="@+id/fragment1"
        android:gravity="center"
        android:layout_gravity="center"/>

    <Button
        android:id="@+id/fragment2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="fragment 2" />

</LinearLayout>

</RelativeLayout>

fragment1 XML:
 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0F0">

 </android.support.constraint.ConstraintLayout>

fragment2 XML:
<?xml version="1.0" encoding="utf-8"?>
 <android.support.constraint.ConstraintLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#00F">
 </android.support.constraint.ConstraintLayout>

This is Main Activity:   enter image description here
and when click on fragment1:     enter image description here
Plz Help Me  :)
TNX

A: Add a framelayout in relativelayout before the linearlayout and inflate the fragment in the framelayout.
 <RelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          tools:context=".MainActivity"
          android:id="@+id/relativeLayout">

         <FrameLayout
         android:id="@+id/container"
         android:layout_width="match_parent"
         android:layout_height="match_parent"/>

        <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="60dp"
          android:id="@+id/linearLayout"
          android:background="#F00"
          android:orientation="horizontal">

       <Button
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="fragment 1"
         android:id="@+id/fragment1"
         android:gravity="center"
         android:layout_gravity="center"/>

        <Button
          android:id="@+id/fragment2"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="center"
          android:gravity="center"
          android:text="fragment 2" />

      </LinearLayout>

    </RelativeLayout>

A: I think you should change your Fragment1 XML and Fragment2 XML from Constraint Layout to LinearLayout. It should work else initiate your LineaLayout in your MainActivity.

A: You are inflating fragments on Parent Layout. Make two child of Relativelayout and inflate fragment one of them like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      tools:context=".MainActivity"
      android:id="@+id/relativeLayout">

    <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="60dp"
      android:id="@+id/linearLayout"
      android:background="#F00"
      android:orientation="horizontal">

   <Button
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="fragment 1"
     android:id="@+id/fragment1"
     android:gravity="center"
     android:layout_gravity="center"/>

    <Button
      android:id="@+id/fragment2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:gravity="center"
      android:text="fragment 2" />

  </LinearLayout>

<!-- inflate fragments on FrameLayout -->
  <FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/linearLayout">

  </FrameLayout>

</RelativeLayout>

Inflate your fragments on this FrameLayout
 ....Hope this helps :)


text:
Q: Electron Spin Resonance and Free electrons When performing an experiment to observe electron spin resonance, we use DPPH molecules as they contain an unpaired electron on one of the N atoms.
My question is, why cant free electrons be used in this experiment? What is wrong with a beam of electrons or a metal?
Any help would be greatly appreciated.

A: The physical issue you are interested in is the Zeeman effect lifting the degeneration of energy states. For that you need an unpaired electron that is tightly bound in a system.
A free electron is... free. You cannot see energy state splitting if there are no quantized energies. (See free electron Laser for something similar that happens if the electrons are free).
In a metal, the situation is again similar. The electrons of the conduction band are delocalized states of the whole crystal. Again, you have an unbound system that would react to the external magnetic field which thereby does not show the effect you're after.
Most importantly, ESR is an easily conductible experiment to which the theory is calculable with a reasonable ammount of work. You see the two important quantum mechanical concepts of angular momentum addition and degenerate perturbation theory at work.
Let me stress again that the important thing is that you can ask a student to actually calculate an expection of the Landé factor and energy splitting that will then show up in the experiment.


text:
Q: how to map multi field in java using org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder I want to map exactly same reference_link by java.

A: Well i found the solution,what i have done is :
other code above (to start from beginning):-
.startObject(tags.getTitle()).field("type", "string")
                    .startObject("fields").startObject("raw")
                    .field("type", "string")
                    .field("analyzer", "case_insensitive_sort").endObject()
                    .endObject().endObject()
then end code.


text:
Q: How to target the 2nd index in pairs of arrays in jQuery? options = [['first', 1], ['second', 2], ['third', 3], ['fourth', 4]]

Say i've selected 'second', how would I select it's paired value?

A:

options = [
  ['first', 1],
  ['second', 2],
  ['third', 3],
  ['fourth', 4]
]

console.log(options[1][0])
console.log(options[1][1])

for (var i = 0; i < options.length; i++) {
  for (var ii = 0; ii < options[i].length; ii++) {
    console.log(options[i][ii])
  }
}

Try this samples and work your way to what you wanted


text:
Q: ECONNRESET(Connection reset by peer) Does someone know what happen when i receive this error, I am lock for some hours on this problem. My code is :
HttpPost httpPost = new HttpPost(SERVICE_DATA_ADRESSE);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
Scanner sc = new Scanner(entity.getContent());

On the server side the method call is working well when i debug it (It is a Csharp server)
When the code run i receive this error
ECONNRESET(Connection reset by peer)

but i have no idea what does it really mean. Does someone can translate to me this error ?
Thanks,
Eliott

A: It was due to a problem in serialisation when the server want to send the answer.


text:
Q: Create a python script that install python modules and run some commands I want to create a thin wrapper around this library https://github.com/jupyter-incubator/sparkmagic#installation
As you can see in the link, the installation step requires

*

*installing some packages with pip

*run some command of the type jupyter enable ... or jupyter-kernelspec install

*custom configuration file that I want to generate and place in the correct place

I am checking which options I have to make the installation as automatic as calling a script. So far I have came up creating a bash script with all these commands. In this way it works with a simple install.sh but I might have problems since I will not know which python binaries to use. If a user wants to install the lib for python2 or python3 he cannot have this choice unless he touches the script.
I have then tried to use setup.py and override the cmdclass to insert custom code
from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.install import install

class PostDevelopCommand(develop):
  """Post-installation for development mode."""
  def run(self):
    develop.run(self)
    print("do things")

class PostInstallCommand(install):
  """Post-installation for installation mode."""
  def run(self):
    install.run(self)
    print("do things")

setup(
  ...
  install_requires=['sparkmagic'],
  cmdclass={
    'develop': PostDevelopCommand,
    'install': PostInstallCommand,
},

...
)

but the custom prints worked only when running python setup.py install but not for pip install
I would like to make this last option work but if this is not the right patter to do this kind of things, could you suggest me which way to go?

A: The issue is not with pip install directly but with wheels. Projects packaged as wheel can not have custom install steps. See for example this discussion. Since pip prefers working with wheels, building them locally if necessary, your custom steps are not run at install time. There are probably ways to prevent the wheel step though.
Knowing this, you probably should follow the advice from Jan Vlcinsky in his comment for his answer to this question: Post install script after installing a wheel.

*

*Add a setuptools console entry point to your project (let's call it myprojectconfigure). Maybe you prefer using the distutils script feature instead.

*Instruct the users of your package to run it immediately after installing your package (pip install myproject && myprojectconfigure).

*Eventually think about providing myprojectconfigure --uninstall as well.


text:
Q: How to enable to check both checkbox from the same column in datawindow I have 2 checkboxs from the same column, one for Eat and another one for Drink, I plan if user check Eat, it will save as Eat data in 'a_type' column in database, same goes with Drink. In additional the user also able to check both Eat and Drink checkboxs and saved as Both in database , My problem now I can't check both, I only can check one of its

A: Use a radio button with three choices: Eat, Drink, Eat & Drink.

A: If you associated 2 different values to the checkboxes, it is normal that when clicking on one of the checkboxes the other unckeck. Each checkbox has a dedicated value and when you click one, it will set the column to its value and the second box will uncheck due to that same value change. You won't be able to check directly both boxes that way.
If you absolutely want to keep 2 checkboxes linked to the same column, you could add two computed fields with the apparence of a checkbox based on your column for the display part, and handle the clicked event to modify that column by code.


text:
Q: In NASM, is MOV EBX, AX a valid instruction? In NASM, is MOV EBX, AX a valid instruction?
Basically, can you move the contents of a small register into a register bigger than it?

A: That's not valid anywhere. To get the effect you want, do
MOVZX EBX, AX, or
MOVSX EBX, AX

depending on whether you want to zero or sign extend the source operand.


text:
Q: How to use Win XP mode,where can I find it? I have windows 7 Ultimate 64bit on my laptop and the ultimate version is supposed to have "WinXP Mode"(installed together with os) ,but I can't find it anywhere.
Where is it located?

A: A very quick web search would have showed you that it is not installed by default, but needs to be installed separately. It can be found here.


text:
Q: Writing data to two databases with EF within one Transaction Scope We are using Entity Framework 6 and are dealing with the following requirement:

*

*We are writing data to two different and independent databases let's call them Main and External, they both exist on the same instance of SQL Server and the connection string used to connect to them are identical except for the initial catalog value.

*In the application each DB has its own EF DBContext.

*The Main DB has an AuditLog table in which data changes get recorded.

*Data changes that happen on the External DB need to be recorded on the AuditLog table within Main DB.
Because of certain restrictions that are not important to discuss the way we implemented this was to have ExternalContext to have a reference of MainContext in order to call MainContext.SaveAuditLogs whenever ExternalContext.SubmitChanges was called, like so (only showing relevant code):
public class ExternalContext : IDataContext
{
    private readonly IAuditLogContext auditLogContext;

    public ExternalContext (IAuditLogContext auditLogContext){
        this.auditLogContext = auditLogContext;
    }

    public override void SaveChanges()
    {
        base.SaveChanges();
        this.auditLogContext.SaveAuditLogs(auditLogs);
    }
}

public class MainContext : IAuditLogContext
{
    public void SaveAuditLogs(List<AuditLog> auditLogs)
    {
        this.Set<AuditLog>().AddRange(auditLogs);

        this.SaveChanges();
    }
}

An example of how this is being used:
public class SomeBusinessClass
{
    private readonly IDataContext dataContext;

    public SomeBusinessClass(IDataContext dataContext)
    {
        this.dataContext = dataContext;
    }

    public void SomeOperation(Entity someEntity)
    {
        .....

        using(var scope = new TransactionScope())
        {
            this.dataContext.Insert(someEntity);
            this.dataContext.SaveChanges();
        }
        scope.Complete();
    }
}

For this to work the Distributed Transaction Coordinator service needs to be running. When tested on development environments it works fine but on QA environments it fails with the error message as if the Distributed Transaction Coordinator is not running even though it is.
Apparently this happens because in our development environments the DB Server and the Web Server are the same computer weather in QA they are two separate boxes and the DTC does not like it when there are multiple servers and the two operations run within a TransactionScope, if we remove the TransactionScope then it works fine on both environments but then there is the risk that if the AuditLog fails the whole transaction is not rolled back.
How can we make this work?
Thank you.


text:
Q: How do I know how much DPI the device has? How do I know how much DPIs a device has (and thus if it's ldpi / mdpi / hdpi / xhdpi, - and screen size, which is also measured in dp - xlarge / large / normal / small -  according to http://developer.android.com/guide/practices/screens_support.html)?
I know the device's resolution and diagonal size, for example:

Display   TFT LCD, 3.5 in (89 mm) diagonal.
320×480 px HVGA with Gorilla Glass
16M colors

(Taken from http://en.wikipedia.org/wiki/Samsung_Galaxy_Ace)
Don't need it programmatically, just to calculate myself.

A: Use DPI calculator to calculate dpis, and Figure 1 in the dev docs to determine whether its ldpi, mdpi, etc.

A: I think DPI reffers to printers... IN your case DPI = PPI. Please correct me if i'm wrong [edit: I'm wrong :P]
'So a 1200 dpi printer uses 1200 dots of ink in every inch to make up the colours. If you were printing a 300 PPI image, then every pixel would be made up of 16 smaller ink dots (1200 DPI x 1200 DPI / 300 PPI x 300 PPI). A lower DPI would have fewer ink dots making up each pixel, which would make the colour look worse. A higher DPI would have more ink dots for each pixel and should give more accurate colour (especially under close examination).'


text:
Q: How to set a path for savefiledialog I want to set a path when saving.
Here's my code. This code is supposed to set a path but it didn't work
SaveFileDialog1.ShowDialog()
SaveFileDialog1.InitialDirectory = "C:\Users\owner\Downloads"

A: You have to set InitialDirectory before you're showing your dialog.
SaveFileDialog1.InitialDirectory = "C:\Users\owner\Downloads"
SaveFileDialog1.ShowDialog()

A: Declare path before showing dialog
string path="C:\Users\owner\Downloads";
SaveFileDialog1.InitialDirectory = path;
SaveFileDialog1.ShowDialog();

A:         SaveFileDialog dialog = new SaveFileDialog();
        dialog.InitialDirectory = @"C:\"; //you should to set before showing dialog
        dialog.Title = "My Title";
        dialog.CheckFileExists = true;
        dialog.Filter = "Notepad (*.txt)|*.txt";
        dialog.ShowDialog();


text:
Q: Publish the Column which has Missing Values - oracle I have source table with details about employees, i need to derive an Missing information table. with list of Missing values. The missing values may be NULL or JUST empty Spaces.
Source Table
**************

Name    Age       Gender     Experience
-------------------------------------------------------------
David   22         M           IT
John    [NULL]     M          POLITICS
Judy    19      [NULL]        [NULL]
Jasmine [NULL]  [NULL]        [NULL]

Target Table
**************

Name    Missing_description
---------------------------------------------
John    Missing Age
Judy    Missing Gender, Experience
Jasmine Missing Age, Gender, Experience

A: try
insert into TargetTable (name, description)
select name,'Missing'||description from (
select name, LISTAGG(descr, ', ') within group (order by descr) as description
from (
 select name, 'age,' as descr from SourceTable where age is null
 union all
 select name, 'Gener,' from SourceTable where gender is null
 union all
 select name, 'Experience' from SourceTable where Experience  is null
) as a
group by name) as b

http://www.oracle-base.com/articles/misc/string-aggregation-techniques.php

A: Writing by memory, havent oracle installed right now, but query can be something like this:
insert into TargetTable (name, description)
select name, LISTAGG(descr, ', ') within group (order by descr) as description
from (
 select name, 'Missing age' as descr from SourceTable where age is null
 union all
 select name, 'Missing Gener' from SourceTable where gender is null
 union all
 ...
) as a
group by name

String aggregation is taken from String Aggregation Techniques


text:
Q: Check if hydrated doctrine result is NULL I'm trying to check if a result in my DQL is NULL.
I got the following DQL query:
    $q = self::createQuery("l")
        ->select('i.*, s.aantal, m.naam, c.cat_naam, a.app_id')
        ->from('InstalledBase i, i.Spare s, i.Apparaat a, a.Categorie c, a.Merk m')
        ->execute();

    return $q;

Now i want to check if the s.aantal is NULL so i do:
if(is_null($installedbase->Spare->spare_id))

when the variable is NOT null everything works, but when it is actually NULL i get a E notice message:
Notice: Trying to get property of non-object in \installedbase\templates\_index.php on line 29

It does see that it is null though because the if condition is executed.
Weird thing is i'm doing the exact same thing on another page where it works no problem.
But i must be doing something wrong or stupid since those messages generally don't show for nothing.
So can anybody explain this to me? :)

A: I'm really not familiar with DQL, but you could extend your if statement to;
if (!is_object($installedbase->Spare) || is_null($installedbase->Spare->spare_id))

A: How about....
if(isset($installedbase->Spare->spare_id)) {
  if(is_null($installedbase->Spare->spare_id)) {
    // do something
  }
}

...or maybe try using the PHP get_object_vars function, something like:
if(!empty(get_object_vars($installedbase->Spare)) && is_null($installedbase->Spare->spare_id)) {
  // do something
  }

What I'm not so clear about it is how you're getting spare_id from s.aantal.

A: Is it really needed to check if it is strictly null?
 if ($q) ...

should be enough for most cases. Take a look at PHP type comparsion tables.
Also, you may be interested in Doctrine_Null:
final class Doctrine_Null
{
    public function exists()
    {
        return false;
    }

    public function __toString()
    {
        return '';
    }
}

A: Should you not be left joining in i.Spare?
So:
$q = self::createQuery("l")
        ->select('i.*, s*, m.naam, c.cat_naam, a.app_id')
        ->from('InstalledBase i')
        ->leftJoin('i.Spare s')
        ->innerJoin('i.Apparaat a, a.Categorie c, a.Merk m')
        ->execute();

return $q;

Unless spare_id isn't the primary key that is. Then maybe changing the select statement to what I have done might help then adding this to your test:
if(isset($installedbase->Spare) && is_null($installedbase->Spare->spare_id))


text:
Q: Cleaning SQL "Incorrect string value" Error from PHP I've seem this question a million times, but everyone seems to want to solve the problem in the database. I do not. I'm getting this error when parsing a large text file, picking out what I need and inserting it into my database. Out of 24 thousand rows or so, 30 or so have invalid characters in them.
Here is an example of the error, followed by the query that caused it:
[Query Error: Incorrect string value: '\xEF\xBC\x89' for column 'company' at row 1]
[INSERT INTO mac_address_db_new (hex,company) VALUES('0847D0','Nokia Shanghai Bell Co. Ltd.)')]
The 'bad' characters in the string I'm inserting are probably not going to make it all the way to your browser, so you likely can't see the character.
But I'm looking for a simpler solution. Is there a way I can filter out these characters in PHP before I try to send them to MySQL? I already filter with the following functions: trim( ), mb_convert_encoding( ) (to UTF-8), htmlentities( ), ~ some case-related functions ~, and finally mysqli_real_escape_string( ). But still bad characters are getting through. I have no control over the text file input.

A: I finally found a solution. I ditched the mb_convert_encoding( ) function and instead used iconv( ), specifically this:
$output = iconv( 'UTF-8', "ISO-8859-1//IGNORE", $input );
Apparently the "//IGNORE" part is very important. This quietly strips these 'bad' characters out of my string before I send it off to the database.


text:
Q: Magento Custom Module How to install a custom module in magento from admin panel itself, I don't want to copy module files and paste into local folder.
Is there any UI feature for installation a custom module ?

A: You'll want to use Magento Connect. From your Magento Admin Panel (MAP) go to System » Magento Connect » Magento Connect Manager.

A: You can do that if you access the magento connect section from System menu item.
You should see an option to upload an archive with your extension.
But in order for this to work, you have to have the archive in a special format compatible with Magento Connect.
If you have a simple archive with all the files and folders it won't work. You will have do to it manually.


text:
Q: How to generate a 9 digit number I'm trying to use php to generate a 9 digit number that does not start with a 0 and is separated by dash every third number.
e.g. 102-394-458
I'm also debating whether

*

*to store it as a number or do the formatting on the front end

*or to store it as a number and do the formatting on the backend

*or to just store the dashes in the database as well

Of course the choice will affect how the number is generated.

A: Use number_format() on the frontend. Storing it formatted will mean you will have to "deformat" it if you want to perform any operation with it that requires it being a number.
The way to generate such a number is:
$number = mt_rand(100000000,999999999);

You can use number_format like this:
echo number_format($number,0,"","-");

A: You should save as an unsigned integer in your database and format on display (but still on server-side, if this is what you mean by backend.)
To generate the number use
mt_rand(100000000, 999999999);

To display use:
wordwrap($number, 3, '-', true);

A: Generate a random number between 1 and 9.
Generate 8 random numbers between 0 and 9.
Combine them into a string, adding dashes where desired.

A: implode('-',str_split(rand(100000000,999999999),3))

Generally, it's probably better simply to store as a number, and format it with the - only for display purposes


text:
Q: Insert image in WordPress with HTML5  tag and caption function When I upload an image through the WordPress media uploader and then insert it into the editor, it comes also with the width and height attributes (eg width="440" height="340")
But now I'm using the following code (source) to replace the image tags with figure. Unfortunately the width and height attributes are missing. Any idea how to insert them to?
    function html5_insert_image( $html, $id, $caption, $title, $align, $url, $size, $alt ) {
        $src  = wp_get_attachment_image_src( $id, $size, false );
        $html5 = "
";

        if ( $url ) {
        $html5 .= "";
        } else {
            $html5 .= "";
        }

        if ( $caption ) {
            $html5 .= "
$caption
";
        }

        $html5 .= "
";
        return $html5;
    }
    add_filter( 'image_send_to_editor', 'html5_insert_image', 10, 9 );

A: The width and height are [1] and [2]. So these are added on the img tag. If a theme has html5 caption support this outputs mangled html if you have a caption (it's pretty standard these days).
Corrected to check if there is a caption and return the WP shortcode or if no caption, then use the figure markup. Tested and works.
function html5_insert_image( $html, $id, $caption, $title, $align, $url, $size, $alt ) {

    if( empty( $caption ) ) :

        $src  = wp_get_attachment_image_src( $id, $size, false );

        $html = "
";

        if ( $url ) {
            $html .= "";
        } else {
            $html .= "";
        }

        $html .= "
";

    endif;

    return $html;

}
add_filter( 'image_send_to_editor', 'html5_insert_image', 10, 9 );


text:
Q: TypeError: object of type 'NoneType' has no len() tengo esta parte de código.
    auditor = driver.find_element_by_xpath('//*[@id="uid"]')
    auditor.clear()
--> auditor.send_keys(l[i])
    time.sleep(2)

y al momento de ejecutar me esta dando este error TypeError: object of type 'NoneType' has no len()
que puede ser?
l corresponde a una lista, i es una variable del for i in range...


text:
Q: Loading an attribute on a catalog/product object I've started working through some practice material for the Magento Certified Developer exam, and one of the questions that I ran into, and that I am still not sure about (I'm struggling to find material about this specific subject) is this:
For an attribute to be loaded on a catalog/product object, which two of the following conditions
must be satisfied? (Choose two)

A. The eav_attribute table must contain a row defining the attribute's properties and its entity type.
B. The attribute must have a backend model configured in the XML config.
C. The attribute must be part of the attribute set pertaining to the object being loaded.
D. There must be a record of the attribute on the catalog_product_super_atti:ibute table.
E. There must be a column added to the catalog_product_entity table.

My answers are A and C, is this right? If not, what is right, and why?

A: The right answers are indeed A and C.

*

*B is wrong because an attribute does not necessarily have a backend model configured in the XML configuration.

*D is wrong because the catalog_product_super_attribute table is only related to the configurable products attributes.

*E is wrong because the EAV system does not add extra columns to flat tables, it adds rows to the EAV tables to handle attributes relations.


text:
Q: Chrome search input width not same as text input In Firefox text and search input types both appear to be the same width.
In Chrome they are different widths.
Funnily enough my Codepen http://codepen.io/rachelreveley/pen/eBpyzK has the opposite result to my actual code (search appears wider).

input {
  width: 100%;
  padding: 1rem;
  box-sizing: padding-box !important;
}

form {width: 500px;}
<form>
 <input type="search" placeholder="Search" />
 <input type="text" placeholder="Text" />
</form>

A: You shouldn't use the padding-box anymore:

The width and height properties include the content, the padding but neither the border, nor the margin. Only Firefox implemented this value, and it was removed in Firefox 50.
  https://developer.mozilla.org/en/docs/Web/CSS/box-sizing

But why is this happening?
So you are using the not supported padding-box, Google Chrome is using the default values for box-sizing. The default value for the <input type="search"> is border-box. The default value of the <input type="text"/> is content-box.
See this example (should look like your example):

input {
  width: 100%;
  padding: 1rem;
}
input[type="search"] {
  box-sizing:border-box; /** default for this input */
}
input[type="text"] {
  box-sizing:content-box; /** default for this input */
}
form {
  width: 500px;
}
<form>
  <input type="search" placeholder="Search" />
  <input type="text" placeholder="Text" />
</form>

You can use border-box instead:

input {
  width: 100%;
  padding: 1rem;
  box-sizing: border-box;
}
form {
  width: 500px;
}
<form>
  <input type="search" placeholder="Search" />
  <input type="text" placeholder="Text" />
</form>

Difference between padding-box and border-box?
On border-box the width and height of the element includes the content, padding and border but not the margin of the element. On padding-box the width and height includes the content and padding but not the border and margin.
So if you want to simulate the padding-box you have to include the width of the border to the padding and using the border-box.
Your example would look like this:

input {
  width: 100%;
  padding: calc(1rem + 2px);
  box-sizing: border-box;
}
form {
  width: 500px;
}
<form>
  <input type="search" placeholder="Search" />
  <input type="text" placeholder="Text" />
</form>

Hint: The default width of the <input> border is 2px.


text:
Q: Using PowerBI How can I return the correct grade if I have a table which has the lower and upper values for each grade I have a table with the final numeric value for each student in a class, using powerBI how would i convert that to a grade value (A+, B....F) if I have a table with the each grade and its upper and lower values e.g. A+, 80, 100 . So if the student got 82 then the grade would be A+, if it was 34, it would be something else
I don't want to expand out the table so I have 100 rows each with 1 grade value if I don't have to

A: You should be more specific about your current model (tables/relationships etc).
Suppose we have two tables (without relationship)

I can calculate it like this :
GRADE =
var __StudVal = SELECTEDVALUE(StudentExam[Value])
return

CALCULATE(min(Grades[Grade]), FILTER(ALL(Grades),__StudVal > Grades[Lband] && __StudVal <= Grades[Uband] ))


text:
Q: FTS3 use of "BETWEEN" I'm getting error in this code.
Cursor cursor = ourDatabase.rawQuery(
    "SELECT * FROM " + DATABASE_TABLE + " WHERE KEY_ID BETWEEN 15 AND 20",
     null);

My LogCat says error near ? ****** BETWEEN ?
It says what are you doing. I'm not being able to figure out the mistake. Please help.

A: I believe KEY_ID is your variable, like DATABASE_TABLE, not the actual column name. Try:
Cursor cursor = ourDatabase.rawQuery(
    "SELECT * FROM " + DATABASE_TABLE + " WHERE " + KEY_ID + " BETWEEN 15 AND 20",
     null);


text:
Q: The Google-Login with Socialite doesn't work when i push my Laravel PHP application on Heroku I have an Laravel/PHP application with Google-Login from Socialite. It works fine on localhost. But when i push it on Heroku the Google-Login gets an error after I selected the account which I want to log in. So I think something with the callback is wrong. The google id, secret and redirect are already in Config Vars on Heroku.I also added the right auth-url on google's api.
What else could be wrong?

A: I don't know if this has any effect or not but it worked in my case when I changed APP_NAME in .env to the same as apk name when registering api


text:
Q: How to substitute " for" loop and if/ else if statements? Extracting data form data frame I am working in R on data frame consisting of time and precipitation data (over 3 000 000 values, measured every minute)
I would like to extract all "precipitation episodes", which are actually all moments when it was raining (dp != 0, but also including possible break in raining but no longer then "a" of the next measurements)
I would like all episodes to be stored in the new data frame with additional column with the number of each of them. First rain - 1, Second - 2....
The example of "precipitation episode":
time <- c("2013-01-01 11:39:00",
        "2013-01-01 11:40:00", "2013-01-01 11:41:00",
        "2013-01-01 11:42:00","2013-01-01 11:43:00",
        "2013-01-01 11:44:00","2013-01-01 11:45:00",
        "2013-01-01 11:46:00","2013-01-01 11:47:00",
        "2013-01-01 11:48:00","2013-01-01 11:49:00",
        "2013-01-01 11:50:00","2013-01-01 11:51:00",
        "2013-01-01 11:52:00","2013-01-01 11:53:00")

time <- as.POSIXct(time , origin="1899-12-30",tz="GMT")

p<- c(1.565, 1.565, 1.658, 1.795, 1.795, 1.795, 1.896, 1.896, 2.985, 2.985,
      2.985, 2.985, 3.5, 3.7, 3.85)

df <- data.frame(time, p)
dp <- diff(df$p)

df$dp<- c(dp,0)

I created a function using for loop and (a lot of) if conditions, which I hope represents well my intentions. Its currently not working well - still looking for the reason why.
rain.episodes<- function(x) {
  a<- 300
  episode.number <- 1
  rain <- reja.clean[1,] #just for column names

  for (i in 1:nrow(x)) {

    if (x[i,"dp"] >0) {
        rain[i,]<- x[i,]
        rain[i, "episode.number"]<- episode.number
        a<-0

    } else if (x[i,"dp"] ==0 & a<300) {
        rain[i,]<- x[i,]
        rain[i, "episode.number"]<- episode.number
        a<-a+1

    } else if (a==301) {
        episode.number<-episode.number+1

    } else{
          a<-a+1
    }
  }
  return(rain)
}

Is there any way to create a function helping me with that issue, with the same output as the one I pasted, but using different (better) method?
I would also like to know why my function doesnt work.

A: This may work:
#load libraries
library(dplyr)
library(lubridate)
library(zoo) # for `na.locf`
library(data.table) # for Step 2

Step 1: Identify the rainy/non-rainy episodes: TRUE/FALSE
df_new <- df[-1,] %>% #remove the first non-rainy observation to suit `na.locf`**
  arrange(time) %>%
  # create ind_hour to keep the time when it rained
  mutate(ind_hour = ifelse (dp != 0, format(as.POSIXct(time) ,format = "%Y-%m-%d %H:%M:%S"), NA)) %>%
  # when it did not rain (i.e. ind_hour is NA), add an extra hour to the last known time when it rained (use na.locf to get the last time when it rained)
  mutate(ind_hour_complete = ifelse(is.na(ind_hour), (na.locf(as.POSIXct(ind_hour, format = "%Y-%m-%d %H:%M:%S", tz="GMT")) + hours(1)), time)) %>%
  # if `time` is lower or equal to the `ind_hour_complete`, then we are looking at the same episode
  mutate(same_episode = time <= ind_hour_complete) %>%
  select(-ind_hour, -ind_hour_complete)

**Note: within a vector that starts by an NA, na.locf will remove it and the resulting vector will have length (n-1). Here, the results would shift up one row. You may try the code without removing the first row from df to see what I mean. If needed, you may add back this first row  at the very end, with an ep_number equal to max(df_new$ep_number) + 1 (to ensure the ep_number is unique). I have removed it completely because you do not seem to need it (according to your expected output).
Step 2: Add indexes for the identified episodes: ep_number
df_new <- setDT(df_new)[, ep_number:= rleid(same_episode)]


text:
Q: PHP. Регулярное выражение, допускающее отсутствие некоторых частей Есть текст, типа: "Осталось  10 часов 15 минут 12 секунд". Некоторые компоненты (часы, минуты, секунды) могут отсутствовать. Нужно выдернуть циферки и соотнести с часами, минутами, секундами.
Делаю так:
Осталось\s+(?!(\d+)\s+(час).*?)(?!(\d+)\s+(минут).*?)(?!(\d+)\s+(секунд).*?)

Текст подходит под регулярное выражение, но от него всегда остается только "Осталось  " при любых комбинациях час., мин., сек.
P.S. Нашел информацию по (?!...). Они, оказывается, используются только для проверки, но ничего не выводят.
Каким образом можно одновременно проверить наличие фрагментов и выдернуть данные?

A: Мне кажется, Вы путаете необязательные группы с блоками предварительного просмотра (look-ahead). Вместо (?!...) надо использовать (?:...)?, а окончания отлавливать с помощью \p{L}*:
Осталось\s+(?:(\d+)\s+час\p{L}*)?(?:\s*(\d+)\s+минут\p{L}*)?(?:\s*(\d+)\s+секунд\p{L}*)?
            ^^                  ^

Код:
$re = '/Осталось\s+(?:(\d+)\s+час\p{L}*)?(?:\s*(\d+)\s+минут\p{L}*)?(?:\s*(\d+)\s+секунд\p{L}*)?/u';

См. демо

A: Нужно использовать комбинацию из проверяемой части и захватывающей части. Примерно вот так:
Осталось\s+((?<hours>\d+)\s+час(а|ов)?\s*)?((?<minutes>\d+)\s+минут(а|ы)?\s*)?((?<seconds>\d+)\s+секунд(а|ы)?)?
После обработки в именованных группах будут требуемые значения.
Демо тут (спасибо за наводку @stribizhev)


text:
Q: Tap to focus for camera implementation I'm trying to implement a manual focus feature for my camera page so that the user can tap to focus the camera.
I'm following this StackOverflow question that's currently written in Java for native Android. I've been converting it to C# for my Xamarin.Forms Android app.
Here's what I have so far:
public class CameraPage : PageRenderer, TextureView.ISurfaceTextureListener, Android.Views.View.IOnTouchListener, IAutoFocusCallback
{
    global::Android.Hardware.Camera camera;
    TextureView textureView;

    public void OnAutoFocus(bool success, Android.Hardware.Camera camera)
    {
        var parameters = camera.GetParameters();
        if (parameters.FocusMode != Android.Hardware.Camera.Parameters.FocusModeContinuousPicture)
        {
            parameters.FocusMode = Android.Hardware.Camera.Parameters.FocusModeContinuousPicture;

            if (parameters.MaxNumFocusAreas > 0)
            {
                parameters.FocusAreas = null;
            }
            camera.SetParameters(parameters);
            camera.StartPreview();
        }
    }

    public bool OnTouch(Android.Views.View v, MotionEvent e)
    {
        if (camera != null)
        {
            var parameters = camera.GetParameters();
            camera.CancelAutoFocus();
            Rect focusRect = CalculateTapArea(e.GetX(), e.GetY(), 1f);

            if (parameters.FocusMode != Android.Hardware.Camera.Parameters.FocusModeAuto)
            {
                parameters.FocusMode = Android.Hardware.Camera.Parameters.FocusModeAuto;
            }
            if (parameters.MaxNumFocusAreas > 0)
            {
                List<Area> mylist = new List<Area>();
                mylist.Add(new Android.Hardware.Camera.Area(focusRect, 1000));
                parameters.FocusAreas = mylist;
            }

            try
            {
                camera.CancelAutoFocus();
                camera.SetParameters(parameters);
                camera.StartPreview();
                camera.AutoFocus(OnAutoFocus); //Here is the issue. How do I use the callback?
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.Write(ex.StackTrace);
            }
            return true;
        }
        return false;
    }

    private Rect CalculateTapArea(object x, object y, float coefficient)
    {
        var focusAreaSize = 500;
        int areaSize = Java.Lang.Float.ValueOf(focusAreaSize * coefficient).IntValue();

        int left = clamp((int)x - areaSize / 2, 0, textureView.Width - areaSize);
        int top = clamp((int)y - areaSize / 2, 0, textureView.Height - areaSize);

        RectF rectF = new RectF(left, top, left + areaSize, top + areaSize);
        Matrix.MapRect(rectF);

        return new Rect((int)System.Math.Round(rectF.Left), (int)System.Math.Round(rectF.Top), (int)System.Math.Round(rectF.Right), (int)System.Math.Round(rectF.Bottom));
    }

    private int clamp(int x, int min, int max)
    {
        if (x > max)
        {
            return max;
        }
        if (x < min)
        {
            return min;
        }
        return x;
    }
}

I've managed to convert most of it but I'm not sure how to properly use the AutoFocusCallback here. What should I do to call OnAutoFocus from my OnTouch event like in the java answer I linked above?
After I attached the callback, then all I need to do is subscribe the OnTouch event to my page correct or...?
For example, I tried:
textureView.Click += OnTouch; but 'no overload for 'OnTouch' matches delegate 'EventHandler'. Is there a specific event handler I need to use?

A: You can try change
camera.AutoFocus(OnAutoFocus);

to
camera.AutoFocus(this);

and it will be using OnAutoFocus because it implementation from IAutoFocusCallback.
And for your question about subscribe event you can try to subscribe event in OnElementChanged like this
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e)
        {
            base.OnElementChanged(e);
            if (e.OldElement != null || Element == null)
            {
                return;
            }
            try
            {
                this.SetOnTouchListener(this);
            }
            catch (Exception e)
            {

            }

        }

And btw I don't see to use TextureView.ISurfaceTextureListener in this code.

A: All that happened in the linked Java answer is that they provided the code to run when the OS calls the callback:
camera.autoFocus(new Camera.AutoFocusCallback() {
    @Override
      public void onAutoFocus(boolean success, Camera camera) {
           camera.cancelAutoFocus();
           Parameters params = camera.getParameters();
           if(params.getFocusMode() != Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE){
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                camera.setParameters(params);
        }
    }
});

the above does not "call" the call back, just provides the call back code to run. the OS calls the call back. So in Xamarin, you need to pass in the type that is implementing the IAutoFocusCallback interface, so You should be able to do this I would think since CameraPage is implementing the IAutoFocusCallback interface:
camera.AutoFocus(this); // "this" refers to your current CameraPage which implements the interface.

the clue here is that when you type the opening parenthesis after camera.AutoFocus the popup shows that you need to pass in a type IAutoFocusCallback, which means any type that implements that interface, so in this case that is "this" CameraPage. :-)

A: Since there's no complete example here, here's mine.
This solution works fine, at least for me. The camera will focus continously until a focus point is tapped. It will then focus on the tap point until you move the camera away. Then it goes back to continous focus mode.
public class CameraPageRenderer : PageRenderer, TextureView.ISurfaceTextureListener, Android.Hardware.Camera.IPictureCallback, Android.Hardware.Camera.IShutterCallback, IAutoFocusCallback
{

    // ... code removed for brevity

    /// <summary>
    /// Occurs whenever the user touches the screen. Here we set the focus mode to FocusModeAuto and set a focus area based on the tapped coordinates.
    /// </summary>
    public override bool OnTouchEvent(MotionEvent e)
    {
        var parameters = camera.GetParameters();

        parameters.FocusMode = Camera.Parameters.FocusModeAuto;

        if (parameters.MaxNumFocusAreas > 0)
        {
            var focusRect = CalculateTapArea(e.GetX(), e.GetY(), textureView.Width, textureView.Height, 50f);

            parameters.FocusAreas = new List<Area>()
            {
                new Area(focusRect, 1000)
            };
        }

        try
        {
            camera.CancelAutoFocus();
            camera.SetParameters(parameters);
            camera.AutoFocus(this);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }

        return true;
    }

    /// <summary>
    /// Auto focus callback. Here we reset the focus mode to FocusModeContinuousPicture and remove any focus areas
    /// </summary>
    public void OnAutoFocus(bool success, Camera camera)
    {
        var parameters = camera.GetParameters();

        parameters.FocusMode = Parameters.FocusModeContinuousPicture;

        if (parameters.MaxNumFocusAreas > 0)
        {
            parameters.FocusAreas = null;
        }

        camera.SetParameters(parameters);
    }

    /// <summary>
    /// Calculates a tap area using the focus coordinates mentioned in <see href="https://developer.android.com/reference/android/hardware/Camera.Parameters.html#getFocusAreas()"/>
    /// <para>
    /// Coordinates of the rectangle range from -1000 to 1000. (-1000, -1000) is the upper left point. (1000, 1000) is the lower right point. The width and height of focus areas cannot be 0 or negative.</para>
    /// </summary>
    /// <param name="x">The X coordinate of the tapped area</param>
    /// <param name="y">The Y coordinate of the tapped area</param>
    /// <param name="width">The total width of the tappable area</param>
    /// <param name="height">The total height of the tappable area</param>
    /// <param name="focusAreaSize">The desired size (widht, height) of the created rectangle</param>
    /// <returns></returns>
    private Rect CalculateTapArea(float x, float y, float width, float height, float focusAreaSize)
    {
        var leftFloat = x * 2000 / width - 1000;
        var topFloat = y * 2000 / height - 1000;

        var left = RoundFocusCoordinate(leftFloat);
        var top = RoundFocusCoordinate(topFloat);
        var right = RoundFocusCoordinate(leftFloat + focusAreaSize);
        var bottom = RoundFocusCoordinate(topFloat + focusAreaSize);

        return new Rect(left, top, right, bottom);
    }

    /// <summary>
    /// Round, convert to int, and clamp between -1000 and 1000
    /// </summary>
    private int RoundFocusCoordinate(float value)
    {
        var intValue = (int)Math.Round(value, 0, MidpointRounding.AwayFromZero);
        return Math.Clamp(intValue, -1000, 1000);
    }

    // ... code removed for brevity

}


text:
Q: erro na execução do node.js ola, estou com esse erro no meu app:

Servidor Rodando!
  URL: /
  Method: GET
  _http_outgoing.js:482
      throw new ERR_HTTP_HEADERS_SENT('set');
      ^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
      at ServerResponse.setHeader (_http_outgoing.js:482:11)
      at Server.http.createServer (C:\Users\Samuel Melo da Silva\Desktop\node.js\index.js:13:8)
      at Server.emit (events.js:193:13)
      at parserOnIncoming (_http_server.js:680:12)
      at HTTPParser.parserOnHeadersComplete (_http_common.js:113:17)

codigo:
const http = require('http');

let server = http.createServer((req, res)=>{

    console.log('URL:', req.url);
    console.log('Method:', req.method);

    res.end('ok');

    switch(req.url){
        case '/':
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/html');
            res.end('
Olá
');
            break;
        case '/users':
            res.statusCode = 200;
            res.setHeader("Content-Type", 'application/json');
            res.end(JSON.stringify({
                user:[{
                    name:'Samuel',
                    email: 'samuel@samuel.com',
                    id: 1
                }]
            }));
            break;
    }
});

server.listen(300, '127.0.0.1', ()=>{

    console.log('Servidor Rodando!');

});

A: O erro está dizendo que você não pode alterar os headers da resposta depois de já ter enviado a mesma.
Note que você está utilizando o comando res.end('ok') e logo depois no seu switch você faz res.statusCode = 200 e res.setHeader(). Isso não é possível.


text:
Q: groovy call for optional parameters I have a method as follows:
void display(def a = null, def b = null) {

// user provides either value for a, or b
// if he gives value for a, it will be used
// if he gives value for b, it will be used

// not supposed to provide values for both a and b

}

My question is, how is user supposed to provide value for b?
If I use
display(b = 20)

It assigns 20 to a, which I don't want.
Is the only way to accomplish this is to call as follows?
display(null, 20)

A: With optional parameters, yes you'd have to call display(null, 20). But you can also define method to accept a Map instead.
void display(Map params) {
    if(params.a && params.b) throw new Exception("A helpful message goes here.")

    if(params.a) { // use a }
    else if(params.b) { // use b }
}

The method could then be called like this:
display(a: 'some value')
display(b: 'some other value')
display(a: 'some value', b: 'some other value') // This one throws an exception.


text:
Q: How to draw and resize polygon using mouse In my web application i need to draw shapes in the image using mouse.But i was struck draw and resize polygon..i have dawned polygon..How to resize it?
i can able to draw polygon using the above code.
But i need to resize it..any idea to resize the drowned polygon?
Please refer the below code.
private function onDrawTriangle() : void {
    var ui:UIComponent = new UIComponent();
    drawPanel = new Sprite();
    drawPanel.graphics.clear();
    drawPanel.graphics.lineStyle(2, 0xFF0000);
    drawPanel.graphics.beginFill(0xDEFACE);
    drawPanel.graphics.drawRect(0,0,300,300);
    drawPanel.graphics.endFill();
    ui.addChild(drawPanel);
    addChild(ui);
    ui.x = 20;
    ui.y = 20;

    _lineArr = new Array();
    line = new Shape();
    drawPanel.addEventListener(MouseEvent.CLICK,onAddPoint);
}

private function onAddPoint(evt:MouseEvent) : void {
    if(numSpot <= 10) {
        var point:Sprite = new Sprite();
        point.graphics.clear();
        point.graphics.lineStyle(0,0x0000FF);
        point.graphics.beginFill(0x0000FF);
        point.graphics.drawCircle(0,0,5);
        point.graphics.endFill();

        point.x = evt.localX;
        point.y = evt.localY;
        _lineArr.push({x:point.x,y:point.y});
        drawPanel.addChild(point);
        if(numSpot > 0) drawLine();

        numSpot++;
    }
}

private function drawLine() : void {
    line.graphics.clear();
    line.graphics.lineStyle(2,0x000000);
    if(_lineArr.length > 2) line.graphics.beginFill(0xFF0000,0.5);
    line.graphics.moveTo(_lineArr[0].x,_lineArr[0].y);
    for(var i:int=1;i<_lineArr.length;i++) {
        line.graphics.lineTo(_lineArr[i].x,_lineArr[i].y);
    }
    line.graphics.lineTo(_lineArr[0].x,_lineArr[0].y);
    if(_lineArr.length > 2) line.graphics.endFill();
    drawPanel.addChildAt(line,0);
}

A: Rather pushing points to array you may push the point(sprite variable).
Have a look on the modified codes for the above codes where I added some more events to re size the polygon
Here is the sample code:
private function onDrawTriangle() : void {
                var ui:SpriteVisualElement = new SpriteVisualElement();
                //ui.x = 20;
                //ui.y = 20;
                addElement(ui);
                drawPanel = new Sprite();
                drawPanel.graphics.clear();
                drawPanel.graphics.lineStyle(2, 0xFF0000);
                drawPanel.graphics.beginFill(0xDEFACE);
                drawPanel.graphics.drawRect(0,0,300,300);
                drawPanel.graphics.endFill();
                ui.addChild(drawPanel);

                _lineArr = new Array();
                line = new Shape();
                drawPanel.addEventListener(MouseEvent.CLICK,onAddPoint);
            }

            private function onAddPoint(evt:MouseEvent) : void {
                if(numSpot <= 10) {
                    var point:Sprite = new Sprite();
                    point.graphics.clear();
                    point.graphics.lineStyle(0,0x0000FF);
                    point.graphics.beginFill(0x0000FF);
                    point.graphics.drawCircle(0,0,5);
                    point.graphics.endFill();

                    point.x = mouseX;
                    point.y = mouseY;

                    point.addEventListener(MouseEvent.MOUSE_DOWN , onDown);
                    _lineArr.push(point);
                    drawPanel.addChild(point);
                    if(numSpot > 0) drawLine();

                    numSpot++;
                }
            }

            private function drawLine() : void {
                line.graphics.clear();
                line.graphics.lineStyle(2,0x000000);
                if(_lineArr.length > 2)     line.graphics.beginFill(0xFF0000,0.5);
                line.graphics.moveTo(_lineArr[0].x,_lineArr[0].y);
                for(var i:int=1;i<_lineArr.length;i++) {
                    line.graphics.lineTo(_lineArr[i].x,_lineArr[i].y);
                }
                line.graphics.lineTo(_lineArr[0].x,_lineArr[0].y);
                if(_lineArr.length > 2) line.graphics.endFill();
                drawPanel.addChildAt(line,0);
            }

            protected function onDown(event:MouseEvent):void
            {
                var point:Sprite = event.currentTarget as Sprite;
                point.addEventListener(Event.ENTER_FRAME , onResize);
                point.addEventListener(MouseEvent.MOUSE_UP , onUp);

                drawPanel.removeEventListener(MouseEvent.CLICK,onAddPoint);

            }

            protected function onResize(event:Event):void
            {
                var point:Sprite = event.currentTarget as Sprite;
                point.x = mouseX;
                point.y = mouseY;
                drawLine();
            }

            protected function onUp(event:MouseEvent):void
            {
                var point:Sprite = event.currentTarget as Sprite;
                point.removeEventListener(Event.ENTER_FRAME , onResize);
                point.removeEventListener(MouseEvent.MOUSE_UP , onUp);

                drawPanel.addEventListener(MouseEvent.CLICK,onAddPoint);
            }


text:
Q: Error executing stored procedure fails I created a stored procedure in mysql database, which fires multiple insert statemets.
As shown below:
DELIMITER //

DROP PROCEDURE IF EXISTS insert_user_group_info
//
CREATE PROCEDURE insert_group_user_info(groupname varchar(50), groupdesc varchar(100),
createddate varchar(50), createdby varchar(100))
BEGIN
   DECLARE RETURN_VAL INT UNSIGNED DEFAULT 0;
   DECLARE NEWGROUPID INT UNSIGNED DEFAULT 0;
START TRANSACTION;

   Insert into group_tbl (`groupname`,
   `groupdesc`,
   `groupusers`,
   `createdon`,
   `createdby`,
   `groupstatus`)
    values
   (groupname,
    groupdesc,
    '1',
    createddate,
    createdby,
    '1');

    SET NEWGROUPID = LAST_INSERT_ID();

   INSERT INTO useringroup_tbl
   ( groupid,
     username,
     regdate,
     joindate,
     userstatus,
     roleid)
   VALUES
   ( NEWGROUPID,
     createdby,
     createddate,
     createddate,
     '1',
     '1');

     INSERT INTO userinrole_tbl
   ( username,
     groupid,
     roleid)
   VALUES
   (createdby,
    NEWGROUPID,
    '1');

   SET RETURN_VAL = LAST_INSERT_ID();

   SELECT RETURN_VAL;

COMMIT;
END//
DELIMITER ;

Schema for tables are as follows
Table 1 group_tbl
CREATE TABLE `group_tbl`
(
  `groupid` int(11) NOT NULL auto_increment,
  `groupname` varchar(50) NOT NULL,
  `groupdesc` varchar(100) NOT NULL,
  `groupusers` int(11) NOT NULL,
  `createdon` datetime NOT NULL,
  `createdby` varchar(50) NOT NULL,
  `groupstatus` tinyint(4) NOT NULL,
  PRIMARY KEY  (`groupid`)
);

Table 2 useringroup_tbl
CREATE TABLE IF NOT EXISTS `useringroup_tbl`
(
  `groupid` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `regdate` datetime NOT NULL,
  `joindate` datetime NOT NULL default '0000-00-00 00:00:00',
  `userstatus` tinyint(4) NOT NULL,
  `closingdate` datetime NOT NULL default '0000-00-00 00:00:00',
  `roleid` int(11) NOT NULL default '0',
  PRIMARY KEY  (`groupid`,`username`)
);

Table 3 userinrole_tbl
CREATE TABLE IF NOT EXISTS `userinrole_tbl`
(
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(50) NOT NULL,
  `groupid` int(11) NOT NULL,
  `roleid` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
);

While executing this procedure by this statement
call insert_group_user_info('test name','test description','2015-05-10 12:10:12','XYZuser')

I get an error

1062 - Duplicate entry '1-XYZuser' for key 1

and each time it the number appended to the username gets incremented
like this

1062 - Duplicate entry '2-XYZuser' for key 1

So please if anybody can give me direction what I am doing wrong,
Thanks in advance.

A: According to the error you have pasted,

*

*1062 - Duplicate entry '1-XYZuser' - PRIMARY KEY  (groupid,username) - It doesn't matter if you truncate the tables or not. You might be inserting the same data again.

*You might be using last_insert_id() incorrectly.

Why is there no auto_increment in useringroup_tbl?


text:
Q: Upload file using Dropzone in react.js component to backend in sails.js The backend of my app uses sails.js, and there's an API api/question/new for creating a new question. This API supports uploading a file or a picture by using its skipper module here, which I've verified working in the REST client PostMan using a file field for upload along with text fields for title, content, and tags.
Now, I am trying to make my react.js-based component (Question Form) work for posting text and uploading file at the same time. I came across a nice library called react-dropzone here, and I am trying to integrate it with my form. The form in react.js is handled by a saga function for posting with the whatwg-fetch library.
Question Form Component:
export const fields = ['title', 'content', 'tags', 'images'];

const validate = values => {
    const errors = {};
    if (!values.title) {
        errors.title = 'Required';
    }
    if (!values.content) {
        errors.content = 'Required';
    } else if (values.content.length < 2) { // TODO: specify a constant for length of content
        errors.content = 'Question is too short';
    }

    return errors;
}

class QuestionForm extends React.Component {

    constructor(props, context) {
        super(props, context);
        this.dropFile = this.onDrop.bind(this);
    }

    onDrop(files) {
        console.log('received files: ', files);
        this.props.fields.images = [];
        files.forEach((file) => {
            this.props.fields.images.push(file);
        });
    }

  render() {
      const { fields: {title, content, tags, images}, resetForm, handleSubmit, submitting, pristine} = this.props;
    return (

          <form onSubmit={handleSubmit}>
              <Row>
                  Title

                      <input className="form-control" type="text" maxlength="100" placeholder="Title" {...title} name="title" />

                  {title.touched && title.error &&
{title.error}
}
              </Row>
              <Row>
                  Content

                      <input className="form-control" type="text" maxlength="100" placeholder="Content" {...content} name="content" />

                  {content.touched && content.error &&
{content.error}
}
              </Row>
              <Row>
                  Tags

                      <input className="form-control" type="text" maxlength="100" placeholder="Tags" {...tags} name="content" />

              </Row>
              <Row>
                   <Dropzone onDrop={this.dropFile}>

Try dropping some files here, or click to select files to upload.

                    </Dropzone>
              </Row>
              <Row>

                  <button className="btn btn-warning" type="button" disabled={pristine || submitting} onClick={resetForm}>Clear Values</button>
                  <button className="btn btn-primary" type="submit" disabled={pristine || submitting}>Submit</button>
              </Row>
          </form>

    );
  }
}

Below is the saga function for posting the form data with whatwg-fetch:
export function* askQuestion() {
    while(true) {
        const action = yield take(types.SUBMIT_QUESTION);
        let askQUrl = 'http://localhost:1337/api/question/new';
        const curToken = getJwtToken();
        var formData = new FormData();

        action.questionObj.images.forEach(function(img) {
            formData.append('images', img);
        });

        formData.append('title', action.questionObj.title);
        formData.append('content', action.questionObj.content);
        formData.append('tags', action.questionObj.tags);
        console.info('formData: ', formData); // here the images field shows as undefined
        try {
            let options = {
                method: 'POST',
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                // body: JSON.stringify(action.questionObj),
                body: formData,
            };
            const response = yield call(request, askQUrl, options);
            if (response.data) {
                yield put(submitQuestionSuccess(response.data));
            } else {
                yield put(submitQuestionFailed(response.error));
            }
        } catch(e) {
            yield put(submitQuestionFailed('server problem in taking your question'));
        }
    }
}

When I submit the form with the title/content/tags and a file, I got the following errors in the browser console:

uncaught at askQuestion   TypeError: Cannot read property 'forEach' of
  undefined

I am not sure why the action.questionObj.images is undefined, because in the dropFile() function, I push the file into the images array. Could anyone spot where I am doing wrong? or is there a better way to post both text and file same time to sails.js-based backend?


text:
Q: How to sort hashable objects I have a situation where I need to sort the keys of a dictionary to make sure that the list always has the same order.  I don't care what that order is.  But I need to have consistency of order.  This is causing people using a package I've written difficulties because they want to set a random seed and have consistent results for testing purposes, but even when they set a key, the order that the dictionary returns its values changes, and this ends up affecting the randomization.
I would like to do some thing like sorted(D.keys()).  However, in principle the keys may not be sortable.  I don't have any control over what those keys are.
I know this is solved in recent versions of python, but I don't want to restrict uses to 3.7.
More detail here: https://github.com/springer-math/Mathematics-of-Epidemics-on-Networks/issues/22#issuecomment-631219800

Since people think this is a bad question, here's more detail (or see the original link I provided for even more detail):
I have written an algorithm to do stochastic epidemic simulations.  For reproducibility purposes people would like to specify a seed and have it run and produce the same outcome on any machine.  The algorithm uses a networkx graph (which is built on a dictionary structure).
As part of the steps it needs to perform a weighted selection from the edges of the graph.  This requires that I put the edges into a list.  If the list is in a different order, then different outcomes occur regardless of whether the same seed is used.
So I'm left with having to find a way to make the list of edges be in a consistent order on any machine.

A: If you only want to preserve order one possibility is insertion order with a list of pairs. If you combine with a OrderedDict you will preserve order and have dictionary functions.
>>> import collections
>>> d = collections.OrderedDict([(1,'a'),(3,'2')])
>>> d.keys()
odict_keys([1, 3])

A: So if I understand correctly... the task is to consistently select the same random key from a vanilla dict on an old version of Python where insertion order is not preserved, while knowing nothing at all about the key type, and without setting the hash seed explicitly. I believe that's impossible in the general case, because the whole notion of object "identity" does not even exist with such restrictive assumptions.
The only thing that comes to mind is to serialize the keys in some way, and sort their serialized forms. pickle.dumps should work on most key types (although not everything can be pickled). But if the key type does allow sorting, it's probably more robust to simply use that instead.
import pickle

try:
    sorted_keys = sorted(my_dict)
except TypeError:
    sorted_keys = sorted(my_dict, key=lambda x: pickle.dumps(x, protocol=3))

There are some caveats though:

*

*The pickled representation is not the same across Python versions (see Data stream format). That's why I'm setting protocol=3 in the example above; this should work the same for Python 3.0 and newer, although it doesn't support as many object types as protocol 4.

*Objects can define their own pickling, so there is no guarantee that it's reproducible. In particular...

*The pickled representation of dictionaries is still dependent on the ordering of the dictionary, which depends the Python version and the hash seed. The same goes for objects, because by default these are pickled by invoking their __dict__ method.
If you want to get really tricky, maybe you can create a custom Pickler that sorts dictionaries (using OrderedDict for portability across Python versions) before pickling them... but in the end, it's not going to solve the full problem.


text:
Q: SQL/PHP - REPLACE statement not working as intended I'm trying to 'remove' part of a string in a DB entry after a delete command is made.
Say a PDF file gets deleted, i want to remove the reference of it by replacing it with '' (but keep the other references). That works fine, but now i also want to do it with another column, and the exact same setup doesn't seem to work and i can't figure out why.
This works:
$stmt_2 = $db->prepare("UPDATE data_videothek SET pdfAttachment = REPLACE(pdfAttachment, $id, '') WHERE pdfAttachment LIKE ?");
$stmt_2->execute(array( $like_id_string ));

This doesn't:
$stmt_2 = $db->prepare("UPDATE data_videothek SET speaker_img = REPLACE(speaker_img, $thefile, '' ) WHERE speaker_img LIKE ?");
$stmt_2->execute(array(  $like_filename_string ));

Both columns are defined as 'varchar' and all input in the query is as 'string'
I can't wrap my head around why the pdf one works, but the speaker_img doesn't.
The problem must be in REPLACE(speaker_img, $thefile, '' ) because if i replace that with a simple = '', the query performs fine and clears the whole cell if a match is made.
This is how i define the 2 input variables:
$thefile = (string)basename($row['filename'], ".png");
$like_filename_string = "%".$thefile."%";

For the curious why i save the info like that: There's only 1 field for the filenames, seperated by a "-", which when loaded gets 'exploded' into an array. It allows me to haven an open-ended number of attachments. Maybe not the best way of doing things?

A: If you use parameters for $id and $thefile instead of variable interpolation, you won't need to worry about escaping chars, which is probably the reason the sql is malformed when you try to just use the value of $thefile inside a sql string.


text:
Q: Воспроизведение музыки с онлайн радио Хочу написать код, который обращается к радиостанции и выбирает нужную радиостанцию, затем запускает её воспроизведение на ПК, как это сделать на java, вообще не знаю, куда двигаться.

A: Можно использовать библиотеку JLayer
Тогда код для консольного плеера будет примерно таким -
URL url = new URL(urlString);
InputStream fin = url.openStream();
InputStream is = new BufferedInputStream(fin);

Player player;
player = new Player(is);
player.play();

Может есть и более продвинутые библиотеки для воспроизведения потокового аудио. Это первое, что нашлось.


text:
Q: Apache Camel: MailMessage email Headers are empty I am new to Apache camel. we are using Apache camel 2.11.0 to poll a microsoft exchange Indox, using POP3 as FROM endpoint and created a bean class to process the email message in the route before sending it to target endpoint. The issue i have is MailMessage object return from Exchange.getIn(MailMessage.class).getMessage() in Processor method does not have any email headers. When i put a Debug option on FROM endpoint i can see the email headers of receiving email in the Apache camel trace. Your help is much appreciated.
Route Config
<!-- Route email exchange-->
    <route id="gateMail">
        <from uri="pop3://MyUser@MyMailServer.com?password=MyPassword&debugMode=true&contentType=multipart/alternative" />
        <bean ref="MailProcessor" />
        <to uri="file:D:/Mail" /></route>

Output in console of Tomcat v7.0 Server at localhost [Apache Tomcat] c:\Program Files\Java\jdk1.7.0_21\bin\Javaw.exe
DEBUG POP3: pipeline message size 2243
    S: +OK
    Received: by MyMailServer.com id <01CF1183.AA71B3C0@MyMailServer.com>; Wed, 15 Jan 2014 10:52:21 +1100
x-protective-marking: VER=2005.6, NS=com.au, SEC=UNCLASSIFIED:AUDIT, ORIGIN=MyUser@MyMailServer.com
x-titus-version: 3.3.8.1
x-tituslabs-classifications-30: TLPropertyRoot=Titus;Classification=UNCLASSIFIED;Precedence=ROUTINE;Privacy=AUDIT;
x-tituslabs-classificationhash-30: YifyyqlCDo9l8ySQLTGzHX5c15nHvPqznjIb8keFNu8UEVGWAssd6R0LjeoelHoKfBmfwLv3tDicWe12NsuQFLTSJLlcdr56aL59f1GzpTBosa6XLoHlIutAnNQcPA+xRA5fzirrVFmPv2jTtl8Bqp30thtdKQvwpzqD/KcGI3vS033ldtUOzAF1+/gwx9zL+SBDwxSwUor1ihlW6uCx36tFLjtDF7M9GjKi5Cd/jUFyjCypZnCyZkCmSjvL9iG/
Content-class: urn:content-classes:message
Subject: Test Design [SEC=UNCLASSIFIED:AUDIT]
MIME-Version: 1.0
Content-Type: multipart/alternative;

Bean Class Code
 public class MailProcessor implements Processor {

public void process(Exchange exch) throws Exception {
    String filename = exch.getIn().getHeader(Exchange.BREADCRUMB_ID,String.class);
    POP3Message mailMSG = (POP3Message)exch.getIn(MailMessage.class).getMessage();
    String mailTo = getRecipients(mailMSG);
    String from = this.getFrom(mailMSG);`enter code here`
    String subject = mailMSG.getSubject();
    String headers = GetHeaders(mailMSG);
    String body = this.getText(mailMSG);
    Map<String, DataHandler> attachments = exch.getIn().getAttachments();
    String attFileName = "";
    if(attachments.size() > 0)
    {
        for(String name: attachments.keySet())
        {
            DataHandler dh = attachments.get(name);
            attFileName = attFileName + "; " + dh.getName();
        }
    }
    String strMessage = (" ----------- From:" + from  + " ----------- To:" + mailTo
            + " ----------- Subject:" + subject + " ----------- Attchements:" + attFileName +
            " ----------- Header:" + headers +" ----------- Body:" + body);
    File mailFile = new File("D:\\IOI\\Mail\\" + filename + ".txt");
    BufferedWriter writer = new BufferedWriter(new FileWriter(mailFile));
    writer.write(strMessage);
    writer.close();
}

private String getText(Part p) throws
    MessagingException, IOException
{

if (p.isMimeType("text/*")) {
String s = (String)p.getContent();
return s;
}

if (p.isMimeType("multipart/alternative")) {
// prefer html text over plain text
Multipart mp = (Multipart)p.getContent();
String text = null;
Part bp = null;
for (int i = 0; i < mp.getCount(); i++) {
    bp = mp.getBodyPart(i);
    if (bp.isMimeType("text/plain")) {
        if (text == null)
            text = getText(bp);
        continue;
    } else if (bp.isMimeType("text/html")) {
        String s = getText(bp);
        if (s != null)
            return s;
    } else {
        return getText(bp);
    }
}
return text;
} else if (p.isMimeType("multipart/*")) {
Multipart mp = (Multipart)p.getContent();
for (int i = 0; i < mp.getCount(); i++) {
    String s = getText(mp.getBodyPart(i));
    if (s != null)
        return s;
}
}
return null;
}

private String GetHeaders(Part p)
        throws MessagingException
{
    Enumeration<?> headers = p.getAllHeaders();
        //Get the mail Header
        String strHeader = "";
        while(headers.hasMoreElements())
            {
                Header h = (Header)headers.nextElement();
                strHeader = strHeader + "-" + h.getName() + " : " + h.getValue();
            }
        return strHeader;
}
private String getRecipients(Message msg)
        throws MessagingException
      {
        javax.mail.Address[] addrs = msg.getRecipients(Message.RecipientType.TO);
        if (addrs == null || addrs.length == 0)
            return null;

        String str = "";
        for (int i = 0; i < addrs.length; i++) {
            if (i != 0)
                str += ", ";
            String text = addrs[i].toString();
            str += removeChars(text);
        }

        return str;
      }
private String getFrom(Message msg)
        throws MessagingException
      {
        javax.mail.Address[] addrs = msg.getFrom();
        if (addrs == null || addrs.length == 0)
            return null;

        String str = "";
        for (int i = 0; i < addrs.length; i++) {
            if (i != 0)
                str += ", ";
            String text = addrs[i].toString();
            str += removeChars(text);
        }

        return str;
      }
private String removeChars(String text)
  {
    if (text == null)
        return null;

    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        if (c == '<' || c == '>' || c == '\'' || c == '\"' || c == '&')
            buf.append(' ');
        else
            buf.append(c);
    }
    return buf.toString();
  }}

Thanks
Sunil

A: I had this same issue and the cause a was conflict on library javax.mail, which is a transitive dependency of camel-mail and also of another library I had on my project.
To fix this, you'll have to exclude the conflicting dependency.
Finding the conflicting dependency with Maven
Run the following command and check if javax.mail is listed as a transitive dependency of another dependency.
Please be aware that other dependencies may import the same classes that exist on javax.mail, but on a different dependence, and this can cause the same issue.
On my case this happened with org.apache.geronimo.specs:geronimo-javamail_1.4_spec
mvn dependency:tree -Dverbose

Output snippet:
[INFO] +- org.apache.neethi:neethi:jar:2.0.4:compile
[INFO] |  +- org.apache.ws.commons.axiom:axiom-api:jar:1.2.7:compile
[INFO] |  |  +- org.apache.geronimo.specs:geronimo-javamail_1.4_spec:jar:1.2:compile

Excluding the dependency with Maven
Now that you've found which dependency imports the conflicting transitive dependency, add the exclusion to your pom.
    <dependency>
      <groupId>org.apache.neethi</groupId>
      <artifactId>neethi</artifactId>
      <version>${version}</version>
      <exclusions>
        <exclusion>
          <groupId>org.apache.geronimo.specs</groupId>
          <artifactId>geronimo-javamail_1.4_spec</artifactId>
        </exclusion>
      </exclusions>
    </dependency>


text:
Q: SQL Server : how to get the 1st or 2nd letter in a word? I have a bunch of UK postal codes as follow:
Sector
S1 1
RH16 9
NP23 9
N81 1

This is at a Sector Level. I can get a District level by just taking the first part of the Sector Level code before the space. ie: "S1" instead of "S1 1".
PARSENAME(REPLACE(c.Sector, ' ','.'),2)

And the Postal Area can be found by just using the letters: ie:"S" instead of "S1 1" or "RH" instead of "RH16 9".
I can write a query where it takes the first letter or the second letter, but how do I get it so that I can get the first 1 or 2 letters before I hit a number?
The final result should look something like:
Sector                PostArea
S1 1                     S
RH16 9                   RH
NP23 9                   NP
N81 1                    N

Thanks in advance for your help.

A: Declare @YourTable table (Sector varchar(50))
Insert Into @YourTable values
('S1 1'),
('RH16 9'),
('NP23 9'),
('N81 1')

Select *
      ,PostArea=Substring(Sector,1,patindex('%[0-9]%',Sector)-1)
 from @YourTable

Returns
Sector  PostArea
S1 1    S
RH16 9  RH
NP23 9  NP
N81 1   N

Edit:
To trap Non-Digit Strings
PostArea=case when patindex('%[0-9]%',Sector)=0 then '' else Substring(Sector,1,patindex('%[0-9]%',Sector)-1) end

A: select SUBSTRING(Sector,0,PATINDEX('%[0-9]%',Sector))