text:
Q: Find element in array --> Method post. Typescript When I login in app, ws post me and my user permission, like this json
   {"StatusCode":0,"StatusMessage":"Authentificated Successfully",
    "Token":"eyJhbGciOiJIUzI1NiIs",
    "StatusDescription":{
    "Role":"admin",
    "Permissions":["homeboxpackageactivate",
    "eventscreate",
    "pollinglivememory",
    "pollinglivememorygetall",
    "usersgetall",
    "app_rolescreate",
    "app_rolesupdatebyid"
     ....]}}

Can you suggest me how to find my permissions from this array?
I create
canActivate(component: string): boolean {
        return this.permissions && this.permissions.find(x => x.permissin_desc === component) != null;
    }

in html code I use *ngIf like this:
*ngIf="ws.canActivate('usersgetall')"

In this, don't show nothing because i control outside my array Permissions. Can you help please?

A: You just need to check if Permissions array contains component value or not and for that you can use includes
canActivate(component: string): boolean {
   return this.Permissions && this.Permissions.includes(component);
}

Note the case of your Permission property.


text:
Q: Cannot run fsck on broken FAT after "unsafe" device removal I've got an SD card I've accidentally removed without unmounting on an Android phone. After this, the card shows up as having files with garbage names and dates. Seems, that FAT got broken but I cannot run fsck on this drive:
$ sudo dosfsck -n /dev/sdb
dosfsck 3.0.7, 24 Dec 2009, FAT32, LFN
Logical sector size (64543 bytes) is not a multiple of the physical sector size.

How I can work around this error and recover the data?

A: While it doesn't help to repair the file system, the error actually means that you have to specify partition and not disk to fsck:
$ sudo dosfsck -n /dev/sdb1

as opposed to
$ sudo dosfsck -n /dev/sdb

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exit PowerShell script using 'exit' kills my program completely I am using a form window to get some input from a user and I am asking in a do-while loop if the input is correct (like this:)
while(($ParID -ne 6) -or ($Research_Groups -ne 3) -or ($Customer -lt 1) -or ($Projectname -lt 1))

The problem with this request is that I wanna ask if the field is empty but if he presses cancel without entering anything the window will open again like a while(true) loop...
I have also made a cancel button to 'exit' the programm where I did put (yeah you guessed right) an exit behind this button and my problem is that PowerShell throws me an error that the programm has crashed so I am searching for a save way to stop my programm from crashing!
 $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") #Escape (ESC) -> when the key 'Escape (ESC)' has been pressed then the window closes
        {$objForm.Close()}}) #windowclose -> closes the window

this it he error it throws:

DO {

    $objForm = New-Object System.Windows.Forms.Form #init -> initializing window form

    $objForm.Text = "Input Window v0.5" #name -> the name which will be display in the top border of the window

    $objForm.Size = New-Object System.Drawing.Size(300,250) #size -> set the size of the window

    $objForm.StartPosition = "CenterScreen" #location -> where the window will appear on the screen

    $objForm.FormBorderStyle = 'Fixed3D' #sizing -> fixes the size of the window so you cannot make it bigger

#objForm Keys -> here are the keys 'Enter' and 'Escape (ESC)' defined to the buttons 'OK' and 'Cancel'

    $objForm.KeyPreview = $True

    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") #Enter -> when the key 'Enter' has been pressed read out the input fields and assign them to variables

        {$ParID=$ParIDInbox.Text;$Research_Groups=$ResearchGroupInbox.Text;$Customer=$CustomerInbox.Text;$Projectname=$ProjectnameInbox.Text;$objForm.Close()}}) #variables -> assigns the variables

    $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") #Escape (ESC) -> when the key 'Escape (ESC)' has been pressed then the window closes

        {$objFOrm.Close()}}) #windowclose -> closes the window

#OKButton -> creates a button with the value 'OK'

    $OKButton = New-Object System.Windows.Forms.Button #initialization -> initializes the button

    $OKButton.Location = New-Object System.Drawing.Size(75,180) #Location -> where the button is located in the window

    $OKButton.Size = New-Object System.Drawing.Size(75,23) #Size -> defines the size of the button

    $OKButton.Text = "OK" #value -> sets the value of the button to 'OK'

    $OKButton.Add_Click({$ParID=$ParIDInbox.Text;$Research_Groups=$ResearchGroupInbox.Text;$Customer=$CustomerInbox.Text;$Projectname=$ProjectnameInbox.Text;$objForm.Close()}) #variables -> assigns the variables

    $objForm.Controls.Add($OKButton) #adding -> adds the button to the window

#CancelButton -> creates a button with the value 'Cancel'

    $CancelButton = New-Object System.Windows.Forms.Button #initialization -> initializes the button

    $CancelButton.Location = New-Object System.Drawing.Size(150,180) #Location -> where the button is located in the window

    $CancelButton.Size = New-Object System.Drawing.Size(75,23) #Size -> defines the size of the button

    $CancelButton.Text = "Cancel" #value -> sets the value of the button to 'Cancel'

    $CancelButton.Add_Click({$objFOrm.Close()}) #closing -> closes the window after clicked

    $objForm.Controls.Add($CancelButton) #adding -> adds the button to the window

#ParID_Label -> creates a Label for the 'Par ID' input field

    $ParIDLabel = New-Object System.Windows.Forms.Label #initialization -> initializes the label

    $ParIDLabel.Location = New-Object System.Drawing.Size(10,10) #Location -> where the label is located in the window

    $ParIDLabel.Size = New-Object System.Drawing.Size(280,20) #Size -> defines the size of the label

    $ParIDLabel.Text = "Par ID (6 numbers!)" #value -> sets the value of the Label to 'Par ID (6 numbers)'

    $objForm.Controls.Add($ParIDLabel) #adding -> adds the label to the window

#ParID Input Box -> Input box for the Par ID input

    $ParIDInbox = New-Object System.Windows.Forms.TextBox #initialization -> initializes the input box

    $ParIDInbox.Location = New-Object System.Drawing.Size(10,30) #Location -> where the label is located in the window

    $ParIDInbox.Size = New-Object System.Drawing.Size(260,20) #Size -> defines the size of the inputbox

    $objForm.Controls.Add($ParIDInbox) #adding -> adds the input box to the window

#Research Group Label -> creates a Label for the 'Research Group' input field

    $ResearchGroupLabel = New-Object System.Windows.Forms.Label #initialization -> initializes the label

    $ResearchGroupLabel.Location = New-Object System.Drawing.Size(10,50) #Location -> where the label is located in the window

    $ResearchGroupLabel.Size = New-Object System.Drawing.Size(280,20) #Size -> defines the size of the label

    $ResearchGroupLabel.Text = "Research Group (3 letters!)" #value -> sets the value of the Label to 'Research Group (3 letters!)'

    $objForm.Controls.Add($ResearchGroupLabel) #adding -> adds the label to the window

#Research Group Input Box -> Input box for the Research Group input

    $ResearchGroupInbox = New-Object System.Windows.Forms.TextBox #initialization -> initializes the input box

    $ResearchGroupInbox.Location = New-Object System.Drawing.Size(10,70) #Location -> where the label is located in the window

    $ResearchGroupInbox.Size = New-Object System.Drawing.Size(260,20) #Size -> defines the size of the inputbox

    $objForm.Controls.Add($ResearchGroupInbox)  #adding -> adds the input box to the window

#Customer Label -> creates a Label for the 'Customer' input field

    $CustomerLabel = New-Object System.Windows.Forms.Label #initialization -> initializes the label

    $CustomerLabel.Location = New-Object System.Drawing.Size(10,90) #Location -> where the label is located in the window

    $CustomerLabel.Size = New-Object System.Drawing.Size(280,20) #Size -> defines the size of the label

    $CustomerLabel.Text = "Customer" #value -> sets the value of the Label to 'Customer'

    $objForm.Controls.Add($CustomerLabel) #adding -> adds the label to the window

#Customer Input Box -> Input box for the Customer input

    $CustomerInbox = New-Object System.Windows.Forms.TextBox #initialization -> initializes the input box

    $CustomerInbox.Location = New-Object System.Drawing.Size(10,110) #Location -> where the label is located in the window

    $CustomerInbox.Size = New-Object System.Drawing.Size(260,20) #Size -> defines the size of the inputbox

    $objForm.Controls.Add($CustomerInbox) #adding -> adds the input box to the window

#Projectname Label -> creates a Label for the 'Projectname' input field

    $ProjectnameLabel = New-Object System.Windows.Forms.Label #initialization -> initializes the label

    $ProjectnameLabel.Location = New-Object System.Drawing.Size(10,130) #Location -> where the label is located in the window

    $ProjectnameLabel.Size = New-Object System.Drawing.Size(280,20) #Size -> defines the size of the label

    $ProjectnameLabel.Text = "Projectname"  #value -> sets the value of the Label to 'Projectname'

    $objForm.Controls.Add($ProjectnameLabel) #adding -> adds the label to the window

#Projectname Input Box -> Input box for the Projectname input

    $ProjectnameInbox = New-Object System.Windows.Forms.TextBox #initialization -> initializes the input box

    $ProjectnameInbox.Location = New-Object System.Drawing.Size(10,150) #Location -> where the label is located in the window

    $ProjectnameInbox.Size = New-Object System.Drawing.Size(260,20) #Size -> defines the size of the inputbox

    $objForm.Controls.Add($ProjectnameInbox) #adding -> adds the input box to the window

    $objForm.Topmost = $True #topmost -> A topmost form is a form that overlaps all the other (non-topmost!) forms!

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

$checkInputs =  {
    (($using:ParID -ne 6) -or
    ($using:Research_Groups -ne 3) -or
    ($using:Customer -lt 1) -or
    ($using:Projectname -lt 1)) -and
    !$using:Exit
}

while(Invoke-Command $checkInputs)
{
    exit
}

} while($ParID)

A: Have you tried break instead of exit? This will stop your While loop.
Or, if you need to exit your program entirely, you should dispose your active form $Form.Dispose() instaed of brutal exit.
EDIT:
In most cases you should not create and spawn your form itself inside do/while loop. In my opinion it's better to use while for checks not for the entire form. That is how I imagine that:
#OKButton -> creates a button with the value 'OK'
$OKButton = New-Object System.Windows.Forms.Button #initialization -> initializes the button
$OKButton.Location = New-Object System.Drawing.Size(75,180) #Location -> where the button is located in the window
$OKButton.Size = New-Object System.Drawing.Size(75,23) #Size -> defines the size of the button
$OKButton.Text = "OK" #value -> sets the value of the button to 'OK'

$OKButton_OnClick = {

    if (
        ($ParIDInbox.Text.Length -lt 6) -or
        ($ResearchGroupInbox.Text.Length -lt 3) -or
        [string]::IsNullOrWhiteSpace($CustomerInbox.Text) -or
        [string]::IsNullOrWhiteSpace($ProjectnameInbox.Text.Length)
    ) {
        [System.Windows.Forms.MessageBox]::Show("Please fill out all of the form fields", "ERROR",
            [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
    }
    else {
        $ParID=$ParIDInbox.Text
        $Research_Groups=$ResearchGroupInbox.Text
        $Customer=$CustomerInbox.Text
        $Projectname=$ProjectnameInbox.Text

        Write-Host -f Yellow "$ParID | $Research_Groups | $Customer | $Projectname"

        $objForm.Dispose()
    }
}

$OKButton.Add_Click($OKButton_OnClick) #variables -> assigns the variables
$objForm.Controls.Add($OKButton) #adding -> adds the button to the window

The code above works for me. Have just checked.
If you need to call your form multiple times just call it in a while loop - dont recreate it. Everytime you call the form it takes default values for the form objects. It's better to check form fields, not the variables you provide values to.
while ($condition) {
    $objForm.ShowDialog()
}

$objForm.Dispose()

EDIT2:
More bright ideas: you do not need to check values length - you can set the MaxLength parameter for them
$ParIDInbox.MaxLength = 6
$ResearchGroupInbox.MaxLength = 3

A: You could also set a bool e.g. $Exit and check it within your while condition:
$checkInputs =  {
    (($using:ParID -ne 6) -or
    ($using:Research_Groups -ne 3) -or
    ($using:Customer -lt 1) -or
    ($using:Projectname -lt 1)) -and
    !$using:Exit
}

while(Invoke-Command $checkInputs)
{
    # do your things here
}


text:
Q: Shoretel - Maximum length of name for Shoregear SG-50 For a Shoregear SG-50, what is the maximum number of characters you can use for the name of the switch? We'd like to use 20 characters but before we do, are there any practical limitations of a name this long?
How many characters are allowed in this field:

A: In the database, the name field is called HostName and is defined as 255 characters long. The Description field is called SwitchName in the database and only 50 characters long.


text:
Q: AWK: search for filename within another text file producing syntax error I have a text file (file_list.txt) that contains a list of filenames (e.g. contour_0.6_266_midpoints_2_0_0.dat).
I have a second file ($iw_fitted_midpoints_file.dat) which contains these filenames followed by a series of parameters and x, y information. The first 10 lines of $iw_fitted_midpoints_file.dat are:
> -Z contour_0.6_266_midpoints_2_0_0.dat 0.125512 96 0.009539 0.000017 1524.160000 1.000000 97.000000 44.000000 4 6 0.670000 0.214029 0.214030 -1.180430 -0.636157 1.307050 -0.647329 -1.101411 36.000000 -0.647530 0.145132 -1.400605 0.219184 30.949074 0.670000 48.602367 0.200000 -4.915458 -1.573416 0.428059 3376.000000
3333.000000 0.105569
3334.000000 0.106486
3335.000000 0.107501
3336.000000 0.109010
3337.000000 0.110718
3338.000000 0.107739
3339.000000 0.107382
3340.000000 0.106499
3341.000000 0.106408

I am trying to search the second file ($iw_fitted_midpoints_file.dat) for each filename and extract column 32 of the relevant line. My problem is that I cannot get the syntax for escaping the "." in the filenames correct.
This is my code
for f in `cat file_list.txt`; do

name=$(echo "$f" | cut -f 1,2,3 -d '.')
K=awk '{if ($1 == ">" && $2 ~ '\${name}') print $0}'$iw_fitted_midpoints_file.dat
echo $K

  done

And this is my error
awk: {if ($1 == ">" && $2 ~ contour_0.6_96_midpoints_16_0_0.dat) print $0}
awk:                                                       ^ syntax error

For example, if I was searching for contour_0.6_266_midpoints_2_0_0.dat the above code would give me K=-1.573416 (i.e. the 32nd column from the first line in $iw_fitted_midpoints_file.dat)

A: instead of escaping special chars, just do an exact match, pass the value as an awk variable
$ awk -v name="$f" '$1==">" && $2==name {print $32}' datafile


text:
Q: Display the locally inserted time stamp everywhere At 6:00am Sydney time, Rory Allan clicks the foofoo button in their browser.
This inserts into the foofoo table with an 8:00pm UTC timestamp in the database of my server.
A lot of people are excited about this foofoo button, and they wanted to see what time of the day Sydney time Rory clicked it.
As I stare at my screen in California and view the status of the click, I want to see that he clicked it at 6:00am, not 1:00pm, which is what I will see if I pull the UTC time from the server and let my browser convert it.
You see, a lot of different people click foofoo, such as Phillip Herman in Germany, or Ivan Efimiov in Russia. And all we care about is the relative time of the day they clicked it, in the location they clicked it, regardless of the viewing location.

I don't know the best way to do this. Do I take the local timestamp and convert it to a string, storing it in addition to the real UTC timestamp? Or is this a common problem with a common resolution that I haven't found? I'm guessing / hoping the latter.

This isn't Language specific. These dates have a long journey:
Unix timestamp > Python date > JSON > Node > Mongo > Node > Browser

A: Ok, clearly 8:00pm UTC is not enough information.  But what do you really want to know?

*

*Is 06:00 enough information?

*

*Look for time-only data types, preferably those that reflect time-of-day, rather than elapsed-time.  These are often called LocalTime, TimeOfDay, etc.

*Or, use strings in HH:MM format (on a 24-hour clock)

*Or record the total number of minutes as an integer (60 * HH) + MM.

*Or if you need a higher precision, then use seconds, or milliseconds, or microseconds, etc...

*Is 06:00 Australia/Sydney enough information?

*

*Store the time as mentioned earlier and store the time zone name in a separate string.

*But be careful, because without a date you don't know if UTC+10 or UTC+11 was in effect.

*Is 06:00+10:00 enough information?

*

*You could look for a time with time zone data type, such as the one that exists in PostgreSQL, though even the PostgreSQL docs strongly discourage using this type.

*Instead, store the time and offset as separate components.

*Be careful, because you'd not necessarily know if this data was from Sydney.  There are other time zones with UTC+10 at parts of the year too.

Assuming you have the date, such as today, then:

*

*Is 2017-05-31T06:00 enough information?

*

*Store the date and time together in a component that is sometimes called DateTime or LocalDateTime in various languages - but be careful that it is not bound to any specific time zone.  Use DateTimeKind.Unspecified in .NET, or "naive" DateTime's in Python, etc.

*For MongoDB and others that don't have such a type, use a string in ISO8601 format.

*Be careful, because this time could come from anywhere in the world.  Nothing here relates it to a specific point in time.

*Is 2017-05-31T06:00+10:00 enough information?

*

*Some languages and databases have a DateTimeOffset or OffsetDateTime type for this purpose.

*If not, you can store a "Unix Timestamp" and also store the offset from UTC separately.

*Or you can just store a string in ISO8601 format with the offset included - just be very careful with regard to comparisons / sorting.

*Is 2017-05-31T06:00 Australia/Sydney enough information?

*

*Store separately the date+time component from the time zone.

*Consider that a time may be ambiguous during a DST fall-back transition.

*Is 2017-05-31T06:00+10:00 Australia/Sydney enough information?

*

*Here we have everything we might possibly need.  Use a ZonedDateTime in Java/Joda-Time/Noda-Time, or an "aware" DateTime in Python (pytz, dateutils, etc.), or similar types when they exist in your platform.

*Watch out for timestamp with time zone, as you might expect it to store the time zone and it typically does not (despite the name).

*If not available, then consider storing a Unix timestamp and separate the time zone name as a string.

As you can tell - there are a LOT of options, and it really depends on exact use case and features available in each language/platform.  You'll find more details if you search/ask for each one separately.

A: tl;dr
Exchange date-time values in UTC as strings in standard ISO 8601 format.
Work in UTC
General rule in date-time handling is to think in UTC, work in UTC, log in UTC, share in UTC, and store in UTC. But present in zoned time for the user.
By think in UTC, I mean every programmer needs to learn to stop their parochial thinking about their own particular home time zone. Translating back-and-forth to your own zone to UTC to other zones will drive a person nuts. Think of UTC as The One True Time®. All other zones and offsets are mere variations.
This strategy is much like internationalization. The programmer uses key strings in her own human language to look up string values from the localization tool to present a value (piece of text) in the human language preferred by her user. In date-time handling, the programmer works in UTC but applies a zone preferred by her user for presenting text in the user-interface.
Moment in UTC
The basic Java class for this Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
So when Rory in Sydney clicks his button, we record an Instant object.
Instant instant = Instant.now() ;

instant.toString(): 2017-06-01T09:24:54.435Z

Zoned
To present that moment to Rory in his own time zone, we apply a ZoneId to get a ZonedDateTime object.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Australia/Sydney" ) ;
ZonedDateTime zdt = instant.atZone( z );

zdt.toString(): 2017-06-01T19:24:54.435+10:00[Australia/Sydney]

Now we have two objects, instant & zdt, that both refer to the same simultaneous moment on the timeline. The only difference is wall-clock time.
If the user in California wants to see the moment of Rory's button click according to Sydney time, then we already have that solution seen above. If not, if the California user wants to see the moment of Rory's button click in her own California clock, then read on.
We can adjust into yet another region's wall-clock time by applying another time zone.
ZoneId zAmericaLosAngeles = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdtAmericaLosAngeles = instant.atZone( zAmericaLosAngeles );

zdtAmericaLosAngeles.toString(): 2017-06-01T02:24:54.435-07:00[America/Los_Angeles]

Now we have three objects that all represent the same simultaneous moment: instant, zdt, and zdtAmericaLosAngeles. One moment, three wall-clock times.
See this above code run live at IdeOne.com.
Time-of-day
If you literally meant you want the time-of-day only, without the date, you can extract a LocalTime object from those objects above.
But think twice about doing this, as presenting a time-only without date and zone can lead to ambiguity and misunderstanding.
LocalTime lt = zdt.toLocalTime();

all we care about is the relative time of the day they clicked it, in the location they clicked it, regardless of the viewing location

If you are really really really sure that is what you want, then combine my advice above. (But I doubt this is a wise way to go.)
LocalTime lt = LocalTime.now( ZoneId.of( "Australia/Sydney" ) ) ;  // Current time-of-day in Sydney.

Library for date-time
We have been using the modern java.time classes in examples above. They are exceptional – I mean than literally. They are virtually unique. Virtually all other platforms have terrible support for date-time work. The predecessor to java.time was the Joda-Time project which was ported to .Net platform as Noda Time. Other than java.time & Noda Time, I know of no other decent library on other platforms.
ISO 8601
The ISO 8601 standard defines many sensible practical formats for textual representation of date-time values.
The java.time classes use the standard formats by default when generating & parsing strings. You have been viewing those ISO 8601 formats in examples above. Except for ZonedDateTime which wisely extends the standard by appending the name of the time zone in square brackets.
The T in the middle separates the date portion from the time-of-day portion.
For UTC, the Z on the end is short for Zulu and means UTC.
For offset-from-UTC, you see a plus/minus number of hours and minutes ahead of or behind UTC. A time zone is history of past, present, and future offsets in use by a particular region.
Database
How databases handle date-times varies widely, though poor support is most common. A database driver, such as JDBC drivers, add another layer of behavior. So no way to succinctly address that here. And this topic is already asked and answered in many other pages in Stack Overflow.
If your database lacks serious date-time support, you may be better off storing the ISO 8601 strings with the Z on the end. These values when sorted alphabetical are also in chronological order.


text:
Q: Itô diffusion and Kolmogorov backward and forward equations For the Kolmogorov backward and forward (aka Fokker-Planck) equations to hold, and also for the Feynman-Kac formula, is it necessary for the terms in the stochastic differential equation
$$
dX_t = \mu(X_t,t)dt + \sigma(X_t,t)dW_t
$$
to be time-independent
$$
dX_t = \mu(X_t)dt + \sigma(X_t)dW_t
$$
or not? My impression is that the requirement is markovity, and thus one often finds the theorems in terms of Itô's diffusions, which are always Markov processes.


text:
Q: Return multiple category value from XML column `<cassettes>
 <cassette>
    <cassetteId>A</cassetteId>
    <capacity>290</capacity>
    <denominations>
      <denomination>
        <value>1</value>
        <currency>US</currency>
        <notesAvailable>398</notesAvailable>
        <notesToDispense>24</notesToDispense>
        <notesDispensed>24</notesDispensed>
        <notesDeposited>0</notesDeposited>
        <notesSuggested>398</notesSuggested>
      </denomination>
    </denominations>
    <status>0</status>
    <position>0</position>
  </cassette>...`

Above is an excerpt from the xml column value. The node with the amount in question is "notesdispensesed".There are 12 cassetteId's A-K. Each cassette holds a denomination. For example: cassettes A & B contain 1s, Cassette C contain 5s, Casette D & E contain 10's etc...
The below select stmt returns the value 24 for cassetteId A. Im trying to avoid having to write this out twelve times for each cassette. Is there a way to return the dispensed amounts based on denomination value. Any solutions are greatly appreciated
Select column.value('(/cassettes/cassette/denominations/denomination/notesDispensed)[1]','varchar(max)')

A: Does this look like what you are looking for using sql:variable?
DECLARE @iterator = 1

SELECT
    Child.value('(/cassettes/cassette/denominations/denomination/notesDispensed)[1]', 'varchar(max)'),
FROM
    XMLField.nodes("/cassettes/denomination[sql:variable("@iterator")]/ChildNode") AS N(Child)


text:
Q: Traversing an object in JS. Is there a way to go *up*? I'm traversing n-depth nested objects (and arrays). I use a "breadcrumb" trail to determine a particular object's location, and delve through the object as so:
let i: number;
let obj: any = update.history.present;
let depth = 2
for (i = 0; i < path.length-depth; i++){
  // do something if we're at the correct level, else:
  obj = obj[path[i]];
}

Specifically, I overwrite obj with a new obj each time I go deeper, which makes each trip through the object one-way.
Is there another way to approach this, so I can go into the object, get some information, then go up n levels in the object and continue traversal, in potentially a different path?
Maybe I could make obj an array that holds each object level, allowing me to keep each traversal level as a sort of snapshot?


text:
Q: Euler problem number #4 Using Python, I am trying to solve problem #4 of the Project Euler problems. Can someone please tell me what I am doing incorrectly?  The problem is to Find the largest palindrome made from the product of two 3-digit numbers.  Here is what I have thus far.
import math

def main():
    for z in range(100, 1000):
        for y in range(100, 1000):
            for x in range(1, 1000000):
                x = str(x)
                if x == x[::-1] and x == z*y:
                    print x

if __name__ == '__main__':
    main()

A: Try computing x from the product of z and y rather than checking every number from 1 to a million. Think about it: if you were asked to calculate 500*240, which is more efficient - multiplying them, or counting up from 1 until you find the right answer?

A: Here's some general optimizations to keep in mind. The posted code handles all of this, but these are general rules to learn that might help with future problems:
1) if you've already checked z = 995, y = 990, you don't need to check z = 990, y = 995. Greg Lind handles this properly
2) You calculate the product of z*y and then you run x over a huge range and compare that value to y*z. For instance, you just calculated 900*950, and then you run x from 1000 to 1M and see if x = 900*950. DO you see the problem with this?
3) Also, what happens to the following code? (this is why your code is returning nothing, but you shouldn't be doing this anyway)
x = str(100)
y = 100
print x == y

4) If you figure out (3), you're going to be printing a lot of information there. You need to figure out a way to store the max value, and only return that value at the end.
5) Here's a nice way to time your Euler problems:
if __name__ == "__main__":
    import time
    tStart = time.time()
    print "Answer = " + main()
    print "Run time = " + str(time.time() - tStart)

A: Some efficiency issues:

*

*start at the top (since we can use this in skipping a lot of calculations)

*don't double-calculate

def is_palindrome(n):
    s = str(n)
    return s == s[::-1]

def biggest():
    big_x, big_y, max_seen = 0,0, 0
    for x in xrange(999,99,-1):
        for y in xrange(x, 99,-1):  # so we don't double count
            if x*y < max_seen: continue  # since we're decreasing,
                                # nothing else in the row can be bigger
            if is_palindrome(x*y):
                big_x, big_y, max_seen = x,y, x*y

    return big_x,big_y,max_seen

biggest()
# (993, 913, 906609)

A: comparing string with an integer in
x == z*y

there are also logical errors
start in reverse order range(999, 99, -1). that'll be more efficient. remove third loop and second comparison altogether.

A: rather than enumerating all products of 3-digit numbers (~900^2 iterations),
enumerate all 6- and 5-digit palyndromes (this takes ~1000 iterations);
then for each palyndrome decide whether it can be represented by a product
of two 3-digit numbers (if it can't, it should have a 4-digit prime factor,
so this is kind of easy to test).
also, you are asking about problem #4, not #3.

A: Wow, this approach improves quite a bit over other implementations on this page, including mine.
Instead of

*

*walking down the three-digit factors row by row (first do all y for x = 999, then all y for x = 998, etc.),

we

*

*walk down the diagonals: first do all x, y such that x + y = 999 + 999; then do all x, y such that x + y = 999 + 998; etc.

It's not hard to prove that on each diagonal, the closer x and y are to each other, the higher the product. So we can start from the middle, x = y (or x = y + 1 for odd diagonals) and still do the same short-circuit optimizations as before. And because we can start from the highest diagonals, which are the shortest ones, we are likely to find the highest qualifying palindrome much sooner.
maxFactor = 999
minFactor = 100

def biggest():
    big_x, big_y, max_seen, prod = 0, 0, 0, 0

    for r in xrange(maxFactor, minFactor-1, -1):
        if r * r < max_seen: break

        # Iterate along diagonals ("ribs"):

        # Do rib x + y = r + r
        for i in xrange(0, maxFactor - r + 1):
            prod = (r + i) * (r - i)

            if prod < max_seen: break

            if is_palindrome(prod):
                big_x, big_y, max_seen = r+i, r-i, prod

        # Do rib x + y = r + r - 1
        for i in xrange(0, maxFactor - r + 1):
            prod = (r + i) * (r - i - 1)

            if prod < max_seen: break

            if is_palindrome(prod):
                big_x, big_y, max_seen = r+i,r-i-1, prod

    return big_x, big_y, max_seen

# biggest()
# (993, 913, 906609)

A factor-of-almost-3 improvement
Instead of calling is_palindrome() 6124 times, we now only call it 2228 times. And the total accumulated time has gone from about 23 msec down to about 9!
I'm still wondering if there is a perfectly linear (O(n)) way to generate a list of products of two sets of numbers in descending order. But I'm pretty happy with the above algorithm.

A: The question states:
What is the largest prime factor of the number 600851475143?

I solved this using C#, but the algorithm itself is language-agnostic.

*

*Create a method for determining if a number is prime or not.  This can be brute-force (rather than using a much more efficient sieving algorithm) and looks like this:

private static long IsPrime(long input)
        {
            if ((input % 2) == 0)
            {
                return 2;
            }
            else if ((input == 1))
            {
                return 1;
            }
            else
            {
                long threshold = (Convert.ToInt64(Math.Sqrt(input)));
                long tryDivide = 3;
                while (tryDivide < threshold)
                {
                    if ((input % tryDivide) == 0)
                    {
                        Console.WriteLine("Found a factor: " + tryDivide);
                        return tryDivide;
                    }
                    tryDivide += 2;
                }
                Console.WriteLine("Found a factor: " + input);
                return -1;
            }
        }

*Once I have a function to determine primality, I can use this function to find the highest prime factor

private static long HighestPrimeFactor(long input)
{
    bool searching = true;
    long highestFactor = 0;
    while (searching)
    {
        long factor = IsPrime(input);
        if (factor != -1)
        {
            theFactors.Add(factor);
            input = input / factor;
        }
        if (factor == -1)
        {
            theFactors.Add(input);
            highestFactor = theFactors.Max();
            searching = false;
        }
    }
    return highestFactor;
}

I hope this helps without giving too much away.

A: The other advice here is great. This code also works. I start with 999 because we know the largest combination possible is 999*999. Not python, but some quickly done pseudo code.
public static int problem4()
    {
    int biggestSoFar=0;
        for(int i = 999; i>99;i--){
            for(int j=999; j>99;j--){
                if(isPaladrome(i*j))
                   if(i*j>biggestSoFar)
                        biggestSoFar=i*j;
            }
        }
        return biggestSoFar;
    }

A: This adds a couple of optimizations to @GreggLind's good solution, cutting the run time in half:
def is_palindrome(n):
    s = str(n)
    return s == s[::-1]

def biggest():
    big_x, big_y, max_seen = 0,0, 0
    for x in xrange(999,99,-1):
        # Optim. 1: Nothing in any row from here on can be bigger.
        if x*x < max_seen: break

        for y in xrange(x, 99,-1):  # so we don't double count
            # Optim. 2: break, not continue
            if x*y < max_seen: break  # since we're decreasing,
                                # nothing else in the row can be bigger

            if is_palindrome(x*y):
                big_x, big_y, max_seen = x,y, x*y

    return big_x,big_y,max_seen

biggest()
# (993, 913, 906609)

The line
if x*x < max_seen: break

means that once we get to the point where x is less than sqrt of largest palindrome yet seen, not only do we not need to investigate any more factors on that row; we don't even need to investigate any more rows at all, since all remaining rows would start from a number less than the current value of x.
This doesn't reduce the number of times we call is_palindrome(), but it means many fewer iterations of the outer loop. The value of x that it breaks on is 952, so we've eliminated the checking of 853 rows (albeit the "smaller" ones, thanks to the other break).
I also noticed that
if x*y < max_seen: continue

should be
if x*y < max_seen: break

We are trying to short-circuit the whole row, not just the current iteration of the inner loop.
When I ran this script using cProfile, the cumulative time for biggest() was about 56 msec on average, before the optimizations. The optimizations shrank it to about 23 msec. Either optimization alone would deliver most of that improvement, but the first one is slightly more helpful than the second.

A: Here is a solution that you might consider. It could be far more efficient but only takes a little time to run.
largest = 0
for a in range(100, 1000):
    for b in range(100, 1000):
        c = a * b
        if str(c) == ''.join(reversed(str(c))):
            largest = max(largest, c)
print(largest)

A: Here is an efficient general solution (~5x faster than others I have seen):
def pgen(factor):
    ''' Generates stream of palindromes smaller than factor**2
        starting with largest possible palindrome '''
    pmax = str(factor**2)
    half_palindrome = int(pmax[0:len(pmax)/2]) - 1
    for x in xrange(half_palindrome, 0, -1):
        yield int(str(x) + str(x)[::-1])

def biggest(factor):
    ''' Returns largest palindrome and factors '''
    for palindrome in pgen(factor):
        for f1 in xrange(factor/11*11, factor/10, -11):
            f2 = palindrome/f1
            if f2 > factor:
                break
            if f2*f1 == palindrome:
                return palindrome, f1, f2

>>> biggest(99)
(9009, 99, 91)
>>> biggest(999)
(906609, 993, 913)
>>> biggest(9999)
(99000099, 9999, 9901)
>>> biggest(99999)
(9966006699L, 99979, 99681L)
>>> biggest(9999999)
(99956644665999L, 9998017, 9997647L)
>>> biggest(99999999)
(9999000000009999L, 99999999, 99990001L)
>>> biggest(999999999)
(999900665566009999L, 999920317, 999980347L)

A: This code is more efficient. I've also included a print statement to output the time taken for completion.
import time
start_time = time.time()

def palindrome(n):
    if str(n)==str(n)[-1::-1]:
        return True
    else:
        return False
def highestprod(n):
    global x
    x=''
    for i in range (n):
        x+='9'
    x=int(x)
    return x**2

def smallestprod(n):
    global y
    y=''
    for i in range (n):
        y+='1'
    y=int(y)
    return y**2

def lpp(n):  #where n is the no of digits
    lst=[]
    k=highestprod(n)
    l=smallestprod(n)
    for i in range(k,int(k/1.15),-1):
        if i%10==0:
            pass
        elif palindrome(i):
            lst.append(i)
    val=0
    for m in lst:
        no=int(x)
        while True:
            if no<y:
                break
            elif m%no==0 and x>(m/no)>y and no>y:
                val=m
                break
            else:
                no-=1
        if val:
            break
    print(val)

lpp(3) #<<<==== type here. Can find the answer for n=2,3 and 4 (4 might take 9-10 seconds) but n>4 takes so much time.

print("--- %s seconds ---" % (time.time() - start_time))

Ive tried lpp(5). Took too much time so I killed the program.

A: If your program is running slow, and you have nested loops like this:
for z in range(100, 1000):
    for y in range(100, 1000):
        for x in range(1, 1000000):

Then a question you should ask yourself is: "How many times will the body of the innermost loop execute?"  (the body of your innermost loop is the code that starts with: x = str(x))
In this case, it's easy to figure out.  The outer loop will execute 900 times.  For each iteration the middle loop will also execute 900 times – that makes 900×900, or 810,000, times.  Then, for each of those 810,000 iterations, the inner loop will itself execute 999,999 times.  I think I need a long to calculate that:
>>> 900*900*999999
809999190000L

In other words, you're doing your palindrome check almost 810 billion times.  If you want to make it into the Project Euler recommended limit of 1 minute per problem, you might want to optimise a little :-) (see David's comment)

A: This is what I did in Java:
public class Euler0004
{
    //assumes positive int
    static boolean palindrome(int p)
    {
        //if there's only one char, then it's
        //  automagically a palindrome
        if(p < 10)
            return true;

        char[] c = String.valueOf(p).toCharArray();

        //loop over the char array to check that
        //  the chars are an in a palindromic manner
        for(int i = 0; i < c.length / 2; i++)
            if(c[i] != c[c.length-1 - i])
                return false;

        return true;
    }

    public static void main(String args[]) throws Exception
    {
        int num;
        int max = 0;

        //testing all multiples of two 3 digit numbers.
        // we want the biggest palindrome, so we
        // iterate backwards
        for(int i = 999; i > 99; i--)
        {
            // start at j == i, so that we
            //  don't calc 999 * 998 as well as
            //  998 * 999...
            for(int j = i; j > 99; j--)
            {
                num = i*j;

                //if the number we calculate is smaller
                //  than the current max, then it can't
                //  be a solution, so we start again
                if(num < max)
                    break;

                //if the number is a palindrome, and it's
                //  bigger than our previous max, it
                //  could be the answer
                if(palindrome(num) && num > max)
                    max = num;
            }
        }

        //once we've gone over all of the numbers
        //  the number remaining is our answer
        System.out.println(max);

    }
}

A: Here is my solution:
polindroms = [(x, y, x * y) for x in range(100, 999) for y in range(100, 999) if str(x * y) == str(x * y)[::-1]]
print max(polindroms, key = lambda item : item[2])


text:
Q: React - как убрать определнные даты с datepicker'a Я получаю определённый массив с датой типа let excludedDates = [{12/12/2022},{11/12/2022},{10/12/2022},]  и мне нужно как то указать в datepicker'e что даты в этом массиве должны быть disabled,использую https://reactdatepicker.com/#example-exclude-dates

A: Судя по документации (скриншот который вы сделали) у вас дата должна быть Date, следовательно вам нужно перевести из значение из string в Date
let excludedDates = ["12/12/2022","11/12/2022","10/12/2022"].map(el => new Date(el))

P.S: не совсем понимаю что означает {12/12/2022} но предполагаю что это строка


text:
Q: How to send sms from php using the application smssync? I want to send sms from my website using my phone number in some time.
I'm trying Smssync (this is URL of application's website) but I din't know how to use it with php.
How can send sms from php using the Smssync app? Pleas help me.


text:
Q: Estimate the maximum possible error in the approximation - Taylor Polynomials I am given the following example.
Estimate the maximum possible error in the approximation.
$cos(x) = T_{\displaystyle4,\frac{\displaystyle\pi}{\displaystyle2}}$ for $x \in \left[\frac{\displaystyle\pi}{\displaystyle2} -0.2, \frac{\displaystyle\pi}{\displaystyle2} + 0.2\right]$. $\\$
$R_{\displaystyle4,\frac{\pi}{2}}(x) \le \frac{\displaystyle|-\sin(z)|}{\displaystyle5!} |x-\frac{\pi}{2}|^5$ $\\$
$\Rightarrow R_{\displaystyle4,\frac{\displaystyle\pi}{\displaystyle2}}(x) \le \frac{\displaystyle1}{\displaystyle 5!}(0.2)^5 $
I don't understand how the example went from $|x-\frac{\pi}{2}|^5$ to $(0.2)^5$. Please specify the logical reasoning behind this and exactly how it is achieved. Thank you.

A: We have that
$$\dfrac{\pi}{2}-0.2\le x\le\dfrac{\pi}{2}+0.2$$
and that
$$  \cos(x)\approx 1-\dfrac{\left(x-\frac{\pi}{2}\right)^2}{4}+\dfrac{\left(x-\frac{\pi}{2}\right)^4}{24}$$
Thus we know that
$$ \dfrac{\pi}{2}-0.2\le x\le\dfrac{\pi}{2}+0.2$$
from which it follows that
$$ -0.2\le x-\dfrac{\pi}{2}\le 0.2$$
One should point out, however, that since this is an alternating series, a better estimation of the error would be to use the next term of the series to get $$ R<\left\vert\dfrac{\left(x-\frac{\pi}{2}\right)^6}{6!}\right\vert\le\dfrac{(0.2)^6}{720} $$

A: Consider the Lagrange form for the remainder.
There is a value of the independent variable in the interval $\xi$ for which $-sin(\xi)(x−π2)^5\over{5!}$ is equal to the remainder.
The guarantee is that $\xi\in[a,xEval]$ where a is the "base point", and xEval is the point in which you are approximating the function.
Therefore, the maximum possible absolute value for the remainder comes from locating the maximum for $|-sin(x)|, x\in [xEval,a]$ and multiplying it by ${|xEval-a|^5}\over{5!}$
The maximum for $|sin(x)|$ is 1.
And $|xEval-a|=0.2$ for "both" intervals considered in your question $[-0.2,\pi/2]$ and $[\pi/2,0.2]$


text:
Q: Print into file After my previous question that was ansered here , I can manage to print the pages I need but with a small problem. With Jtable.print there is always appear a window with the preferences for printing , select printer even print in a file the resaults.
With the   pj.print() I got an outcome to my printer when ever is connected and no other promt before . I tried   pj.printDialog(); and gives me the prompt window with printers etc but nor the normal printer or the the print to file gives a resault.
What am I doing wrong?
Thank you!

A: The printing dialogs vary across platforms and OS versions, so I'm probably seeing something different. In addition to printDialog(), you might try pageDialog(), which has a promising looking Printer… button.


text:
Q: Local Admin to retrieve other logon process MainWindowTitle I have a Win2012 server, 10 non-admin-account logonIDs interactively log on into it to run some automated app, these apps sometime will cause exception and pop a msgbox titled "AutoApp.exe - Application Error" with OK button. So we have to logon with each 10 logonID to manually click on it to release resources.
I'm writing a monitoring C# console program, to fetch each process then their MainWindowTitle, simulate a key stroke of  to let it go. This monitoring program is run with Admin right.
    IntPtr hwnd;
    Process[] pp = Process.GetProcesses();
    try
    {
        foreach (Process p in pp)
        {
            ...
            title = p.MainWindowTitle;
            Console.WriteLine(title);
            if (title.Equals(...) )
            {
                hwnd = p.MainWindowHandle;
                SetForegroundWindow(hwnd);
                // simulate keystroke below...
            }

Test shows it's able to display all local process's window title, not other logon's. I guess this is reasonable for security reason. But is there any way to do that and how?


text:
Q: How can I draw the following graph with tikz? Some irregular curves and their surrounding shadows are all needed to draw a graph in graph theory. I'm not very good at drawing this with Tikz, but I want to do my best to draw the following graph.

I used some code from Drawing Königsberg landscape showing the bridges  and it seems that no good and concise. But I didn't draw it well enough, and the code wasn't clean enough.
\documentclass{article}
\usepackage{xcolor}
\usepackage{tikz}
\usetikzlibrary{decorations.pathmorphing, calc}
\definecolor{babypink}{rgb}{0.96, 0.76, 0.76}
\tikzset{%
    contour/.style={dashed,%
        very thick,%
        decoration={%
            random steps,%
            segment length=4pt,%
            amplitude=0.5pt%
        },%
        rounded corners=1pt,%
        decorate%
    }%
}

\begin{document}
    \begin{tikzpicture}[x=10cm, y=9.19cm]
        \filldraw[babypink] ($(0, 1) + (0.241, -0.622)$) -- ($(0, 1) + (0.235,
        -0.587)$)
        --
        ($(0, 1) + (0.240, -0.540)$) -- ($(0, 1) + (0.249, -0.524)$) --
        ($(0, 1) + (0.252, -0.498)$) -- ($(0, 1) + (0.266, -0.482)$) --
        ($(0, 1) + (0.271, -0.462)$) -- ($(0, 1) + (0.288, -0.454)$) --
        ($(0, 1) + (0.300, -0.434)$) -- ($(0, 1) + (0.308, -0.418)$) --
        ($(0, 1) + (0.320, -0.412)$) -- ($(0, 1) + (0.328, -0.404)$) --
        ($(0, 1) + (0.399, -0.399)$) -- ($(0, 1) + (0.453, -0.393)$) --
        ($(0, 1) + (0.518, -0.386)$) -- ($(0, 1) + (0.549, -0.388)$) --
        ($(0, 1) + (0.609, -0.404)$) -- ($(0, 1) + (0.624, -0.410)$) --
        ($(0, 1) + (0.644, -0.438)$) -- ($(0, 1) + (0.663, -0.486)$) --
        ($(0, 1) + (0.670, -0.519)$) -- ($(0, 1) + (0.668, -0.546)$) --
        ($(0, 1) + (0.658, -0.590)$) -- ($(0, 1) + (0.648, -0.612)$) --
        ($(0, 1) + (0.636, -0.648)$) -- ($(0, 1) + (0.633, -0.666)$) --
        ($(0, 1) + (0.617, -0.677)$) -- ($(0, 1) + (0.596, -0.700)$) --
        ($(0, 1) + (0.535, -0.708)$) -- ($(0, 1) + (0.500, -0.709)$) --
        ($(0, 1) + (0.457, -0.717)$) -- ($(0, 1) + (0.412, -0.708)$) --
        ($(0, 1) + (0.372, -0.702)$) -- ($(0, 1) + (0.336, -0.695)$) --
        ($(0, 1) + (0.291, -0.679)$) -- ($(0, 1) + (0.268, -0.652)$) --
        cycle;
        \draw[contour] ($(0, 1) + (0.241, -0.622)$) -- ($(0, 1) + (0.235, -0.587)$) --
        ($(0, 1) + (0.240, -0.540)$) -- ($(0, 1) + (0.249, -0.524)$) --
        ($(0, 1) + (0.252, -0.498)$) -- ($(0, 1) + (0.266, -0.482)$) --
        ($(0, 1) + (0.271, -0.462)$) -- ($(0, 1) + (0.288, -0.454)$) --
        ($(0, 1) + (0.300, -0.434)$) -- ($(0, 1) + (0.308, -0.418)$) --
        ($(0, 1) + (0.320, -0.412)$) -- ($(0, 1) + (0.328, -0.404)$) --
        ($(0, 1) + (0.399, -0.399)$) -- ($(0, 1) + (0.453, -0.393)$) --
        ($(0, 1) + (0.518, -0.386)$) -- ($(0, 1) + (0.549, -0.388)$) --
        ($(0, 1) + (0.609, -0.404)$) -- ($(0, 1) + (0.624, -0.410)$) --
        ($(0, 1) + (0.644, -0.438)$) -- ($(0, 1) + (0.663, -0.486)$) --
        ($(0, 1) + (0.670, -0.519)$) -- ($(0, 1) + (0.668, -0.546)$) --
        ($(0, 1) + (0.658, -0.590)$) -- ($(0, 1) + (0.648, -0.612)$) --
        ($(0, 1) + (0.636, -0.648)$) -- ($(0, 1) + (0.633, -0.666)$) --
        ($(0, 1) + (0.617, -0.677)$) -- ($(0, 1) + (0.596, -0.700)$) --
        ($(0, 1) + (0.535, -0.708)$) -- ($(0, 1) + (0.500, -0.709)$) --
        ($(0, 1) + (0.457, -0.717)$) -- ($(0, 1) + (0.412, -0.708)$) --
        ($(0, 1) + (0.372, -0.702)$) -- ($(0, 1) + (0.336, -0.695)$) --
        ($(0, 1) + (0.291, -0.679)$) -- ($(0, 1) + (0.268, -0.652)$) --
        ($(0, 1) + (0.241, -0.622)$);
    \node[draw,circle] (u) at ($(0, 1) + (0.5, -0.388)$)[label={$u$}]{};
 \node[draw,circle] (u2)  at ($(0, 1) + (0.658,
 -0.582)$)[label=right:{$u_2$}]{};
\node[draw,circle] (v) at ($(0, 1) + (0.5, -0.71)$)[label=below:{$v$}]{};
\node[draw,circle] (u1) at ($(0, 1) + (0.23, -0.582)$)[label=left:{$u_1$}]{};
\draw [in=-165, out=165, looseness=5.00](u) to (v);
\node[] at (0.5,0.5) {$f$};
\end{tikzpicture}
\end{document}

Holding a learning attitude,  I'd like to learn more concise tikz code which can draw the graph I want. For those irregular curves in the original graph, I don't know if there is any software that can assist in generating them.

A: I start by apologize for giving a MetaPost/MetaFun+ConTeXt answer, even though you were asking for a TikZ one. This is a method I have used before to draw some random smooth curves. I can probably be used also for TikZ, but I do not know how.
The idea is to randomize and smoothen a path. Look at the following picture:

Here we have started with a circle (defined by circularpath(10), which gives a circle with 40 points), drawn in blue. We then randomize it by using randomized (the light pink curve). This curve is not smooth. We get a smooth curve by applying curved to the result (the dark pink curve). The pink curves are built by the same points (shown in dark red), but with different control points.
For your example, the full code could look like this (this is the code I used, it is compiled with context). Note that since it uses randomization, your result might look a bit different.
\startMPpage[offset=3bp]
u:=1cm;
pickup pencircle scaled 1.5bp;

path blob,handle;
pair blobtop, blobleft, blobbottom, blobright;

blob = curved(circularpath(10) scaled 6u randomized 0.5u);

blobtop := (ulcorner blob -- urcorner blob) intersectionpoint blob;
blobleft := (ulcorner blob -- llcorner blob) intersectionpoint blob;
blobbottom := (llcorner blob -- lrcorner blob) intersectionpoint blob;
blobright := (lrcorner blob -- urcorner blob) intersectionpoint blob;

handle = blobtop{dir 160} .. {dir 25}blobbottom;

fill blob withcolor 0.95white;
draw blob dashed withdots scaled 0.75bp;
draw handle;

for i = blobtop,blobleft,blobbottom,blobright:
  unfill fullcircle scaled 8bp shifted i;
  draw fullcircle scaled 8bp shifted i;
endfor;

label.rt("$e$", point 0.5 of handle);
label("$f$", center blob);
label.lft("$P_1$", point 33 of blob);
label.rt("$P_2$", point 9 of blob);
labeloffset := 6bp;
label.urt("$u$",blobtop);
label.lft("$z_1$",blobleft);
label.lrt("$v$",blobbottom);
label.rt("$z_2$",blobright);
\stopMPpage

A: That's a very painful way of drawing something like that. Unfortunately, the random steps command is not very easy to use in this context so maybe drawing this step by step with rounded corners could be a solution:

\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{positioning}

\begin{document}
    \tikzset
        {
        dot/.style={circle,draw,thick,fill=white,inner sep=2pt},
        rdm/.style={thick,dotted,rounded corners=5pt},
        }
    \begin{tikzpicture}[node distance=2cm]
        \draw[cyan] (-2,-2) grid (4,2);
        \node[dot,label=below left:$z_1$] (z1) {};
        \node[dot,above right = of z1,label=above right:$u$] (u) {};
        \node[dot,below right = of z1,label=below right:$v$] (v) {};
        \node[dot,above right = of v,label=below right:$z_2$] (z2) {};

        \draw[thick] (u) to[out=160,in=190,looseness=3] node[midway,left] {$e$} (v) ;

        \def\a{0.35}
        \draw[rdm] (z1) --++ (.5*\a,\a) --++ (\a,0) --++ (0,1.5*\a) node[left] {$P_1$} --++ (\a,0) --++ (0,\a) -- (u);
        \draw[rdm] (z1) --++ (0,-\a) --++ (\a,0) --++ (0,-1.5*\a) --++ (\a,0) --++ (0,-\a) -- (v);
        \draw[rdm] (v) --++ (\a,0.5*\a) --++ (\a,0) --++ (0,\a) --++ (\a,0) --++ (0,\a) --++ (\a,0) -- (z2);
        \draw[rdm] (u) --++ (.75*\a,0) --++ (0,-\a) --++ (1.75*\a,0) --++ (0,-\a) --++ (1.5*\a,0) node[right] {$P_2$} -- (z2);
        \path (u) -- (v) node[midway] {$f$};
    \end{tikzpicture}
\end{document}

This is obviously strongly customizable.


text:
Q: HTML to PDF conversion in java I am trying to create a PDF file using HTML.
Following is my code.
try {
     String k = "    <title></title>   <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>

   	   International Trade Department

   	   ACCOUNTING VOUCHER DIFFERENT TEMPLATE

   	   Dated:	   11/01/2017

   	   To

   	   Intellect

   	   jay coach Goregoan Mumbai Maharashtra  INDIA

   	   Ref No. :	   0202091116FL1739   	   	   Product:	   Import LC - Sight_AT

   	   Operation:	   Issuance

   	   Charges :

   Description	   Debit Amount	   Credit Amount

   Bank Commission	   USD 300.00 (1) A/C No: [890890123126]	   USD 300.00 (1) A/C No: [3456734567]

   	   Accounting :

   Account Set	   Debit Role	   Credit Role

   BOOK LC CONTINGENT LIABILITY	   USD 1136668.00  A/C No: [3456734567]	   USD 1136668.00 A/C No: [3456734567]

   BOOK CASH MARGIN	   USD 397833.80  A/C No: [890890123126]	   USD 397833.80 A/C No: [3456734567]

   	   TRADE SERVICES DEPT.

  ";

        OutputStream file = new FileOutputStream(new File("D:\\NEW_PDF.pdf"));
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, file);
        document.open();
        InputStream is = new ByteArrayInputStream( k.getBytes() );
        //document.close();
        //XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);

        HTMLWorker htmlWorker = new HTMLWorker(document);
        htmlWorker.parse(new StringReader(k));

        document.close();
        file.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

However PDF is not being displayed properly.
Can someone please help me with this?
Thank you so much.


text:
Q: Segmentation fault when byte coding a function? I get a segmentation fault when I run the following C program (compiled with gcc in Ubuntu).
#include <stdio.h>

char f[] = "\x55\x48\x89\xe5\x48\x89\x7d\xf8\x48\x89\x75\xf0\x48\x8b\x45\xf8\x8b\x10\x48\x8b\x45\xf0\x8b\x00\x89\xd1\x29\xc1\x89\xc8\xc9\xc3";

int main()
{
    int (*func)();
    func = (int (*)()) f;

    int x=3,y=5;
    printf("%d\n",(int)(*func)(&x,&y));
    return 0;
}

The string f contains the machine code of the following function.
int f(int*a, int*b)
{
    return *a-*b;
}

c.f.:
f.o:     file format elf64-x86-64

Disassembly of section .text:

0000000000000000 <f>:
   0:   55                      push   %rbp
   1:   48 89 e5                mov    %rsp,%rbp
   4:   48 89 7d f8             mov    %rdi,-0x8(%rbp)
   8:   48 89 75 f0             mov    %rsi,-0x10(%rbp)
   c:   48 8b 45 f8             mov    -0x8(%rbp),%rax
  10:   8b 10                   mov    (%rax),%edx
  12:   48 8b 45 f0             mov    -0x10(%rbp),%rax
  16:   8b 00                   mov    (%rax),%eax
  18:   89 d1                   mov    %edx,%ecx
  1a:   29 c1                   sub    %eax,%ecx
  1c:   89 c8                   mov    %ecx,%eax
  1e:   c9                      leaveq
  1f:   c3                      retq

This is compiled using:
gcc test.c -Wall -Werror
./a.out
Segmentation fault

The expected output is -2 - how can I get it to work?

A: Apparantly below suggestion no longer works with gcc, as the array data nowadays gets located in a separate non-executable read-only ELF segment.
I'll leave it here for historical reasons.

Interestingly, the linker didn't complain that you attempt to link a char f[] = "..."; as a function f() to your application. You attempt to call a function f(). There is a symbol f linked to the executable, but suprisingly it is no function at all, but some variable. And thus it fails to execute it. This is likely due to a stack execution protection mechanism.
To circumvent this, apparantly, you just need to get the string to the text segment of the process memory. You can achieve this, if you declare the string as const char f[].
From Smashing The Stack For Fun And Profit, by Aleph One:

The text region is fixed by the program and includes code (instructions)
  and read-only data.  This region corresponds to the text section of the
  executable file.

As the const char[] is read-only, the compiler puts it together with the code into the text region. Thereby the execution prevention mechanism is circumvented and the machine is able to execute the machine code therein.

Example:
/* test.c */
#include <stdio.h>

const char f[] = "\x55\x48\x89\xe5\x48\x89\x7d\xf8\x48\x89\x75\xf0\x48\x8b\x45\xf8\x8b\x10\x48\x8b\x45\xf0\x8b\x00\x89\xd1\x29\xc1\x89\xc8\xc9\xc3";

int main()
{
    int (*func)();
    func = (int (*)()) f;

    int x=3,y=5;
    printf("%d\n",(int)(*func)(&x,&y));
    return 0;
}

yields:
$ gcc test.c -Wall && ./a.out
-2

(Fedora 16, gcc 4.6.3)

A: If I understand you correctly you're trying to run simple code that is not in text space, but instead is in your initialized static storage? If this is failing then there can only be three reasons: either your code was initialized incorrectly (unlikely in this simple case), your data space has been stepped on (doesn't look like it in this simple case), or your system is preventing it as a security measure (quite likely since what you're trying to do is fairly atypical, primarily used for buffer overflow exploitation).


text:
Q: List .contains ParseUser always FALSE I have an if statement written below:
//Set Friend Action OnClickListener & Image
    if (ParseUser.getCurrentUser().getList("friendsArray").contains(searchResultsList.get(position))) {
        Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_phone_black_24dp).into(holder.imgFriendAction);
        ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.green)));
    }
    else if (ParseUser.getCurrentUser().getList("pendingFriendsArray").contains(searchResultsList.get(position))) {
        Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_check_black_24dp).into(holder.imgFriendAction);
        ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.gray_dark)));
    }
    else {
        Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_person_add_black_24dp).into(holder.imgFriendAction);
        ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.colorPrimary)));
    }

The problem is that every single time I run that statement it always returns FALSE for both if statements even though I know for a fact that 'friendsArray' & 'pendingFriendsArray' return TRUE in many circumstances.
Both arrays contain pointers to the _User table.
searchResultsList is declared as follows:
private List<ParseUser> searchResultsList;

I've logged all three items (friendsArray, pendingFriendsArray & searchResultsList.get(position)) to the console and they show the following:
D/friendsArray: [com.parse.ParseUser@ae66779, com.parse.ParseUser@8371cbe, com.parse.ParseUser@32d511f, com.parse.ParseUser@5fd2c6c, com.parse.ParseUser@7dd0235, com.parse.ParseUser@9c446ca, com.parse.ParseUser@5fe03b]

D/pendingFriendsArray: [com.parse.ParseUser@7c6a358, com.parse.ParseUser@3688cb1, com.parse.ParseUser@480596]

D/searchResultsList.get(position) =: com.parse.ParseUser@5fe03b

The entire class is below:
public class SearchUserAdapter extends RecyclerView.Adapter<SearchUserAdapter.ViewHolder> {
private Context searchContext;
private List<ParseUser> searchResultsList;
OnItemClickListener onItemClickListener;

public SearchUserAdapter(Context context, List<ParseUser> dataSet) {
    searchContext = context;
    searchResultsList = dataSet;
}

public interface OnItemClickListener {
    public void onItemClick(View view, ParseUser searchUserObject, int position);
}

public void setOnItemClickListener(final OnItemClickListener onItemClickListener) {
    this.onItemClickListener = onItemClickListener;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(searchContext).inflate(R.layout.ly_search_user, parent,false);
    return new ViewHolder(v);
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    //Set User Name
    holder.txtUserName.setText(searchResultsList.get(position).getString("fullName"));

    //Set User Location
    holder.txtUserLocation.setText(GlobalFunctions.getParseUserLocationAsString(holder.txtUserName.getContext(), searchResultsList.get(position)));

    //Set User Profile Image
    if (searchResultsList.get(position).getParseFile("profilePicture") != null) {
        Glide.with(holder.imgUserProfilePicture.getContext()).applyDefaultRequestOptions(RequestOptions.circleCropTransform()).load(searchResultsList.get(position).getParseFile("profilePicture").getUrl()).into(holder.imgUserProfilePicture);
    }
    else {
        Glide.with(holder.imgUserProfilePicture.getContext()).applyDefaultRequestOptions(RequestOptions.circleCropTransform()).load(R.drawable.ic_profile_place_holder).into(holder.imgUserProfilePicture);
    }

    //Set Row OnClickListener
    holder.rlUserItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (searchResultsList.get(position).getObjectId().equalsIgnoreCase(ParseUser.getCurrentUser().getObjectId())) {
                Intent openProfile;
                openProfile = new Intent(holder.rlUserItem.getContext(), TimelineActivity.class);
                holder.rlUserItem.getContext().startActivity(openProfile);
            }
            else {
                Intent openOtherProfile = new Intent(holder.rlUserItem.getContext(), OtherUserTimelineActivity.class);
                openOtherProfile.putExtra("otherUserProfileId", searchResultsList.get(position).getObjectId());
                holder.rlUserItem.getContext().startActivity(openOtherProfile);
            }
        }
    });

    //Set Friend Action OnClickListener & Image
    if (ParseUser.getCurrentUser().getList("friendsArray").contains(searchResultsList.get(position))) {
        Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_phone_black_24dp).into(holder.imgFriendAction);
        ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.green)));
    }
    else if (ParseUser.getCurrentUser().getList("pendingFriendsArray").contains(searchResultsList.get(position))) {
        Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_check_black_24dp).into(holder.imgFriendAction);
        ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.gray_dark)));
    }
    else {
        Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_person_add_black_24dp).into(holder.imgFriendAction);
        ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.colorPrimary)));
    }
    holder.imgFriendAction.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            friendActionListenerAction(holder, searchResultsList.get(position));
        }
    });
}

private void friendActionListenerAction(ViewHolder holder, ParseUser parseUser) {
    if (ParseUser.getCurrentUser().getList("friendsArray").contains(parseUser)) {
        FLKCallUtils.showCallDialog(holder.imgFriendAction.getContext());
    }
    else if (ParseUser.getCurrentUser().getList("pendingFriendsArray").contains(parseUser)) {
        //Do nothing
    }
    else {
        //Add Friend
        FLKFriendUtils.sendFriendRequestFromUserToUser(ParseUser.getCurrentUser(), parseUser);

        //Update Image
        Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_check_black_24dp).into(holder.imgFriendAction);
        ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.gray_dark)));
    }
}

@Override
public int getItemCount() {
    return searchResultsList.size();
}

class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public MediumRobotoTextView txtUserName;
    public RegularRobotoTextView txtUserLocation;
    public RelativeLayout rlUserItem;
    ImageView imgUserProfilePicture;
    ImageView imgFriendAction;

    public ViewHolder(View itemView) {
        super(itemView);

        rlUserItem = (RelativeLayout) itemView.findViewById(R.id.rl_user_container);
        rlUserItem.setOnClickListener(this);

        txtUserName = (MediumRobotoTextView) itemView.findViewById(R.id.txt_user_name);
        txtUserLocation = (RegularRobotoTextView) itemView.findViewById(R.id.txt_user_location);

        imgUserProfilePicture = (ImageView) itemView.findViewById(R.id.img_profile_picture);
        imgUserProfilePicture.setOnClickListener(this);

        imgFriendAction = (ImageView) itemView.findViewById(R.id.img_friend_action);
        imgFriendAction.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        //TODO - do something here if you wish
    }
}

A: Upon further investigation I found that the parse-android SDK does not fetch pointers the same every single time. For example when I fetch 'friendsArray', let's say right now, it will return
[com.parse.ParseUser@ae66779, com.parse.ParseUser@8371cbe, com.parse.ParseUser@32d511f, com.parse.ParseUser@5fd2c6c, com.parse.ParseUser@7dd0235, com.parse.ParseUser@9c446ca, com.parse.ParseUser@5fe03b]

However if I then fetch it, let's say in 5 minutes, it will return
[com.parse.ParseUser@ec99877, com.parse.ParseUser@674bcg, com.parse.ParseUser@749hhc, com.parse.ParseUser@6fh3d6dg, com.parse.ParseUser@jdj8dk, com.parse.ParseUser@4c966ca, com.parse.ParseUser@3f0eeb]

Additionally, I noted that even the pointer to searchResultsList.get(position) changes it's reference every time I loaded it.
The way I got around this was to create a function (seen below) that returns an array of the actual objectId's of the pointers inside the 'friendsArray'. This way I can guarantee that it will always be returning the same items and can therefore create an accurate 'contains' comparison.
public static List<String> friendsArrayObjectIdsArray() {
    //Create Array of Friends
    List<ParseUser> friendsArray = ParseUser.getCurrentUser().getList("friendsArray");

    //Create Temp Array of Object Id's
    List<String> tempObjectIdsArray = new ArrayList<>();

    //Iterate List
    for (ParseUser friendUser : friendsArray) {
        tempObjectIdsArray.add(friendUser.getObjectId());
    }

    return tempObjectIdsArray;
}

I then run the following comparison to get the result I am looking for
if (FLKUserUtils.friendsArrayObjectIdsArray().contains(searchResultsList.get(position).getObjectId())) {
//Do something
}


text:
Q: Photoshop & Gimp simpler alternatives While doing web development, I often need to edit images. Not photos, not creative work, just simple editing. For example: adding shadow on a button, resizing multiple images, tweaking few pixels here and there, etc.
Photoshop always felt like a huge overkill (not to mention the price). Gimp's price tag is right, but it's still an overkill and somehow I feel clumsy while using it.
So what free/ open source Windows products are simpler yet do the same job?
Note that if product was really great, I would consider paying up to $50 but no more than that.

A: you can use Paint.Net on http://www.getpaint.net/download.html
Its free

A: PAINT.NET
This may be an option. I know that I have used this in the past but it may not be exactly what you need. There are plugins for it though I believe.
http://www.getpaint.net/


text:
Q: HTML Forms Array Submission Simulation I'm trying to mockup a simple HTML form that simulates an HTTP POST from an external party. When I look at the POST data coming in it looks like this:
array (
  'submission_id' => '1234567890',
  'name' =>
  array (
    0 => 'Bart',
    1 => 'Simpson',
  ),
  'address' =>
  array (
    0 => '1000 Springfield Road',
    1 => 'Level 2',
    2 => 'Los Angeles',
    3 => 'CA',
    4 => '90210',
    5 => '',
  ),
  'date' =>
  array (
    0 => '05',
    1 => '01',
    2 => '2017',
  ),

I'm trying to simulate a simple HTML form with inputs but haven't worked with arrays before so not sure of the syntax. For example for the 'name' would it be:

<input type="text" name="name[]">
<input type="text" name="name[]">

A: using the same name attribute should result in the array in the form post
<input type="text" name="name">
<input type="text" name="name">

A: I did need to use the [] syntax to get the numbered arrays:
<input type="text" name="name[]">
<input type="text" name="name[]">


text:
Q: como mostrar una consulta de php en una card horizontal de bootstrap4 Tengo el siguiente problema, necesito mostrar en una Card Horizontal de Bootstrap 4 una consulta desde base de datos para mostrar las entradas de un blog sencillo.
¿como hago para imprimir la información traída desde la base de datos en Blog mediante una Card horizontal de Bootstrap?
Mi código es el siguiente:
<?php
    include_once("../modelo/drive.php");

    try{
      $myconnect=new PDO('mysql:host=localhost; dbname=inspirablog', 'root', '');
      $myconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      //$myconnect=new PDO('mysql:host=localhost; dbname=gaxenreh_inspiraBlog', 'gaxenreh_secursoft', 'Ledic@8848999');
      //$myconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      $driveObjetos=new driveObjetos($myconnect);

      $tablaBlog=$driveObjetos->getContenidoPorFecha();

      if(empty($tablaBlog)){

        echo "No se encontraron entradas en el Blog!";

      }else{

        foreach($tablaBlog as $valor){

          echo "
" .$valor->getTitulo() ."
";

          echo "
" .$valor->getFecha() ."
";

          echo "
";

          echo $valor->getComentario() ."
";

          if($valor->getImagen()!=""){

            echo "getImagen() . "' width='300px' />";

          }

          echo "
";

        }

    }

    }catch(exception $e){

      die("error:" .$e->getMessage());

  }

?>

 volver al formulario de entradas del Blog

A: Si lo que buscas es hacer algo simple, podes probar algo con este estilo, meter todo el card dentro del foreach y crearlo para mostrar la entrada.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<?php
include_once("../modelo/drive.php");

try{
  $myconnect=new PDO('mysql:host=localhost; dbname=inspirablog', 'root', '');
  $myconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  //$myconnect=new PDO('mysql:host=localhost; dbname=gaxenreh_inspiraBlog', 'gaxenreh_secursoft', 'Ledic@8848999');
  //$myconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $driveObjetos=new driveObjetos($myconnect);

  $tablaBlog=$driveObjetos->getContenidoPorFecha();

  if(empty($tablaBlog)){

    echo "No se encontraron entradas en el Blog!";

  }else{

    foreach($tablaBlog as $valor){

      echo "
" .$valor->getTitulo() ."
";

      echo "
" .$valor->getFecha() ."
";

      echo "
";

      echo $valor->getComentario() ."
";

      if($valor->getImagen()!=""){

        echo "getImagen() . "' width='300px' />";

      }

      echo "
";

    echo "

".$valor->getTitulo()."

Titulo del post

".$valor->getComentario()."

";

    }

}

}catch(exception $e){

  die("error:" .$e->getMessage());

}

?>

 volver al formulario de entradas del Blog

No te olvides de agregar la librería de Bootstrap.
Saludos.


text:
Q: Is there any limit on the number of Scheduled Tasks that can be created in MarkLogic? Is there any limit on:

*

*The number of Scheduled Tasks that can be created in MarkLogic?

*The number of Scheduled Tasks that can run at the same time?

Note: It took me around 20 minutes to create 1000 Schedule tasks on 16 GB RAM machine in MarkLogic 7.
The following script was used to insert the Scheduled Tasks:
xquery version "1.0-ml";

import module namespace admin = "http://marklogic.com/xdmp/admin"
                  at "/MarkLogic/admin.xqy";

for $i in 1 to 1000

let $config := admin:get-configuration()
let $group := admin:group-get-id($config, "Default")

let $new-task :=
  admin:group-one-time-scheduled-task(
    "/tasks/write-log.xqy",
    "/",
    xs:dateTime("2014-10-27T11:40:00"),
    xdmp:database("SampleDB"),
    xdmp:database("Modules"),
    xdmp:user("admin"),
    (),
    "normal")

let $addTask := admin:group-add-scheduled-task($config, $group, $new-task)

return admin:save-configuration($addTask)

Please let me know if MarkLogic defines any limit of these.
Thanks!

A: If these are one-time tasks, why not call xdmp:spawn directly?
Scheduled tasks run on the task server, so at runtime they are limited by the same factors as ordinary tasks: thread count and queue size.
Your code appears to call admin:save-configuration 1000 times, so it doesn't surprise me that it's slow. You're also getting the initial configuration 1000 times, which is sub-optimal. Remember that a FLWOR expression evaluates the return expression for every item in the input sequence, as filtered by any where expression.
The bottleneck for creating scheduled tasks is probably the admin API itself, which does a lot of internal validation of the new configuration. That's fine when creating a dozen new forests, but it isn't designed for fast performance of hundreds of configuration changes.
Assuming there's a reason to create scheduled tasks instead of calling xdmp:spawn, try something like this:
xquery version "1.0-ml";

import module namespace admin = "http://marklogic.com/xdmp/admin"
  at "/MarkLogic/admin.xqy";

let $config := admin:get-configuration()
let $group := admin:group-get-id($config, "Default")
let $now := current-dateTime()
let $db := xdmp:database("SampleDB")
let $modules := xdmp:database("Modules")
let $user := xdmp:user("admin")
let $_ :=
  for $i in 1 to 1000
  let $new-task := admin:group-one-time-scheduled-task(
    "/tasks/write-log.xqy", "/", $now,
    $db, $modules, $user,
    (), 'normal')
  return xdmp:set($config, admin:group-add-scheduled-task($config, $group, $new-task))
return admin:save-configuration($config)

But since these are one-time tasks, you're probably better off with xdmp:spawn. You might also look into using https://github.com/mblakele/taskbot


text:
Q: VBA Access No Current Record Error I cant seem to figure out this error, and all I want is to be able continue to the next item I am trying to include in the email.
I am using queries to send emails via Access.
Dim MyDb As DAO.Database
Dim rsEmail As DAO.Recordset
Dim InfoQuery As DAO.Recordset
Dim secondQuery As DAO.Recordset

Dim sToName As String
Dim sSubject As String
Dim sMessageBody As String
Dim test As String
Dim test2 As String

Set MyDb = CurrentDb()
Set rsEmail = MyDb.OpenRecordset("firstEmailCAD", dbOpenSnapshot)
Set InfoQuery = MyDb.OpenRecordset("InformationTableQueryEmail", dbOpenSnapshot)
Set secondQuery = MyDb.OpenRecordset("secondEmailCAD", dbOpenSnapshot)

test = rsEmail.Fields(2)
test2 = ""

With rsEmail

        If IsNull(test) Then
           test2 = test2 & "0"
        End If

        InfoQuery.MoveFirst
        Do Until rsEmail.EOF
            If IsNull(InfoQuery.Fields(0)) = False Then
                sToName = InfoQuery.Fields(0)
                sSubject = "Earnings for: " & InfoQuery.Fields(1)
                sMessageBody = "Email Body Text " & vbCrLf & _
                    "Field A: " & .Fields(1) & vbCrLf & _
                    **"Field B: " & test2 & vbCrLf & _**
                    "Field C: " & secondQuery.Fields(2)

                DoCmd.SendObject acSendNoObject, , , _
                    sToName, , , sSubject, sMessageBody, False, False
            End If
            .MoveNext
        Loop
End With

Set MyDb = Nothing
Set rsEmail = Nothing
Set InfoQuery = Nothing
Set secondQuery = Nothing

So the rsEmail query doesn't have a record at the moment, it depends on the day whether it will have a record or not, but what I want to do is be able to assign 0 to a specific column on that query.
test = rsEmail.Fields(2) --> this gives an error as No current record, considering I am only using it in an if statement, so I can put 0 when I create the message
I am new to VBA Access, any help will be appreciated :)
Thank you,

A: As Wayne puts it you should check if you have records at all BEFORE the command
InfoQuery.MoveFirst

In general it would be better to check both .BOF and .EOF
So it would be something like this:
If Not (InfoQuery.EOF And InfoQuery.BOF) Then
  InfoQuery.MoveFirst
  .....
Else
  'manage the lack of records condition here
  ....
End If

If a recordset has no records both BOF and EOF are set to true


text:
Q: how to detect when page scrolled to bottom and execute a function ONE time I am using ajax to dynamically load XML from a web service, the returned records are limited to just 25 items for each url 'load' or 'call'.... to work around that I have a process whereby the user scrolls down the page and when they reach 90% of the page height (or when  they reach page bottom - not sure which I'll choose yet), a variable named startindexnum is incremented by 25.
so startindexnum starts out at 25... then  after the first 'fire' of the function, the startindexnum becomes 50, on the 3rd it becomes 75, etc. etc.
my problem is that it fires multiple times and is somewhat erratic - processing multiple times when I scroll to the bottom and increasing by MORE than 25 sometimes (no doubt a result of running multiple times I think).
anyone have any idea what I need to tweak to get this to correctly generate the incremental startindex variable to append to my ajax URL where Im retrieving XML?  thanks.
var scrollcount = 1;
var startindexnum = 25;
var processing;

$(document).ready(function(){
    $(document).scroll(function(e){
       if (processing)
            return false;

            window.onscroll = function(ev) {

             if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight){
                //if ($(window).scrollTop() >= ($(document).height() - $(window).height())*0.9){
                    // you're at x%  of the page
                    processing = true;
                    scrollcount = scrollcount + 1;
                    startindexnum = scrollcount * startindexnum;
                    console.log(scrollcount);
                    docall();

                    processing = false;

                };
            };
    });
});

A: The problem is I am betting docall() is an asynchronous call, so setting of processing to false after that call does nothing to block the future scroll events.
The setting of false is happening before the results are returned. You want to set processing back to false when docall() is done doing its task.
         if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight){
            //if ($(window).scrollTop() >= ($(document).height() - $(window).height())*0.9){
                // you're at x%  of the page
                processing = true;
                scrollcount = scrollcount + 1;
                startindexnum = scrollcount * startindexnum;
                console.log(scrollcount);
                docall();

                //processing = false;  <--get rid of this

            };

and
function docall(){

    //When you are done fetching the new data and update the page set
    function AjaxCallIsDone() {
        processing = false;
    }

}

A: In addition to epascarello's post...
you don't need the $(document).scroll(fn) and the window.onscroll, which you are attaching to every time your document scroll handler is executed.  A few things:
1) Firstly, take a look at this scroll post by John Resig. Scrolling by J.Resig
2) If you want the jquery method then use window instead of document $(window).scroll(fn).
3) If not then I think the following will work for you:
var scrollcount = 1;
var startindexnum = 25;
var processing;

$(document).ready(function(){
    window.onscroll = function(ev) {
        if (!processing) {
            if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight){
                processing = true;
                scrollcount = scrollcount + 1;
                startindexnum = scrollcount * startindexnum;
                console.log(scrollcount);
                docall();
            }
        }
    }
});


text:
Q: Xpath slow running query I'm querying an xml using Xpath and JavaScript. The query get the results but damm slow and it takes ages to execute.
 var doc = $.parseXML(xml);
doc.xpath("(//NAMESET| //NAMESETFROMDATA) [HANDLE/STRINGVALUE = '" + handle+ "']");

where handle = NameSpaceAssoc::HighlightSet

Could anyone point me whats its doing and any pointer to improve its performance?
Consider myself a newbie in JavaScript and xml.

A: If you want to use xpath to select elements in javascript, should use evaluate() method. To better understanding See this.
To selecting element by evaluate() you must to write name of tags in lowercase in select path because browser convert every uppercase in tag name and attribute to lowercase. To better understanding See this.
var document = "Your xml document";
var handle = "NameSpaceAssoc::HighlightSet";
var path = "(//objectset | //objectsetfromdata) [handle/stringvalue = '" + handle + "']";
var query = document.evaluate(path, doc, null, XPathResult.ANY_TYPE, null);

You can compute execute time of code using this code
var startDate = new Date().getTime();

// Your code

var endDate = new Date().getTime();
var executeTime = endDate - startDate;

I check execute time of code, it is right.
See full example in jsfiddle


text:
Q: UTF characters in listings I use lstlistings for code and a lot of special characters can be displayed with literate. See my MWE
\documentclass{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{listings,textcomp,eurosym}
\begin{document}
\lstset{extendedchars=true,language=java,basicstyle=\ttfamily,showspaces=false,showstringspaces=false,literate=%
{€}{\euro}1%
{§}{\S}1%
{°}{\textdegree{}}1%
{ä}{{\"a}}1%
{ö}{{\"o}}1%
{ü}{{\"u}}1%
{ß}{{\ss}}1%
{Ä}{{\"A}}1%
{Ö}{{\"O}}1%
{Ü}{{\"U}}1%
{µ}{\textmu}1%
}

\begin{lstlisting}[language=Java]
// only for demonstration purposes
  public class keystrokes {
    public static void main(String[] args) {
      System.out.println("keystrokes on a German keyboard: €§°äöüßÄÖܵ");
    }
  }
\end{lstlisting}
\end{document}

But I don't know, how I can literate the following characters: ¹²³¼½¢

A: I see nothing strange with
\lstset{
  extendedchars=true,
  language=java,
  basicstyle=\ttfamily,
  showspaces=false,
  showstringspaces=false,
  literate=%
    {€}{\euro}1%
    {§}{\S}1%
    {°}{\textdegree{}}1%
    {ä}{{\"a}}1%
    {ö}{{\"o}}1%
    {ü}{{\"u}}1%
    {ß}{{\ss}}1%
    {Ä}{{\"A}}1%
    {Ö}{{\"O}}1%
    {Ü}{{\"U}}1%
    {µ}{\textmu}1%
    {¹}{{\textsuperscript{1}}}1%
    {²}{{\textsuperscript{2}}}1%
    {³}{{\textsuperscript{3}}}1%
    {¼}{\textonequarter}1%
    {½}{\textonehalf}1%
    {¢}{\textcent}1%
}

The input
\begin{lstlisting}[language=Java]
// only for demonstration purposes
  public class keystrokes {
    public static void main(String[] args) {
      System.out.println("keystrokes on a German
        keyboard: €§°äöüßÄÖܵ¹²³¼½¢");
    }
  }
\end{lstlisting}

produces


text:
Q: Is double tapping or bursting more effective? Since the Orange Box update and the updates after that, CSS has changed a lot with regards to hitboxes and recoil.  Before the updates I played pro skill and most people would just burst and some would do the double tap (burst), which is tapping twice to get a smaller recoil than using the normal burst which uses 3 or 4 bullets.  However, I started playing again and I noticed that the better players are using the double tap now.
Is it better to double tap?

A: Depends,
on how your style is...
I mean its a classic FPS which even these days people play it a lot even with the "hitboxes"
Double tap will bring more accuracy to your hits and most of the bullets will end at the target
Burst on the other hand need more movement on the mouse when you burst you need to move it to the opposite direction of the gun that burst.. :)
So close target i would say burst
far targets double tap!


text:
Q: Magento 2.2.6: Programmatically unchecking "My billing and shipping address are the same" I need to programmatically uncheck the "My billing and shipping address are the same" checkbox in Magento 2.2.6 checkout when a button is pressed.
Background:
I have built a button and some js into my template for simple "in-store pickup" option. It automatically adds the store address to the shipping address and selects the "In Store Pickup" shipping method.
I am using this jquery code in the extensions onepage.phtml file and it works fine, but I just can't figure out the last step to uncheck that button.
        $(document).on('click', '#in-store-pickup', function() {
            // Set Shipping Address
            $('.shipping-address-box').find("input[name='firstname']").val( "In-Store" ).change();
            $('.shipping-address-box').find("input[name='lastname']").val( "Pickup" ).change();
            $('.shipping-address-box').find("input[name='city']").val( "<?php echo $city; ?>" ).change();
            $('.shipping-address-box').find("input[name='region_id']").val( "<?php echo $regionId; ?>" ).change();
            $('.shipping-address-box').find("input[name='postcode']").val( "<?php echo $postcode; ?>" ).change();
            $('.shipping-address-box').find("input[name='telephone']").val( "<?php echo $phone; ?>" ).change();
            $('.shipping-address-box').find("input[name='company']").val( "<?php echo $name; ?>" ).change();
            $('.shipping-address-box').find("input[name='street\\[0\\]']").val( "<?php echo $street1; ?>" ).change();
            $('.shipping-address-box').find("input[name='street\\[1\\]']").val( "<?php echo $street2; ?>" ).change();

            // Set payment method
            $('#s_method_amstrates_amstrates8').trigger('click');

            // Need to uncheck the "My billing and shipping address are the same"

        });

(For the record, I am sure there is a cleaner way of doing above as well)
I have tried several things including triggering a change on the checkbox, but I believe the knockout bindings interfere with it. Thanks


text:
Q: URL to open a CashApp payment? I'm building an app where I want users to be able click a link to open up CashApp (as well as various other P2P payment apps), as far along in the transaction as possible. My client doesn't want the app to actually handle the payments, just for it to forward along to a place to make the payment.
So, for example, I can go to venmo.com/username to open the Venmo app to a certain user's profile, which is basically enough for me. (anyone know how to include an amount or message in the url?)
But cash.app/username goes to a webpage that directs me to the App Store get the app, and doesn't even open the app on my phone if it's already downloaded.
Anyone know how to do this?

A: This is actually quite simple with a universal link:
https://cash.app/$username/amount

The following example will open a cash app payment of $12.50 for the user with username 'helloworld':
https://cash.app/$helloworld/12.50

A: To pass info to Venmo app you can use:
venmo://paycharge?txn=pay&recipients=someone&amount=9.99&note=For%20Things

A: This is the url format for Venmo deeplinking:
https://venmo.com/<USER_NAME_1>,<USER_NAME_2>...?txn=<charge|pay>&note=<NOTE>&amount=<AMOUNT>
You can read more about the url format for Venmo Deeplinking here.

A: At this time, the ability to integrate with Cash app or accept or send Square Cash payments aren't currently available for Square's API.

A: ##"This is actually quite simple with a universal link:
https://cash.app/$username/amount
The following example will open a cash app payment of $12.50 for the user with username 'helloworld':
https://cash.app/$helloworld/12.50"##
I also used the same format but instead of app I used me:
https://cash.me/$username/5.00/
And when i click on the button with the as anchored:
"href="https://cash.me/$username/5.00/">"
The phone with the APP opens the payment of $5.00 with the username and the person just needs to hit send.


text:
Q: When do we get "'NaN' is not a valid numeric or approximate numeric value" in SQLException? I have added the following code in my JSP and getting some exception on saving entity to db.
 $('.validateWeight').click(function(event) {
var id = event.target.id;
var value;
$("#saveValue").val("");
if(id == "saveAndContinue"){
   var el = document.getElementById('saveValue');
   el.value = 1;
   //<c:set var="saveValue" scope="page" value="1"/>;
}else if(id=="saveAndClose"){
   var el = document.getElementById('saveValue');
   el.value = 2;
   //<c:set var="saveValue" scope="page" value="2"/>;
}

and

and in my Java Action Class, I have added the getter and setter
I am getting values set to 1 and 2 in needed cases but when saving the entity I do not how and from where 'NAN' value is coming and I am getting issues with save call.
Exception:
org.springframework.dao.TransientDataAccessResourceException: Hibernate operation: could not update: [com.hk.domain.inventory.GrnLineItem#100]; SQL [update person set age=?, no_of_children=?, address_line_1=?, address_line_2=?, mrp=?, state=?, city=?, pincode=?, weight=? where id=?]; 'NaN' is not a valid numeric or approximate numeric value; nested exception is java.sql.SQLException: 'NaN' is not a valid numeric or approximate numeric value
org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:107)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
org.springframework.orm.hibernate3.HibernateAccessor.convertJdbcAccessException(HibernateAccessor.java:424)
org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:410)
org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
org.springframework.orm.hibernate3.HibernateTemplate.flush(HibernateTemplate.java:881)
com.hk.impl.dao.BaseDaoImpl.resetHibernateAfterWrite(BaseDaoImpl.java:247)

and
java.sql.SQLException: 'NaN' is not a valid numeric or approximate numeric value
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
com.mysql.jdbc.PreparedStatement.setDouble(PreparedStatement.java:3572)
org.apache.commons.dbcp.DelegatingPreparedStatement.setDouble(DelegatingPreparedStatement.java:129)
org.apache.commons.dbcp.DelegatingPreparedStatement.setDouble(DelegatingPreparedStatement.java:129)
org.apache.commons.dbcp.DelegatingPreparedStatement.setDouble(DelegatingPreparedStatement.java:129)
org.hibernate.type.DoubleType.set(DoubleType.java:60)
org.hibernate.type.NullableType.nullSafeSet(NullableType.java:154)
org.hibernate.type.NullableType.nullSafeSet(NullableType.java:131)
org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2025)
org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2399)
org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2335)
org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2635)
org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:115)
org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:168)
org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
org.springframework.orm.hibernate3.HibernateTemplate$28.doInHibernate(HibernateTemplate.java:883)
org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
org.springframework.orm.hibernate3.HibernateTemplate.flush(HibernateTemplate.java:881)
com.hk.impl.dao.BaseDaoImpl.resetHibernateAfterWrite(BaseDaoImpl.java:247)
com.hk.impl.dao.BaseDaoImpl.save(BaseDaoImpl.java:237)

A: You could modify your javascript to use Jquery
$('.validateWeight').click(function(event) {
   var id = event.target.id;

   $("#saveValue").val("");
   if (id == "saveAndContinue")
      $("#saveValue").val(1);
   else if (id == "saveAndClose")
      $("#saveValue").val(2);
}

You have to take into account that if id isn't "saveAndContinue" or "saveAndClose", the value of the input with ID "saveValue" will be "", which is not numeric and will produce your NaN error.
In the other hand, you should check if in the server side you receive a String or a Integer, because you should pass to your Hibernate function an Integer.


text:
Q: How to debug compiled Java code in Eclipse I wonder if there are any solutions for Eclipse IDE to debug Java code for which I have no source, i.e. to debug dynamically decompiled code, step through it, etc.? I tried to use JD-Eclipse, JadClipse, and these plug-ins work great if I want to look at some class files, but as I debug, I get "Source not found." - how can I "attach" these plug-ins to "provide" source?
My environment:

*

*Eclipse 3.5

*Windows XP (but I look for a cross platform solution, if possible)

Thank you.

A: Realignment fragment for JD-Eclipse host plug-in. This plug-in for Eclipse makes the decompiled code line numbers actually appropriate to the line numbers from the java-class file. As a result, it becomes possible debugging without source code. https://sourceforge.net/projects/realignmentjd/

A: This plugin should hopefully be of help. JD-Eclipse
In eclipse open Window -> Preferences -> General ->Editors -> File Associations
Select *.class file type
Associate it with JD-Eclipse
Set it to default
Good Luck

A: You can use JD-GUI to decompile jar files and save the whole lot into a source zip file which can then be added to the source search list (via Configure Build Path).
The problem with JD-GUI is that the line numbers are out which makes debugging very difficult, so you need to

*

*extract the source files from the decompiled source zip file

*Run the script found at https://bushlife.com.au/groups/python/wiki/7539a/Adjust_line_numbers_in_file.html

*zip the generated source back up

*add it as the source path associated with your java file - using Configure Build Path after right clicking on the jar file in your java project.

A: Decompile all the classes, put all the Java files ordered in the proper hierarchy (directory for package, etc.) and then add them as the source of the original jar by right clicking the jar file -> Java Source Attachment -> External folder.
You can also have them inside a folder in the project (click on Workspace in this case)

A: The solution that worked for me is using the JD-Eclipse after applying the patch:  http://java.decompiler.free.fr/?q=node/464
This is an extension of jd-eclipse which realigns the code after decompiling.
When debugging with eclipse you just need to have the jar files in the classpath and that's it!
There's no need to decompile the whole jar, realign or whatsoever... Just debug and be happy :-)
Here's how to do it:
http://gauchoacomecable.wordpress.com/2011/10/14/eclipse-debug-java-without-source-code-jd-eclipse-and-realignment/

A: I have the same problem. Today, no decompilers are efficent to debug compiled Java code. I'm working on JD-Eclipse. In the next 3 to 6 months, the layout of JD-Eclipse should be really improved. We will start to debug classes without sources and solve some intractable problems.

A: I have good experience with Jadclipse - http://jadclipse.sourceforge.net/wiki/index.php/Main_Page - there is an update site at http://jadclipse.sf.net/update
For best results, use jad and configure it to list line numbers as comments which will enable the output where the code is on the correct line.  This is best for debugging sessions.
Then set it to be the default view for classes.  See the documentation for details.  This works well for me.

A: I have enhanced the "Realignment for JD Eclipse" plugin to properly line up enums and fields and published it along with JD Eclipse on my own update site: http://mchr3k-eclipse.appspot.com/
Details about my changes: http://mchr3k-coding.blogspot.co.uk/2012/07/realignment-for-jd-eclipse.html