text:
Q: How can I get a street from a zipcode using google API I want to use google API to get the street address from a zip code so that when a user fills out his zip code in my registration form I then can automatically fill the street of the user.
Thanks

A: You cannot, because there can be multiple street addresses for any ZIP code.
For example, look up "Beverly Hills, CA 90210" in Google Maps. You can see there are streets such as "Lomitas Avenue" and "Sunset Boulevard" for this ZIP code.


text:
Q: com.amazonaws.services.s3.model.AmazonS3Exception: The XML you provided was not well-formed or did not validate against our published schema I am trying to delete content from an Amazon S3 bucket using deleteObjects method as below :
DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(s3BucketName);
        List<DeleteObjectsRequest.KeyVersion> keys = new ArrayList<>();
        //here s3 is the AmazonS3 object , bucketName is String Object & s3Filepath is also a string object.
        for (final S3ObjectSummary summary : S3Objects.withPrefix(s3, s3BucketName, s3FilePath)) {
            keys.add(new DeleteObjectsRequest.KeyVersion(summary.getKey()));
            System.out.println("Deleting the S3 object "+ summary);
        }
        deleteObjectsRequest.setKeys(keys);
        try {
            s3.deleteObjects(deleteObjectsRequest);
        } catch (Exception e) {
            System.out.print("Error when cleaning up S3-data: " + e);
        }

Reference has been taken from here : https://docs.aws.amazon.com/AmazonS3/latest/userguide/delete-multiple-objects.html
Weirdly , i'm getting below error message with catch block execution .
com.amazonaws.services.s3.model.AmazonS3Exception: The XML you provided was not well-formed or did not validate against our published schema (Service: Amazon S3; Status Code: 400; Error Code: MalformedXML; Request ID: someRequestID; S3 Extended Request ID: someExtendedRequestId=; Proxy: null)

Full StackTrace :
com.amazonaws.services.s3.model.AmazonS3Exception: The XML you provided was not well-formed or did not validate against our published schema (Service: Amazon S3; Status Code: 400; Error Code: MalformedXML; Request ID: SomeRequestId; S3 Extended Request ID: SomeExternalRequestId; Proxy: null)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1819) ~[AWSJavaClientRuntime-1.11.x.jar:?]
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleServiceErrorResponse(AmazonHttpClient.java:1403) ~[AWSJavaClientRuntime-1.11.x.jar:?]
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1372) ~[AWSJavaClientRuntime-1.11.x.jar:?]
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1145) ~[AWSJavaClientRuntime-1.11.x.jar:?]
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:802) ~[AWSJavaClientRuntime-1.11.x.jar:?]
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:770) ~[AWSJavaClientRuntime-1.11.x.jar:?]
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:744) ~[AWSJavaClientRuntime-1.11.x.jar:?]
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:704) ~[AWSJavaClientRuntime-1.11.x.jar:?]
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:686) ~[AWSJavaClientRuntime-1.11.x.jar:?]
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:550) ~[AWSJavaClientRuntime-1.11.x.jar:?]
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:530) ~[AWSJavaClientRuntime-1.11.x.jar:?]
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:5437) ~[AWSS3JavaClient-1.11.x.jar:?]
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:5384) ~[AWSS3JavaClient-1.11.x.jar:?]
    at com.amazonaws.services.s3.AmazonS3Client.deleteObjects(AmazonS3Client.java:2327) ~[AWSS3JavaClient-1.11.x.jar:?]

Can someone please help here , what wrong i'm doing ?
Is this due to size limit of S3 bucket that it can only delete these much number of records . Because there are 10 files present in S3 & one file can have 1000 records .
Thanks !

A: Try moving to the latest Amazon S3 Java V2 API, not the old V1 API.
Here is the latest code example for this use case.
https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/s3/src/main/java/com/example/s3/DeleteObjects.java
If you are not familiar with how to work with the Amazon S3 Java V2 API, see:
Get started with the AWS SDK for Java 2.x
UPDATE
I just tested this V1 code and it worked perfectly:
import com.amazonaws.AmazonServiceException;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;

import java.util.Arrays;

/**
 * Delete multiple objects from an Amazon S3 bucket.
 *
 * This code expects that you have AWS credentials set up per:
 * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html
 *
 * ++ Warning ++ This code will actually delete the objects that you specify!
 */
public class DeleteObjects {
    public static void main(String[] args) {
        final String USAGE = "\n" +
                "To run this example, supply the name of an S3 bucket and at least\n" +
                "one object name (key) to delete.\n" +
                "\n" +
                "Ex: DeleteObjects <bucketname> <objectname1> [objectname2, ...]\n";

     //   if (args.length < 2) {
      //      System.out.println(USAGE);
      ///      System.exit(1);
     //   }

        String bucket_name = "<bucketName>"; // args[0];
        String[] object_keys = {"book.pdf", "JUnit.pdf"}; // objects to delete

        System.out.println("Deleting objects from S3 bucket: " + bucket_name);
        for (String k : object_keys) {
            System.out.println(" * " + k);
        }

        final AmazonS3 s3 = AmazonS3ClientBuilder.standard()
                .withRegion(Regions.US_EAST_1)
                .build();

        try {
            DeleteObjectsRequest dor = new DeleteObjectsRequest(bucket_name)
                    .withKeys(object_keys);

            s3.deleteObjects(dor);
        } catch (AmazonServiceException e) {
            System.err.println(e.getErrorMessage());
            System.exit(1);
        }

        System.out.println("Done!");
    }
}

A: S3 delete operation support up to 1000 object deletes, however, I can't see any mechanism in your code to safeguards keys more than 1000 passing to S3.
Can you print the length of the keys list? If it going beyond 1000, limit it and pass multiple delete invocations to S3.
https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObjects.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you move a div element in jquery So basically i have a menu like this: [home, projects, sounds, contact], with a little circle on top of the menu. so i want it that when i click a menu item the little circle moves to the item(on top of it).
So something like this:

This is my jquery so far:
$(document).ready(function(){
  var position = 80;
    $('.navP').click(function(){
        // change all to black, then change the one I clicked to red
       $('#indicatorBar').animate({'margin-left':'+='+position+'px'}, 1000);
       $('.navP').css('color', 'white');
        $(this).css('color', 'red');
    });

});

My html:

 Ipalibo Whyte

Home

Projects

Sounds

Contact me

Css:
#indicatorBar{
  top: 0px;
  right: 60px;
  font-size: 7px;
  color: #B4FF47;

}

.menuContainer{
    position: fixed;

    width: 100%;
    top: 0%;
    left: 0%;
    bottom: 92%;
    opacity: 0.7;
  z-index:9;
  background: #16161F;

   animation: fadein 3s;
    -moz-animation: fadein 3s; /* Firefox */
    -webkit-animation: fadein 3s; /* Safari and Chrome */
    -o-animation: fadein 3s; /* Opera */

Examples will be greatly appreciated, Thanks a million !

A: Here's a quick demo based on the code that you provided: http://jsfiddle.net/k7ypa/
Basically, I'm just getting the position of the element that was clicked.
JavaScript:
 $('.navP').click(function () {
     // move dot
     var position = $(this).position().left + $(this).width()/2 - 5;
     $('#indicatorBar').animate({
         'margin-left': position + 'px'
     }, 1000);
     // change all to black, then change the one I clicked to red
     $('.navP').css('color', 'white');
     $(this).css('color', 'red');
 });

A: I suggest you use absolute positioning for #indicatorBar.
In the click event of a menu item, get the event's target (event.target where event is parameter in the function). Now add to the existing position the value of : [target's position().left + target's width() / 2], you will get your new position.
Note: Use jQuery's outerWidth() instead of width() if there are paddings/margins for the menu items. It looks like there are.

A: a quick and dirty answer is

*

*add a class to manage this little circle.

*when on of your menu object is select add this class to it and hide it from the previous one (you need to store in a variable the previous menu... or you can check which one is not selected and with this class)

and you're set


text:
Q: How to create test for control/form (*.designer.cs) to detect error on View Designer (Visual Studio) Given a control/form (*.designer.cs), when opening it on Visual Studio and right click "View Designer", often it won't load with following error message:
"To prevent possible data loss before loading the designer, the following errors must be resolved:"

The exact errors aren't relevant because we would like to create failing test for any errors that cannot load "View Designer".
Several solutions that I found but not quite work:

*

*Using EnvDTE library
This option will run Visual Studio and open solution and select *.designer.cs and "View Designer".
We don't prefer this solution because it requires Visual Studio installed on our test machines.

*Roslyn
Looks promising but by looking inside "View Designer" code i.e. Microsoft.VisualStudio.Design.Serialization.CodeDom, it doesn't seem to use Roslyn at all but instead, it uses the good old CodeDom

*IVSMDCodeDomProvider/IVsSolution/...
Visual Studio has several interfaces that seems to able to LoadDesigner without running Visual Studio.
But unfortunately those interfaces require the project to be 'visual studio package'  or vsix

*Reverse Engineer Microsoft.VisualStudio.Design to use DesignerSerializationManager/CodeDomSerializer/...
Seems to be the most likely solution but seems to be tedious work.
The question is any elegant/simpler solution?
Thank you in advance for any suggestions/helps.


text:
Q: QGIS changing map options distance units I want to change the map distance units option in QGIS from metres to centimetres.  I am currently using projection British National Grid EPSG 27700.  I would like the print composer to print a map out on the scale 1cm:5000cm.  Also how accurate is this projection relating to actual distance measured on the ground?  To the nearest metre (as EPSG 27700 projection is in metres?)?  Would there always be some margin of error in QGIS as it is open source software?

A: The distance-distortion in the map projection will be independent of the software (ignoring blunders); it is instead dependent on the projection used, and is also spatially variable.
Ordnance Survey National Grid is a Transverse Mercator projection chosen that the distances on the ground are identical to distances in the grid along two meridians: two lines of true
scale about 180 km to the east and west of the central meridian (2°W).  Away from these lines distance distortion is spatially variable.  For example:

*

*In London, UK, the OSNG distance distortion is ~200PPM (or 20cm
distortion per km)

*In Birmingham, UK, the OSNG distance distortion is
~400PPM (or 40cm distortion per km)

Note that this does not take into the height effect - the distance between two points on the ground increases the higher the elevation (about 1PPM per 6.4m height change).
For general mapping purposes this distortion between ground and grid may be considered entirely negligible; for precise engineering however this distortion is very significant and must be dealt with in some manner (for example, use of alternate projections: Snake Projection or Highways England Grids).

A: If you are using EPSG:27700 and all you want to do is measure distances any errors will depend on the accuracy of the data. If this is OS data the errors will be very small.


text:
Q: How to add data into ManyToMany field? I can't find it anywhere, so your help will be nice for me :) Here is that field:
categories = models.ManyToManyField(fragmentCategory)

FragmentCategory:
class fragmentCategory(models.Model):

        CATEGORY_CHOICES = (
                        ('val1', 'value1'),
                        ('val2', 'value2'),
                        ('val3', 'value3'),
                        )

        name = models.CharField(max_length=20, choices=CATEGORY_CHOICES)

Here is the form to send:
<input type="checkbox" name="val1" />
<input type="checkbox" name="val2" />
<input type="checkbox" name="val3" />

I tried something like this:
categories = fragmentCategory.objects.get(id=1),

Or:
categories = [1,2]

A: In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:
my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)

A: There's a whole page of the Django documentation devoted to this, well indexed from the contents page.
As that page states, you need to do:
my_obj.categories.add(fragmentCategory.objects.get(id=1))

or
my_obj.categories.create(name='val1')


text:
Q: Can't add function to MFC ActiveX I' trying to create ActiveX component mfc_activeX using Visual Studio 2010 c++ MFC library. After finishing wizard system compiles without errors.
After adding simple new method by clicking right mouse on Cmfc_activeXCtrl Add>>Add Function and filling in/out params form I got simple function:
int Cmfc_activeXCtrl::Hello(int i)
 {
 return 0;
 }

After this procedure I can't compile code anymore. I have messages:
Error   85  error MSB8011: Failed to register output. Please try enabling Per-user Redirection or register the component from a command prompt with elevated permissions.   C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets   744 6   mfc_activeX

86  IntelliSense: #error directive: Please use the /MD switch for _AFXDLL builds    c:\program files (x86)\microsoft visual studio 10.0\vc\atlmfc\include\afxver_.h 81  3

How to escape from these errors?

A: Visual Studio is running with a user that does not have permission to run regsvr32, which attempts to register the component after a successful build.
You can get around this by running Visual Studio as Administrator.
As for the 2nd error
#error Please use the /MD switch for _AFXDLL builds
Actually, I had to switch to another /Mx setting, and then switch back so the selection was in bold, it seems the IDE isn't updating properly.


text:
Q: Relationships and keys? I am still learning this stuff and am new to it so please go easy on me lol!
the first attributes SerialNum, PlayerID, and CompanyID are the primary keys i think, but i do not know how to find what other keys are involved here, or the relationships for these tables, this is where I just got stuck any help would be great.
Games (SerialNum, Title, Release, CompanyID, Price)

Genre (SerialNum, Title, Category, MaturityLvl)

Players (PlayerID, Gender, FirstName, LastName, SerialNum, Owned, Played)

Company (CompanyID, CompanyTitle, Address, PhoneNum)

A: As per your schema design, It seems that Games table is related to Company table using CompanyID attribute it has one-to-many relationship, like one company can have zero, one or many Games associated with it. If SerialNum is primary key of Games, then CompanyID is a foreign key
Similarly your Players table is associated with Games table with a SerialNum attribute.
You should read about E-R model and relational database,Here are some links for basics of relational database design
link1, link2


text:
Q: Why do I have poor video performance in browsers with a ATI HD3650 GPU?
Possible Duplicate:
How do I fix Flash issues?

I'm experiencing poor video performance on Youtube, both in Firefox and in Opera - Flash and HTML5 (all of the combinations). HTML5 is actually worse. Videos on Vimeos such as http://vimeo.com/channels/hd#33971928 play super smoothly sometimes, choppy other times. Usually smoothly for first 5 seconds, choppy later, sometimes recover.
Lenovo Thinkpad T500

Ubuntu 11.10 x64

AMD 3650 graphics, Catalyst 11.10

Unity 3D, Unity 2D

Flash 11,2,202,160 (IIRC the 64 bit one installed through Flash-Aid didn't make any difference)

It's frustrating as on Windows I haven't experienced this kind of issue on a decade old hardware.
It seems it got solved by a single change - switching from ATI HD3650 to integrated Intel graphics card. Now I can play smoothly even 1080p YT videos. But the performance is poor if switched back.


text:
Q: create list of all files in every subdirectories in bash I trying to write script in bash which will loop over all subdirectories, starring from given path, and will create list with md5 sums of all files in current directory.
I need something like ls -R, but I'm not sure how to start

A: There is a very easy way of doing this with find:
find . -type f -exec md5 {} \;

The command finds all files (-type f), and executes the command md5 on each file (-exec md5 {} \;).

A: There is also a program called tree, but you can simulate it with only shell builtins:
#!/bin/sh
DIR=${1:-`pwd`}
SPACING=${2:-|}
cd $DIR
for x in * ; do
    [ -d "$DIR/$x" ] &&  echo "$SPACING\`-{$x" && $0 "$DIR/$x" "$SPACING  " || \
    echo "$SPACING $x : MD5=" && md5sum "$DIR/$x"
done

Note it requires a full path argument (or none for current directory)
Its not as fast as find (though there are plenty of ways to speed it up that make the code more complicated to follow), but gives a graphical representation of the tree structure.
You can modify it to not follow symlinks by adding- && [ ! -L "$DIR/$x" ] or to only list directories: remove the || echo $SPACING $x


text:
Q: FOR cycle in a batch file I am trying to write a really basic batch file, but I am stuck on this problem. I have written:

for %n in (1 1 10) do pause

For what I understand, this should open a terminal window and pause 10 times. The problem is that when I run the batch, the terminal window only flashes open and doesn't do anything. What am I doing wrong?

A: Your first problem is the single %.  That's the right syntax for running this directly at the command line, but in a batch file you need to use %%.  See help for for details.
Additionally, the code you wrote will only call pause three times:  once for the 1, once for the second 1, and once for the 10.  If you want to loop from 1 to 10 stepping by 1, you need to use /l:
for /l %%n in (1 1 10) do pause


text:
Q: How to use Unicode symbols on webpages? I'm using some Unicode symbols on a webpage I'm making. For purposes of this example, let's say it's this guy: '☺'.
As I understand it, under the correct implementation of CSS, you can set any font you want, and if it runs into a character that is not present in that font, it will start falling back through the font-family backup choices until it finds one that works.
In light of that, I have my font-family set up like this in css:
font-family: Tahoma, Helvetica, "Arial Unicode MS", sans-serif

My rationale is that Tahoma comes bundled with Windows. However, I found out online that only some versions of Windows' bundled Tahoma had Unicode support. Helvetica is a font that is similar to Tahoma for Macs. "Arial Unicode MS" comes bundled with Office 2000 and up and definitely support Unicode. San-serif is the fallback in all cases that should also hopefully support Unicode.
For the most part, this works well. However, as it is wont to do, Internet Explorer seems to be ruining my well-laid plan. I can't figure out what the pattern is, as I'm seeing it on one computer running Vista with IE8, and another on Windows XP with IE7, but it works fine on my development machine with Win7 with IE8/IE7 Tester/IE6 Tester. I have found the claim on some obscure webpages that on old versions of IE, it will only look for the first font that it has, and then use that for everything, even if that font is missing a given symbol, but this doesn't explain why it's happening on Vista/IE8. Thus, my lovely Unicode symbols turn up as boxes to some, but not all IE users.
What's the recommended way to be handling Unicode symbols on the web? Are they just not usable for projects where wide browser compatibility is needed? Should I be looking to include code specifically to handle old IE? Are there any other gotcha situations or platforms I should be worrying about?
Edit: Updated with new information on systems this is failing on.

A:
only some versions of Windows' bundled Tahoma had Unicode support

It's not really "Unicode support". Tahoma supports Unicode in as much as it has Unicode code point lookup tables. That doesn't mean you get a glyph for every character defined by Unicode... actually almost no font has glyphs for every character.
No version of Tahoma includes a glyph for U+263A White Smiling Face, so your code is a test of font fallback capabilities, something IE (especially IE6) is bad at, compared to other browsers. A more common Windows-bundled font that does include U+26A3 is plain Arial (not "Arial Unicode"), since version 3.00 (included in WinXP).

A: You can use IE overrides in your CSS file to create different behavior for older versions of internet explorer. The over-rides are # and _ before each statement depending on the version of internet explorer.
Put an _ before each statement in your css for internet explorer 6.0 and earlier
Put a # before each statement in your css for internet explorer only
Example:
 //Normal
    font-family: Tahoma, Helvetica, "Arial Unicode MS", sans-serif;
    //  IE 6.0 Earlier
    _font-family: Tahoma, Helvetica, sans-serif;
    // IE Only
    #font-family: Tahoma, Helvetica, "Arial Unicode MS", sans-serif;

A:
As I understand it, under the correct implementation of CSS, you can set any font you want, and if it runs into a character that is not present in that font, it will start falling back through the font-family backup choices until it finds one that works.

Unfortunately, that's not how it works in Internet Explorer, at least not in older versions. These browsers only use the first font family available on a system. One approach I sometimes use is to add a separate CSS class for Unicode characters:
[Unicode character]

.unicode { font-family: "Lucida Sans Unicode", ..., sans-serif; }

I found Lucida Sans Unicode to be a good choice as it's preinstalled on all Windows versions since Windows 98. Its Unicode support isn't as complete as you'd expect, though.
But I started to prefer icon fonts. They have the advantage that the glyphs always look the same regardless of the font actually used. As John Slegers mentions in his answer, there are great online tools to create your own customized icon font.


text:
Q: How do I cast from char** to char* in C? I have this problem:
I have a matrix in which stores diferent characters. Now I have to compare these characters to another one, but when compiling, it says strcmp recives char* and I have char**. So, how do I cast it?
This is the code I have:
For the matrix:
for (i = 0; i < x; i++){
        for (j = 0; j < y; j++){
            if (!fscanf(fol, "%c", &mat[i][j])){
                break;}
            //printf("%c", mat[i][j]);
            }
        }

The part I have problems with:
    for (x = 0; x < largo; x++){
        for (y = 0; y < ancho; y++){
            char *charcha;
            strcpy (charcha, mat[x][y]);

            //char *charcha = "%c", mat[x][y];
            int algo = strcmp(charcha, "0");
            if (algo == 0){
                printf (" ");
                }
            else{
            printf("%c", mat[x][y]);}
            }
            }

    printf ("\n");

I tried with strcpy, but it failed as well :C
Thanks

A: If you want to compare strings, use:
for (x = 0; x < largo; x++)
{
   if ( strcmp(mat[x], "0") == 0 )
   {
      // Do whatever.
   }
   else
   {
      // Do whatever.
   }
}

If you want to compare characters, use:
for (x = 0; x < largo; x++)
{
   for (y = 0; y < ancho; y++)
   {
      if (mat[x][y] == '0' )
      {
         // Do whatever.
      }
      else
      {
         // Do whatever.
      }
   }
}

A: To go from char** to char* use *
example:
char ** twoLevel = ..
char * oneLevel = *twoLevel;


text:
Q: What is the URL in opeshift for javascript? I want to use external javascript libraries in openshift hosted account ? What is the URL I should refer to get the javascript files. ( I have stored the javascript files inside the project)?

A: I think we can refer js files using the local url system. As a example if you have those files in the same location you can refer using {path to file}/javascriptfile.js style
<link rel="stylesheet" type="text/css" href="../../libraries/dhtmlxCalendar/dhtmlxCalendar/codebase/dhtmlxcalendar.css">
<link rel="stylesheet" type="text/css" href="../../libraries/dhtmlxCalendar/dhtmlxCalendar/codebase/skins/dhtmlxcalendar_dhx_skyblue.css">
<script src="../../libraries/dhtmlxCalendar/dhtmlxCalendar/codebase/dhtmlxcalendar.js"></script>


text:
Q: Dojo - How to set "label" of togglebutton inside a grid from row.data.SOMEFIELD value? i'm new to Dojo.
I have a "FullEditable" grid, with many columns, and one of them is a widget, it's a ToggleButton. This grid is used to show details of a purchase, so every line represents a product sold. When i click a button inside one of the columns it launches the product (dialog) browser and then the data of that product is passed to the grid. After some work i managed to display the button and being able to set it's label accordingly to the row.data.FIELD value received from that dialog.
But now i am editing that purchase and i need to be able to do the same, to be able to load the data from the preloaded array with data ("detalle") (as it's label) into the togglebutton, but nothing seems to work, not even the direct assignment of the widget or the row data or anything.
Here's a fragment of my code:
  var grid = this;
  var selectedRow = grid.row(i);
  var cell = grid.cell(selectedRow, 'Moneda');
  selectedRow.Moneda = detalle.MonedaItem; //didn't work
  if(cell.row !== null && cell.row !== undefined && cell.row.data !== null && cell.row.data !== undefined)
    cell.row.data.Moneda = detalle.MonedaItem; //didn't work

    if(cell.element !== null && cell.element !== undefined){
      cell.element.innerText = detalle.MonedaItem; //didn't work
      cell.element.textContent = detalle.MonedaItem; //didn't work

      if(detalle.MonedaItem === 'UF')
        cell.element.widget.set('checked', true);
      if(detalle.MonedaItem === 'CLP')
        cell.element.widget.set('checked', false);

      cell.element.widget.set('label', detalle.MonedaItem); //didn't work
      cell.element.widget.set('value', detalle.MonedaItem); //didn't work
    }
  }

Whenever i set the value through the change event with "cell.element.widget.set('checked', boolean);" i get an error message from the editor, when it tries to get a cell but the variable is null, so it crashes.
The values of "label" and "value" of the widget, row.data en cell are perfectly set, BUT the grid DISPLAYS the "emptyValue" value of the widget and not the one that is actually set.

A: AFAIK, best way to change the grid data is to update the store/ collection that is associated with the grid and just invoke grid.refresh(). The new data will be loaded automatically.
The statement cell.row.data.Moneda = detalle.MonedaItem is actually changing the data in your store. Just refresh the grid after this and you are done!
Never try to set something in grid DOM element directly. Always work with store, renderCell and renderColumn. This will ensure consistency in store and grid attributes that reference the store.

A: I finally managed to get what i need through renderCell like this:
,{
      id: 'Moneda',
      field: 'Moneda',
      label: "Moneda",
        renderCell: function (object, value, node, options) {
          try {
            var button = new ToggleButton({
              node: node,
              isWidgetInGrid: true,
              parameterName: 'codigoMoneda',
              label: object.Moneda,
              showLabel: true,
              onChange: function(newValue){
                var grid = this.getParent();
                var row = grid.row(this.node);
                var data = row.data;
                if(this.get('label') === 'CLP')
                {
                  data.Moneda = 'UF';
                  this.set('label','UF');
                  this.set('value', 'UF');
                }
                else
                {
                  data.Moneda = 'CLP';
                  this.set('label','CLP');
                  this.set('value', 'CLP');
                }
                grid.getParent().getParent()._calcularTotales();
              }
            });

            node.appendChild(button.domNode);
          }
          catch (ex) {
            Debug.log(this.declaredClass, arguments, ex);
          }
        },
      emptyValue: 'CLP',
      autoSave: true
    }


text:
Q: Use Azure SQL db with a reactjs application using Nodejs I have a basic reactjs application which has a form that I want on submit, should store the value of input elements(text-boxes, selects and radio buttons), to store the data to the database in azure SQL DB. The react app (front-end only yet) is deployed using the Azure App service.
I have been looking for ways on how to approach this, but the more i explored the more i got confused. The official documentation suggests using tedious, and some sources recommend using express with sequelize, and a few more.
I'm looking for a direction on how to approach this. I, being a beginner in this, am open to suggestions or if someone can direct me to a source that might be of some help.

A: It sounds like you want to directly connect Azure SQL Database from the front-end of your ReactJS App in a browser. There is a similar SO thread How to connect to SQL Server database from JavaScript in the browser? had been answered for this scenario. But it's impossible for working in modern browsers, because the solution using ActiveXObject only works in the old IE browser.
So a backend server using express for NodeJS or other framework in other language is necessary to get the data submitted from the frontend page of ReactJS page and store to Azure SQL Database using tedious for NodeJS or other ORM framework for other language.
For Node.js, please refer to the offical tutorial Node.js Driver for SQL Server to know how to operate SQL Server at the Node backend.


text:
Q: Compare two values in document and display the common values in each row in result I have documents in which am storing two main objects scan and result, I want the output such that in result I get separate row for each match of scan.location and result.location.
Date:
{
    "_id" : ObjectId("6024d02a1bf5152b44baf521"),
    "scan" : {
        "customerId" : "e2565eac-2086-48fc-ba18-dbce74602e22",
        "customerGenderSelection" : "F",
        "scanQuery" : {
            "service" : "MA",
            "date" : "08-Nov-2020",
            "locations" : [
                {
                    "locationId" : "0023",
                    "locationName" : "dobson"
                },
                {
                    "locationId" : "0001",
                    "locationName" : "shea"
                }
            ]
        },
        "sessionId" : "70511849-97f8-4318-a96e-bb3a573c52ea",
    },
    "result" : [
        {
            "employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
            "time" : "11:00",
            "locationId" : "0023"
        },
        {
            "employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
            "time" : "12:00",
            "locationId" : "0023"
        },
        {
            "employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
            "time" : "12:30",
            "locationId" : "0023"
        },
        {
            "employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
            "time" : "13:00",
            "locationId" : "0001"
        }
    ]
}

I want result where scan.scanQuery.locations.locationId == result.locationId.  So expecting a result in the below format:
Expected Response:
{
    "scan" : {
        "customerId" : "e2565eac-2086-48fc-ba18-dbce74602e22",
        "customerGenderSelection" : "F",
        "scanQuery" : {
            "service" : "MA",
            "date" : "08-Nov-2020",
            "locations" : [
                {
                    "locationId" : "0023",
                    "locationName" : "dobson"
                }
            ]
        },
        "sessionId" : "70511849-97f8-4318-a96e-bb3a573c52ea",
    },
    "result" : [
        {
            "employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
            "time" : "11:00",
            "locationId" : "0023"
        },
        {
            "employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
            "time" : "12:00",
            "locationId" : "0023"
        },
        {
            "employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
            "time" : "12:30",
            "locationId" : "0023"
        }
    ]
},
{
    "scan" : {
        "customerId" : "e2565eac-2086-48fc-ba18-dbce74602e22",
        "customerGenderSelection" : "F",
        "scanQuery" : {
            "service" : "MA",
            "date" : "08-Nov-2020",
            "locations" :
                {
                    "locationId" : "0001",
                    "locationName" : "shea"
                }
            ]
        },
        "sessionId" : "70511849-97f8-4318-a96e-bb3a573c52ea",
    },
    "result" : [
        {
            "employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
            "time" : "13:00",
            "locationId" : "0001"
        }
    ]
}

Any suggestions or ideas would be helpful.

A: Try this:
db.locations.aggregate([
    {
        $unwind: "$scan.scanQuery.locations"
    },
    {
        $addFields: {
            result: {
                $filter: {
                    input: "$result",
                    as: "item",
                    cond: {
                        $eq: ["$scan.scanQuery.locations.locationId", "$$item.locationId"]
                    }
                }
            }
        }
    }
]);

Output:
{
  "_id": ObjectId("6024d02a1bf5152b44baf521"),
  "scan": {
    "customerId": "e2565eac-2086-48fc-ba18-dbce74602e22",
    "customerGenderSelection": "F",
    "scanQuery": {
      "service": "MA",
      "date": "08-Nov-2020",
      "locations": {
        "locationId": "0023",
        "locationName": "dobson"
      }
    },
    "sessionId": "70511849-97f8-4318-a96e-bb3a573c52ea"
  },
  "result": [
    {
      "employeeId": "224f55b2-27bc-4e34-8249-a8d201540ac2",
      "time": "11:00",
      "locationId": "0023"
    },
    {
      "employeeId": "224f55b2-27bc-4e34-8249-a8d201540ac2",
      "time": "12:00",
      "locationId": "0023"
    },
    {
      "employeeId": "224f55b2-27bc-4e34-8249-a8d201540ac2",
      "time": "12:30",
      "locationId": "0023"
    }
  ]
},
{
  "_id": ObjectId("6024d02a1bf5152b44baf521"),
  "scan": {
    "customerId": "e2565eac-2086-48fc-ba18-dbce74602e22",
    "customerGenderSelection": "F",
    "scanQuery": {
      "service": "MA",
      "date": "08-Nov-2020",
      "locations": {
        "locationId": "0001",
        "locationName": "shea"
      }
    },
    "sessionId": "70511849-97f8-4318-a96e-bb3a573c52ea"
  },
  "result": [
    {
      "employeeId": "224f55b2-27bc-4e34-8249-a8d201540ac2",
      "time": "13:00",
      "locationId": "0001"
    }
  ]
}


text:
Q: how to make a wplang for network fill automatically I made a new network in my website its default language was ar when I add a new website it does not fill it WPLANG automatically, I made it manually but how to make it fill automatically.

A: OK Thanks all I found the answer
update_option( 'WPLANG', 'ar' );


text:
Q: Error when receive json only Android 4.0 I connect from my Android device to Webservice, then send parameter and get json.
It ok when i test with android API < 4.0 ex 2.3.3
When i test with another device, it's api is 4.0.3, 4.0.4
then I can not receive json.
This is my code
json = getJson("http://search.twitter.com/search.json?result_type=recent&rpp=3&q=iphone");

private String getJson(String uri) {

    String json = null;
    try {
        URL url = new URL(uri);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        Log.d(TAG,"1");
        // conn.setConnectTimeout(10 * 1000); //6s
        if (conn.getResponseCode() == 200) {
            // get successfull
            // read Json
            Log.d(TAG,"2");
            BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
            int len = 0;
            byte[] buf = new byte[1024];
            StringBuffer stringBuffer = new StringBuffer();
            while ((len = in.read(buf)) != -1) {
                String s = new String(buf, 0, len);
                stringBuffer.append(s);
            }
            Log.d(TAG,"3");

            json = stringBuffer.toString();
            Log.d(TAG,json);
        }
    } catch (Exception e) {
        Log.e(TAG, "error get json :" + e.toString());
        json = null;
    }
    return json;
}

Error.
11-20 19:42:22.555: E/TEST(29097): error get json :android.os.NetworkOnMainThreadException

A: it works on your 2.3.3 because the NetworkOnMainThreadException has been in android since api 11
You need to move the part that uses the HTTP connection to another thread, or better use AsyncTask..
 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }
}

A: Call the webservice from Asynctask<>. The problem will solved.


text:
Q: Retornar elemento contido em tag no BeautifulSoup Site: Malha do metrô do município de São Paulo.
Objetivo: Scraping do nome das estações de cada linha.
Dificuldade: Não estou conseguindo isolar os nomes, por exemplo: Jabaquara, Liberdade...
from bs4 import BeautifulSoup
from urllib.request import urlopen
html = urlopen('http://www.metro.sp.gov.br/sua-viagem/trajeto/')
soup = BeautifulSoup(html, 'html.parser')

linha_1 = soup.findAll(class_='linha-1-azul')
linha_1

#[

Jabaquara

Conceição

São Judas

Saúde

Praça da Árvore

Santa Cruz

Vila Mariana

Ana Rosa

Paraíso

Vergueiro

São Joaquim

Japão-Liberdade

Sé

São Bento

Luz

Tiradentes

Armênia

Portuguesa-Tietê

Carandiru

Santana

Jardim São Paulo-Ayrton Senna

Parada Inglesa

Tucuruvi

]

A: Caso seu objetivo seja extrair o conteúdo textual de um documento ou conteúdo textual sob uma tag, você pode usar o método get_text() que retorna todo o conteúdo textual do documento ou sob uma tag:
from bs4 import BeautifulSoup
from urllib.request import urlopen
html = urlopen('http://www.metro.sp.gov.br/sua-viagem/trajeto/')
soup = BeautifulSoup(html, 'html.parser')

linha_1 = soup.findAll(class_='linha-1-azul')

#Itera por cada elemento e obtido na consulta...
for e in linha_1:
  print(e.get_text())                 #...extrai e imprime o conteúdo textual sob o elemento.

 Jabaquara
 Conceição
 São Judas
 Saúde
 Praça da Árvore
 Santa Cruz
 Vila Mariana
 Ana Rosa
 Paraíso
 Vergueiro
 São Joaquim
 Japão-Liberdade
 Sé
 São Bento
 Luz
 Tiradentes
 Armênia
 Portuguesa-Tietê
 Carandiru
 Santana
 Jardim São Paulo-Ayrton Senna
 Parada Inglesa
 Tucuruvi

Teste o código no Repl.it


text:
Q: Fill Postgres column with highest available accuracy based on other column-id/table I have a pretty large database with 4 tables:

*

*post (200 Million)

    CREATE TABLE public."post" (
        origin_id int REFERENCES public."origin"(origin_id),
        post_guid text,
        PRIMARY KEY (origin_id, post_guid),
        post_latlng geometry(Point, 4326), --only if lat/lng coordinates are available, otherwise add location information as in place, city or country table
        place_guid text,
        FOREIGN KEY (origin_id, place_guid) REFERENCES public."place"(origin_id, place_guid),
        city_guid text,
        FOREIGN KEY (origin_id, city_guid) REFERENCES public."city"(origin_id, city_guid),
        country_guid text,
        FOREIGN KEY (origin_id, country_guid) REFERENCES public."country"(origin_id, country_guid),
    );

*

*place (1 Million)

    CREATE TABLE public."place" (
        origin_id int REFERENCES public."origin"(origin_id),
        place_guid text,
        PRIMARY KEY (origin_id, place_guid),
        geom_center geometry(Point, 4326)
    );

*

*city (500k) - definition synonymous to place

*country (200) - definition synonymous to place

Index:
CREATE UNIQUE INDEX idx_post ON public.post(origin_id, post_guid);
CREATE UNIQUE INDEX idx_post_place ON public.place(origin_id, place_guid);

The Table post is most important, it has among others the columns "origin_id" (integer, either 1, 2 or 3) and "post_guid" which together function as the Primary key. Similarly, place has "source_id" and "place_guid" etc.
In table post, I have 4 columns:

*

*post_latlng

*place_guid

*city_guid

*country_guid

I don't always have the lat/lng coordinates for all posts. In these cases, post_latlng should be substituted by location information (of lower accuracy) from place, city or country tables.
I am not there yet to apply triggers to do this automatically, but even manually filling this information takes too long. For example, if I add a new geocode for a place that is already in the place-table, I do the following:
insert_sql = '''
            INSERT INTO "place" (origin_id, place_guid, geom_center)
            VALUES (%s,%s,ST_GeomFromText(%s,4326))
            ON CONFLICT (origin_id,place_guid)
            DO UPDATE
            SET geom_center = EXCLUDED.geom_center;
            '''
cursor.execute(insert_sql,(source_origin_id,iPlaceid,iCoordinates_WKT))

..afterwards, I run the following code to update posts with this place:
update_sql = '''UPDATE "post"
                SET post_latlng = ST_GeomFromText(%s,4326)
                WHERE (origin_id, place_guid) IN (VALUES (%s,%s));
            '''
cursor.execute(update_sql,(iCoordinates_WKT,source_origin_id,iPlaceid))

But this takes forever (1 Minute for 1 location, when I need to update 200k locations). Similarly, the other way around: if I add thousands of new posts and (in case no specific coordinates are available) looking up coordinates from tables place, city or country is very slow.
I have the feeling, given my limited experience with databases, I am generally following the wrong approach. What would be a best practice for my example, substituting a missing value (e.g. lat/lng coordinates) from other columns/tables in specific order?


text:
Q: External JavaScript accessing html elements and assigning to a variable I am starting out using JavaScript and I cannot understand why I cannot assign a HTML attribute description to a variable in an external JavaScript function. It works ok when inside the HTML page but will not work in the external script as the variable I am assigning tests out as undefined.
function NewFunction() {

  var x = document.getElementById("Year").href;
  //var x="hello"
  if (x === undefined) {
      alert("x is undefined");
  } else {
      alert("x is defined");
  }
 document.getElementById("demo").innerHTML = x;

I can change demo if I use the var x="hello".  However if I try to assign
x the document.getElementById("Year").href it reports back as undefined. This code works well inside the source page as a local script.
I am missing something as it seems you cannot assign a variable, information read from the HTML page.
What am I missing?
Thanks

A: Likely problem in the time moment when script is loaded. Just call your function when DOM is ready ( see event DOMContentLoaded for more info).
document.addEventListener("DOMContentLoaded", function(event) {
  NewFunction()
});

Below is your code ( with func calling on DOM Ready ) and everything seems to work fine. Try to compare with our actual code.

function NewFunction() {
  var x = document.getElementById("Year").href;
  //var x="hello"
  if (x === undefined) {
      alert("x is undefined");
  } else {
      alert("x is defined");
  }
 document.getElementById("demo").innerHTML = x;
};
document.addEventListener("DOMContentLoaded", function(event) {
  NewFunction()
});
123

123

Good Luck !

A: You have to put


text:
Q: Paper Trail: create a version on parent whenever associated model changes? I'm working on a Rails app where I need to show the audit trail on a Record, which has_many Data. I have paper_trail on my Record, and associated Datum models, and it is saving versions of them just fine.
However, what I need is for one version for Record to be created whenever one or more associated Data are changed. Currently, it creates versions on each Datum that changes, but it only creates a version of the Record if the Record's attributes change; it's not doing it when the associated Data change.
I tried putting touch_with_version in Record's after_touch callback, like so:
class Record < ActiveRecord::Base
  has_many :data

  has_paper_trail

  after_touch do |record|
    puts 'touched record'
    record.touch_with_version
  end

end

and
class Datum < ActiveRecord::Base
  belongs_to :record, :touch => true

  has_paper_trail

end

The after_touch callback fires, but unfortunately it creates a new version for each Datum, so when a Record is created it already has like 10 versions, one for each Datum.
Is there a way to tell in the callbacks if a version has been created, so I don't create multiples? Like check in one of the Record callbacks and if Datum has already triggered a version, don't do any more?
Thanks!

A: This works for me.
class Place < ActiveRecord::Base
  has_paper_trail
  before_update :check_update

  def check_update
    return if changed_notably?

    tracking_has_many_associations = [ ... ]
    tracking_has_has_one_associations = [ ... ]

    tracking_has_many_associations.each do |a|
      send(a).each do |r|
        if r.send(:changed_notably?) || r.marked_for_destruction?
          self.touch
          return
        end
      end
    end
    tracking_has_one_associations.each do |a|
      r = send(a)
      if r.send(:changed_notably?) || r.marked_for_destruction?
        self.touch
        return
      end
    end
  end
end


text:
Q: Maximum lifetime for nonce In our project we allow users to buy a coupon ( WooCommerce product ) for some service. We save every coupon as a custom post type with all the customer data inserted during purchase.
We then via email send a link to download the coupon in PDF. We use WooCommerce PDF Invoices & Packing Slips plugin for generating PDFs and links are generated in this manner:
$url = wp_nonce_url( admin_url( 'admin-ajax.php?action=generate_wpo_wcpdf&template_type=Coupon-PDF&order_id=' . $order->id ), 'generate_wpo_wcpdf' );

The problem is obviously the lifetime of nonce. We would need to link to be active at least one year, meaning that we should set the nonce to 2 years. I did quite some research but could not find proper information.
Question is: what is the maximum lifetime for nonce?
Additionally: It would be great it somebody shared their experiences with extending nonce lifetime by a lot, like in this case.

A: As time varies, WordPress needs to allow for a nonce generated at 10:01 AM to be valid at 10:02 AM. It does this by using a time "tick" instead of the actual time, which is generated in two steps:

*

*First divide the lifespan of a nonce, in seconds, by two

*Divide the Unix timestamp by the above value, and round it up using
ceil()

By default, the lifespan is 86400 seconds, or 24 hours (and can be adjusted with the nonce_life filter). Half this, 12 hours, is 43200.
Nonce time caveat
Based on a 24-hour lifespan, a "tick" as calculated above is the same for each 12-hour span of a day. At 07:45 AM the "tick" is the same as 9:30 AM and 11:59 AM. But it will be one less than a "tick" created at 12:01 PM (a new 12-hour span within the day) or 15:30 PM.
Because of this, a WordPress nonce is not valid for exactly 24-hours from the moment that it was created, but up to 24 hours, depending how far into a 12-hour period a nonce was created.
Further reading: https://medium.com/myatus/wordpress-caching-and-nonce-lifespan-bb357d984da9


text:
Q: Android retrieve text from current view I have an Android application with a ViewPager that displays motivational messages. I am targeting Oreo and later
This is the view I'm referring to

I have implemented the "Share Quote" button and it works fine. When I click on the button the following method is called and I can retrieve the displayed quote without issue:
 private void shareQuote() {

    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);

    sharingIntent.setType("text/plain");
    sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

    // Add data to the intent, the receiving app will decide
    // what to do with it.
    sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Good Vibrations");
    sharingIntent.putExtra(Intent.EXTRA_TEXT, getCurrentQuote());
    //sharingIntent.putExtra(Intent.EXTRA_TEXT, "http://www.codeofaninja.com");
    startActivity(Intent.createChooser(sharingIntent, "Share quote!"));

}

The above code calls the getCurrentQuote() method . which returns the displayed info no problem:
private String getCurrentQuote() {
    String currentQuote = "currentQuote";

    FragmentManager fm = getSupportFragmentManager();

    if (fm != null) {
        currentQuote = "NewCurrentQuote";
        List<Fragment> fragments = fm.getFragments();
        currentQuote = ""+fragments.size();

        for(int i = fragments.size() - 1; i >= 0; i--){

            //Kept getting the following quote...hence the "-1" below...that is for the current quote
            Fragment fragment = fragments.get(i - 1);

            if(fragment != null) {
                // found the current fragment
                currentQuote = "fragment != null";
                // if you want to check for specific fragment class
                if(fragment instanceof QuoteFragment) {

                    currentQuote = fragment.getArguments().getString("quote") + " ~ " + fragment.getArguments().getString("author");

                    setCurrentQuoteString(currentQuote);
                }
                break;
            }
        }

    }

    return currentQuote;
}

I have an alarm manager that sends notifications and I am trying to populate those notifications with the same current quote functionality as above. However, I am getting 0 from here:
currentQuote = ""+fragments.size();
When not calling this via a button click. Somehow I do not have the relevant "context" when not doing this via the GUI as the share quote button does.
So the short question is when I try create a Service or intent Service to populate the notification like this:
.setContentText(getCurrentQuote())

I get 0 <-- essentially a null from the getQuotes method, but the same functionality works fine when using the "shareQuote()" method above.
How do I populate a notification automatically with the currently displayed text without some GUI interaction as is the case with the share quote button?
public class QuoteViewPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;

    public QuoteViewPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {

        return this.fragments.get(position);
    }

    @Override
    public int getCount() {
        return this.fragments.size();
    }
}

A: You can paste the following class as it is:
public class PreferenceHelper {

    private static final String PREF = "MyAppPreference";

    private static SharedPreferences getSharedPreference(Context mContext) {
        return mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE);
    }

    private static SharedPreferences.Editor getSharedPreferenceForEdit(Context mContext) {
        return getSharedPreference(mContext).edit();
    }

    public static String getCurrentQuote(Context mContext) {
        return getSharedPreference(mContext).getString("CurrentQuote", "");
    }

    public static void setCurrentQuote(Context mContext, String mQuote) {
        getSharedPreferenceForEdit(mContext).putString("CurrentQuote", mQuote).apply();
    }
}

And use it wisely like:
To get Current Quote: (Call this method when you want to get a current quote)
PreferenceHelper.getCurrentQuote(mContext);

To save Current Quote: (Call this method to save your current quote, better to put this line when you set text into TextView)
PreferenceHelper.setCurrentQuote(mContext, currentQuote);

Hope it will help you. Thank you.

A: Store quotes into preference when page changed
your_pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //get your item form list by position and store your quotes in Preference
                SharedPreferences pref=getApplicationContext().getSharedPreferences("your_pref", Context.MODE_PRIVATE);
                pref.edit().putString("quote","selected_quoate").commit();

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

Share Quotes:
 private void shareQuote() {

    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);

    sharingIntent.setType("text/plain");
    sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

    // Add data to the intent, the receiving app will decide
    // what to do with it.

     SharedPreferences pref=getApplicationContext().getSharedPreferences("your_pref", Context.MODE_PRIVATE);
    sharingIntent.putExtra(Intent.EXTRA_SUBJECT, pref.getString("quote");
    sharingIntent.putExtra(Intent.EXTRA_TEXT, getCurrentQuote());
    //sharingIntent.putExtra(Intent.EXTRA_TEXT, "http://www.codeofaninja.com");
    startActivity(Intent.createChooser(sharingIntent, "Share quote!"));

}

Notification
SharedPreferences pref=getApplicationContext().getSharedPreferences("your_pref", Context.MODE_PRIVATE);

 .setContentText(pref.getString("quote")

FYI : Store 0th or initial selected position quote in Preference when open this view on each open


text:
Q: How to use includes with 3 models w ActiveRecord? Given the following model:
Room (id, title, suggested)
  has_many :room_apps, :dependent => :destroy

RoomApp (room_id, app_id, appable_id, appable_type)
  belongs_to :appable, :polymorphic => true
  has_many :colors, :as => :appable
  has_many :shirts, :as => :appable

Colors (room_id)
  belongs_to :room
  belongs_to :room_app
  belongs_to :app

What I want to do is get all the suggested rooms. In my controller I have:
@suggested_rooms = Room.includes(:room_apps).find_all_by_suggested(true).first(5)

Problem here is the includes is not working and the db is being hit several times:
Processing by PagesController#splash as HTML
  Room Load (0.6ms)  SELECT "rooms".* FROM "rooms" WHERE "rooms"."suggested" = 't' ORDER BY last_activity_at DESC
  RoomApp Load (0.6ms)  SELECT "room_apps".* FROM "room_apps" WHERE "room_apps"."published" = 't' AND ("room_apps".room_id IN (5,4,3)) ORDER BY created_at DESC
  RoomApp Load (5.9ms)  SELECT "room_apps".* FROM "room_apps" WHERE "room_apps"."published" = 't' AND "room_apps"."id" = 6 AND ("room_apps".room_id = 5) ORDER BY created_at DESC LIMIT 1
  Color Load (0.4ms)  SELECT "colors".* FROM "colors" WHERE "colors"."id" = 5 LIMIT 1
  RoomApp Load (0.6ms)  SELECT "room_apps".* FROM "room_apps" WHERE "room_apps"."published" = 't' AND "room_apps"."id" = 5 AND ("room_apps".room_id = 4) ORDER BY created_at DESC LIMIT 1
  Color Load (0.4ms)  SELECT "colors".* FROM "colors" WHERE "colors"."id" = 4 LIMIT 1
  RoomApp Load (0.4ms)  SELECT "room_apps".* FROM "room_apps" WHERE "room_apps"."published" = 't' AND "room_apps"."id" = 4 AND ("room_apps".room_id = 3) ORDER BY created_at DESC LIMIT 1
  Color Load (0.3ms)  SELECT "colors".* FROM "colors" WHERE "colors"."id" = 3 LIMIT 1

Is something setup incorrectly? I'd like to be able to get suggested rooms and use includes for room_apps with one hit versus currently where it's a hit for every room.
Ideas? Thanks

A: I think you'll either want to use the full Rails3 arel interface like so:
@suggested_rooms = Room.includes(:room_apps).where(:suggested => true).limit(5)
Or do this for Rails 2.3x:
@suggested_rooms = Room.find_all_by_suggested(true, :include=>:room_apps).first(5)

A: Did some digging around and I think I have an idea what's going on.
include by default does not generate a single query. It generates N queries, where N is the number of models being included.
ruby-1.9.2-p180 :014 > Room.where(:suggested => true).includes(:room_apps => :colors)
  Room Load (0.5ms)  SELECT "rooms".* FROM "rooms" WHERE "rooms"."suggested" = 't'
  RoomApp Load (0.8ms)  SELECT "room_apps".* FROM "room_apps" WHERE "room_apps"."room_id" IN (1)
  Color Load (0.5ms)  SELECT "colors".* FROM "colors" WHERE "colors"."room_app_id" IN (1)

One exception to this is if you have a where clause that references one of the model tables being included, in this case it will use a LEFT OUTER JOIN to add the where clause to that table.
If you want to INNER JOIN a bunch of models AND include them, you have to use both joins and includes with the given models. joins alone will only do the INNER JOIN across the relations, includes will pull in the fields and setup the returned models with their relations intact.
ruby-1.9.2-p180 :015 > Room.where(:suggested => true).joins(:room_apps => :colors)
  Room Load (0.8ms)  SELECT "rooms".*
                     FROM "rooms"
                     INNER JOIN "room_apps"
                       ON "room_apps"."room_id" = "rooms"."id"
                     INNER JOIN "colors"
                       ON "colors"."room_app_id" = "room_apps"."id"
                     WHERE "rooms"."suggested" = 't'

ruby-1.9.2-p180 :016 > Room.where(:suggested => true).joins(:room_apps => :colors).includes(:room_apps => :colors)
  SQL (0.6ms)  SELECT "rooms"."id" AS t0_r0, "rooms"."suggested" AS t0_r1, "rooms"."created_at" AS t0_r2, "rooms"."updated_at" AS t0_r3, "room_apps"."id" AS t1_r0, "room_apps"."room_id" AS t1_r1, "room_apps"."created_at" AS t1_r2, "room_apps"."updated_at" AS t1_r3, "colors"."id" AS t2_r0, "colors"."room_id" AS t2_r1, "colors"."room_app_id" AS t2_r2, "colors"."created_at" AS t2_r3, "colors"."updated_at" AS t2_r4
               FROM "rooms"
               INNER JOIN "room_apps"
                 ON "room_apps"."room_id" = "rooms"."id"
               INNER JOIN "colors"
                 ON "colors"."room_app_id" = "room_apps"."id"
               WHERE "rooms"."suggested" = 't'

The big convoluted SELECT part in the last query is ARel making sure that the fields from all of the models are unique and able to be differentiated when they need to be mapped back to the actual models.
Whether you use includes alone or includes with joins is a matter of how much data your bringing back, and how much speed difference there might be if you were not doing the INNER JOIN, causing a great deal of duplicate data to be returned. I would imagine that if 'rooms' had something like a dozen fields and 'colors' had 1 field, but there was 100 colors that mapped to a single room, instead of pulling back 113 fields in total (1 room * 13 + 100 colors * 1) you would end up with 1400 fields (13 + 1 * 100 colors). Not exactly a performance boost.
Though the downside of using includes alone is that if you do have a large number of colors per room, the IN(ids) will be huge, bit of a double edged sword.
Here's a quick test I did with various configurations using sqlite3
I setup two sets of rooms, one with :suggested => true, the other :suggested => false. The suggested rooms had a 1:1:2 ratio between rooms/room_apps/colors, the suggested false rooms were setup with a 1:1:10 ratio of the same, and there is a 10:1 ratio between suggested and  not suggested.
# 100/10 rooms
# insert only
100 * 1/1/2: 8.1ms
10 * 1/1/10: 3.2ms

# insert + joins
100 * 1/1/2: 6.2ms
10 * 1/1/10: 3.1ms

# 1000/100 rooms
# insert only
1000 * 1/1/2: 76.8ms
100 * 1/1/10: 19.8ms

# insert + joins
1000 * 1/1/2: 54.5ms
100 * 1/1/10: 23.1ms

The times are not relevant themselves, this is being run via IRB on a Ubuntu guest on a WinXP host on a crappy HDD. Given that you've got a limit(5) in there it probably isn't going to make a huge difference either way.


text:
Q: Incremental deploy from a shell script I have a project, where I'm forced to use ftp as a means of deploying the files to the live server.
I'm developing on linux, so I hacked together a bash script that makes a backup of the ftp server's contents,
deletes all the files on the ftp, and uploads all the fresh files from the mercurial repository.
(and taking care of user uploaded files and folders, and making post-deploy changes, etc)
It's working well, but the project is starting to get big enough to make the deployment process too long.
I'd like to modify the script to look up which files have changed, and only deploy the modified files. (the backup is fine atm as it is)
I'm using mercurial as a VCS, so my idea is to somehow request the changed files between two revisions from it, iterate over the changed files,
and upload each modified file, and delete each removed file.
I can use hg log -vr rev1:rev2, and from the output, I can carve out the changed files with grep/sed/etc.
Two problems:
I have heard the horror stories that parsing the output of ls leads to insanity, so my guess is that the same applies to here,
if I try to parse the output of hg log, the variables will undergo word-splitting, and all kinds of transformations.
hg log doesn't tell me a file is modified/added/deleted. Differentiating between modified and deleted files would be the least.
So, what would be the correct way to do this? I'm using yafc as an ftp client, in case it's needed, but willing to switch.

A: You could use a custom style that does the parsing for you.
hg log --rev rev1:rev2 --style mystyle

Then pipe it to sort -u to get a unique list of files. The file "mystyle" would look like this:
changeset = '{file_mods}{file_adds}\n'
file_mod = '{file_mod}\n'
file_add = '{file_add}\n'

The mods and adds templates are files modified or added. There is a similar file_dels and file_del template for deleted files.
Alternatively, you could use hg status -ma --rev rev1-1:rev2 which adds an M or an A before modified/added files. You need to pass a different revision range, one less than rev1, as it is the status since that "baseline". Deleted files are similar - you need the -d flag and a D is added before each deleted file.


text:
Q: How can I work around the expired Sectigo certificate on my old mobile device? As you may know, a CA certificate issued by Sectigo expired recently. This is affecting certain mobile apps and possibly websites, rendering them unable to connect to required network resources.
This can affect applications for two (three) reasons:

*

*The application may be using an incorrect mechanism for validating certificates (as mostly detailed in the referenced articles).

*The application may not have a replacement certificate. This is the case for older devices that manufacturers are no longer supporting.

*Both of the above.

The solution to the first issue is to remove the expired certificate from the trust store. What about the second issue? What can users do to work around that?
(Let's please not get into whether or not anyone should be using such devices. Not everyone can afford to spend $200-$1000 every year or so to buy a new device.)

A: (This answer will cover Android users that have access to Firefox on a desktop computer. Please add other answers to cover other users!)
What's wrong? What do we do about it?
If you use an app that uses an affected certificate, you may have noticed on May 30 that it suddenly refuses to operate. "Better" apps may show an actually useful error message, but many simply throw an immediate error to "check your internet connection" when there is nothing wrong with the network connection.
The cause, as noted, is an expired CA certificate which causes the initial handshake with the server to be rejected.
For laypersons, a typical session starts like this:
Client: Hello, server? Can I talk to you?
Server: Sure! Here's my identification!
*Client checks identification*

When things are working, the client recognizes the identification and continues to talk to the server. What's happening with the Sectigo-issued certificates is that the client sees a) an expired signature and b) an unrecognized signature, so it refuses the connection as "insecure". Apps may or may not even know what is happening, but in any case, the effect is that the attempt to connect to the server is denied.
Newer devices don't have this problem because they know about the updated certificate. So, the problem can be resolved on older devices by manually installing the relevant CA certificate. But first...
Is this safe?
Probably. This guide will explain how to install a certificate that you already trust. I can't promise that that certificate isn't compromised, but if it is, you are already pwned. You can (and should!) also verify the certificate's fingerprint via another means, for example, by comparing the fingerprints against those on a second device.
After installation, your device may complain that "an unknown party may be able to monitor your network traffic". While this may be true, if you are really worried about CA's, you shouldn't be online at all. (Also, AFAIK this would only "expose" information encrypted with certificates signed by Sectigo; anything else is still as secure as always.)
Is this "cracking"? Will it violate my ToS?
Absolutely not! What you are doing is essentially applying (a small portion of) an update that your device vendor should have been making available to you in the first place. Any device with an up-to-date trust store already has this certificate. (That is, in fact, where you are going to obtain the certificate in the first place.) Additionally, installing a CA certificate is in no way specific to any particular app or service.
If any company believes this to be a violation of their ToS, they are incompetent and frankly you should avoid dealing with them.
Enough already, what do I do?
First, you will need a) a computer with a reasonably up-to-date web browser (as noted earlier, I'm using Firefox, but the procedure for Chrome should be similar) and b) a way to transfer a file from said computer to the device that needs to be "fixed". A USB cable is the "obvious" and probably most secure choice, but you could also e-mail the file to yourself. (If you do this, make sure to verify the fingerprint!)
You could also download the certificate from Sectigo, but how do you know you trust them? Your web browser / OS vendor did the legwork (hopefully!) to verify that they are trustworthy. You shouldn't just take the word of some guy on a web forum that the certificate is "safe". Again, this is why you are going to obtain a copy of the certificate that you already trust.
How do I obtain the certificate?

*

*Open Firefox and navigate to about:preferences#privacy. You can also get there by selecting "Preferences" from the 'hamburger' menu and selecting the "Privacy" tab.

*Scroll to the bottom and press the "View Certificates.." button.

*Scroll until you find "The USERTrust Network".

*Under the aforementioned item, find and select "USERTrust RSA Certification Authority".

*Press "Export..." and save the certificate somewhere.

*Don't close your web browser yet. Press "View..." first and leave that tab open.

*Copy the resulting file to your device.

How do I install the certificate?

*

*On your Android device, go to "System settings".

*Go to "security" (on my device, it is under "Personal").

*Under "Credential storage", tap "Install from SD card". (You don't need an SD card; the option is badly named. You can install from a bunch of places, including internal storage or Google Drive.)

*Locate and select the certificate you obtained previously.

*Give it a name (e.g. "USERTrust RSA" or "foo"; the name you enter doesn't appear to actually be used anywhere). Make sure that for "Credential use" you have selected "VPN and apps" (it should be selected by default).

*Tap "OK" to add the certificate. You apps should work now!

WAIT!
How do I verify the certificate?
While still in "Security", tap on "Trusted credentials", then "User". You should see the certificate you just added. Tap on it to see its details. In particular, look for the "SHA-256 fingerprint", which should be (assuming neither my computer nor this answer have been compromised):
E7:93:C9:B0:2F:D8:AA:13:E2:1C:
31:22:8A:CC:B0:81:19:64:3B:74:9C:
89:89:64:B1:74:6D:46:C3:D4:CB:D2

(I've added line breaks to match how it shows on my tablet, which may be convenient if your device adds line breaks in the same place. They don't mean anything, though, so don't panic if you see line breaks in different places.)
You should also compare the fingerprint against the certificate as it is stored on your computer (using the tab you left open earlier). If all three match, the probability that your copy of the certificate is compromised somehow is very low.

A:
The solution to the first issue is to remove the expired certificate from the trust store

In many cases there is an alternate validation path which is not considered by non-compliant software; you have hinted at this in your question. So why do you believe that removing the expired CA cert would resolve the validation? It might in some cases, but we are completely off the reservation here.
If you have access to remove a certificate then you should have access to install a new certificate, but you are still heading for a world of pain in reverse engineering different stacks to map exactly why they are not complaint / find solutions that work.

A: I got it working by adding Sectigo RSA DV Bundle (Intermediate + Cross Signed) to my bundle on the server, which I downloaded from the Sectigo support page
So it serves 4 certificates now:

*

*Domain certificate

*Sectigo RSA Domain Validation Secure Server CA [ Intermediate ]

*USERTrust RSA Root xSigned using AAA CA [ Cross Signed ]

*SHA-2 Root: USERTrust RSA Certification Authority


text:
Q: Adapter doesn't response after popping an AleartDialog from another fragment Hello guys I am for first time here so if there are some mistakes with my problem just notify me to correct my self. My problem is in the adapter I think. My application is with 3 fragment tabs. In each tab I have a ListView with some items. Also I have button in each tab that updates,deletes or adds items. I make that by popping up an AleartDialog for adding a new item or clicking on the item from the list to update it or delete it. So after I login in my application I can do what ever I want with that list. Its not a problem. I can rotate the screen and my list still updates. Changing the tabs its not a problem also. The problem comes when I go to other fragment I click on the button for adding  or on some of the items for updating  and the AleartDialog pops up. After that when I close it I return to the first tab. Trying to add an item doesn't update the list and I see the same items. Deleting the item from the list then throws exception IndexOutOfBounds because the item its not in the list. I think I use arrayAdapter.notifyDataSetChanged() properly. Here I will share some other code.
Like that I update my list. In the jsonObject is list the with the items.
private void fillList(Gson gson, String jsonObject) {
listWithNames.clear();
Type collectionType = new TypeToken<ArrayList<PersonalSaveDTO>>() {
}.getType();

personalSaveList = gson.fromJson(jsonObject, collectionType);
Log.wtf(TAG, "OT REQUEST: " + personalSaveList);
  for (int i = 0; i < personalSaveList.size(); i++) {
    listWithNames.add(personalSaveList.get(i).getName());
  }
  Log.wtf(TAG, "fillList: " + listWithNames);
  getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
      arrayAdapter.notifyDataSetChanged();
      buttonEnable(true);
    }
  });
}

Like that I starts the fragment.
 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                       Bundle savedInstanceState) {

final View viewFragment = inflater.inflate(R.layout.user_fragment, container, false);
listViewUser = (ListView) viewFragment.findViewById(R.id.listViewForUser);
addItem = (Button) viewFragment.findViewById(R.id.buttonAddUserElements);
updateList = (Button) viewFragment.findViewById(R.id.refreshListUser);
updateList.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    makeRequestForList(viewFragment);
  }
});
addItem.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    addElement(viewFragment);
  }
});
configureArrayAdapter(viewFragment);
setListenerForUserList(viewFragment);
if (savedInstanceState != null) {
  isRequestMade = savedInstanceState.getBoolean("isRequestMade");
  listWithNames = savedInstanceState.getStringArrayList("listWithNames");
  personalSaveList = savedInstanceState.getParcelableArrayList("personalSaveList");
  arrayAdapter.addAll(listWithNames);
  arrayAdapter.notifyDataSetChanged();
}

if (!isRequestMade) {
  makeRequestForList(viewFragment);
  isRequestMade = true;
}
return viewFragment;

}
And here is how I create the adapter.
  private void configureArrayAdapter(View view) {
listWithNames = new ArrayList<>();
arrayAdapter = new ArrayAdapter<String>(view.getContext(),
    R.layout.list_personal_group_fragment, R.id.adapterFragmentPersonalGroups, listWithNames);
arrayAdapter.clear();
listViewUser.setAdapter(arrayAdapter);
}


text:
Q: Clickable links in UI Chat Application I am using AngularJS in front-end and Socket.io for chat application.
When a user sends a message, Its getting rendered in UI as follows:

{{chat.msg}}

But If user sends any link how can I make it clickable?
One approach was to pass message to a regular expression and check if it contains a link and put them in a  tag and rendering that message in above tag worked.
But If message contains some html tags which user is trying to send it across to another user, then it is getting replaced in html.
Example:
User1:  Show me your code in example.com
User2:  My code is as follows :
This is a simple app</b
 in example.com
User3:  Looks Good

Here in above code only example.com should be clickable and
 tag should be shown as a part of message instead of rendering it in UI.
Any idea how this can be done?
Thanks in Advance

A: You should make use build-in linky filter (from ngSanitize module).

However note, that example.com is not a linkable resource, since it must start with http/https/ftp/mailto.


text:
Q: Switching Limits and Suprema suppose, $f(x,y)$ is a bounded continuous function on $\mathbb{R}^2$. Consider
$$\lim_{ y \rightarrow y' }\> \sup_{x \in \mathbb{R}} f(x,y).$$
In how far can you switch suprema and limits, or which possible term comes closest to switching these two? Ideally, there would be something like
$$\sup_{x \in \mathbb{R}}\> \lim_{ y \rightarrow y' } f(x,y).$$
Best

A: You cannot in general. To take a very simple example, consider $f(x,y) = \sin(xy)$, and $y'=0$. Then we have:
$$\lim_{y\to 0}\>\sup_{x\in\mathbb{R}}\sin(xy) = 1.$$
(Remember that if we take the limit as $y\to 0$, then we do not consider $y=0$, so $y\neq 0$ in $\sin(xy)$).
But
$$\sup_{x\in\mathbb{R}}\>\lim_{y\to 0}\sin(xy) = \sup_{x\in\mathbb{R}}\ 0 = 0.$$
However, if the limit of $f(x,y)$ as $y\to y'$ exists for every $x$, and the limit of the suprema exist, then you get one inequality:
$$\sup_{x\in\mathbb{R}}\>\lim_{y\to y'}f(x,y) \leq \lim_{y\to y'}\>\sup_{x\in\mathbb{R}} f(x,y).$$
To see this, note that for each fixed $x_0\in\mathbb{R}$, $f(x_0,y) \leq \sup\limits_{x\in\mathbb{R}}f(x,y)$, so taking limits we have
$$\lim_{y\to y'} f(x_0,y) \leq \lim_{y\to y'}\>\sup_{x\in\mathbb{R}}f(x,y).$$
Since this holds for each $x_0$, the supremum also satisfies the inequality, so
$$\sup_{x\in\mathbb{R}}\>\lim_{y\to y'}f(x,y) \leq \lim_{y\to y'}\>\sup_{x\in\mathbb{R}}f(x,y).$$


text:
Q: Scrapy parse webpage, extract results pages, and download images I've written a web crawler in python using Beautiful Soup and requests to scrape images for a project, but the speed is slow. I heard Scrapy is much faster so I've installed it and read a load of tutorials but I can't figure out how to implement the crawler in the parse function of the spider script.
If I provide the link to the first page of search results, it should:

*

*Find the number of pages in search results, by analyzing the <a> tag for a specific class

*Get links based on the <a> tag for a specific class, and

*Download the images from these links based on a specific 'id'
I've updated the items and settings scripts as shown down below. Any help you can give me is massively appreciated.
items.py
import scrapy

class SampleItem(scrapy.Item):
    # define the fields for your item here like:
    images = scrapy.Field()
    image_urls = scrapy.Field()

settings.py
ITEM_PIPELINES = {
   'scrapy.pipeline.images.FilesPipeline': 1
}
FILES_STORE = '/Documents/scraped_images/'

A: it is minimal example which downloads images from main page on http://books.toscrape.com/
You can put all code in one file and run python script.py without creating project.
You have to find images on HTML and add to Item (or yield as dictionary). It doesn't do this automatically.
If you use FilesPipeline then you have to use file_urls instead of images_urls.
Path which you use in FILES_STORE has to exists. It will not create it - and if folder doesn't exist then it doesn't download files. But it will create automatically subfolder full/ in FILES_STORE to keep original images.
import scrapy
from scrapy.pipelines.files import FilesPipeline

class MySpider(scrapy.Spider):

    name = 'myspider'

    #allowed_domains = []

    start_urls = ['http://books.toscrape.com/']

    def parse(self, response):
        print('url:', response.url)

        # download files (not only images, but without converting to JPG)
        for url in response.css('img::attr(src)').extract():
            url = response.urljoin(url)
            yield {'file_urls': [url]}

# --- run it in the same file ---

from scrapy.crawler import CrawlerProcess

c = CrawlerProcess({
    'USER_AGENT': 'Mozilla/5.0',

    # save in file CSV, JSON or XML
    #'FEED_FORMAT': 'csv',     # csv, json, xml
    #'FEED_URI': 'output.csv', #

    # used standard FilesPipeline (download to FILES_STORE/full)
    'ITEM_PIPELINES': {'scrapy.pipelines.files.FilesPipeline': 1},

    # this folder has to exist before downloading
    'FILES_STORE': '.',
})

c.crawl(MySpider)
c.start()

EDIT: I add RenameFilesPipeline which renames path to move files to subfolder with current date and time. You don't have to create subfolder - it will create it automatically.
import scrapy
from scrapy.pipelines.files import FilesPipeline
import datetime
import time

class MySpider(scrapy.Spider):

    name = 'myspider'

    #allowed_domains = []

    start_urls = ['http://books.toscrape.com/']

    def parse(self, response):
        print('url:', response.url)

        # download files (not only images, but without converting to JPG)
        for url in response.css('img::attr(src)').extract():
            url = response.urljoin(url)
            yield {'file_urls': [url]}

class RenameFilesPipeline(FilesPipeline):
    '''Pipeline to change file names - to add folder name with date and time'''

    # create it only once - when Scrapy creates instance of RenameFilesPipeline
    pattern = datetime.datetime.now().strftime('images/%Y.%m.%d-%H.%M.%S/{}')

    def file_path(self, request, response=None, info=None):
        '''Changing file name - adding folder name with date and time'''

        name = request.url.split('/')[-1]
        filename = self.pattern.format(name)
        print('filename:', filename)

        return filename

# --- run it in the same file ---

from scrapy.crawler import CrawlerProcess

c = CrawlerProcess({
    # used standard FilesPipeline (download to FILES_STORE/full)
    #'ITEM_PIPELINES': {'scrapy.pipelines.files.FilesPipeline': 1},

    'ITEM_PIPELINES': {'__main__.RenameFilesPipeline': 1},

    # this folder has to exist before downloading
    'FILES_STORE': '.',
})

c.crawl(MySpider)
c.start()


text:
Q: Как компилировать код на C в macOS? Каким образом можно работать с языком C в macOS? Нужен именно C, не C++.
Я совсем новичок в этом. Пробовал поставить VS Code с расширениями позволяющими якобы компилировать код на C. К сожалению, ничего не вышло.
Чем я могу воспользоваться для компиляции C? Возможно какая-то IDE или же можно как-то использовать VS Code/Sublime Text? Будут интересны различные варианты/инструкции.

A: Как варик, через терминал:
gcc -o hello main.c
./hello

Если это крупный проект - то через Xcode:

Xcode supports source code for the programming languages C, C++, Objective-C, Objective-C++, Java, AppleScript, Python, Ruby, ResEdit (Rez), and Swift, with a variety of programming models

Если ты студент или не проч платить за IDE - CLion в помощь)


text:
Q: C++ self-adding a static-polymorphic class to a constexpr list of subclasses I have a large number of subclasses which subscribe to various events such as initialization and entity deletion.
Currently I solve this by doing
class A{ static void init(); void kill(ID); }
class B{ static void init(); void kill(ID); }
class C{ static void init(); void kill(ID); }
A::init();
B::init();
C::init();

Which, with a multiline editor isn't difficult, and is trivial to read, but there's lots of room for mistakes, mostly remembering to add each new class to the invoking section, instead of the class adding itself as it would with dynamic polymorph.
How do I use static polymorphy to get this into a form resembling
//interface, with default behavior implementation
class W{ static void init(){...} void kill(ID){...} }

class A : W<A> {}
class B : W<B> { static void init(){...} }

constexpr auto w_classes = magic_classlist(A, B, ...)

w_classes::init();

With objects-methods, making a list of static_casted objects is easy.
But I need classes-functions. So to make an iterable list of classes, without manually adding them to a template, ideally by inheriting the superclass, if possible.

A: Maybe the following is enough for you:
template <typename ... Ts>
class magic_classlist
{
    static void init()
    {
        (Ts::init(), ...); // C++17, but can be done for C++11
    }
};

and then:
constexpr auto w_classes = magic_classlist<A, B, ...>();

w_classes::init();


text:
Q: Rearranging HTML elements with css I have in my layout three elements like this:

shown this way:
| element1 | element2 | element3 |

I want them to show like this:
element1 | element2
element3 |

The closest thing I've achieved to do is this:
element1 |
element3 | element2

I can't achieve to align element1 and element2
Does anybody knows how to do it only with CSS ?

A: Here is the working example

    This is elem1

    This is the elem2

    This is elem3

A: Your question is quite open-ended (no context whatsoever), there's a very simple solution, which is to use float: left...

#element1, #element2, #element3 {
  float: left;
  width: 50%;
  box-sizing: border-box; // <- Not necessary for this basic example unless you add padding, etc.
}

El 1

El 2

El 3

A: This is how you use div tags :

Example Text

An example made by Sören Kuklau can be seen here
Here is an example Fiddle using the float: left css property

A: You can't do it only using CSS because CSS can't do real DOM modifications for that you have to use jQuery.
I hope this link can help you:
What is the easiest way to order a
/
 in jQuery?

A: define them all as float: left and add clear: both to the third one.

A:

El 1

El 2

El 3

#container > div {
 float: left;
}
#container{
 position:relative;
}
#element3{
 bottom: -40px;
 display: block;
 position: absolute;
}

In my explaination the #container #element3 and #container > div are ids of div so please dont read as comment thanks


text:
Q: Create a function to return the length of an int array in C I'm new to c programming. I want to create a function that takes an integer array as argument and returns length of the array. I know that the code below calculates the length correctly.
    int arr[] = {1, 2, 3, 4, 5};
    int length = sizeof(arr) / sizeof(arr[0]);

But if I create a function like below and pass the array as an argument, it doesn't work.
    int length_of(int* arr) {
        return sizeof(arr) / sizeof(arr[0]);
    }

My guess is that I'm not passing the array into the function correctly. What is the correct way of implementing this?

A: Well, there's no way of getting this done from a function. Any array, passed to a function as argument will decay to a pointer type (to the first element). So, inside the called function, all you will get is a size of a pointer.
An indirect way of achieving this would be to have something called a sentinel value in the array, and from the called function, iterate over the array elements to find the sentinel value while incrementing a counter, and once found, take the length of that counter.

A: Here's what the standard says (C99 6.3.2.1/3 - Other operands - Lvalues, arrays, and function designators):

Except when it is the operand of the sizeof operator or the unary & operator, or is a
string literal used to initialize an array, an expression that has type ''array of type'' is
converted to an expression with type ''pointer to type'' that points to the initial element of
the array object and is not an lvalue.

This means that pretty much anytime the array name is used in an expression, it is automatically converted to a pointer to the 1st item in the array.

A: You are passing a pointer as the parameter into your function, so it is not possible to know the size of the array by just knowing the size of parameter you pass to the function.
The most standard way of calculating size of an array in C is the one you mentioned in your question:
int a[10];
size_t n = sizeof(a) / sizeof(a[0]);

A: As already answered, you cannot do this in a function. A common solution for that is to use a Macro. See e.g. Common array length macro for C?

A: As other answers have pointed out, it is not possible to determine the size of an array inside of a function in the general case, i.e. without assumptions.
If this is really about returning the size of an array from a function at any cost, I chip in the general method of determining the length based on special knowledge/assumptions on the CONTENT of the array. This is how the strlen() function determines the length of NULLTERMINATED character sequences, which is the closest thing C has to string.
The special assumption on the content of the character sequence is that they only contain the terminating '\0' at the end. Many a StackOverflow question was asked because of the traps and vulnerabilities involved in that concept causing misunderstandings.
So, if you can for example assume that the array in question only contains non-negative integers (i.e. positive values and 0) and that the last valid value inside the array, at index (size-1), is negative, then you can determine the length of the array by search for that terminator, i.e. the first negative value you find at or behind the address from the pointer parameter.

A: If your prime intention is to return the array size from the function then pass the size as the argument.
Because once the argument is passed to function it will be pointing to the first element
So the code goes like
#include <stdio.h>
int func_len(int number)
{
    return number;
}
int main()
{
    int arr[]={1,2,3,4,5};
    int size = sizeof(arr)/sizeof(arr[0]);
    printf("Length is %d\n",size);
    printf("Length is %d",func_len(size));
}

Output will be
Length is 5
Length is 5


text:
Q: Rendering MJpeg stream in html5 I'm trying to render MJpeg stream in HTML5 using the img tag.
When I'm running the following, everything works great, meaning, the video starts to play until the video ends:

My question is how can I get the stream frame by frame.
For each frame, I want to get it, do something (ajax call to the server) and then display the frame as an image.
Thanks.

A: You can do this without repeatedly making Http requests. Only one will suffice. You can use the fetch api to create a ReadableStream, access it's Reader and keep reading from the stream.
Once you have the reader keep reading chunks from the stream recursively. Look for the SOI (    0xFF 0xD8) in the byte stream which signals the end of the header and the beginning of the JPEG frame. The header will contain the length of the JPEG in bytes to be read. Read that many bytes from the chunk and any successive chunks and store it into a Uint8Array. Once you've
successfully read the frame convert it into a blob, create a UrlObject out of it and assign it to the src property of your img object.
Keep doing this till the connection is closed.
Shameless plug. Here's a link to a working sample on github.

A: If the camera exposes raw JPEG images (not .MJPEG extension) you'll have to reaload it manually (if the extension is .MJPEG the browser will do everything, just put the correct src). If you have .MJPEG and want to use the raw .JPEG check your camera documentation. Most cameras expose both the .MJPEG and raw .JPEG streams (just on different URLs).
Unfortunately you won't be able to easily get the image through ajax, but you could change the src of the image periodically.
You can use Date.getTime() and add it to the querystring to force the browser to reload the image, and repeat each time the image loads.
If you use jQuery the code will look something like this:
camera.html
<!DOCTYPE html>

    <title>ipCam</title>

ipCam

motionjpeg.js
function motionjpeg(id) {
    var image = $(id), src;

    if (!image.length) return;

    src = image.attr("src");
    if (src.indexOf("?") < 0) {
        image.attr("src", src + "?"); // must have querystring
    }

    image.on("load", function() {
        // this cause the load event to be called "recursively"
        this.src = this.src.replace(/\?[^\n]*$/, "?") +
            (new Date()).getTime(); // 'this' refers to the image
    });
}

Note that my example will play the MotionJPEG on page load, but won't allow play/pause/stop functionalities

A: If you stream source can't return frames on another address (http://[some ip]:[port]/frame/XXX) then you can use MJPEG stream parser on the server. For example, Paparazzo.js parse stream and return single jpeg. Actually it returns only last frame without saving previous, but it can be changed.
Problem can't be solved only in browser with js without some plugins and server.


text:
Q: Inelastic scattering problem
Regarding this example, I am unable to get the last step. The confusion I have is: I think that the threshold energy remains the same for both CM frame and lab frame(i.e $4m_p$). Hence, to get 4 protons(/anti-proptons) in the output (at rest), with 2 incoming proton (with one at rest) implies $2m_p$=Kinetic energy of the colliding proton. Thus $2m_p=(\gamma -1)m_p \implies \gamma=3\implies v_{p,lab frame}=\sqrt(8)/3.$ Thus momentum of colliding proton in lab frame is $\gamma \times m_p \times v_{p,lab frame} =2.65$. I can't understand where I am going wrong.

A: Something appears to be off in this example. Given the mass $m$ and the momentum $p$, the energy is determined by:
$$
\frac{E}{c} = \sqrt{m^2c^2 + |\mathbf{p}|^2}
$$
Putting in the momentum from the last step the energy must be:
$$
E = 6.56737 \; \text{GeV}
$$
Which is twice as much as the threshold energy in the example, while in fact it should be $E^* - mc^2$ because one particle is at rest.


text:
Q: iTunes connect override accidentally Our company has Company iOS Dev Account.
Last Friday, 25/9/2015, we registered Company iOS Dev Account Apple ID as internal tester in client iOS Dev Account. First time, itunes connect showed error message that registered email(Company Apple ID) already have iTunes connect account. But when we tried second time, it passed validation and registered as internal tester in client iOS Dev Account. After a while, we realised our company apps in iTunes Account were gone and only left as tester of client app. So, we removed our company account as tester in client itunes connect. But it didn't solve, now all apps're gone.
We contacted Apple Tech Support Team Mail. But no reply yet until now.
May I know how can I solve this situation ?
Shall I use DTS to report that ? Will it be fast ?
Thanks for your time

A: Finally, we got help from Apple and can login and see as original itunes connect when we login with secondary email as instructed by Apple. Soon, apple made it to login with primary apple id as original.
Thanks


text:
Q: asp.net core dropdown list not setting selected value I have  a bootstrap drop down and I am using tag helpers to enter render values and read them on post.
Below is the code
asp-for="CfgType"  -- value is set to SIN or UN based on that set the view to the selected value
-- and on submittig the page I need to get the selected value for the drop down from CfgType property.

                                <select id="dwType" class="form-control  custom-select" asp-for="CfgType">
                                    @if(Model.VehFlg)
                                    {
                                        <option value="SIN">Serial Num</option>
                                    }

                                    @if(Model.VinFlg)
                                    {
                                        <option value="UN">Unit Number</option>
                                    }

                               </select>
                                 Configuration Type

Below is how the value is being tried to retrive using controller
//now for fvIdentViewModel.CfgType is null
  [Route("/fv-identification/Save"), HttpPost, ValidateAntiForgeryToken]
 public IActionResult Save(FleetVehicleIdentificationViewModel fvIdentViewModel)
        {

}

A: Here is a working demo:
Model:
public class FleetVehicleIdentificationViewModel
{
    public string CfgType { get; set; }
    public bool VehFlg { get; set; }
    public bool VinFlg { get; set; }
}

View(Index.cshtml):
@model FleetVehicleIdentificationViewModel
<form action="/fv-identification/Save" method="post">

    @Html.AntiForgeryToken()

                    <select id="dwType" class="form-control  custom-select" asp-for="CfgType">
                        @if (Model.VehFlg)
                        {
                            <option value="SIN">Serial Num</option>
                        }

                        @if (Model.VinFlg)
                        {
                            <option value="UN">Unit Number</option>
                        }

                    </select>
                     Configuration Type

                <input type="submit" value="create" />

</form>

Controller:
For easy testing,I set the value manually to render your Index.cshtml:
public IActionResult Index()
{
    var model = new FleetVehicleIdentificationViewModel()
    {
        VehFlg = true,
        VinFlg = false
    };
    return View(model);
}

Your post action:
[Route("/fv-identification/Save"), HttpPost, ValidateAntiForgeryToken]
public IActionResult Save(FleetVehicleIdentificationViewModel fvIdentViewModel)
{
    //do your stuff...
}

Result:

A: you should put in tag form with button type submit.
<form action="/fv-identification/Save" method="post">
 <button type="submit" class="btn btn-info">@localizer["Submit"] </button>
</form>