text:
Q: is there a way to make robot framework code run a failed testcase multiple times I will like to run this multiple times to test what happens when users try to login with wrong credentials many times. The problem is that this runs once, and if i try duplicating it again, it doesnt run the rest of the code.
The result is supposed to be
'''
HTTP error 401 Unauthorized, Attempt 1
'''
but i will like to see 10 attempts
I have tried this but it fails
'''
${result}=    Run special command    -k    --url    https://${url}    auth    login    ${username}    -p${password}
'''

A: From the same question you most likely presented here https://forum.robotframework.org/t/i-want-to-test-many-attempted-failed-login/4781 - I already suggested to look into  Run Keyword And Expect Error
But apparently that was too cumbersome.
*** Variables ***
${url}    http://localhost
${username}   nobody
${password}   notmypassword

*** Keywords ***
Run special command
  [arguments]   ${arg1}   ${arg2}   ${arg3}   ${arg4}   ${arg5}   ${arg6}   ${arg7}
  [return]    "Nothing to see here folks"
  Log To Console     ${arg1} ${arg2} ${arg3} ${arg4} ${arg5} ${arg6} ${arg7}
  Fail    This is the error message for failure

*** Test Cases ***

Doesnt Repeat Failure
  Log To Console   \nThis does show because its start of the testcase
  ${result}=    Run special command    -k    --url    https://${url}    auth    login    ${username}    -p${password}
  ${result}=    Run special command    -k    --url    https://${url}    auth    login    ${username}    -p${password}
  ${result}=    Run special command    -k    --url    https://${url}    auth    login    ${username}    -p${password}
  Log To Console   \nThis will not be shown because run special command fails

Does Repeat Failure

  Log To Console   \nThis does show because its start of the testcase

  ${result}=    Run Keyword And Expect Error  *
  ...   Run special command    -k    --url    https://${url}    auth    login    ${username}    -p${password}

  ${result}=    Run Keyword And Expect Error  *
  ...   Run special command    -k    --url    https://${url}    auth    login    ${username}    -p${password}

  ${result}=    Run Keyword And Expect Error  *
  ...   Run special command    -k    --url    https://${url}    auth    login    ${username}    -p${password}

  Log To Console   \nThis will be shown because we where expecting the error and last call returned a value: : ${result}

Does Repeat Failure with for loop
  Log To Console   \nThis does show because its start of the testcase
  FOR    ${idx}    IN RANGE    10
    Log To Console    \nIteration: ${idx}
    ${result}=    Run Keyword And Expect Error  *
    ...   Run special command    -k    --url    https://${url}    auth    login    ${username}    -p${password}
  END
  Log To Console   \nThis will be shown because we where expecting the error and last call returned a value: : ${result}

This example has 3 test cases, one that you are trying to do that will fail if you run it .. 2 other cases that will call your "Run Special command" that always fails but the test itself doesnt fail because the test code EXPECTS that the keyword call will fail with given parameters.

A: I would have a keyword that does the login, and then a single test case that calls this keyword multiple times.


text:
Q: Capacitor to provide power to a circuit during a very small interruption I need some help in figuring out what size capacitor I need, and if my idea will even work.
I have a small remotely-controlled helicopter, and a very small camera.  I am trying to record video while flying the helicopter around.  So far, cutting down the body of the helicopter and taking the PCB out of the camera and mounting it to the helicopter has worked well.  However, the usable flight time is reduced from 10 minutes or so to 1 minute.  I noticed that the battery on the camera and the battery on the helicopter are the same type and voltage.  What I would like to do is power the helicopter and the camera from the same battery to save on weight.
My original plan was to simply cut the camera battery out of the picture and tie the camera directly do the helicopter.  However, I thought this would cause problems, as the voltage while charging would likely fry the camera.
Then, I noticed the decorative LED on the front of the helicopter.  The voltage (3.7V or so, depending on battery charge) is exactly what is needed to power the camera.  The LED is also off while the helicopter is turned off and/or charging.  Now, this helicopter alternates the polarity going to the LED twice a second, as it is a bi-color LED.  My current plan is to cut out the LED, rectify the voltage with 4 diodes so I have straight DC, and use this to power the camera.  (Barring any current issues of course.  I plan to measure the current load of the LED vs. the camera before doing this, but I expect they will be similar, given the amount of time the camera can run off of its own battery [1 hour+] of similar capacity to that of the helicopter.)
I am going to experiment with this plan tonight, but I just realized that there is probably a very short time where the LED driver outputs 0V in between its polarity switch.  I'm thinking that sticking a capacitor in there will help with the problem, but I have no idea how to calculate what size I need.
Can you tell me what I need to do to calculate the size cap that would likely keep things running smoothly?  Again, the voltage output of the LED driver and the voltage requirement of the camera is 3.7V, but I'm guessing will be anywhere from 4.2 to 3.6 during operation.  I don't yet know the current requirements, but plan to figure those out tonight.
Thank you for your time.

A: I would guess the camera takes 100-150 mA (180 mAh 3.7V battery, ~1 h runtime), and your LED will only be driven with about 20 mA, plus there should be a resistor in series with it.
I'd just power them both off the same battery if weight is a major issue, and if you're concerned about the charging voltage damaging the camera, add some cutoff switch (or just unplug it) while charging.

A: I think that just putting a 2.2mF capacitor across the battery terminals will work well enough to smooth voltage. I presume the voltage dips when the ESC draws large current pulses for the motor.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SimpleForm: Why password text box does not show on form in Rails 3.2 app? In user update page, there is a password field which is added to the form with attr_accessor:
attr_accessor :password, :password_confirmation

The view code for those 2 fields in _form.html.erb is :

  <%= f.input :password, :label => t('Password'), :hint => t('6 characters or more')  %>
  <%= f.input :password_confirmation, :label => t('Password Confirmation') %>

The erb code had no problem before. After removing a few fields (no change for password and password_confirmation though) from the _form.html.erb, however, the text box for password disappeared (see attached below). The html source for the password is:

Password

There is missing <input id = ....> for the password in the html source code. What could cause the missing of the text box for password? If we rename field to password_new from password, then the text box shows up. Is it a bug of simple_form (version 2.1.1)? We use bootstrap.

A: Please using attr_accessible instead.


text:
Q: When is the best time to write a large number of values in a $_SESSION array into a record in the database? One of my MySQL database's tables has 125 columns. I am gathering the values for these columns by presenting the user with a large number of forms in which they select or enter values that I store in the $_SESSION array.
Given there are 125 values to be stored in the $_SESSION array, when would be the best time to start writing these values into the MySQL database?
I may be answering my own question, but would love to hear from more experienced people. I am guessing the safest method is to write one column value at a time into MySQL. And, I am guessing again, is the quickest way assembling all 125 column values and then writing them all in one INSERT statement into MySQL?

A: It depends on your need.  Do you only need to record the data once all 125 fields are collected, or do you you want to collect partial (incomplete) data a field at a time?  Your need here should determine your strategy around how to persist this data to the database.

A: Presumably you are stuck with this data design.  It sounds very unwieldy.
At any rate, if you actually have all the data items available you should put them into MySQL with a single INSERT.
If you do an INSERT and then a bunch of UPDATE operations, you'll have to figure out how to get your UPDATEs to hit the row you just INSERTed.  That can sometimes be a little tricky.


text:
Q: How to correctly render features with GeoTools to an image using AffineTransformation? I'm trying to correctly render some features I read from a featuretable of a PostGIS enabled database with GeoTools to an image.
My configuration:

*

*PostgreSQL 8.4

*PostGIS 1.5

*Osmosis 0.40.1

*OSMembrane build 845

*GeoTools 2.7.4

Rendering some features inside a bounding box works fine so far.
The issue: I get a result that is

*

*rotated 90° (clockwise)

*mirrored on the y-axis

The features I want to render are based on this CoordinateReferenceSystem
GEOGCS["WGS 84",
  DATUM["World Geodetic System 1984",
    SPHEROID["WGS 84", 6378137.0, 298.257223563, AUTHORITY["EPSG","7030"]],
    AUTHORITY["EPSG","6326"]],
  PRIMEM["Greenwich", 0.0, AUTHORITY["EPSG","8901"]],
  UNIT["degree", 0.017453292519943295],
  AXIS["Geodetic latitude", NORTH],
  AXIS["Geodetic longitude", EAST],
  AUTHORITY["EPSG","4326"]]

I'm aware of excuting an affine transformation, so I have written the following piece of code:
public void render(final MapContext mapContext, final Graphics2D graphics) throws IOException
{
    Rectangle renderingArea = new Rectangle(this.mapWidth, this.mapHeight);

    GTRenderer renderer = new StreamingRenderer();
    renderer.setContext(mapContext);

    //move the result to a visisble area
    AffineTransform translate = AffineTransform.getTranslateInstance(mapHeight, mapWidth);
    //rotate 180° anti-clockwise
    AffineTransform rotate = AffineTransform.getRotateInstance(Math.PI);
    //exchange x and y
    AffineTransform mirror = new AffineTransform(0, 1, 1, 0, 0, 0);

    AffineTransform transform = new AffineTransform(translate);
    transform.concatenate(rotate);
    transform.concatenate(mirror);

    graphics.transform(transform);

    renderer.paint(graphics, renderingArea, mapContext.getAreaOfInterest());
}

This works and makes the features look fine! On the other hand, this does not feel quite right. The question is, why I can't use the same transformation I applied on the graphics-object as a method parameter of the renderer's paint-method?
e.g.
//move the result to a visisble area
AffineTransform translate = AffineTransform.getTranslateInstance(mapHeight, mapWidth);
//rotate 180° anti-clockwise
AffineTransform rotate = AffineTransform.getRotateInstance(Math.PI);
//exchange x and y
AffineTransform mirror = new AffineTransform(0, 1, 1, 0, 0, 0);

AffineTransform transform = new AffineTransform(translate);
transform.concatenate(rotate);
transform.concatenate(mirror);

renderer.paint(graphics, renderingArea, mapContext.getAreaOfInterest(), transform);

This always leads to an empty screen. I think, it is rendered somewhere outside the visible area. I know about the tutorials at the geotools website, but I miss some place where everything is put together.
I'm looking forward to any helpful hints.

A: The most likely problem is Axis-Order, read this page http://docs.geotools.org/latest/userguide/library/referencing/order.html and see if that solves your problem. If that isn't the issue then you'll probably want to look at the referencing faq - I've never had to write my own affine transform to render features so I would expect the issue to be answered there or in one of the other tutorials.


text:
Q: How can I reflect the type of a collection in Scala? I'm trying to reflect on the parameterized type of a collection, for example:
val model = List(1)
val classSymbol = currentMirror.classSymbol(model.getClass )
val typeParamArgs = classSymbol.typeParams
println(typeParamArgs)

Unfortunately this only gives me 'B' as the type, not Int as I'd hoped.  How can I reflect to know that this is a List[Int]?  Can I get this statically (preferred)?


text:
Q: Ajax call for Rest Webservice in Jquery not working in Browser but working in Eclipse ide Browser The below code is a call for rest web service in JSP page. When I try loading the JSP in eclipse ide browser, it displays a success message whereas it displays the error block when I loaded in the Browser(tried ie,FF,chrome). Could not able to assess the main reason why the error function is getting executed on loading of JSP page in external browsers.
<script type="text/javascript">
$(document).ready(function() {
    $.ajax({
        type:'GET',
        url:"http://localhost:8797/WSDemo/book?firstname=srinivas",
        dataType:"xml",
        //url:"http://services.groupkt.com/country/get/all",
        //dataType:"json",
        success:function(result){
            alert("This is success");
            alert(result);
        },
        error:function(xhr, status, error){
            alert(xhr.responseText);
        }
    });
});
</script>


text:
Q: TypeError: Attempted to assign to readonly property when overriding the toString() method I have an object with an instance variable containing a list of objects. Now I want to add a custom toString() method to my list of elements (Element has a custom toString() method, too). I tried the following and it worked in the browser:
class Cell {
  constructor(public id: string, public elements: Element[]) {
    this.elements.toString = (): string => this.elements.join(' | ');
  }
}

However when running tests with jasmine I get the error TypeError: Attempted to assign to readonly property. when initializing a Cell.
What is the best way to get a custom toString() method for the list (instead of [elem1, elem2, elem3])? Is there a way to tell jasmine that this reassignment is fine?

A: Are you trying to add a customized toString to Array ?
It would be better to create a Class, say ElementsList, constructed from an array of Elements and that has a tailored toString method
(note: a simple helper function would do too)


text:
Q: What data is accessible to a disabled Chrome Extension? I recently installed a nice Chrome Extension that is only useful from time to time. I would like to prevent it from gathering private data (history, email adresses, etc) when not in use.
Does the fact of disabling the extension stop all data sharing ?
Thanks a lot !

A: *

*When the browser starts with a disabled extension, the extension never runs.

*When you disable an extension that was previously enabled, its scripts/pages are terminated immediately except for the content scripts. If the extension doesn't have content scripts in currently open tabs, then the extension is completely expunged at this point.

*When you disable an extension that was previously enabled and it has content scripts in some tabs, these content scripts keep running, but they can't communicate with the extension's core, which has been completely terminated and disabled, so they are bound by the restrictions of the site i.e. they can't send data to a cross-origin URL, but they still can expose the data implicitly by loading a hidden image or CSS stylesheet with the data added as a URL query parameter in case the site doesn't have a strict CSP (Content-Security-Policy). Most sites don't have a strict CSP.
You can reload all tabs or restart the browser to get rid of these leftovers.


text:
Q: How to get the bound method derived from a metaclass when the class has a method of the same name Consider the following case:
class Meta(type):
    def shadowed(cls):
        print "Meta.shadowed()"
    def unshadowed(cls):
        print "Meta.unshadowed()"

class Foo(object):
    __metaclass__ = Meta

    def shadowed(self):
        print "Foo.shadowed()"

I can call get the bound method unshadowed on Foo and it works fine:
>>> Foo.unshadowed
<bound method Meta.unshadowed of <class '__main__.Foo'>>
>>> Foo.unshadowed()
Meta.unshadowed()

However, I can't seem to get the bound method shadowed on Foo - it directs me rather to the unbound method which must be called with instances of Foo:
>>> Foo.shadowed
<unbound method Foo.shadowed>
>>> Foo.shadowed()

Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    Foo.shadowed()
TypeError: unbound method shadowed() must be called with Foo instance as first argument (got nothing instead)

Is there any way to get <bound method Meta.shadowed of <class '__main__.Foo'>>?

A: It seems one potential answer (maybe not the best) is found in this answer on how to bind unbound methods. So we can do this:
>>> Meta.shadowed.__get__(Foo, Meta)()
Meta.shadowed()

Better demonstration:
class Meta(type):
    def shadowed(cls):
        print "Meta.shadowed() on %s" % (cls.__name__,)
    def unshadowed(cls):
        print "Meta.unshadowed() on %s" % (cls.__name__,)

class Foo(object):
    __metaclass__ = Meta

    def shadowed(self):
        print "Foo.shadowed()"

class Bar(object):
    __metaclass__ = Meta

Bar.unshadowed()                   #Meta.unshadowed() on Bar
Bar.shadowed()                     #Meta.shadowed() on Bar
Foo.unshadowed()                   #Meta.unshadowed() on Foo
#Foo.shadowed()                    #TypeError
Meta.shadowed.__get__(Foo, Meta)() #Meta.shadowed() on Foo


text:
Q: Rational equivalence and ''$\mathbb{A}^1$-equivalence" for zero cycles Let $k$ be a field, let $X\subset\mathbb{P}^r$ be a smooth projective algebraic variety defined over $k$.
We define an equivalence relation on the group of zero cycles $Z_0(X)$ in the following way:

For  $A_1,A_2\in Z_0(X)$ of degree $n$, we define them to be $\mathbb{A}^1$-equivalent, if there exists a degree $m$ cycle $B\in Z_0(X)$ , such that $A_1+B$ and $A_2+B$ are effecitve, corresponding to points $x_1,x_2\in \mathrm{Sym}^{n+m}(X)$, and there exists a morphism $f\colon\mathbb{P}^1\to\mathrm{Sym}^{n+m}(X)$, such that $f(0)=x_1,f(\infty)=x_2$. Mumford defined the "rational equivalence" to be the equivalence relation on $Z_0(X)$ generated by the $\mathbb{A}^1$-equivalence, see here.

I am not sure if Mumford's rational equivalence coincides with the standard one defined by Fulton... More precisely, I am not sure about the following questions:
(0) By the result here, there is a map $$\mathrm{Sym}^s(X)\to\mathrm{Chow}_{0,s}(X\hookrightarrow\mathbb{P}^r)$$ which is only known to be homeomorphism in char $0$. But in general, conversely, given a zero cycle, how does one assign a $k$-point in the symmetric product?
(1) Over an algebraically closed field of characteristic zero, does this notation coincide with the usual notion of rational equivalence?
(2) Over an algebraically closed field of characteristic $p>0$, do the notions coincide?
(3) Over an non-algebraically closed field of characteristic zero, do the two notions coincide?
(4) In case (2),(3) are false, does Mumford's theorem: "$H^{2,0}(S)>0$ implies $\mathrm{CH}_0(S)$ is not finitely generated" still hold in those cases?


text:
Q: PHP Abstract Class extends Exception I was wondering if an abstract class like MyException could extends Exception class or not.
I would create a generic MyException Class that then I will use how parent of some not abstract specific exceptions classes.
Here's an example
abstract class GenericException extends \Exception {
    public function __construct($message, $code) {
        parent::__construct($message, $code);
    }
    // some abstract methods
}
class SpecificException extends GenericException {
    // implementation abstract method of GerericException
    // some-code
}

ecc.
Another question: parent call must be the first call like in Java or not?


text:
Q: BIRT Reports - Dropping Table elements. Can't find the beforeFactory() script I need the functionality of being able to show the correct table for a BIRT Report (dropping the ones I don't need to see).  I see plenty of examples of dropping tables and they all say to perform the drop in the beforeFactory() script.  How do I access the beforeFactory() script using the BIRT IDE?  I am used to dropping CrossTab elements from within the beforeOpen() script.  This function works great.  The beforeOpen() script is available when I select a Datasource and selecting the 'script' tab.  I can't find the beforeFactory() script!   BTW - when I try dropping the table inside of the beforeOpen() script, I get a BIRT exception and the report doesn't run.  Thanks for the help!

A: In the outline view select the root of the report-design, and then the script tab as shown below.


text:
Q: How to write logs in LaTeX without default indent The output I want is like the following photo:

We can see the middle log lines have different font type and indent compared with other plain text.
I have searched a while. The font type seems like courier(texttt{}). But I have no idea about the indent. Anyone has ideas? Thanks!


text:
Q: Stop zooming the content in iframe and continue scrolling the page Hi there I have an iframe. It's src is another site not mine (On this website there is  360 degree photo player that's why I use it)
I put iframe in the top of my website.
But when I scroll down the page, the content in iframe starts zooming instead of just scrolling down main page.
Do you have any ideas how to catch this scroll event and just scroll down the main page not zooming content in iframe?
do u need some demo code? or my question is clear?

A: try this: (if you are using jQuery)
$('your_iframe_selector').scroll(function(e) {
    e.preventDefault();
});


text:
Q: Hibernate doesn't change column for new parameters I have a simple object which I want save in DB. But for time it was necessary to change someone parameters. I drop my old table but when I turn on my program - Hibernate still create DB with old columns.
For example:
My old class looked like this :
@Entity
@Table(name = "Tests")
public class Test {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String description;
private boolean isFree;
private int status;
private String author;
private String section;
@OneToMany(mappedBy = "qTest", fetch = FetchType.LAZY, cascade = {  CascadeType.ALL })
private List<Question> questions;
private String commentToAdmin;
...
and geters-seters
}

In table I have column "status" like INT.
But then I change this class parameter to String. Now my class looks like this:
@Entity
@Table(name = "Tests")
public class Test {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String description;
private boolean isFree;
@Column(name = "statusT")
private String status;
private String author;
private String section;
@OneToMany(mappedBy = "qTest", fetch = FetchType.LAZY, cascade = { CascadeType.ALL })
private List<Question> questions;
private String commentToAdmin;

And geters-setters
}

But after drop old table and restart my application column "status" still "INT" and his name "status" (not "statust").
Please help me understand why it's happening


text:
Q: Best way to manage asynchronous / push communication with web clients on a Spring based Java server I need to push events to web clients in a cross-browser manner (iPhone, iPad, Android, IE/FF/Chrome/etc.) from a Spring based Java server. I am using backbone.js on the client side.
To my best knowledge, I can either go with a Web socket only approach, or I can use something like socket.io.
What is the best practice for this issue, and which platform/frameworks should I use?
Thanks

A: Looks like you're interested in an AJAX Push engine.  ICEPush (same group that makes ICEFaces) provides these capabilities, and works with a variety of server- and client-side frameworks.  There is also APE.

A: You can have a look at Lightstreamer.
My company is currently using it to push real time financial data from a web server.

A: I suppose Grizzly or Netty may fit your needs. Don't have a real experience in that scope, unfortunately.

A: I'd recommend socket.io as you mentioned in your question, if you're doing browser based eventing from a remote host. Socket.io handles all the connection keep-alives and reconnections directly from javascript and has facilities for channeling messages to specific sessions (users). The real advantage comes from the two-way communication of WebSockets without all the boilerplate code of maintaining the connection.
You will need to do some digging for a java implementation thoughConsider running the server directly from V8.


text:
Q: Get files from filesytem which can be found in any level deep subfolders I am using ML 5 and want to ingest/load documents from local file system to MarkLogic DB. I have created recursive function with the help of xdm;:filesystem-directory() function to check folder depth. But, I am getting XDMP-STACKOVERFLOW error. My file system folder has multiple folder with multiple sub-folder in multiple depth. for example
├───vol_18
│   ├───iss_1
│   ├───iss_2
│   ├───iss_3
│   ├───iss_4
│   ├───iss_5
│   └───iss_6
├───vol_19
│   ├───iss_1
│   ├───iss_2
│   ├───iss_3
│   ├───iss_4
│   ├───iss_5
│   └───iss_6
├───vol_2
│   ├───iss_1
│   ├───iss_2
│   ├───iss_3
│   ├───iss_4
│   ├───iss_5
│   └───iss_6

Is there any other better way to get files recursively from local file system?
My Codes are:
declare function IngestArchive($WhichFolder)
{
  let $FileToIngest := ""
  let $Collection := tokenize($WhichFolder, '\\')[last()]
  for $EachFolder in xdmp:filesystem-directory($WhichFolder)/dir:entry
  return
    if( $EachFolder[dir:type='directory'] )
    then
      let $Result := HasFolder($WhichFolder)
      return xdmp:set($FileToIngest, <File>{$Result/dir:pathname/string()}</File>)
    else
      xdmp:set($FileToIngest, <File>{$EachFolder/dir:pathname/string()}</File>)
};

declare function HasFolder($WhichFolder)
{
  for $EachFolder in xdmp:filesystem-directory($WhichFolder)/dir:entry[1]
  return
    if( $EachFolder[dir:type='directory'] )
    then
      HasFolder($WhichFolder)
    else
      <File>{$EachFolder/dir:pathname/string()}</File>
};

Please give your suggestions.

A: Looks like an endless loop. Your HasFolder function calls itself, but with original argument. I think you want this:
HasFolder($WhichFolder)

to be replaced with:
HasFolder($EachFolder)

HTH!


text:
Q: Deleting photo in text message conversion (iPhone 5s, iOS 9.1) If I receive a photo via text message and I delete the text message conversation before saving the photo to my Camera Roll will the photo be saved in my iCloud Photo Library?

A: Only photos in your camera roll are uploaded to iCloud, if your iCloud settings are set to sync photos.
You would have to select to save the photo from the MMS message to your camera roll first.


text:
Q: How to edit random numbers in a txt file using batch Hello guys I need a bit of help
I am trying to edit a txt file but it has no data in front of it so I am having a hard time find a way to edit the txt file
Here is my script
@ECHO Off
setlocal ENABLEDELAYEDEXPANSION
cd /d "%~dp0"

set "Mfind=    %Random%"

@For %%G In ("%~dp03Ready\NSB") Do Set "sourcedir=%%~fG"
@For %%G In ("%~dp03Ready\NSBEdited") Do Set "destdir=%%~fG"

Set /p "FPats=Enter Your Amount:

FOR /f "delims=" %%q IN ('dir /b /s /a-d "%sourcedir%\(09)Fus.txt"') DO (
 rem calculate new destination directory
 SET "newdest=%%~dpq"
 SET "newdest=!newdest:%sourcedir%=%destdir%!"
 SET "newdest=!newdest:~0,-1!"
 MD "!newdest!" 2>nul

(
  for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "%%q"') do (
   set "line=%%b"
   if defined line IF "%%b" neq "!line:%Random%=!" CALL :nidC1
      echo(!line!
 )
)>"!newdest!\%%~nxq"

)
GOTO :NSBEditing

:nidC1
SET "line=%line:-=%"
SET "original=%line%"
FOR /L %%s IN (0,1,9) DO set "line=!line:%Mfind%%%s=%Mfind%!"
IF "%original%" neq "%line%" goto nidC1
set "line=!line:%Mfind%=%Mfind%%FPats%!"
GOTO :eof

Here is my txt file The text file cna reach up to 100K line even more then that this is only a small part of it
(09)Fus.txt
    "cpup": [
    {
      "upma": "id",
      "upnn": 0,
      "upfb": true,
      "upcu": {
        "adid": "Dge_ChngerSTemon_2018_nit2",
        "ulid": "TT_UPADE_NROU03",
        "upty": "NOUS",
        "isnc": false,
        "erpm": 0
      }
    },
    58, < ---------------- Trying to edit these numbers
    {
      "upma": "id",
      "upnn": 0,
      "upfb": true,
      "upcu": {
        "adid": "lphaSixoSSCrewcycled_016_tur1",
        "ulid": "TT_RADE_TUO02",
        "upty": "BO",
        "uplv": 1,
        "erpm": 0,
        "adtc": [
          {
            "kfti": 1000.0,
            "kfva": 0.321
          }
        ]
      }
    },
    70 < ---------------- Trying to edit these numbers
  ],

A: I would Like to thank you very much for helping me with my problem, I am 100% sure your scripts works great, but I still struggled a little to understand them, But good news I found a work around it is not the best methods compared to what you guys offered but it does the job
What I did was I combined 3 scripts one to find and change the numbers found
here     58, it now does this     XXXXX,8,
Doing this it now gives me a code to find when I set
Next I have a cleaner that will find ,8 and delete it
Next I have a editor to find XXXXX and edit it with the typed input
Here is my final updated script
:EditingData
@ECHO Off
setlocal ENABLEDELAYEDEXPANSION
cd /d "%~dp0"

set "FindA1=    "

SET "LETTER=XXXXX,"

@For %%G In ("%~dp0Folder1") Do Set "sourcedir=%%~fG"
@For %%G In ("%~dp0Folder2") Do Set "destdir=%%~fG"

FOR /f "delims=" %%q IN ('dir /b /s /a-d "%sourcedir%\TXTFilename.txt"') DO (
 rem calculate new destination directory
 SET "newdest=%%~dpq"
 SET "newdest=!newdest:%sourcedir%=%destdir%!"
 SET "newdest=!newdest:~0,-1!"
 MD "!newdest!" 2>nul

(
  for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "%%q"') do (
   set "line=%%b"
   if defined line IF "%%b" neq "!line:=!" CALL :Gas1
   echo(!line!
 )
)>"!newdest!\%%~nxq"

)
GOTO :FusCleaner1

:Gas1
SET "line=%line:-=%"
SET "original=%line%"
FOR /L %%s IN (0,1,9) DO set "line=!line:%FindA1%%%s=%FindA1%1!"
IF "%original%" neq "%line%" goto Gas1
set "line=!line:%FindA1%1=%FindA1%%LETTER%!"
GOTO :eof

:FusCleaner1
@echo off

set "source=Folder2"
set "target=Folder2"
set "file=TXTFilename.txt"

setlocal enableDelayedExpansion
(
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "%source%\%file%"') do (
      set "line=%%b"
rem This part deletes from file
      if defined line set "line=!line:,0=!"
      if defined line set "line=!line:,1=!"
      if defined line set "line=!line:,2=!"
      if defined line set "line=!line:,3=!"
      if defined line set "line=!line:,4=!"
      if defined line set "line=!line:,5=!"
      if defined line set "line=!line:,6=!"
      if defined line set "line=!line:,7=!"
      if defined line set "line=!line:,8=!"
      if defined line set "line=!line:,9=!"
      echo(!line!
   )
) > "%target%\%file%.bak"

del "Folder2\%file%"
ren "Folder2\%file%.bak" "%file%"
goto :FusCleaner2

:FusCleaner2
@ECHO Off
setlocal ENABLEDELAYEDEXPANSION
cd /d "%~dp0"

set "FindA2=   "

@For %%G In ("%~dp0Folder2") Do Set "sourcedir=%%~fG"
@For %%G In ("%~dp0Folder2") Do Set "destdir=%%~fG"

set /P FusPQ=Enter Parts Quantity:

FOR /f "delims=" %%q IN ('dir /b /s /a-d "%sourcedir%\%file%"') DO (
 SET "newdest=%%~dpq"
 SET "newdest=!newdest:%sourcedir%=%destdir%!"
 SET "newdest=!newdest:~0,-1!"
 MD "!newdest!" 2>nul

(
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "%%q"') do (
   set "line=%%b"
   if defined line IF "%%b" gtr "!line:XXX=!" CALL :FPTS4
   echo(!line!
 )
)>"!newdest!\%file%.bak"
del "Folder2\%file%"
ren "Folder2\%file%.bak" "%file%"
)
GOTO :eof

:FPTS4
SET "original=%line%"
FOR /L %%s IN (0,1,9) DO set "line=!line:%FindA2%%%s=%FindA2%XXXXX!"
IF "%original%" gtr "%line%" goto FPTS4
set "line=!line:%FindA2%XXXXX=%FindA2%%FusPQ%!"
GOTO :eof

A: The below function can be used to modify lines containing only whitespace numbers and ','
 indicates a manditory argument, argument positions are fixed.
It uses a flag to mark line as being a number only - a For /f loop with delims overides the flag if the line is not empty after removing those delims.
@Echo off

:ReplaceNum <inputfilepath.ext> <outputfilepath.ext>
    Set "ScriptName=%~0"
    For /f "tokens=1,2* Delims=:" %%G in (":.%ScriptName%")Do If "%%G"=="." Set "ScriptName=Call :%%H"
    If "%~1"=="" (
        Echo(%ScriptName% ^<inputfilepath.ext^> ^<outputfilepath.ext^>
        Exit /B 0
    )

    %= Error 1; No Source =%            If not Exist "%~1" Exit /B 1
    %= Error 2; Filepaths Same =%       If "%~1"=="%~2" Exit /B 2

    Set "Class="
    1>"%~2" (
        For /f "usebackq delims=" %%G in ("%~1")Do (
            Set "Line=%%G"
            Setlocal EnableDelayedExpansion
            Set "isnum=true"
            For /f "delims=0123456789, " %%i in ("!Line!")Do Set "isnum=false"
            If "!isnum!"=="true" (
                Set "nLine=!Line: =!"
                Set "nLine=!nLine:,=!"
                Mode 120,40
                1> Con Call :GetNum Replace number:'!nLine!' for Class: !Class!
                For /f "tokens=1,2" %%i in ("!nLine! !Num!")Do Echo(!Line:%%i=%%j!
                Set "Class="
            )Else (
                Set ^"cLine=!Line:"=!"
                For /f "tokens=1,2 delims=:," %%u in ("!Line!")Do If not "%%~b"=="" Set "Class=!Class! %%u"
                For %%c in ("{" "}" "[" "]") Do Set "Class=!Class:%%~c=!"
                For /L %%i in (1 1 4)Do Set "Class=!Class:  = !"
                Echo(!Line!
            )
            For /F "Delims=" %%c in ("!Class!")Do Endlocal & Set "Class=%%c"
        )
    )

Exit /B 0

:GetNum
(   Set LF=^

%= Linefeed Definition - Do not modify =%)
    Set "Num="
    Set /P "Num=%*!LF!>:"
    2> nul Set /A "Num+=0","1/Num" || Goto:GetNum
Exit /B 0

A: Ok. Here we go (again)...
First step: (trying to) identify the lines to be edited:
@echo off
setlocal EnableDelayedExpansion

set "last=1"
set "lines=:"
for /F "delims=:" %%a in ('findstr /N "{ } ]" (09)Fus.txt') do (
   set /A "prev=%%a-2, line=%%a-1"
   if !prev! equ !last! set "lines=!lines!!line!:"
   set "last=%%a"
)

for /F "tokens=1* delims=:" %%a in ('findstr /N "^" (09)Fus.txt') do (
   if "!lines::%%a:=!" neq "%lines%" (
      echo %%b   ^< - This line will be edited
   ) else (
      echo %%b
   )
)

Output example:
    "cpup": [
    {
      "upma": "id",
      "upnn": 0,
      "upfb": true,
      "upcu": {
        "adid": "Dge_ChngerSTemon_2018_nit2",
        "ulid": "TT_UPADE_NROU03",
        "upty": "NOUS",
        "isnc": false,
        "erpm": 0
      }
    },
    58,   < - This line will be edited
    {
      "upma": "id",
      "upnn": 0,
      "upfb": true,
      "upcu": {
        "adid": "lphaSixoSSCrewcycled_016_tur1",
        "ulid": "TT_RADE_TUO02",
        "upty": "BO",
        "uplv": 1,
        "erpm": 0,
        "adtc": [
          {
            "kfti": 1000.0,
            "kfva": 0.321
          }
        ]
      }
    },
    70   < - This line will be edited
  ],


text:
Q: expected asm or __attribute__ before CRenderContext I am developing a small app under Linux using the CodeBlocks IDE.
I have defined a class with the following code:
class CRenderContext
{
public:     /*instance methods*/
             CRenderContext() :
             m_iWidth(0), m_iHeight(0),
             m_iX(0), m_iY(0),
             m_bFullScreen(false), m_bShowPointer(false) {};

             CRenderContext  (int                    iWidth,
                              int                    iHeight,
                              int                    iX,
                              int                    iY,
                              bool                   bFullScreen,
                              bool                   bShowPointer)
                              :
                              m_iWidth(iWidth), m_iHeight(iHeight),
                              m_iX(iX), m_iY(iY),
                              m_bFullScreen(bFullScreen), m_bShowPointer(bShowPointer) {};
        virtual ~CRenderContext () {};

    public:     /*instance data*/
        int     m_iWidth;
        int     m_iHeight;
        int     m_iX;
        int     m_iY;
        bool    m_bFullScreen;
        bool    m_bShowPointer;
};

I always get the following error when compiling the above code:
error: expected '=', ',', ';', 'asm' or 'attribute' before CRenderContext
Any ideas about how to solve the error?
Thanks in advance,
Eugenio

A: You are compiling it as C code, not C++. You probably need to rename the source file to have a .cpp extension. The code compiles perfectly (as C++) with g++ and comeau, although you have some superfluous semicolons. For example:
virtual ~CRenderContext () {};

No need for the semicolon ot the end there.


text:
Q: Are nested resources RESTful? How architecturally sound and up to industry standards nesting resource representations in REST APIs is, especially when it comes to nested lists of resources (like books of an author)?
I'm interested in finding links to authoritative sources that answer to this question.

A: The authoritative source for REST is the dissertation of Roy Fielding, based on work he did during the standardization of HTTP/1.1 (RFC 2068, RFC 2616, etc) in the 1990s.
REST defines resource ("Any information that can be named can be a resource..."), and requires that all resources understand messages the same way (uniform interface) but does not actually constrain your resource model.
"RESTful", historically, is context sensitive; in practice it means something like "more like REST than our current designs".  In the web services community, it meant "more like REST than WS-* and SOAP".  In Rails, it meant more like REST than the resource models that were recommended prior to Rails 1.2.  And so on.

If what you are interested in is describing the relationship between a resource that is a collection and a resource that is an item in that collection, then the standard you want is RFC 6573.
But again, it doesn't tell you how to design the resources, or how to design the identifiers for those resources -- it just tells you how to indicate a relationship between them.

A: As far as I understand the web resource is something abstract identified by the IRIs and accessible through the web. What dereferencing the IRI gives back is the representation of the actual state of the identified resource, this is why it is called representational state transfer. I don't remember any standard that discusses nested resources. Maybe RDF is the closest what you are looking for. In practice if we follow RDF concepts, then to answer a GET request the REST API responds with a representation of an RDF subgraph starting with the resource indentified by the giving IRI and it can be any level deep. Nestedness is not something I would consider here, because it is a graph, not a hierarchy, it is sort of expanding relationships between resources or returning hyperlinks the API consumers can follow to do the exact same thing.
Not sure if this helps. I did not find any RFC beyond what VoiceOfUnreason's answer contains, I remember to read explicitly about web resources and identifying real things with hashtags or non-dereferenceable IRIs in an RFC 5+ years ago, but I have no idea which one it was. Maybe it was the Lanthaler dissertation or the SemWeb document VoiceOfUnreason suggested. What is certain it was somehow connected to the semantic web and RDF.

REST's identification of resources constraint requires that resources
are identifiable so that they can be accessed and manipulated via
generic interfaces. On the Web, resources are identified by IRIs [44].
Since a resource may represent con- cepts which cannot be serialized
into a byte stream (e.g., persons or a feeling), resources are not
manipulated directly. Instead, REST is built on the concept of
manipulation of resources through representations; i.e., an additional
layer of indirection in the form of resource representations is
introduced.

https://www.markus-lanthaler.com/research/third-generation-web-apis-bridging-the-gap-between-rest-and-linked-data.pdf

On the Semantic Web, all information has to be expressed as statements
about resources, like the members of the company Example.com are Alice
and Bob or Bob's telephone number is "+1 555 262" or this Web page was
created by Alice. Resources are identified by Uniform Resource
Identifiers (URIs) [RFC3986]. This modelling approach is at the heart
of Resource Description Framework (RDF) [RDFPrimer]. A nice
introduction is given in the N3 primer [N3Primer].
Using RDF, the statements can be published on the Web site of the
company. Others can read the data and publish their own information,
linking to existing resources. This forms a distributed model of the
world. It allows the user to pick any application to view and work
with the same data, for example to see Alice's published address in
your address book.

https://www.w3.org/TR/cooluris/#semweb
So what I want to say that what you see in the HTTP response is not the resource itself, just a representation of it and its relationship to other resources.
REST does not have a constraint which tells you how verbose that response must be. It just tells you that you must use hyperlinks to connect resources and that you must use standard MIME types and document your API. At least this is how I interpret the uniform interface constraint.
I think the question is very good, because this part of the architecture is open and there were many questions in the past years which ask how to use the URIs for querying nested resources. The answer is always that REST does not cover it, the URI and URI template standards don't cover it either. There are standards like OData and Hydra, which have suggestions, but it is just up to you. Your problem is connected to it, because it asks how verbose a response to such a query can be. It is not covered as well as far as I can tell, but what is certain that it can and must contain at least hyperlinks to other resources. RDF allows describing several resources in a single document, so if we extend the RDF approach to REST, which does not say this is forbidden, then I guess we can do it.
From practical perspective for example a collection is a sort of nested resource too and if the API consumer would send a dedicated request for every collection item just to know basic things like product names, then it would be wasting resources. Normally we respond this kind of requests with a single HTTP response or multiple ones with 25-50-100 items on a page. It does not make much sense from usability and scalability perspective to give hyperlinks to the consumer for each item and force them to follow those links one by one. In fact we like to respond with the exact view model the consumer needs and design APIs this way. I think the same is true for nested properties as well. From RDF perspective these responses represent a subgraph of a massive resource graph, which are managed by the REST service and by for example RDF vocabulary maintainers like OWL, Schema.org, etc.
So to have a one sentence answer: the representation of "nested resources" is not covered by REST and as far as I know not covered by standards like HTTP and URI either, but currently it is the best practice to use them and MIME types we frequently use for REST e.g. HAL+JSON or RDF/JSON-LD support nested representations too, so I would say yes.


text:
Q: Get all commits for a given file with LibGit2Sharp From a local repository, I want to get all commits that either created or changed a specific file. Until now our application handled this by putting the filename in the commit message and then searching for commit messages with that name when creating the history. I'd like to have a cleaner solution that doesn't involve commit messages, if possible.
This is what I tried so far:
private List<Commit> GetAllCommitsForFile(string repositoryPath, string filename)
{
    using (var repo = new Repository(repositoryPath))
    {
        List<LogEntry> logs = repo.Commits.QueryBy(Path.Combine(RepositoryPath, filename)).ToList();
        List<Commit> commits = new List<Commit>();

        foreach(LogEntry log in logs)
        {
            commits.Add(log.Commit);
        }

        return commits;
    }
}

The description of the QueryBy-method says:

Returns the list of commits of the repository representing the history of a file beyond renames.

To me, that sounds like it's exactly what I want. Yet, when I pass only the filename, I get a KeyNotFoundException, and when I combine it with the repository path, I get an empty list.

A: I wanted to do something similar and found this post. Maybe this "just works" now due to library updates, but for what it's worth, the following similar code worked for me:
 var repoPath = @"C:\Users\whoever\Documents\git\SomeRepoName";
 var fileOffset = @"YouTube\subscriptions\subscriptions.json";
 var fileOffsetFwdSlash = fileOffset.Replace("\\", "/");
 using (var repo = new Repository(repoPath))
 {
     var logs = repo.Commits.QueryBy(fileOffsetFwdSlash).ToList();
     foreach (var log in logs)
     {
         Debug.WriteLine(log.Commit.Author.When);
     }
 }

I used the file's offset from the repository root, and I needed to replace backslashes with forward slashes. I got almost exactly the same output as from the command line
git log --follow -- YouTube/subscriptions/subscriptions.json

With the exception of the fact that the first commit affecting the file appeared in the command line output and not in LibGet2Sharp's output.


text:
Q: How to delete a single Feature Class from a geodatabase using FME I am trying to produce an FME script that is a replication of an existing python script in order to compare "apples to apples". The point of this project is to prove that FME can process "big data" faster than traditional methods.
Anyways, in order for me to try to accomplish this, I must
1. Not use Python in my FME script and
2. Try to match the logic in the original script verbatim (including unnecessary steps).
My question is then: How can I delete a single feature class from a geodatabase using FME? I understand that the recommended way is to use Python, but since this is not an option for me, and there is no transformer for deleting a single feature class, and there is no way that I can see to do it within a writer, then how can this be accomplished?

A: Initially, I hadn't read the question properly, and answered with a python solution. However, I see now that you can't use python, so I have a different solution for you. It requires that you use the ArcObjects File Geodatabase Writer which I believe is only available if you have ArcGIS installed on the same computer as FME.
The trick is to take advantage of an option in the Advanced Writer Parameters called "SQL To Run After Write". Because File Geodatabases support SQL92, you should be able to run most SQL queries with that. The query you need is:
DROP TABLE "Feature Class Name"

In the below example, I have a file geodatabase with two point feature classes.

My writer is writing to FeatureClass2.

However, with the SQL Query running after the writer finishes, it drops FeatureClass1.

I tried to run this command with multiple tables but didn't have any luck.
Here's some documentation on SQL92.


text:
Q: Problems with global styles on Android, iOS working fine (Xamarin) I'm facing some strange behaviour in my Xamarin App.
In the shared project I separated all control based styles in single xaml files.

All styles are combined in the DefaultTheme.xaml file.

Then, the DefaultTheme.xaml will be used by the LightTheme.xaml and DarkTheme.xaml.

That's how my styles are managed. Then, depending on "Darkomde on/off" I either load the LightTheme.xaml or the DarkTheme.xaml in the iOS and Android project.
On Android I set the themes like this in the MainActivity.cs (I'm using a SplashActivity.cs as well, should it be set there already?)
protected override void OnCreate(Bundle savedInstanceState)
{
    TabLayoutResource = Resource.Layout.Tabbar;
    ToolbarResource = Resource.Layout.Toolbar;

    base.OnCreate(savedInstanceState);

    Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

    LoadApplication(new App());

    SetAppTheme();
}

void SetAppTheme()
{
    if (Resources.Configuration.UiMode.HasFlag(UiMode.NightYes))
        SetTheme(RemoteControlRepetierServer.Theme.Dark);
    else
        SetTheme(RemoteControlRepetierServer.Theme.Light);
}

public void SetTheme(Theme theme)
{
    switch (theme)
    {
        case RemoteControlRepetierServer.Theme.Light:
            // Night mode is not active, we're using the light theme
            if (App.AppTheme == "light")
                return;
            App.Current.Resources = new LightTheme();
            App.AppTheme = "light";

            break;
        case RemoteControlRepetierServer.Theme.Dark:
            // Night mode is active, we're using dark theme
            if (App.AppTheme == "dark")
                return;
            //Add a Check for App Theme since this is called even when not changed really
            App.Current.Resources = new DarkTheme();
            App.AppTheme = "dark";
            break;
    }
    App.CurrentAppTheme = theme;
}

So far so good. Now, if I start my Android app, it seems that not all styles are loaded. For instance the Gauge. While the Gauge on the first tab looks like it should, the Gauge on the second tab doesn't.

Both are using the same XAML for the styling.
<gauge:Scale.Pointers>
    <gauge:NeedlePointer Value="{Binding SelectedExtruder.TempRead}" Color="{DynamicResource Gray-Black}"
                        KnobColor="{DynamicResource Gray-Black}" KnobStrokeColor="{DynamicResource Gray-Black}"/>
    <gauge:RangePointer Value="{Binding SelectedExtruder.TempRead}" Color="{DynamicResource PrimaryColor}"
                    RangeCap="Both"
                    />
    <gauge:MarkerPointer Value="{Binding SetExtruderTemp}" Color="{DynamicResource Red}"/>
</gauge:Scale.Pointers>

Also the Style of the NumericUpDown control is not set on the second tab. This only happens on Android, iOS looks fine all tabs.
I'm not sure what's causing this issue. Any help is appreciated.
If you need further information or code snippets, just let me know.

A: Just figured out that using the SyncfusionTheme was causing this behaviour. Once I removed it from the MergedDictionaries, it worked.


text:
Q: SQL Execute on Certain Date Query I have a small database with my website and I would like to execute a subtraction from everyone's account on a certain date like:
UPDATE Loan SET balance = (balance-amount)
"WHERE Day = 15"

Obviously the last part is just a guess but I have no due date in the loan table so sadly I can't do subtract when curDate= duedate sort of thing so I thought I would just do a set day when everyone's balance is subtracted on a set day.

A: You have to maintain some kind of reference date in order for this to work.
If everyone pays on the same day of the month, add a table that preserves the last time you extracted the fee.  You'll calculate the next fee date using the period and the last time you extracted it.
Remind me not to go to your website.  Too many fees.

A: You can get the DAY() from NOW() function and can use it in your query like
UPDATE Loan SET balance = (balance-amount)
WHERE DAY(NOW()) =15

See fiddle to get day from NOW()


text:
Q: how to open file from ssh server with client program If I have a file (test.cpp) on my server that i have access to via ssh, is it possible to open that file using a program on my machine such as visual studio code without having to create a copy of the file?

A: No from ssh, but you can download/upload file using ssh. You will need additional software for network attached filesystem 'SSHFS, NFS, SAMBA etc.' to make the file accessible for the local system.

A: Yes, this is possible if you use something like sshfs to mount the remote filesystem on your local system - which uses ssh as a transport to create a virtual drive/path a bit like NFS or Windows Filesharing but over ssh.


text:
Q: Why isn't setTimeout cancelling my loop? I wondered how many times can a JavaScript while statement (in Chrome's console) can increment a variable in a millisecond, so I quickly wrote this snippet directly into console:
var run = true, i = 0;
setTimeout(function(){ run = false; }, 1);
while(run){ i++; }

The problem is that it runs forever.
Why is this happening, and how can I solve it?

A: This comes back to the one-threaded nature of JavaScript1. What happens is pretty much this:

*

*Your variables are assigned.

*You schedule a function, to set run = false. This is scheduled to be run after the current function is run (or whatever else is currently active).

*You have your endless loop and stay inside the current function.

*After your endless loop (never), the setTimeout() callback will be executed and run=false.

As you can see, a setTimeout() approach wont work here. You might work around that by checking the time in the while condition, but this will tamper with your actual measurement.
1 At least for more practical purposes you can see it as single-threaded. Actually there is an so called "event-loop". In that loop all functions get queued until they are executed. If you queue up a new function, it is put at the respective position inside that queue. After the current function has finished, the engine takes the next function from the queue (with respect to timings as introduced, e.g., by setTimeout() and executes it.
As a result at every point in time just one function is executed, thus making the execution pretty much single threaded. There are some exceptions for events, which are discussed in the link below.

For reference:

*

*https://stackoverflow.com/a/16757582/1169798
Here a similar scenario was explained in more detail

*https://stackoverflow.com/a/2734311/1169798
A more in-depth description on when JS can be seen as single-threaded and when not.

A: Javascript is single-threaded, that mean it runs only one instruction at a time, sequentially.
The event system, like in many other languages and library, is handle by an event loop. The event loop is basically a loop, which on each iteration check for message in the queue, and dispatch events.
In javascript (as in mot of languages implementing this pattern), the event loop is called when the stack is empty, that is to say, when all functions have returns, in other word, at the end of the program code.
Your "real" program look something like this behind the scene :
var run = true, i = 0;
setTimeout(function(){ run = false; }, 1);
while(run){ i++; }

while(true) {
/*
 * check for new messages in the queue and dispatch
 * events if there are some
 */
  processEvents();
}

So the message from the clock saying timeout is over is never processed.
More info on the event loop on :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop

Of course  it is a bit more complex, check here those examples : Is JavaScript guaranteed to be single-threaded? (tl;dr: In some browser engines, some external events are not dependent on the event loop and are immediately fired when they occur, preempting the current task. But this is not the case with setTimeout, which just add a message to the queue and never fires immediately.)

A: JavaScript is single-threaded so, while you are in the loop, nothing else gets executed.

A: The While loop doesn't access the setTimeout. You have code that sets run true, and then it will never become false.

A: To keep the true speed of Chrome without having to constantly retrieve the time to calculate speed, you could try this JS code:
var start = new Date().getTime()
var i = 0
while(i<1000000)
{
    i++
}
var end = new Date().getTime()
var delta = end-start
var speed = i/delta
console.log(speed + " loops per millisecond")

A: JavaScript has single thread and has single-threaded anywhere.
I think this question in good:
Is JavaScript guaranteed to be single-threaded?
When your code is in loop other ocde not execute and block.


text:
Q: Escape \ in XML? In C# code, I've used the below format for Date Time in .ToString() method.
Format= "\"'\"yyyy-MM-dd HH:mm:ss.fff\"'\""

this format also appends quotes to the formatted date time in string and works well when used in csharp.
However, I want to pass this format in an XML file but serialization fails because of \.
How to escape \"'\" in format ?

A: Backslash (\) is not an escape prefix character in XML:

*

*\ itself does not need to be escaped in XML character data.

*\ itself is not allowed to appear in XML component (element or attribute) names.
To escape:

*

*& use &

*" use "

*' use '

*< use <

*> use >
But be sure to take context into account: XML character escaping requirements are context sensitive.


text:
Q: How to add new sourceset with gradle kotlin-dsl I want to add a sourceset src/gen/java. With groovy this is rather easy and already described in https://discuss.gradle.org/t/how-to-use-gradle-with-generated-sources/9401/5
sourceSets {
   gen {
        java.srcDir "src/gen/java"
    }
}

But I stuck with the kotlin-dsl to add a new one. All I've got is:
java {
    sourceSets {

    }
}

Can anyone help here to

A: kotlin-dsl
sourceSets {
        this.getByName("androidTest"){
            //Adds the given source directory to this set.
            this.java.srcDir("src/mock/java")
        }
        this.getByName("test"){
            this.java.srcDir("src/mock/java")
        }
    }

A: I wanted to add a source set with the name "test-integration" and the source directory src/test-integration/kotlin. I was able to accomplish that by combining the two pre-existing answers:
java.sourceSets.create("test-integration").java {
    srcDir("src/test-integration/kotlin")
}

A: The answer of @s1m0nw1 is correct  to add a new sourceset.
But to just add a new source-folder in an existing sourceset, this can be used:
java.sourceSets["main"].java {
    srcDir("src/gen/java")
}

A: You should try the following:
java.sourceSets.create("src/gen/java")

Hope it's what you need!

A: Worked for me on Gradle 4.10.2:
sourceSets.getByName("main") {
    java.srcDir("src/main/java")
    java.srcDir("src/main/kotlin")
}
sourceSets.getByName("test") {
    java.srcDir("src/test/java")
    java.srcDir("src/test/kotlin")
}

The codes above can also be used in subprojects block.

A: Worked for me on Gradle 4.10.2:
sourceSets.create("integrationTest") {
    java.srcDir("src/integrationTest/java")
    java.srcDir("build/generated/source/apt/integrationTest")
    resources.srcDir("src/integrationTest/resources")
}

A: As of Gradle 7.5:
sourceSets {
    main {
        java.sourceSets {
            create("gen"){
                java.srcDir("src/gen/java")
            }
        }
    }
}

A: This is what I had before:
main.kotlin.srcDirs = main.java.srcDirs = ['src']
test.kotlin.srcDirs = test.java.srcDirs = ['test']
main.resources.srcDirs = ['resources']
test.resources.srcDirs = ['testresources']

Above now translates to:
sourceSets {
main {
    java {
        srcDirs("src")
    }
    resources {
        srcDirs("resources")
    }
}
test {
    java {
        srcDirs("test")
    }
    resources {
        srcDirs("testresources")
    }
}}


text:
Q: Android app loading ARM shared library on x86 device fails I have a really simple android app. I want to load a shared library called 'libcamera.so' and then call methods via JNI.
I do not own this library and I do not have access to the source code. It was originally compiled for ARM.
An x86 version is not available.
The project can detect the library and correctly shows it in the jniLibs folder.
Within my main activity I am trying to load the 3rd party library like so:
static {
    System.loadLibrary("camera");
}

When this line executes, logcat shows the following:
02-06 14:11:38.517 4455-4455/uk.co.test.myApp E/art: dlopen("/data/app/uk.co.test.myApp-2/lib/x86/libcamera.so", RTLD_LAZY) failed: dlopen failed: "/data/app/uk.co.test.myApp-2/lib/x86/libcamera.so" has unexpected e_machine: 40
02-06 14:11:38.519 4455-4455/uk.co.test.myApp E/AndroidRuntime: FATAL EXCEPTION: main
 Process: uk.co.test.myApp, PID: 4455
 java.lang.UnsatisfiedLinkError: dlopen failed: "/data/app/uk.co.test.myApp-2/lib/x86/libcamera.so" has unexpected e_machine: 40
     at java.lang.Runtime.loadLibrary(Runtime.java:371)
     at java.lang.System.loadLibrary(System.java:988)
     at uk.co.test.myApp.MainActivity.<clinit>(MainActivity.java:17)
     at java.lang.reflect.Constructor.newInstance(Native Method)
     at java.lang.Class.newInstance(Class.java:1603)
     at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
     at android.app.ActivityThread.access$800(ActivityThread.java:151)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:135)
     at android.app.ActivityThread.main(ActivityThread.java:5258)
     at java.lang.reflect.Method.invoke(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:372)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Other 3rd party apps which use this library can run on my x86 device (Epson BT350) so I feel like this should be possible.
I have become aware of something called 'Houdini' which allows ARM apps to run on x86 - I have checked and my device has this library so im confused why its not doing its job. But its also quite likely I dont really understand how Houdini works!
I have tried running on an x86 emulator - same error.
Any ideas would be greatly appreciated.

A: I solved the problem by forcing my app to only build an armeabi version. I did this by using an abifilter within gradle. I added the following to my defaultConfig
ndk {
    abiFilters "armeabi"
}

This will then run on my x86 device because Houdini will kick in and do the translation. Its not ideal because this translation affects performance - but its a start and gets me to the next stage.


text:
Q: --diff doesn't appear to compute deltas properly when comparing directories We are using cloc.pl for analysis purpose. And cloc was proved very useful so far when we were just counting lines of code. But now we are trying to get diff between two branches.
Using the documentation mentioned in the link above, I am trying to get the diff:
    perl cloc.pl --diff branch-1.0/ExampleClass.java branch-2.0/ExampleClass.java

This produces perfect result for a single file and reports modified lines correctly. The same is true for other values like removed, added and so on.
-------------------------------------------------------------------------------
Language                     files          blank        comment           code
-------------------------------------------------------------------------------
Java
 same                            0              0            209            294
 modified                        1              0            170             12
 added                           0              0            647              1
 removed                         0              5             64             46
-------------------------------------------------------------------------------
SUM:
 same                            0              0            209            294
 modified                        1              0            170             12
 added                           0              0            647              1
 removed                         0              5             64             46
-------------------------------------------------------------------------------

But now when I'm trying to accomplish same result for complete branch, i.e., all the files under folder, by issuing something like this:
   perl cloc.pl --diff branch-1.0\ branch-2.0\

Now comes the problem.
-------------------------------------------------------------------------------
Language                     files          blank        comment           code
-------------------------------------------------------------------------------
Java
same                            0              0              0              0
modified                        0              0              0              0
added                           0            110           2408            789
removed                         1             32            443            352
-------------------------------------------------------------------------------
SUM:
same                            0              0              0              0
modified                        0              0              0              0
added                           0            110           2408            789
removed                         1             32            443            352
-------------------------------------------------------------------------------

As you can see that when I am trying to issue the command at folder level, all modified number of comments shows 0. All we have is added or removed lines of code or files.
Not sure if I am missing something silly or any issue with cloc tool. I am using version 1.56.

A: This issue got resolved version 1.6. Which helped me to move ahead. Apparently its a bug with version 1.56. Also I moved to use prebuilt "cloc-1.6.exe"
Another thing I found in this regard is one can find more help/support related blog/discussion on http://sourceforge.net/p/cloc/bugs/ which actually helped in my case.


text:
Q: Didn't show counter number and counter bar in php voting system here is my index.html:

        X

Loading........

and rating.php:
include("db.php");
if($_POST['id'] > 0 && $_POST['name']> 0){
    $id=mysql_escape_String($_POST['id']);
    $name=mysql_escape_String($_POST['name']);

    mysql_query("update messages set $name=$name+1 where id='$id'");
    $result=mysql_query("select up,down from messages where id='$id'");
    $row=mysql_fetch_array($result);

    $up_value=$row['up'];
    $down_value=$row['down'];
    $total=$up_value+$down_value;
    $up_per=($up_value*100)/$total;
    $down_per=($down_value*100)/$total;
?>

        Ratings for this blog ( <?php echo $total; ?> total)

            <?php echo $up_value; ?>
            <div id="greebar" style="width:<?php echo $up_per; ?>%">

            <?php echo $down_value; ?>
            <div id="redbar" style="width:<?php echo $down_per; ?>%">

<?php
}

and this is ajax script:

I have tried for a long time, still i can't able to fix error.
It didn't show counter number and count-bar after clicking the like or unlike button.
Now it shows like this http://s15.postimg.org/e6pvjkrej/Untitled_1.png.
I need like this: http://s15.postimg.org/qmmldbkqj/Untitled_2.png
May how can i fix this? can anyone help me to fix this ?
thanks in advance.

A: It was not only the "greenbar" and "redbar". The problem was also the output. You need to echo all the html so that ajax could get the html.

<?php
    include("db.php");
    if($_POST['id'] > 0 && $_POST['name']> 0){
        $id=mysql_escape_String($_POST['id']);
        $name=mysql_escape_String($_POST['name']);

        mysql_query("update messages set $name='".$name+1."' where id='".$id."'");
        $result=mysql_query("select up,down from messages where id='".$id."'");
        $row=mysql_fetch_array($result);

        $up_value=$row['up'];
        $down_value=$row['down'];
        $total=$up_value+$down_value;
        $up_per=($up_value*100)/$total;
        $down_per=($down_value*100)/$total;
    //HTML Output for AJAX Calls
      echo  "

            Ratings for this blog (". $total ." total)

                ". $up_value ."

                ".$down_value."

";
        }
    ?>

Here's the code for HTML Output from the tutorial for reference:
echo 'Ratings for this blog ( '.$total.' total)
Like :'.$up_value.'

Dislike:'.$down_value.'

';

link


text:
Q: A problem using Lagrange multiplier 3 My friend ask me to solve a problem for him, and he told me if I was gonna put it on MSE, I should say this is "dual problem of support vector machine"
Anyway, I can state the problem like this. Let
$$f=x_1+x_2+x_3+x_4+x_5+x_6\\ -x_1^2-4x_2^2-2x_3^2-\frac{1}{2}x_5^2-\frac{1}{2}x_6^2\\-4x_1x_2-2x_1x_3-4x_2x_3
+x_1x_5+x_1x_6\\
+2x_2x_5+2x_2x_6+2x_3x_5$$
Find maximum and minimum of $f$ S.T. $x_i\geq0$ $\forall i$ and $x_1+x_2+x_3=x_4+x_5+x_6$.
I only know the Lagrange multipliers method and it seems not effective. So help me with this problem.
Thank you.

A: Minimization:
By taking $x_1=x_4=t$, $x_2=x_3=x_5=x_6=0$ we get
$$
f(x)=2t-t^2\to -\infty,\quad \text{as }t\to +\infty,
$$so the minimum does not exists.
Maximization: let's replace $g:=-2f$ and minimize it. We substitute also $x_4=x_1+x_2+x_3-x_5-x_6$ and complete some squares to get
\begin{align}
g(x)&=2(x_1+2x_2+x_3)^2+2x_3^2+x_5^2-2x_5(x_1+2x_2+2x_3)+x_6^2-2x_6(x_1+2x_2)-\\
&-4(x_1+x_2+x_3)
\end{align}
and $x_1+x_2+x_3\ge x_5+x_6$ plus positivity constraints.

*

*Try minimization w.r.t. $x_5$ first. The minimum without constraints would be at $x_5=x_1+2x_2+2x_3$, but then
$$
x_1+x_2+x_3\ge x_5+x_6\quad\Leftrightarrow\quad 0\ge x_2+x_3+x_6,
$$
which together with positivity yields $x_2=x_3=x_6=0$. It means that the minimization w.r.t. $x_5$ is always going to be when the constraint is active, that is
$$
x_1+x_2+x_3=x_5+x_6.
$$
(Either it does not let $x_5$ come to $x_5=x_1+2x_2+2x_3$ and becomes active, or it does, but becomes active there anyway.)

*Let's substitute now $x_5=x_1+x_2+x_3-x_6$ and try minimization w.r.t. $x_6$
\begin{align}
g(x)&=x_1^2+4x_1x_2+5x_2^2+2x_2x_3+x_3^2+2x_6^2-2x_6(x_1+x_2-x_3)-\\
&\quad -4(x_1+x_2+x_3)=\\
&=(x_1+2x_2)^2+(x_2+x_3)^2+2x_6^2-2x_6(x_1+x_2-x_3)-\\
&\quad -4(x_1+x_2+x_3)
\end{align}
subject to the constraint $x_1+x_2+x_3\ge x_6$ plus positivity. We have two possibilities here.

Case 1: $x_1+x_2-x_3\le 0$. Then the minimum is at $x_6=0$.
Case 2: $x_1+x_2-x_3\ge 0$. Then differentiation w.r.t. $x_6$ gives
$$
4x_6-2(x_1+x_2-x_3)=0\quad\Leftrightarrow\quad x_6=\frac12(x_1+x_2-x_3)\ge 0.
$$
With this $x_6$ the constraint $x_1+x_2+x_3\ge x_6$ $\Leftrightarrow$ $x_1+x_2+3x_3\ge 0$ is satisfied. The function is convex in $x_6$ and we have found a feasible critical point, thus, it is the minimum w.r.t. $x_6$.

*Continuing minimization in Case 1 above. We substitute $x_6=0$ and will have to minimize
$$
g_1(x)=(x_1+2x_2)^2+(x_2+x_3)^2-4(x_1+x_2+x_3)
$$
subject to $x_1+x_2\le x_3$ plus positivity. Let's change the variables as
$$
y=x_1+2x_2,\quad z=x_2+x_3.
$$
Then we need to minimize
$$
g_1=y^2+z^2-4(x_1+z)
$$
subject to $0\le x_1\le y\le z$. Obviously, we have to take $x_1=y$ (as large as possible), hence
$$
g_1=y^2-4y+z^2-4z,\quad 0\le y\le z.
$$
Differentiation gives the critical point $y=z=2$ which is feasible. The function is convex, thus, it is the minimum. Therefore, the minimization in Case 1 is solved as
$$
x=(2,0,2,0,4,0),\quad \min=-8.
$$

*Doing Case 2 above now. Substitute $x_6=\frac12(x_1+x_2-x_3)$ and minimize
\begin{align}
g_2&=\frac12x_1^2+3x_1x_2+\frac92x_2^2+x_1x_3+3x_2x_3+\frac12x_3^2-4(x_1+x_2+x_3)=\\
&=\frac12\left((x_1+3x_2+x_3)^2-8(x_1+x_2+x_3)\right)
\end{align}
subject to $x_1+x_2\ge x_3$ and positivity. The same change of variables
$$
y=x_1+2x_2,\quad z=x_2+x_3
$$
gives
$$
2g_2=(y+z)^2-8x_1-8z,\quad 0\le x_1\le y,\ z\le y\le x_1+2z.
$$
It is again obvious that minimization w.r.t. $x_1$ is done by $x_1=y$ (as large as possible), hence,
$$
2g_2=(y+z)^2-8(y+z),\quad 0\le z\le y,
$$
and we get the minimum of $g_2$ as $-8$ when $y+z=4$.

*Finally the maximization of $f$ has the parametric solution
$$
x=(2,0,2,0,4,0)+t(1,0,-1,0,-1,1),\quad 0\le t\le 2,
$$
and the maximum is $4$.

A: The three conditions on $x_i$'s can be replaced with two
$f(x_i)=2x_1+2x_2+2x_3-x_1^2-4x_2^2-2x_3^2-\frac{1}{2}x_5^2-\frac{1}{2}x_6^2-4x_1x_2-2x_1x_3-4x_2x_3+x_1x_5+x_1x_6+2x_2x_5+2x_2x_6+2x_3x_5$
and
$x_i \ge 0$.
A max or min of $f$ will occur either at a boundary or an extremum. One of these conditions will be met.
If $x_i$ is a local max or min then
I) $x_i=0$ for some $i$
II) $\nabla_ \mathbf v f(x_i) =0, \\ \forall {\mathbf v}$
$\nabla f_1=2-2x_1-4x_2-2x_3+x_5+x_6$
$\nabla f_2=2-8x_2-4x_1-4x_3+2x_5+2x_6$
$\nabla f_3=2-4x_3-2x_1-4x_2+2x_5$
$\nabla f_5=-x_5+x_1+2x_2+2x_3$
$\nabla f_6=-x_6+x_1+2x_2$
$\nabla f_i =0$ because $\nabla \mathbf v f =0$ when $\nabla f \cdot \mathbf v =0$ for all $\mathbf v$.
This is five equations and five unknowns. Expressed best as a linear transformation similar to the comments.
$$\begin{bmatrix}
-2 & -4 & -2 & 1 & 1 \\
-4 & -8 & -4 & 2 & 2 \\
-2 & -4 & -4 & 2 & 0 \\
1 & 2 & 2 & -1 & 0 \\
1 & 2 & 0 & 0 & -1 \\
\end{bmatrix}\begin{bmatrix} x_1 \\ x_2 \\ x_3 \\ x_5 \\ x_6 \\ \end{bmatrix}=\begin{bmatrix} -2 \\ -2 \\ -2 \\ 0 \\ 0 \\ \end{bmatrix}$$
The inverse is sought as it allows to solve for $\mathbf x$ in $\mathbf A \mathbf x = \mathbf 0 + \mathbf c$
But typically you can just use Gaussian elimination method to reduce to upper diagonal with leading coefficient of $1$. Solving for the $x_i$.
These solutions will be possible max, min, or inflexion. Additional possible max or min in which will not be covered above are all the combinations of $x_i$ where at least one are zero. But $\nabla_{\mathbf v} f$ may not be zero here. One solution is to reduce $f$ by having combinations of $x_i$ be zero and minimizing the resulting function as above. Is it $5!$ possibilities or 121 equations to take derivitive of and check $f$ values?
You have
$$\begin{Bmatrix} 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ \end{Bmatrix}
\begin{Bmatrix} 0 \\ 0 \\ 0 \\ 0 \\ x_5 \\ \end{Bmatrix}
\begin{Bmatrix} 0 \\ 0 \\ 0 \\ x_4 \\ 0 \\ \end{Bmatrix}...$$
However this can be avoided by considering the entire domain for example, if we were so lucky that it only had one derivative having a value of zero while simultaneously the second derivative being constant; there would be no need to check the boundaries.
$\nabla (\nabla f \cdot  \mathbf v) \cdot \mathbf v= \nabla^2 f \Vert \mathbf v \Vert ^2$
Edit
After some thought you do not have to test each of the combinations of $x_i$ as those points lay on the individual curves/hyper surfaces intersecting $f$ and $x_i=0$. Therefore there are give additional equations each the intersection of
$f(x_i)$ and $x_i=0$ for each $i$.
This gives each four equations and four unknowns. The max/min needs to be found and you proceed with the same procedures as before.
Simply compare these zeros with the earlier ones and select the max/ min respectively (throw away ones here less than zero).
Edit 2
You actually do have to test the 120 or however many points as well. Sorry.
Edit 3
Should be $5+4+3+2+1+1=16$ funtions to minimize not 121.


text:
Q: HAXM doesn't support nested virtual machine in AWS I'm using AWS with Windows Server 2016 OS, Android Studio 3.4.2, Java 8. When I tried to create new AVD it shows HAXM doesn't support nested virtual machine. I tried installing BlueStacks and genemotion but both failed.

A: Don't run it on AWS.  AWS is already a virtual machine.  You can't run a virtual machine on a virtual machine-  the CPU architecture doesn't support it.  Run the emulator locally instead.  If you're trying to do this for testing purposes, I'd look into CI platforms that already have all of this solved for you rather than rolling your own.


text:
Q: Finding displacement as a function of time given a Force F(x) If I have a force $F = 4 - 2x$ and want to find the displacement as a function of time i.e. $x(t)$ I'm confused why the answer wouldn't just be $4 - 2x$ integrated twice. Also for this question $m = 1$ so I don't need to worry about it for now.
If anyone could help me I would greatly appreciate it. I've tried searching for an answer but I don't think I'm searching correctly and I'm really disappointed I can't answer this

A: The displacement is just the acceleration integrated twice, but it is integrated with respect to time.  To get the velocity you would integrate once, so you have $v=v_0+\int_o^\tau x(\tau) d\tau$.  We don't (yet) know what $x(\tau)$ is so we cannot do the integral.  The differential equation approach solves this problem.  If we write $F=x''$ because you have $m=1$ you get $x''=4-2x$.  You still need starting conditions before you get a complete solution.


text:
Q: Understanding array sorting behavier php I have this array
$array = array(2, 1, "img1", "img2", "img10", 1.5, "3.14", "2.72");

after applying sort function it becomes
sort($array);

Array
(
    [0] => 2.72
    [1] => 3.14
    [2] => img1
    [3] => img10
    [4] => img2
    [5] => 1
    [6] => 1.5
    [7] => 2
)

I did't understand how the sorting is performed.
Can anyone explain how the output array is achieved?
EDIT:
Here the question is not that which SORT FLAG should I use but the question is how the above sorting is performed. Any advise to use another SORT FLAG is useless here.

A: The first two numbers were actual strings (you passed them within quotes), so they are treated like so: numbers come before any letter in alphabetic sorting.
The other ones were real numbers (without quotes), so the function put them separately, sorting them numerically.
array(8)
    0 => '2.72'    [alphabetical]
    1 => '3.14'    [alphabetical]
    2 => 'img1'    [alphabetical]
    3 => 'img10'   [alphabetical]
    4 => 'img2'    [alphabetical]
    5 => 1         [numeric]
    6 => 1.5       [numeric]
    7 => 2         [numeric]

So, the function has to decide if it will sort the elements alphabetically (a,b,c...) or numerically (1,2,3..) so it just checks the variable type.
Like Pekka pointed out, there are flags that can be set to force the type of sorting. They are described in the docs.

EDIT
This theory was proved wrong in the comments and I'm totally lost now (:
This comment at the docs contains some interesting points on this issue.

A: Using the information in the link for Coanda as a starting point, it is clear that PHP using type juggling when comparing objects of different types. The problem is understanding what is getting casted to what during comparison, and I still havn't been able to find a complete list, but in general:
string compared to int will turn into
(int) string <,>,=, (int) int

In this case the string, after casting becomes 0, so all ints are greater than a string. (expected). This is the only case we need to worry about for this sort.
PHP uses quicksort, and most likely chooses its pivot point as array[n/2] where n is the number elements in the array. Knowing these two pieces of information we quicksort the above array:
$pivot = $array[n/2] //n is the number of elements, this sets $pivot='img2'
//compare each element in the list (i am going to this by hand for demonstration)

(int) 'img2' < 2 //int to int comparison;'img2' resolves to 0 and 0 < 2
(int) 'img2' < 1 //int to int comparison;'img2' resolves to 0 and 0 < 1
      'img2' > 'img1' // string to string comparison; strcmp is +256
      'img2' > 'img 10' //string to string comparison; strcmp is +256
(float) 'img2' < 1.5 //float to float comparison;'img2' resolves to 0 and 0<1.5
      'img2' > '3.14' //string to string comparison; strcmp is +54
      'img2' > '2.72' //string to string comparison; strcmp is +55

We now have to two new arrays (one for greater and one for less than).
 $greater = array('img1', 'img10', '3.14', '2.72);
 $less = array(2, 1, 1.5);

Now there is little need to go into further detail as we have accidentally made 2 arrays that have all easily comparable objects in it. $greater has only strings, and we can assume sort will work normally here and considering everything a string.
sort($greater);
var_dump($greater);

produces
array(4) {
  [0]=>
  string(5) "2.72"
  [1]=>
  string(4) "3.14"
  [2]=>
  string(4) "img1"
  [3]=>
  string(5) "img10"
}

This is what we expected and also the result above. We do the same with $lesser
$lesser = array(2, 1, 1.5);
sort($lesser);
var_dump($lesser);

we get
array(3) {
  [0]=>
  int(1)
  [1]=>
  float(1.5)
  [2]=>
  int(2)
}

Which is also expected. Now when we concat all three arrays together (for the sake of recursiveness I am calling 'img2' an array). We get the results above.
Array
(
[0] => 2.72
[1] => 3.14
[2] => img1
[3] => img10
[4] => img2
[5] => 1
[6] => 1.5
[7] => 2
)

To prove this point, you can follow the same process for this same array, but switch out the $arr[3] with an integer.
$arr = array("img2", 1, "img1", 2, "img10", 1.5, "3.14", "2.72");
sort($arr);
var_dump($arr)

gives you a totally different result because the pivot changed from a string to an int causing the float strings to evaluate as floats.
array(8) {
[0]=>
string(4) "img1"
[1]=>
string(5) "img10"
[2]=>
string(4) "img2"
[3]=>
int(1)
[4]=>
float(1.5)
[5]=>
int(2)
[6]=>
string(4) "2.72"
[7]=>
string(4) "3.14"
}

A: The following bug gives more insight in sorting mixed types: https://bugs.php.net/bug.php?id=21728
Quote:
<?php
$arr1 = array("a","b","c","d","4",5,4,"true","TRUE",true);
sort($arr1);
var_dump($arr1);
?>

The output is :
array(10) {
  [0]=>
  bool(true)
  [1]=>
  int(4)
  [2]=>
  string(1) "4"
  [3]=>
  string(4) "TRUE"
  [4]=>
  string(1) "a"
  [5]=>
  string(1) "b"
  [6]=>
  string(1) "c"
  [7]=>
  string(1) "d"
  [8]=>
  string(4) "true"
  [9]=>
  int(5)
}

It may look strange - why (int)5 is after all the strings. This is because "4" is lower than (int) 5, "4" is before "true" and "true" is
  before 5. The first 2 are obvious, the third one is not. But it is ok.
  It's better not to mix types in the array. If 5 is changed to "5" then
  "5" goes right after "4".


text:
Q: Can't run selenium test through Jenkins in Docker So I have VM with Ubuntu on it. The host is on Win10. Inside this VM I installed a docker where I pulled jenkins and installed selenium plugin for jenkins.
I could reached a selenium node from win10. But when I try to launch a test from my IDE :
val cap: DesiredCapabilities =  DesiredCapabilities.chrome()
cap.setBrowserName("chrome")
webDriver = new RemoteWebDriver(new URL("http://192.168.10.223:4445/wd/hub/"), cap)
go to "https://www.google.com"

I have this error and i don't understand why...
Exception encountered when invoking run on a nested suite - Unable to create new service: ChromeDriverService
Build info: version: '3.12.0', revision: '7c6e0b3', time: '2018-05-08T15:15:08.936Z'
System info: host: '2d3135afb490', ip: '172.17.0.2', os.name: 'Linux', os.arch: 'amd64', os.version: '4.15.0-24-generic', java.version: '1.8.0_171'
Driver info: driver.version: unknown
Command duration or timeout: 101 milliseconds

Am I doing something wrong ? or am I missing some configuration ?

A: Docker Containers do not have a Desktop(and your selenium process is running inside such a container if I udnerstood it right) so they will not run UI tests. Your chances are:

*

*Use PhantomJS Driver. This is a browser that won't render anything and does not need a Desktop. Disclaimer: Tried it in Headless(Desktopless) sessions but not on Docker

*Try to Hack your Docker image and create an X Desktop Session.


text:
Q: Law of large numbers for transformed and non-transformed random variables Law of large numbers states that:
If $X_1, \dots X_n \sim p(x)$ are IID, then $ \frac{1}{n} \sum_{i=1}^{n} X_i \rightarrow \mathbb{E}_{p(x)}\{X\}= \mu$, where $X \sim p(x)$.
Below is what I'm having trouble connecting to this, as this is new notation for me from an online lecture:
If we have a function $f(X)$ of some random variable $X$ and a pdf $p(x)$, then by LLN $\frac{1}{n} \sum_{i=1}^{n} f(X_i) \rightarrow \mathbb{E}_{p(x)}\{f(X)\}$, where $X_1, \dots , X_n \sim p(x)$
Is $p(x)$ referring to the transformed PDF of $X$ under $f(\cdot)$ or a different distribution? Or is this notation too ambiguous to tell?
So in the first case, $X_1, \dots X_n \sim g(x)$, therefore $f(X_1), \dots, f(X_n)$ are random variables with pdf $p(x)$, where $p(x)$ can be computed using the formula for transformation of a random variable. Hence, we can use LLN to state that the summation will eventually converge to $\mathbb{E}\{f(X)\}$ where $X \sim p(x)$, which can also be written as $\mathbb{E}_{p(x)}\{f(X)\}$.


text:
Q: Constructing a Homothety This exercise has me stumped.  I am meant to apply concepts concerning homotheties with circles to solve it.  The problem states:
Given halflines k, l starting at a common point (let's call this point V), and a point P inside the angle formed by k and l, construct a circle through P tangent to k and l.
I tried multiple approaches to constructing this circle however I have yet to solve the problem.
Any help is much appreciated!

A: Consider the following figure:

Here are the steps of construction you have to follow:

*

*Construct the angle bisector of $k$ and $l$

*Take an arbitrary point (red thick) on the angle bisector.

*Drop a perpendicular to $l$ from the red point.

*Draw the red circle.

*Draw a line through $P$ and the intersection of $k$ and $l$.

*This line will intersect the red circle.

*Connect this latter intersection point with the center of the red circle.

*Draw a parallel with this latter line through $P$.

*This parallel will intersect the angle bisector of $k$ and $l$.

*This intersection point will be the center of the circle wanted.

Note that there is another circle through P that is tangent to $k$ and $l$. We could have chosen the other intersection point on the red circle...


text:
Q: How to place some text visually before a heading without breaking the logical heading structure? Often designers require something like this, e.g. when displaying search results:

Search results

Home > Departement > Section > Bla

Title of the document

Some content... some content...

Home > Departement > Section > Bla

Title of the document

Some content... some content...

...etc...

While visually this is nice, it's pretty hard code it in HTML, because the breadcrumb (Home > Departement...) is placed in front of the heading to which it actually belongs.
In fact, the HTML would look something like this:

Search results

Title of the document

Home > Departement > Section > Bla

Some content... some content...

Title of the document

Home > Departement > Section > Bla

Some content... some content...

...etc...

I know there are ways to position stuff absolutely etc., making stuff look as needed while keeping the correct HTML in the background, but this is always tricky and is dependent of some assumptions like that you know how much height needs to be reserved for the absolutely positioned element, etc., which comes to its limits quickly.
Are there better ways of doing this? Maybe the HTML articles come to our rescue, so we can simply surround each search element with it? Would this be correct?

Search results

Home > Departement > Section > Bla

Title of the document

Some content... some content...

Home > Departement > Section > Bla

Title of the document

Some content... some content...

A: Yes, this is exactly the purpose of sectioning content elements (like article).
Thanks to using a sectioning content element here, the .location is in scope of its heading, even when the heading comes later.
And the sectioning content element article is appropriate for a search result.
It's not required, but you might want to use a header element to denote that the .location is not part of the section's main content:

Home → Departement → Section → Bla

Title of the document

Some content … some content …


text:
Q: Is it possible to add settings to "allow-plugins" in config section in composer.json through the CLI? Since composer 2.2 the setting allow-plugins will be compulsory I've tried to push this setting through the composer config command in the CLI but with no luck.
I've tried a few commands like:

*

*composer config --json '{"allow-plugins.composer/installers":true, "allow-plugins.dealerdirect/phpcodesniffer-composer-installer": true, "allow-plugins.roots/wordpress-core-installer": true }'

*composer config config.allow-plugins '{"composer/installers":true, "dealerdirect/phpcodesniffer-composer-installer": true, "wordpress-core-installer": true}'

*composer config --append "allow-plugins" "composer/installers":true, "dealerdirect/phpcodesniffer-composer-installer": true, "wordpress-core-installer": true

*composer config --json "allow-plugins" '{"composer/installers":true, "dealerdirect/phpcodesniffer-composer-installer": true, "roots/wordpress-core-installer": true }'
All I get is error messages like ".. is not defined" or that it is an invalid value.
What I have is this:
 "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist"
},

And, I need to add the settings like this:
"config": {
    "optimize-autoloader": true,
    "preferred-install": "dist",
    "allow-plugins": {
        "composer/installers": true,
        "dealerdirect/phpcodesniffer-composer-installer": true,
        "roots/wordpress-core-installer": true
     }
},

Is this possible through the CLI?

A: You need to pass set them one by one.
composer config allow-plugins.composer/installers true
composer config allow-plugins.dealerdirect/phpcodesniffer-composer-installer  true
composer config allow-plugins.roots/wordpress-core-installer true

Edit per conversation in comments:
OP was looking to also achieve not being prompted during the command. To do this, we must pass the --no-interaction (or -n) option. This can be useful when performing automation tasks.
Full Example of OP's Plugins:
composer config --no-interaction allow-plugins.composer/installerstrue
composer config --no-interaction allow-plugins.dealerdirect/phpcodesniffer-composer-installer true
composer config --no-interaction allow-plugins.roots/wordpress-core-installer true


text:
Q: Finding events that occur together I'm interested in computing hashtag correlation; that is, given one hashtag, which other hashtags are likely? I know how to do correlation when the data is in $(x, y)$ format, but this is in $(timestamp, hashtag)$ format.
I'm looking for a way to find "clumpiness" of any two given hashtags, measured in some unit of time--a "clumpiness" with a small time value means they hang together, whereas a "clumpiness" with a large time value means there isn't as much of a relationship.
EDIT: Sample data--for instance, looking for a link between exercise and mood. Looking at the table there appears to be a link between #exercised and #goodMood, how would I quantify that? Also, there appears to be a negative correlation between #exercised and #okMood.
September 1, 2013 7:00 AM     #exercised
September 1, 2013 9:00 AM     #goodMood
September 2, 2013 10:00 AM    #okMood
September 3, 2013 7:00 AM     #exercised
September 3, 2013 9:00 AM     #goodMood
September 4, 2013 9:00 AM     #okMood

A: The problem with what you intend to quantify, is that you would need to record hashtags in pre-defined and recurring time-points, otherwise you will not be able to draw valid inferences.
For example, if the second #goodMood was recorded at September 3, 2013 11:00 AM, but no record of any hashtag was made at September 3, 2013 9:00 AM, then you would not be able to say, "hmm, not much clumpiness here" (the scientifically recognizable word is "clustering") - because you could not say whether #goodMood has already set in at 9:00 AM, or not...
...except if there is some (actually observed) rule that says that "I record a hashtag the moment I feel it sets in". In such a case, you could easily create a data sample with time intervals (#goodmod set in 2 hours after exercise, 3 hours after exercise, 1 hour after exercise etc)- and then go on and calculate their mean, variance, and other statistics of interest. This would give you for example the average time interval between exercise and #goodMood -an absolute figure, which could then be compared to other central tendency statistics from other pairs, and create a ranking.

A: I'd build a N×N table of N hashtags. Each row corresponds to a hashtag, and each column corresponds to a hashtag too. Each cell is the sum of distances (in hours) between a hashtag row and column. For your example this would be the table:
$$\begin{array}{ccc}\text{#exercised}&\text{#goodMood}&\text{#okMood}\\\hline0&2&4\\2&0&2\\1&2&0\end{array}$$
This tells me that #ex and #go are often close to each other.


text:
Q: Is it thread safe to modify a static variable? Since C++11, static variable initialization is guaranteed to be thread safe. But how about modifying a static variable in multiple threads? like below
static int initialized = 0;
Initialize()
{
 if (initialized)
    return;
 initialized = 1; // Is this thread safe?
}

The reason I ask this question is that I am reading the source code for
Py_Initialize(), I am trying to embed Python in a multithreaded C++ application, I am wondering if it is safe to call Py_Initialize() multiple times in several threads? The implementation of Py_Initialize() boils down to
function _Py_InitializeEx_Private, which is like below
// pylifecycle.c
static int initialized = 0;

_Py_InitializeEx_Private(int install_sigs, int install_importlib)
{
    if (initialized)
        return;
    initialized = 1;
 // a bunch of other stuff
 }

And is the conclusion for C the same as C++?
EDIT
So all the answers are good, I chose the one which clears my head most.

A: No, static in this context is only about the storage duration (see http://en.cppreference.com/w/c/language/static_storage_duration).
The variable has no extra thread safety at all over some other variable.
Try using std::call_once for this, see http://en.cppreference.com/w/cpp/thread/call_once

A: It's not thread safe to modify a static variable, but initializing a static variable is thread safe. So you can do:
void my_py_init() {
    static bool x = (Py_Initialize(), true);
}

That's it. You can now call my_py_init from as many threads as you want and Py_Initialize will only ever get called once.

A: Py_Initialize is not thread-safe. You can call it from multiple threads only if you know that the Python interpreter has already been initialized, but if you can prove that it would be silly to call the function.
Indeed, most Python C-API calls are not thread-safe; you need to acquire the Global Interpreter Lock (GIL) in order to interact with the Python interpreter. (See the Python C-API docs for more details. Read it carefully.)
However, as far as I know you cannot use the standard API to acquire the GIL until the interpreter has been initialized. So if you have multiple threads, any of which might initialize the same Python interpreter, you would need to protect the calls to Py_Initialize with your own mutex. You might well be better off doing the initialization once before you start up any threads, if that is possible with your program logic.

The code you cite:
static int initialized = 0;

void Initialize_If_Necessary()
{
    if (initialized)
        return;
    initialized = 1;
    // Do the initialization only once
}

is clearly not threadsafe in any language, even if initialized is an atomic type. Suppose two threads were simultaneously executing this code before any initialization happened: both of them see initialized as false, so both of them proceed with the initialization. (If you don't have two cores, you could imagine that the first process is task switched between the test of initialized and the assignment.)

A: Modifying a static variable across multiple threads is not safe, since if the variable is put into a register, then other cores' information in the same registers will be different (modifying the variable in another thread would be the same as attempting to access that core's version of the register, which contains completely different data).

A: The first code sample is the typical starting point for what is referred to as 'lazy-initialisation'. It's useful for guaranteeing once-only initialisation of "expensive objects"; but doing so only if needed just before any use of the object.
That specific example doesn't have any serious problems, but it's an oversimplification. And when you look more holistically at lazy-initialisation, you'll see that multi-threaded lazy-initialisation is not a good idea.

The concept of "Thread Safety" goes way beyond just a single variable (static or otherwise). You need to step back and consider things happening to the same1 resources (memory, objects, files, ...) at the same time.
1: Different instances of the same class are not the same thing; but their static members are.
Consider the following extract from your second example.
if (initialized)
    return;
initialized = 1;
// a bunch of other stuff

In the first 3 lines, there's no serious harm if multiple threads execute that code approximately concurrently. Some threads might return early; others might be a little "too quick" and all perform the task of setting initialized = 1;. However, that wouldn't be a concern, since no matter how many threads set the shared variable, the net effect is always the same.
The problem comes in with the fourth line. The one almost nonchalantly brushed aside as "a bunch of other stuff". That "other stuff" is the really critical code, because if it's possible for initialized = 1; to be called multiple times, you need to consider the impact of calling "other stuff" multiple times and concurrently.

Now, in the unlikely event you satisfy yourself that "other stuff" can be called multiple times, there's another concern...
Consider the client code that might be using Python.
Py_Initialize();
//use Python

If 2 threads call the above simultaneously; with 1 'returning early' and the other actually performing the initialisation. Then the 'early-returning thread' would start (or try to start) using Python before it's fully initialised!
As a bit of a hack, you might try blocking at the if (initialized) line for the duration of the initialisation process. But this is undesirable for 2 reasons:

*

*Multiple threads are likely to be stuck waiting in the early stages of their processing.

*Even after initialisation is complete you'd have a small (but totally wasteful) overhead of checking the lock each time you 'lazy-initialise' the Python framework.

Conclusion
Lazy-initialisation has its uses. But you're much better off not trying to perform the lazy initialisation from multiple threads. Rather have a "safe thread" (main thread is usually good enough) that can perform the lazy-initialisation before even creating any threads that would try to use whatever has been initialised. Then you won't have to worry about the thread-safety at all.