text:
Q: Trim leading spaces, then Capitalize first letter of every line, and add new line + string + $var from another file if line begins w specific string I have two files. One is structured questions, the other is an answer key.
SourceQuiz.txt sample:
1)This is the first question.
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4
2)This is the second question
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4
3)This is the third question.
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4
4)This is the fourth question.
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4
etc etc

AnswerKey.txt sample:
a
b
d
d

I need FinalQuiz.txt file to be in this format: https://docs.moodle.org/311/en/Aiken_format
What is the correct answer to this question?
A. Is it this one?
B. Maybe this answer?
C. Possibly this one?
D. Must be this one!
ANSWER: D

The fact that the source questions have ) rather than . is immaterial. Moodle interprets them fine.
So I need to:

*

*Strip the number and right parenthesis from the beginning of each question

*Trim the leading spaces from the beginning of each question's options

*Capitalize the first letter of each line

*then look for every line beginning with D and insert a new line with the string ANSWER: x where x is the value in the line corresponding to the question in AnswerKey.txt

So i know i can:
Get-Content $SourceQuiz.txt  | Foreach {$_.TrimEnd()}

and i know i can:
Get-Content C:\Users\Administrator\Desktop\123.txt | ForEach-Object {
  if ($_) {
    $_.Substring(0, 1).ToUpper() + $_.Substring(1)
  } else {
    $_
  }
} > output.txt

And i know i can use if ($_.StarsWIth("D") in a foreach loop to find lines beginning with D.
What I dont know how to do is nest foreach loops in one another to do these either all at once or in a specific order, nor how to add the value of the right line in AnswerKey.txt (in our example above Question 1 would be ANSWER: A, Question 2 would be ANSWER: B, Question 3 would be ANSWER: D, Question 4 would be ANSWER D.
I could probably get this done if i make multiple scripts, but im not sure. ive been banging my head over this for a bit.

Edit for clarification. Here is source once again:
1)This is the first question.
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4
2)This is the second question
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4
3)This is the third question.
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4
4)This is the fourth question.
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4

The result I'm getting:
This is the first question.
a)  option 1
b)  option 2
c)  option 3
d)  option 4
ANSWER: D
This is the second question
a)  option 1
b)  option 2
c)  option 3
d)  option 4
ANSWER: C
This is the third question.
a)  option 1
b)  option 2
c)  option 3
d)  option 4
ANSWER: A
This is the fourth question.
a)  option 1
b)  option 2
c)  option 3
d)  option 4
ANSWER: B

The result needed:
1)This is the first question.
a)  option 1
b)  option 2
c)  option 3
d)  option 4
ANSWER: D
2)This is the second question
a)  option 1
b)  option 2
c)  option 3
d)  option 4
ANSWER: C
3)This is the third question.
a)  option 1
b)  option 2
c)  option 3
d)  option 4
ANSWER: A
4)This is the fourth question.
a)  option 1
b)  option 2
c)  option 3
d)  option 4
ANSWER: B

The numbers are missing. These are the indicators the importer looks for to define the end of one question and the beginning of the next.

A: This is the best I could think of, there is probably a much better way.
Props to mklement0 and this awesome answer where I learnt about script-block-based substitutions :)
NOTE: This code is all assuming the data looks exactly as you have shown in your question.
# In your case, this would be:
# $sourceQuiz = Get-Content path\to\SourceQuiz.txt

$sourceQuiz = @'
1)This is the first question.
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4
2)This is the second question
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4
3)This is the third question.
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4
4)This is the fourth question.
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4
'@ -split '\r?\n'

# And this would be:
# $answers = Get-Content path\to\answers.txt

$answers = @'
a
b
d
d
'@ -split '\r?\n'

$answerIndex = 0
$loopIndex = 1
$txtInfo = (Get-Culture).TextInfo

$sourceQuiz -split '^\d+\)' -ne '' | ForEach-Object {

    [regex]::Replace($_, '\s+(\w+)\)\s+', {
        param($s)

        $txtInfo.ToTitleCase($s.Groups[1].Value) + '. '
    })

    if($loopIndex % 5 -eq 0)
    {
        'ANSWER: {0}' -f $txtInfo.ToTitleCase($answers[$answerIndex])
        ''
        $answerIndex++
    }

    $loopIndex++
}

The above results in:
This is the first question.
A. option 1
B. option 2
C. option 3
D. option 4
ANSWER: A

This is the second question
A. option 1
B. option 2
C. option 3
D. option 4
ANSWER: B

This is the third question.
A. option 1
B. option 2
C. option 3
D. option 4
ANSWER: D

This is the fourth question.
A. option 1
B. option 2
C. option 3
D. option 4
ANSWER: D

EDIT
Code above was always assuming the number of options would be 4, supposing there would be an unknown number of options, the code would look like below.
Note the usage of -Raw on Get-Content.
# In your case, this would be:
# $sourceQuiz = Get-Content path\to\SourceQuiz.txt -Raw # => -Raw is important here

$sourceQuiz = @'
1)This is the first question.
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4
2)This is the second question
  a)  option 1
  b)  option 2
  c)  option 3
  d)  option 4
  e)  option 5
  f)  option 6
3)This is the third question.
  a)  option 1
  b)  option 2
'@

# And this would be:
# $answers = Get-Content path\to\answers.txt # => Here don't use -Raw

$answers = @'
a
b
d
'@ -split '\r?\n'

$answerIndex = 0
$txtInfo = (Get-Culture).TextInfo

$sourceQuiz -split '\d+\)' -ne '' | ForEach-Object {

    $lines = $_ -split '\r?\n' -ne ''

    for($i=0;$i -lt $lines.Count;$i++)
    {
        switch($i)
        {
            {$i -eq 0}
            {
                $lines[$i]
                break
            }
            {$i -gt 0}
            {
                [regex]::Replace($lines[$i],'\s+(\w+)\)\s+',{
                    param($s)

                    $txtInfo.ToTitleCase($s.Groups[1].Value)+'. '
                })
            }
            {$i -eq $lines.Count-1}
            {
                'ANSWER: {0}' -f $txtInfo.ToTitleCase($answers[$answerIndex])
                ''
            }
        }
    }

    $answerIndex++
}

Now this would look like this:
This is the first question.
A. option 1
B. option 2
C. option 3
D. option 4
ANSWER: A

This is the second question
A. option 1
B. option 2
C. option 3
D. option 4
E. option 5
F. option 6
ANSWER: B

This is the third question.
A. option 1
B. option 2
ANSWER: D

*

*Why is -Raw needed for the 2nd code snippet?

Because when reading the file if you use -Raw, the content will be a single multiline string instead of an array of strings string[].

*

*Why a single multiline string is required?

Because, since the 2nd code snippet is assuming that the number of possible options will not always be 4, we need to find a way to determine how many options there are.
For this, it takes the content of the file a single string and splits where there are _any amount of digits followed by a ) (i.e. 1), 123), 9999), etc) which separates each question and its corresponding options.
Once we have the questions an it's options divided in different arrays / chunks, we can split each chunk again in carriage returns or new lines and here we can assume that the position 0 of the array will always be the question:
{$i -eq 0}
{
    $lines[$i]
    break
}

The positions greater than 0 of the array will be the options, here is where we trim the leading spaces and replace the character followed by ) for the same character followed by . (i.e.:    a) for A.).
{$i -gt 0}
{
    [regex]::Replace($lines[$i],'\s+(\w+)\)\s+',{
        param($s)

        $txtInfo.ToTitleCase($s.Groups[1].Value)+'. '
    })
}

Lastly, to determine when we have reached the end of the available options and to know when to insert the ANSWER:, since I'm using a for loop and using the $i variable as index, on each iteration of the loop the switch is asking if $i is equal to $lines.Count - 1 (if $i has reached the end of the array or last element of the array).
{$i -eq $lines.Count-1}
{
    'ANSWER: {0}' -f $txtInfo.ToTitleCase($answers[$answerIndex])
    ''
}


text:
Q: Rest client post with username and password curl --request POST \
  --url https://example.com/token/grant \
  --header 'password: password' \
  --header 'username: user' \
  --data '{"app_key":"my_app_key","app_secret":"my_app_secret"}'

I am trying to get an equivalent ruby code for the above curl request with rest client.
I have tried:
auth = 'Basic ' + Base64.encode64( "#{AA['user_name']}:#{AA['password']}" ).chomp
response = RestClient.post'https://example.com/token/grant', {"app_key":"my_app_key","app_secret":"my_app_secret"}, {  'Authorization' => auth , :accept => :json, 'Content-Type': 'application/json' }
response = JSON.parse(response)

It did not work.
2nd try:
RestClient.post 'https://example.com/token/grant', {"app_key":"my_app_key","app_secret":"my_app_secret"}.to_json,  {'username': 'username', 'password': 'password', content_type: 'application/json'}

Also did not work.
I have checked username and password is correct.

It showing that username is missing in the header.

Thanks in advance.

A: As per the description it seems like when running the request using RestClient the header is action is unable to process the header (username since it is the first key in the header hash).
I have executed the below command on a custom code and it worked.
 RestClient.post 'https://example.com/token/grant', {"app_key":"my_app_key","app_secret":"my_app_secret"}.to_json,  {username: 'username', password: 'password', content_type: 'application/json'}

Note: I have just updated the representation of header keys passed in the header hash.

A: I have tried with Rest client. It did not work. Then I also tried Faraday, Net HTTP nothing works.
Then I have tried with curb. It works.
require 'curb'
request_path= 'https://example.com/token/grant'
payload = {
          app_key: 'app_key',
          app_secret: 'app_secret'
        }
http = Curl.post(request_path, payload.to_json) do |http|
          http.headers['username'] = 'user_name'
          http.headers['password'] = 'password'
          http.headers['Content-Type'] = 'application/json'
        end
JSON.parse(http.body_str)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java - When using the replace() method, there is a space between the replaced letter in a word. How do I make it where there is no space? So I am I wrote a method to replace all char's in a string, and it works. However if the letter I want to replace is sandwiched in a word, there is a space in place of the replaced letter, so the one word is now two. Here is an example
String str is Hello World . The character I want to make blank is o . My code will return this string Hell   W rld. How do I change my method so it outputs Hell Wrld
Here is my code
public static void main(String[] args) {
    System.out.println(removeAll("Hello World", 'e'));

}
public static String removeAll(String str, char letter) {
    String replace = str.replace(letter,' ');
    return replace;
}

A: You are replacing passed character with space in your replace method.
Replace char with CharSequence version lile str = str.replace("X", "");
"X" here is just an example you can pass your char and convert to string and use it

A: You can use:
str = str.replace("o", "");

Replace your intended letter with empty String.

A: Change
String replace = str.replace(letter,' ');

to
String replace = str.replace(letter,"");

Otherwise, you are putting a white space where 'o' used to be. If you want to completely burn that character, replace it with an empty character.


text:
Q: How Does Initalizing a Javascript Modal Work in Materializecss? I see other answers, but I still do not understand what initializing javascript means and how I am supposed to add the javascript part to my HTML page? If I want to include this modal in my HTML page:

  Modal

Modal Header

A bunch of text

      Agree

I am told I need to initialize it first using this code:
$(document).ready(function(){
  // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
  $('.modal').modal();
});

If I add this (the javascript portion) to the end of the material.js, it has no effect. If I add it in the HTML page and wrap it around using  like this:

A: You can use regular JavaScript to initialize it instead of the jQuery that you're using:
M.Modal.init(document.getElementById('modal1'));

You can put that code in a


text:
Q: Apache connection timeout I recently developed a site using codeigniter. The site is working fine and the ci profiler shows the following (for a random controller)
Loading Time: Base Classes      0.0039
Controller Execution Time ( Test / Index )      0.0152
Total Execution Time    0.0192
Database queries QUERIES: 6 (0.0079 seconds)
Memory usage : 2,891,752 bytes
However, the site is experiencing high peak usage at certain times (in relation to world cup football matches). It's not actually that high (about 60-70 simultaneous users) but the server gets very slow (up to 20s to load a page) and eventually times out.
The site is hosted on an OVH dedicated server under https:
Serveur EG-64 - E5-1650v3 - 64GB - SoftRaid 2x4To.
Bande passante Connexion réseau 1 Gbps; BP OVH/OVH 500 Mbps; BP sortante 500 Mbps; BP entrante 500 Mbps.
It actually takes up to 20s to load the index.php file of CI (debug log created on first line of index.php), once loaded the pages are displayed fast. It's the connection that takes time.
Any idea where to start looking ?

A: Fixed by tweaking the apache httpd.conf


text:
Q: getting a redraw for a second  I have two lists displaying on a web page:
(List of Clients)
(List of Projects)
When the user changes his selection in the client list, I repopulate the Project list.  I make a jquery call to php/mysql to fetch the projects relating to this client and then I use this data to set the options for the client <select>.  Unfortunately changing the list contents for the project <select> element does not cause the display for this element to change like setting the innerHTML for a text element would.
I can force a page refresh and everything looks fine, but I would prefer not to have to refresh the page.  Is there a way to cause a <select> element to redraw?
Here is a set of HTML/javascript that has the problem.  At the bottom of function BuildProjectList() it can be seen that I have tried populating the Project list in 2 ways, by setting innerHTML or by building the list of options.  In either case the display of the Project List does not update when I change its contents in response to a change of selection in the client list.  But if after this you change the selection in the project list, the display does update and you can verify that the underlying data for the Project list has in fact changed.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test List ....</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />

<input type="hidden" id="id_user_info" name="id_user_info" value="1" />
   Client...
   <select data-overlay-theme="a" data-native-menu="false" name="uidCl" id="uidCl" onChange="BuildProjectList()">

</select>

<input type="hidden" id="id_proj" name="id_proj" value="2" />
   Project...
   <select data-overlay-theme="a" data-native-menu="false" name="uidPr" id="uidPr" >

</select>

A: I found a way to use jquery to set in index in the  list and refresh the display.  The javascript function below shows how:
// set the index for a <select> element
function SetIndex(eid, i)
{
    var strEid = "#" + eid;
    var menuSelect = $(strEid);
    menuSelect[0].selectedIndex = i;
    menuSelect.selectmenu("refresh");
}


text:
Q: DeferredResult in spring mvc I have one class that extends DeferredResults and extends Runnable as shown below
public class EventDeferredObject<T> extends DeferredResult<Boolean> implements Runnable {

    private Long customerId;

    private String email;

    @Override
    public void run() {

        RestTemplate restTemplate=new RestTemplate();

        EmailMessageDTO emailMessageDTO=new EmailMessageDTO("dineshshe@gmail.com", "Hi There");

        Boolean result=restTemplate.postForObject("http://localhost:9080/asycn/sendEmail", emailMessageDTO, Boolean.class);

        this.setResult(result);
    }

//Constructor and getter and setters
}

Now I have controller that return the object of the above class,whenever new request comes to controller we check if that request is present in HashMap(That stores unprocessed request at that instance).If not present then we are creating object of EventDeferredObject class can store that in HashMap and call start() method on it.If this type request is already present then we will return that from HashMap.On completion on request we will delete that request from HashMap.
@RequestMapping(value="/sendVerificationDetails")

public class SendVerificationDetailsController {

private ConcurrentMap<String , EventDeferredObject<Boolean>> requestMap=new  ConcurrentHashMap<String , EventDeferredObject<Boolean>>();

    @RequestMapping(value="/sendEmail",method=RequestMethod.POST)
    public EventDeferredObject<Boolean> sendEmail(@RequestBody EmailDTO emailDTO)
    {
        EventDeferredObject<Boolean> eventDeferredObject = null;

        System.out.println("Size:"+requestMap.size());

        if(!requestMap.containsKey(emailDTO.getEmail()))
        {
            eventDeferredObject=new EventDeferredObject<Boolean>(emailDTO.getCustomerId(), emailDTO.getEmail());
            requestMap.put(emailDTO.getEmail(), eventDeferredObject);

            Thread t1=new Thread(eventDeferredObject);
            t1.start();

        }
        else
        {
            eventDeferredObject=requestMap.get(emailDTO.getEmail());

        }
        eventDeferredObject.onCompletion(new Runnable() {

            @Override
            public void run() {
                if(requestMap.containsKey(emailDTO.getEmail()))
                {
                    requestMap.remove(emailDTO.getEmail());
                }
            }
        });

        return eventDeferredObject;
    }

}

Now this code works fine if there no identical request comes to that stored in HashMap. If we give number of different request at same time code works fine.

A: Well, I do not know if I understood correctly, but I think you might have race conditions in the code, for example here:
        if(!requestMap.containsKey(emailDTO.getEmail()))
        {
            eventDeferredObject=new EventDeferredObject<Boolean>(emailDTO.getCustomerId(), emailDTO.getEmail());
            requestMap.put(emailDTO.getEmail(), eventDeferredObject);

            Thread t1=new Thread(eventDeferredObject);
            t1.start();

        }
        else
        {
            eventDeferredObject=requestMap.get(emailDTO.getEmail());

        }

think of a scenario in which you have two requests with the same key emailDTO.getEmail().
Request 1 checks if there is a key in the map, does not find it and puts it inside.
Request 2 comes some time later, checks if there is a key in the map, finds it, and
goes to fetch it; however just before that, the thread started by request 1 finishes and another thread, started by onComplete event, removes the key from the map. At this point,
requestMap.get(emailDTO.getEmail())

will return null, and as a result you will have a NullPointerException.
Now, this does look like a rare scenario, so I do not know if this is the problem you see.
I would try to modify the code as follows (I did not run it myself, so I might have errors):
public class EventDeferredObject<T> extends DeferredResult<Boolean> implements Runnable {

    private Long customerId;

    private String email;

    private ConcurrentMap ourConcurrentMap;

    @Override
    public void run() {
        ...
        this.setResult(result);
        ourConcurrentMap.remove(this.email);
    }

//Constructor and getter and setters
}

so the DeferredResult implementation has the responsibility to remove itself from the concurrent map. Moreover I do not use the onComplete to set a callback thread, as it seems to me an unnecessary complication. To avoid the race conditions I talked about before, one needs to combine somehow the verification of the presence of an entry with its fetching into one atomic operation; this is done by the putIfAbsent method of ConcurrentMap. Therefore I change the controller into
@RequestMapping(value="/sendVerificationDetails")
public class SendVerificationDetailsController {

    private ConcurrentMap<String , EventDeferredObject<Boolean>> requestMap=new  ConcurrentHashMap<String , EventDeferredObject<Boolean>>();

    @RequestMapping(value="/sendEmail",method=RequestMethod.POST)
    public EventDeferredObject<Boolean> sendEmail(@RequestBody EmailDTO emailDTO)
    {
        EventDeferredObject<Boolean> eventDeferredObject = new EventDeferredObject<Boolean>(emailDTO.getCustomerId(), emailDTO.getEmail(), requestMap);
        EventDeferredObject<Boolean> oldEventDeferredObject = requestMap.putIfAbsent(emailDTO.getEmail(), eventDeferredObject );

        if(oldEventDeferredObject == null)
        {
            //if no value was present before
            Thread t1=new Thread(eventDeferredObject);
            t1.start();
            return eventDeferredObject;
        }
        else
        {
            return oldEventDeferredObject;
        }
    }
}

if this does not solve the problem you have, I hope that at least it might give some idea.


text:
Q: How to map level 1 to H1 in asciidoc the default mapping is level 1(==) maps h2 in asciidoc
https://docs.asciidoctor.org/asciidoc/latest/sections/titles-and-levels/#section-level-syntax
How to map level 1 to H1 when convert .adoc to .html?
I use an online markdown-like editor which use H1 as section title.

A: To achieve your goal, you would likely need to modify the converter.
Currently, the document title converts to H1. If a level 1 heading converts to H1, you'd have to figure out what the level 0 heading converts to.
You haven't stated your goal when making this change. However, if it is presentation-based, you can customize the CSS used to make an H2 look like an H1, continuing through the heading levels to making an H6 look like an H5.


text:
Q: Loop through each multi dimensional array and echo one array Multi dimensional array:
Array
(
    [CalculateOverheadDoorSpringsResult] => Array
        (
            [SpringForce] => Array
                (
                    [InputData] => Array
                        (
                            [CalculationMode] => Expert
                            [CalculationVersion] => V100_ProofOfConceptVersion
                            [TrackSystemCode] => 1
                            [TrackSystemTypeDescription] => Normal Lift
                            [DoorWidth_mm] => 5000
                            [DoorHeight_mm] => 5000
                            [LiftHeight_mm] => 0
                            [TrackPitch_deg] => 0
                            [DoorWeight_kg] => 300
                            [VerticalComponentWeight_kg] => 33.33
                            [BottomSectionHeight_mm] => 610
                            [TensionSet] => false
                            [SpringCount] => 2
                            [ShaftConnectorCount] => 1
                            [ShaftDiameterCode] => 1
                            [ShaftDiameterDescription] => Shaft 1" (25.4 mm)
                            [SurfaceFinishCode] => 3
                            [SurfaceFinishDescription] => Powder coated
                            [CycleCount] => 20000
                            [SolutionTypeCode] => 1
                            [SolutionTypeDescription] => Simplex Identical
                            [OptimalSolutionOnly] => false
                            [DrumSpecification] => Automatic
                            [DrumFlexiForceCode] => FFNL18
                            [DrumCustomCode] =>
                            [DrumCustomFlatMomentArm_mm] => 0
                            [DrumCustomHighMomentArm_mm] => 0
                            [DrumCustomFlatWindings] => 0
                            [DrumCustomSipralWindings] => 0
                            [DrumCustomSafetyWindings] => 0
                            [EnforceFlexiForceCableRuling] => True
                            [InputDataValid] => true
                        )

                    [OutputData] => Array
                        (
                            [CalculationVersionBaseData] => V1.3.113
                            [CalculationVersionSolver] => V1.0.1
                            [TorqueTotal_Nmm_turn] => 17123
                            [Turns] => 12.8
                            [EnforceFlexiForceCableRuling] => True
                            [CableDiameter_mm] => 4
                        )

                    [Solutions] => Array
                        (
                            [Solution] => Array
                                (
                                    [0] => Array
                                        (
                                            [SolutionID] => 0604d089-e8cd-47e4-b331-e74373e23861
                                            [SpringCount] => 2
                                            [SpringWeightTotal_kg] => 69.77
                                            [ActualCycleCount] => 35900
                                            [SpringUnit] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [Type] => Simplex
                                                            [Qty] => 1
                                                            [Description] => 1 x Ass. Spring LHW 09,5x95x1810mm Pwdr. Plugged
                                                            [SpringWeightUnitTotal_kg] => 34.89
                                                            [Spring] => Array
                                                                (
                                                                    [Wire_mm] => 9.5
                                                                    [Length_mm] => 1810
                                                                    [Diameter_mm] => 95.25
                                                                    [Direction] => L
                                                                    [ArticleId] => VL95-3-1810PP
                                                                    [SpringWeight_kg] => 34.89
                                                                )

                                                        )

                                                    [1] => Array
                                                        (
                                                            [Type] => Simplex
                                                            [Qty] => 1
                                                            [Description] => 1 x Ass. Spring RHW 09,5x95x1810mm Pwdr. Plugged
                                                            [SpringWeightUnitTotal_kg] => 34.89
                                                            [Spring] => Array
                                                                (
                                                                    [Wire_mm] => 9.5
                                                                    [Length_mm] => 1810
                                                                    [Diameter_mm] => 95.25
                                                                    [Direction] => R
                                                                    [ArticleId] => VR95-3-1810PP
                                                                    [SpringWeight_kg] => 34.89
                                                                )

                                                        )

                                                )

                                        )

                                    [1] => Array
                                        (
                                            [SolutionID] => f495d32f-567e-41a9-ad10-b5b35e1ba20f
                                            [SpringCount] => 2
                                            [SpringWeightTotal_kg] => 69.71
                                            [ActualCycleCount] => 35000
                                            [SpringUnit] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [Type] => Simplex
                                                            [Qty] => 1
                                                            [Description] => 1 x Ass. Spring LHW 09,5x152x1170mm Pwdr. Plugged
                                                            [SpringWeightUnitTotal_kg] => 34.86
                                                            [Spring] => Array
                                                                (
                                                                    [Wire_mm] => 9.5
                                                                    [Length_mm] => 1170
                                                                    [Diameter_mm] => 152.4
                                                                    [Direction] => L
                                                                    [ArticleId] => VL95-6-1170PP
                                                                    [SpringWeight_kg] => 34.86
                                                                )

                                                        )

                                                    [1] => Array
                                                        (
                                                            [Type] => Simplex
                                                            [Qty] => 1
                                                            [Description] => 1 x Ass. Spring RHW 09,5x152x1170mm Pwdr. Plugged
                                                            [SpringWeightUnitTotal_kg] => 34.86
                                                            [Spring] => Array
                                                                (
                                                                    [Wire_mm] => 9.5
                                                                    [Length_mm] => 1170
                                                                    [Diameter_mm] => 152.4
                                                                    [Direction] => R
                                                                    [ArticleId] => VR95-6-1170PP
                                                                    [SpringWeight_kg] => 34.86
                                                                )

                                                        )

                                                )

                                        )

                                    [2] => Array
                                        (
                                            [SolutionID] => 6b97f4eb-1fa2-4885-a93d-63f24d108f1f
                                            [SpringCount] => 2
                                            [SpringWeightTotal_kg] => 93.74
                                            [ActualCycleCount] => 98400
                                            [SpringUnit] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [Type] => Simplex
                                                            [Qty] => 1
                                                            [Description] => 1 x Ass. Spring LHW 10,0x152x1490mm Pwdr. Plugged
                                                            [SpringWeightUnitTotal_kg] => 46.87
                                                            [Spring] => Array
                                                                (
                                                                    [Wire_mm] => 10
                                                                    [Length_mm] => 1490
                                                                    [Diameter_mm] => 152.4
                                                                    [Direction] => L
                                                                    [ArticleId] => VL100-6-1490PP
                                                                    [SpringWeight_kg] => 46.87
                                                                )

                                                        )

                                                    [1] => Array
                                                        (
                                                            [Type] => Simplex
                                                            [Qty] => 1
                                                            [Description] => 1 x Ass. Spring RHW 10,0x152x1490mm Pwdr. Plugged
                                                            [SpringWeightUnitTotal_kg] => 46.87
                                                            [Spring] => Array
                                                                (
                                                                    [Wire_mm] => 10
                                                                    [Length_mm] => 1490
                                                                    [Diameter_mm] => 152.4
                                                                    [Direction] => R
                                                                    [ArticleId] => VR100-6-1490PP
                                                                    [SpringWeight_kg] => 46.87
                                                                )

                                                        )

                                                )

                                        )

                                )

                            [!SolutionsFound] => true
                            [!SolutionCount] => 3
                        )

                    [!XMLVersion] => 1.0
                    [!CreateTimeStamp] => 2017-09-05T15:27:35Z
                    [!XMLID] => 0a1116c0-e140-47f2-acc5-6f8322d3d5f6
                    [!SystemError] => false
                    [!SystemErrorMessage] =>
                )

        )

)

Need to loop through each [Solutions] => Array, [OutputData] => Array and to show results in a simple table, almost like in the picture:

My question is how too loop through multi dimensional array [CalculateOverheadDoorSpringsResult] and echo only the solutions and outputdata arrays? Solutions will always alternate, it ca be 1 solution, 2, 3 or even more.
I was thinking like something, but at least it is a start:
<?php $array = $result['CalculateOverheadDoorSpringsResult'];
    foreach ($array as $item) { ?>

        <?php echo $item['InputData']['DrumFlexiForceCode'] . PHP_EOL; ?>
        <?php echo $item['OutputData']['Turns'] . PHP_EOL; ?>
        <?php echo $item['InputData']['SurfaceFinishDescription'] . PHP_EOL; ?>
        <?php echo $item['InputData']['CycleCount'] . PHP_EOL; ?>

    <?php } ?>

A: You can loop over Solutions like this:
foreach($result['CalculateOverheadDoorSpringsResult']['SpringForce']['Solutions']['Solution'] as $solution) {
    ...
}

and loop over OutputData like:
foreach($result['CalculateOverheadDoorSpringsResult']['SpringForce']['OutputData'] as $output) {
    ...
}


text:
Q: Let us choose a different theme for the Android app Please provide a setting to select themes and an option for a white-text-over-dark-background (e.g. twilight, monokai) theme for the Android app.
This would make reading the posts much easier on the eyes.


text:
Q: Maven Build Failure Windows - Alexa Skill Kit I tried to run Maven (never used it, just installed it with help of this guide) on my Windows 7 Machine to build the  Alexa Skill Kit Example
This was my output:
D:\Downloads\Chrome\alexa-skills-kit-java-master>mvn assembly:assembly -DdescriptorId=jar-with-dependencies package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Alexa Skills Kit 1.2
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-assembly-plugin:2.2-beta-5:assembly (default-cli) > package @ alexa-skills-kit >>>
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ alexa-skills-kit ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\Downloads\Chrome\alexa-skills-kit-java-master\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ alexa-skills-kit ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ alexa-skills-kit ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\Downloads\Chrome\alexa-skills-kit-java-master\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ alexa-skills-kit ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ alexa-skills-kit ---
[INFO] No tests to run.
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ alexa-skills-kit ---
[WARNING] JAR will be empty - no content was marked for inclusion!
[INFO] Building jar: D:\Downloads\Chrome\alexa-skills-kit-java-master\target\alexa-skills-kit-1.2.jar
[INFO]
[INFO] <<< maven-assembly-plugin:2.2-beta-5:assembly (default-cli) < package @ alexa-skills-kit <<<
[INFO]
[INFO] --- maven-assembly-plugin:2.2-beta-5:assembly (default-cli) @ alexa-skills-kit ---
[INFO] META-INF/MANIFEST.MF already added, skipping
[INFO] META-INF/ already added, skipping
[INFO] META-INF/maven/ already added, skipping
[INFO] META-INF/MANIFEST.MF already added, skipping
[INFO] META-INF/ already added, skipping
[INFO] META-INF/LICENSE already added, skipping
[INFO] META-INF/maven/ already added, skipping
[INFO] META-INF/maven/com.fasterxml.jackson.core/ already added, skipping
[INFO] com/ already added, skipping
[INFO] com/fasterxml/ already added, skipping
[INFO] com/fasterxml/jackson/ already added, skipping
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Skipping Alexa Skills Kit
[INFO] This project has been banned from the build due to previous failures.
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.708 s
[INFO] Finished at: 2017-02-25T12:21:53+01:00
[INFO] Final Memory: 16M/224M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-assembly-plugin:2.2-beta-5:assembly (default-cli) on project alexa-skills-kit: Failed to create assembly: Error creating assembly archive
jar-with-dependencies: invalid END header (bad central directory offset) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

mvn -version:
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T17:41:47+01:00)
Maven home: C:\Program Files\Apache\maven
Java version: 1.7.0_45, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.7.0_45\jre
Default locale: de_DE, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"

How can I fix this problem?

A: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-assembly-plugin:2.2-beta-5:assembly (default-cli) on project alexa-skills-kit: Failed to create assembly: Error creating assembly archive
jar-with-dependencies: invalid END header (bad central directory offset) -> [Help 1]

From that error message is clearly that some of your dependency or jar file is corrupted. I checked on the alexa-skills-kit and to make clear is the instruction stated to do the maven command in AWS instead from your local machine?

A: Seems to be that your jar file of maven-assembly-plugin is corrupted. It can be if you first tried to execute maven build from IDE without maven installed on your computer, and only then installed maven.
So, as was said previously in this post, you can remove all content of .m2/repository directory and then rebuild your application with maven.


text:
Q: Prevent opening new window or new tab on the same site? I want to prevent users from opening multiple tabs or windows open to my site. Each page has a different audio file that should not be playing at the same time. It also screws up a popup with background music. I also want any solution to work across various browser types.
I've tried javascript cookies, but they don't seem to work across multiple instances of the same page open in different tabs or windows. If they did work I would simply close down the new window if that cookies was set. (Actually, I think that solution works in safari, but nothing else.) Do php session variable work across multiple instances of the same page?
I don't care if a solution does not work across in incognito mode or across different browser types on the same page simultaneously. That's just asking for trouble.

A: You can check if there is an active tab playing music using the PageVisibility API, then other tabs don't play music!
http://www.html5rocks.com/en/tutorials/pagevisibility/intro/


text:
Q: What does input/output resistance/impedance mean? This keeps coming back in every single class, and I still don't have a clear idea of what it is. I keep seeing certain statements in other explanations such as "seen by X", "looking into Y" and so on. However, I don't quite get what that means?
Could you explain to me what they are intuitively, where we place them on the circuit, how we calculate them, and what would be a desired value for them?

A:
simulate this circuit – Schematic created using CircuitLab
Resistance is the load to DC. Impedance is the load to AC.
Any circuit will have two parts; the load and the source. The source supplies power to the load. Any circuit can be simplified down to these components. There is no such thing as a perfect source. With a load applied the voltage of that source will droop. In this Thevenin equivalent circuit, there is a resistor in series with an ideal voltage source to simulate the droop. When more current is drawn from the supply the resistor drops more voltage reducing the available voltage to the load. There is also a Norton equivalent with a current source and a resistor in parallel. This resistor R1, in this case, is the output impedance.
The load then has the input impedance. Simply put, it's the impedance of the load. Regardless of how complicated the load is it can always be simplified down to a single resistor.
The importance of input and output impedance is matching them properly. Suppose a signal passes through a filter and then to an ADC of a microcontroller. The filter, in this case, is the source and the ADC is the load. The sampling of the ADC causes a current draw on the line. This can be simulated by a resistor. This resistor is the input impedance of the ADC. Suppose it is 1k ohm. The filter will also simplify down to a voltage source and a resistor. That resistor is the output impedance of the filter. That resistor is important because it forms a voltage divider with the input impedance of the ADC. If the output impedance is 1k ohm then you get a 50% voltage divider. Any signal that comes out of the filter will be reduced by 50%. Often this level of attenuation is not acceptable.
This could be solved by a buffer stage between the filter and the ADC. The buffer has a very high input impedance and a very low output impedance. Suppose 1M ohm and 10 ohm respectively. The input to the buffer then has an attenuation of less than 1% and the input to the ADC also has an attenuation of less than 1%. Combined that is an attenuation of less than 2% and that is usually acceptable.
The calculation of the Thevenin and Norton equivalents is outside of a standard answer and I will leave it up to you to learn them.

A: For example, take a 9V battery. It does not always have 9V at the terminals, the more current you take out of the battery, the more the voltage will drop from the original 9V. It can be modeled as internal resistance, so this is the output impedance of a battery.
Same can be said about for example analog video or digital audio connections. As these connections use coaxial cables with 75 ohms of characteristic impedance (not DC resistance but the impedance seen by electrical waves), these input connectors are terminated with input impedance of 75 ohms to avoid reflections (think waves in water hitting a wall, they reflect back unless the wall has similar density than water does). For this reason the output connectors also drive the coaxial cable with 75 ohms impedance, so that anything reflecting back to will be dampened as well. So if the signal voltage is 1 Volt into a terminated 75 ohm input, it means the unterminated voltage at output connector would be 2 Volts.

A: Mathematically, the output resistance or impedance of a device is the derivative
$$r_{out}=\frac{dv_{out}}{di_{out}}$$
where \$i_{out}\$ is considered positive when it flows in to the device (the passive current convention). If we only consider the DC (or quasi-static) behavior, we call this a resistance. If we consider the AC steady-state behavior, we call this an impedance, and we usually change the symbol to \$z_{out}\$.
Similarly, the input resistance or impedance is
$$r_{in}=\frac{dv_{in}}{di_{in}}.$$
Again, the current is considered positive when it flows in to the device.
As the other answer has said, when \$r_{out}\$ is positive we get the very usual behavior that when the current out of an amplifier increases (under the passive current convention, we'd say the output current becomes more negative), the output voltage drops, and vice versa. Similarly if \$r_{in}\$ is positive and we increase the input voltage, we will (as we usually expect) drive more current in to the input terminal.
There are some devices with negative port resistance. For example, a buck regulator driving a constant load will need to draw more input current if its input voltage decreases, meaning it has a negative input resistance.


text:
Q: Extract main page results and continue to next pages with Scrapy I am struggling with accessing all the results from the main search page  and then looping through all the pages available;
def parse(self,response):
    for href in response.xpath('//*[@class="link link--minimal"]/@href'):
        yield response.follow(href, self.parse_property)

        # # follow pagination links
        # # can't get the href
    page_nums = response.xpath('//*[@class="listings-pagination-select"]/select/option/@value').re(r'\d+')
    page_nums[0]=''

Any suggestions?

A: So this is a website that is has most of it's content on the page loaded via javascript. Most modern websites have some content on the page invoked by javascript.
You can see for yourself in chrome. Inspect the page --> Three dots at right hand side --> More tools --> settings --> Debugging --> Disable javascript.
You will see none of the content on this website appears on the screen.
 Dealing with Dynamic Content
The scrapy docs details out quite explicitly what to do with dynamic content here.
There are two ways to deal with dynamically loaded content on the page. But first it's worth understanding how Javascript does this, without too much going into javascript commands. It invokes HTTP requests to a server and the responses are displayed onto the website pages. Javascript is able to do this, and the reason being is that most modern websites you want new content to appear without refreshing the page. Most HTTP requests used by javascript are done through an API endpoint. If you can find this API endpoint you may be able to do the correct HTTP request to get the data.
You can do two things

*

*Re-engineer these HTTP requests

*Browser Activity automation

The first method is the most efficient and less prone to changes to the website itself. It's also well suited The second is slow, more suited to complex browser activity but it is more brittle to website changes and not well suited for large data scrapes.
To think about how to do this you need to get to grips with Chrome Dev Tools, you can monitor the requests and response of the browser to see if there is the correct data/requests you require.
To do this, inspect the page and go to networking. Once this tab is open you can record activity of the browser. Refresh the page and see what happens. You'll see all the requests. Now you can specify what type of requests you want to see. The XHR tab you see in dev tools stands for XML HTTP request. This is any object that interacts with a server will be seen in this tab, i.e an API request. So navigating there is where you'll see potentially where data may be.
It so happens that the data is available for this website.

You can see the request and there's a tab for headers, preview etc.. The preview tab is good to see what data the request gives you. In the headers section you can see exactly the HTTP request, the payload needed to make this request etc...

Here are the request headers you can see in dev tools. Notice that it is a POST HTTP request made. Also, note content-type is JSON. That means highly-structured data.

Here is the payload that is required to make the proper HTTP request Notice it's specifying quite a bit! This is something you may be able to alter to get different searches etc... Some fun to be had playing around with this.

Copy the cURL command for this, I'm lazy and you can use a website to convert this request into a nice format.
Copy this into curl.trillworks.com. This converts the request into a nice format in python. It puts it into a requests package format.
import requests

headers = {
    'authority': 'jf6e1ij07f.execute-api.eu-west-1.amazonaws.com',
    'accept': 'application/json, text/plain, */*',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36',
    'content-type': 'application/json;charset=UTF-8',
    'origin': 'https://www.myproperty.co.za',
    'sec-fetch-site': 'cross-site',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://www.myproperty.co.za/search?last=0.5y&coords%5Blat%5D=-33.9248685&coords%5Blng%5D=18.4240553&coords%5Bnw%5D%5Blat%5D=-33.47127&coords%5Bnw%5D%5Blng%5D=18.3074488&coords%5Bse%5D%5Blat%5D=-34.3598061&coords%5Bse%5D%5Blng%5D=19.00467&description=Cape%20Town%2C%20South%20Africa&status=For%20Sale',
    'accept-language': 'en-US,en;q=0.9',
    'dnt': '1',
}

data = '{"clientOfficeId":[],"countryCode":"za","sortField":"distance","sortOrder":"asc","last":"0.5y","statuses":["For Sale","Pending Sale","Under Offer","Final Sale","Auction"],"coords":{"lat":"-33.9248685","lng":"18.4240553","nw":{"lat":"-33.47127","lng":"18.3074488"},"se":{"lat":"-34.3598061","lng":"19.00467"}},"radius":2500,"nearbySuburbs":true,"limit":210,"start":0}'

response = requests.post('https://jf6e1ij07f.execute-api.eu-west-1.amazonaws.com/p/search', data=data)

Here you can see there's data and headers that are needed to properly make this request. I would suggest you play around with this and making the request. Some API endpoints need headers, cookies, parameters etc... In this case you don't need the headers the curl.trillworks gives you. You do need the data though it specifies.
import requests

data = '{"clientOfficeId":[],"countryCode":"za","sortField":"distance","sortOrder":"asc","last":"0.5y","statuses":["For Sale","Pending Sale","Under Offer","Final Sale","Auction"],"coords":{"lat":"-33.9248685","lng":"18.4240553","nw":{"lat":"-33.47127","lng":"18.3074488"},"se":{"lat":"-34.3598061","lng":"19.00467"}},"radius":2500,"nearbySuburbs":true,"limit":210,"start":0}'

response = requests.post('https://jf6e1ij07f.execute-api.eu-west-1.amazonaws.com/p/search', data=data)

I would also spend sometime with response.json() which will convert the response into a python dictionary. To get the information you want you can go through the nested key and values. You haven't really specified your data needs so I won't go into this much more. But you can easily fiddle around with this so you input what you want into scrapy.
With that, you can now make the appropriate request and the data you get back is a JSON object.
 Code Example
data = '{"clientOfficeId":[],"countryCode":"za","sortField":"distance","sortOrder":"asc","last":"0.5y","statuses":["For Sale","Pending Sale","Under Offer","Final Sale","Auction"],"coords":{"lat":"-33.9248685","lng":"18.4240553","nw":{"lat":"-33.47127","lng":"18.3074488"},"se":{"lat":"-34.3598061","lng":"19.00467"}},"radius":2500,"nearbySuburbs":true,"limit":210,"start":0}'

def start_requests(self):
    url = https://jf6e1ij07f.execute-api.eu-west-1.amazonaws.com/p/search
    yield scrapy.Request(url=url, callback=self.parse, meta={'data',self.data})

def parse(self,response):
    response.json()

 Output
{'count': 1220,
 'listings': [{'id': 'mp1825776',
   'staffRooms': False,
   'propertyMaintype': 'Residential',
   'town': 'CAPE TOWN',
   'hasvirtualtour': False,
   'description': 'This spacious apartment in the Iconic Art Deco Building of Cape Town is waiting for you to view!\nThe double volume ceilings create a spacious feel inside this one bedroom, two bathroom apartment.\nThe staircase is beautifully designed, leading to the bedroom and en suite bathroom\nNatural lighting streams into the open plan dining, lounge and kitchen area through dramatic floor to ceiling famous windows. \n\n24-hour security.\nFully equipped Gym.\nParking Bay within Mutual Heights.\nAirB&B friendly.\nCentrally located with easy access to MyCiti Bus Stops and walking distance to top rated restaurants and coffee shops.\n',
   'propertyid': '1384000',
   'mainphoto': 'https://s3.entegral.net/p/n1384000_a935e9e1-6c37-4baa-996e-1715c2d75d9d1.jpg',
   'priceUnit': None,
   'isPriceReduced': False,
    ......... Continues

 Explanation
We define the data we need to pass in the variable data. In the function start_requests this automatically passes the request to be processed by the spider. But we get to decide instead what type of request to do instead of providing a URL in the start_urls list.
We do a scrapy request, but we pass the meta argument. This allows us to pass data with the HTTP request. It takes a dictionary, the key is called data and self.data is a class variable that we created.
In the parse method, we use response.json() please make sure you have scrapy v2.2+ to use this function. This will convert the response to a python dictionary.
 Additional Information

*

*Before doing a scrape, always check how javascript interacts with the website. Always disable javascript to see what you're dealing with, as in this case, you can't see the data without javascript. This way you know when it's dynamic content you have to deal with.

There are several ways to deal with dynamic content. If there is no HTTP request to make or no endpoint API.

*

*scrapy_splash
Splash pre-renders the HTML with javascript, that way we can access the javascript invoked data that appears on the page. It is better than selenium in that it's faster but does take some setting up. You need to be able to user docker images. To get any flexibility to with it you'll need to use LUA scripts also. The documentation is actually quite good at setting this up. You can do some browser activity but it's not as flexible as the selenium package.

*Consider scrapy_selenium.
If you're arent going to use splash you could use the scrapy selenium option, which will handle requests and mimic browser activity. However it's not that flexibly in doing browser activities like clicking/drop down menus etc...

*Using the spider middleware to make selenium based requests if you know you have a bunch of requests or all pages are going to require browser activity. Bit of a shotgun way to do this but it's an option.

*Importing selenium package stand-alone into the scripts. Remember your spiders are just python scripts, you can import the selenium package just as it is. Again selenium is a last resort if your data needs are great.


text:
Q: Django JWT - Allow request with no credential if key in body is valid I have an endpoint that needs an Access Token for authentication.
Also in this endpoint, there's a serializer UUID field that is not required.
What I would like to do is:

*

*In case the UUID field is passed in the body, check if this UUID is valid and registered in the Database.

*If it's not valid it'll raise a DRF ValidationError.

*If no UUID field is passed then the request needs to be authenticated with an Access Token.

Is there a way to have this kind of seletive auth verification?

A: Well, after some time I figured out the solution.
I opened the permission to access the view to any user, and inside the post method, I verified if the user is anonymous in order to check the request body keys. In case a valid JWT access token is passed, a user would be found and this would return False. If any of these conditions return True a simple credential error response is given.
permission_classes = [
    AllowAny,
]

def post(self, request, *args, **kwargs):
    if request.user.is_anonymous:
        request_token = request.POST.get('token')
        token = Token.objects.filter(token=request_token)
        if token.exists() and token.values()[0]['status'] == 'valid':
            pass
        else:
            return Response(
                data={"Invalid Credentials": "Pass a valid credential."},
                status=status.HTTP_200_OK,


text:
Q: Failed IBM DSX Desktop installation I'm trying to install IBM DSX Desktop, but after the application window is shown, the program shows spinning circles endlessly. Looking in the log, the application seems to be stuck in an endless update loop checking for app updates forever. Latest Docker is installed and running. Hyper-V enabled...
[2018-02-15 15:30:59:0158] [info] Checking for app updates...
[2018-02-15 15:30:59:0165] [info] Update for win32-x64-prod-v1.2.0 is not available
[2018-02-15 15:30:59:0169] [info] Checking for image updates...
[2018-02-15 15:30:59:0177] [info] Update for win32-x64-prod-v1.2.0 is not available
[2018-02-15 15:30:59:0183] [info] controller: emit update-not-available
[2018-02-15 15:30:59:0183] [info] controller: emit update-not-available
[2018-02-15 15:30:59:0201] [info] Update for win32-x64-prod-v1.2.0 is not available
[2018-02-15 15:30:59:0205] [info] Getting update information from updates.json
[2018-02-15 15:30:59:0209] [info] dsxJSON is [object Object]
[2018-02-15 15:30:59:0209] [info] DSX updates not available...
[2018-02-15 15:30:59:0209] [info] util: emit update-not-available for image
[2018-02-15 15:30:59:0209] [info] controller: emit update-not-available
[2018-02-15 15:30:59:0210] [info] controller: emit update-not-available
[2018-02-15 15:30:59:0213] [info] Getting update information from updates.json
[2018-02-15 15:30:59:0223] [info] dsxJSON is [object Object]
[2018-02-15 15:30:59:0224] [info] DSX updates not available...
[2018-02-15 15:30:59:0224] [info] util: emit update-not-available for image
[2018-02-15 15:30:59:0224] [info] controller: emit update-not-available
[2018-02-15 15:30:59:0225] [info] Getting update information from updates.json
[2018-02-15 15:30:59:0226] [info] dsxJSON is [object Object]
[2018-02-15 15:30:59:0226] [info] DSX updates not available...
[2018-02-15 15:30:59:0227] [info] util: emit update-not-available for image
[2018-02-15 15:30:59:0227] [info] controller: emit update-not-available
[2018-02-15 15:30:59:0615] [info] Calling check for updates...
[2018-02-15 15:30:59:0615] [info] Checking for app updates...
[2018-02-15 15:30:59:0618] [info] Checking for image updates...

A: Can you clean your environment and try a fresh install? To do that delete the following images if you have them:
dsx-desktop:v1, hybridcloudibm/dsx-dev-desktop-dsx-core:latest, hybridcloudibm/dsx-dev-desktop-rstudio:latest, hybridcloudibm/dsx-dev-desktop-zeppelin:latest, hybridcloudibm/dsx-dev-desktop-jupyter:ana27spark, hybridcloudibm/dsx-dev-desktop-jupyter:ana27nonspark, hybridcloudibm/dsx-dev-desktop-jupyter:ana35nonspark .
The syntax to delete the image (for ex: dsx-desktop:v1) is:
docker rmi dsx-desktop:v1
If you have a dsx-desktop container delete it using:
docker rm -f dsx-desktop
Finally remove the Settings file:
del %APPDATA%\ibm-dsx-desktop\Settings
Retry the install of the app and post the complete log if the install fails.

A: I'm on the DSX Desktop team. Sorry about the issue.
Unfortunately, nothing jumps out from the logs you included. I recommend installing the latest version, which has a significantly improved installer.
You can find the latest version here: https://www.ibm.com/us-en/marketplace/data-science-experience/purchase#purchasing.
Hope this helps.


text:
Q: requireNativeComponent was not found in the UIManager - React native (IOS) im building my npm package for ios, using native modules because i need to use a third party framework, the package is published and all good, installed to my app but when im about to render the native view from IOS to RN getting the error, heres in the IOS side:
this is my CounterViewManager.swift:
import Foundation

@objc(CounterViewManager)

class CounterViewManager: RCTViewManager {
  override func view() -> UIView! {
    let label = UILabel()
    label.text = "Swift Counter"
    label.textAlignment = .center
    return label
  }
}

my CounterViewManager.m:
#import <Foundation/Foundation.h>
#import "React/RCTViewManager.h"

@interface RCT_EXTERN_MODULE(CounterViewManager, RCTViewManager)
@end

and this how i import it from RN:
import { requireNativeComponent } from 'react-native';

const MyViewManager =  requireNativeComponent('CounterView');

export const Test = () => {

    return (
        <MyViewManager></MyViewManager>
    )
}

in RN i use CounterView because RN by default wont detect Manager at the end, but like i said always getting error that was not found in the UIManager, is driving me crazy, appreciate the help.
started the npm package following the docs: https://reactnative.dev/docs/native-modules-setup
when running in local to test works, can require the native module with that name, just when installing in my app via npm get that error


text:
Q: How to include custom command options in a bash script with $1 and $2? I have a script myscript.sh
#!/bin/sh

echo $1 $2

which is used something like ...
./myscript.sh foo bar

which gives me an output of ...
foo bar

but how can i make this script include custom command options? for example ...
./myscript.sh -a foo and corespond to $1

and
./myscript.sh -b bar and corespond to $2

A: You should to use man 1 bash:
Small example:
#!/bin/bash

while getopts "a:b:" opt      # get options for -a and -b ( ':' - option has an argument )
do
    case $opt in
        a) echo "Option a: $opt, argument: $OPTARG";;
        b) echo "Option b: $opt, argument: $OPTARG";;
    esac
done

A: Since you are listing bash as the shell used, type:
$ help getopts

Which will print something like:

getopts: getopts optstring name [arg]
      Parse option arguments.
Getopts is used by shell procedures to parse positional parameters as options.
OPTSTRING contains the option letters to be recognized; if a letter is followed by a
  colon, the option is expected to have an argument, which should be separated from it by white space.
Each time it is invoked, getopts will place the next option in the shell variable $name, initializing name if it does not exist, and the index of the next argument to be processed into the shell variable OPTIND.  OPTIND is initialized to 1 each time the shell or a shell script is invoked.  When an option requires an argument, getopts places that argument into the shell variable OPTARG.
Getopts normally parses the positional parameters ($0 - $9), but if more arguments are given, they are parsed instead.

Related:

*

*Getopts tutorial.

*getopts How to pass command line options

*How to use getopts in bash

*Getopt, getopts or manual parsing?


text:
Q: UIImageView setImage not working on iPad while working fine on iPhone I started with a Universal app project but have changed it to iPhone only everything works fine in iPad (both pixel doubling mode and 1x mode) except for the following line
in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

......

        UIImageView* iview = (UIImageView*)[cell viewWithTag:405];
    [iview setImage:[UIImage imageNamed:[NSString stringWithFormat:@"searchlist_%@Thumb", c.Name]]];

}

the image simply doesn't show up, what could be different on iPad?
the cell is pre configured in nib and is being loaded properly and other labels are being set properly
I'm also getting these assertions in console
Assertion failed: (cls), function getName, file /SourceCache/objc4_Sim/objc4-427.1.1/runtime/objc-runtime-new.m, line 3939.

A: The problem could be caused by any number of things. First, reformat your code so it looks like this:
UIImageView* iview = (UIImageView*)[cell viewWithTag:405];
NSString *imageName = [NSString stringWithFormat:@"searchlist_%@Thumb", c.Name];
UIImage *image = [UIImage imageNamed:imageName]
[iview setImage:image];

Then set a breakpoint on the last line. In the debugger you can check the values of iview, imageName, and image. Which one of those has an unexpected value will give you a clue where to look for the source of the problem.


text:
Q: Why does Go error when trying to marshal this JSON? I'm trying a rather simple example of trying to decode a JSON file into some structs using golang. However, when attempting to I get the error that

json: cannot unmarshal object into Go value of type []main.Track

Which I don't understand. Here's the code in question, and the JSON can be found here.
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "os"
)

// Tracks a group of Track types
type Tracks struct {
    Tracks []Track
}

// Track represents a singular track
type Track struct {
    Name   string
    URL    string
    Artist Artist
}

// Artist represents a single artist
type Artist struct {
    Name string
    MBID string
    URL  string
}

func main() {
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
    response, err := http.Get(url)

    if err != nil {
        fmt.Printf("%s\n", err)
        os.Exit(1)
    }

    defer response.Body.Close()

    var tracks Tracks
    decodeErr := json.NewDecoder(response.Body).Decode(&tracks)

    if decodeErr != nil {
        fmt.Printf("%s\n", decodeErr)
        os.Exit(1)
    }

    for _, track := range tracks.Tracks {
        fmt.Printf("%s: %s\n", track.Artist.Name, track.Name)
    }
}

My initial thought was maybe you need to categorize every single JSON value with structs, which I didn't do, but upon reading this article which says:

There are two answers to this. The easy option, for when you know what your data will look like, is to parse the JSON into a struct you've defined. Any field which doesn't fit in the struct will just be ignored. We'll cover that option first.

Which leads me to believe that it isn't that.
What am I doing wrong in this scenario?

A: If you look at the JSON structure of the response to your query you'll see that a single object with a tracks property is returned.
{
    "tracks": {
        "track": [ {...} ]
    }
}

If you compare this to to the given structs you can see that the structure does not align. Your given Tracks struct has a field that is a slice of Tracks. If I were to cast this as JSON it would be represented as the following.
{
    "tracks": [ { ... } ]
}

This is the root of your error. The JSON decoder is expecting the tracks field of the root JSON object to be an array. What is returned is an object that contains the tracks property but its values is another JSON object which contains the track property which is the array of tracks. You could update your structures to reflect this schema as follows.
// A response object from the API
type Response struct {
    Tracks Tracks
}

// Tracks a group of Track types
type Tracks struct {
    Track []Track
}

// Track represents a singular track
type Track struct {
    Name   string
    URL    string
    Artist Artist
}

A: The structure of the Go types must match the structure in the JSON data. The application is missing a level of nesting for the bolded range of this JSON:   {"tracks":{"track":[{
Here's how to update the types to match the JSON:
type Tracks struct {
    Tracks struct {
      Track []Track
    }
}

...

for _, track := range tracks.Tracks.Track {
    fmt.Printf("%s: %s\n", track.Artist.Name, track.Name)
}


text:
Q: FindRoot with NIntegrate giving errors I'm struggling with the following code. I have to solve some self consistent equations with FindRoot, but I always get some problem related to slow convergence and/or problems related with NIntegrate.
ClearAll["Global`*"];

U = 0.5;
S = 5;
w1 = 0;
a = 0.1;
R = 0;
a1 = a/S;
b = 2;
b1 = b*a/S^2;

ϕ[z_?NumericQ] := (1 + Erf[z/Sqrt[2]])/2;
x[q_?NumericQ,m_?NumericQ] := x[q,m] = Sqrt[(1 - a1)/b1]*(m/(Sqrt[q] + a1*R));
y[q_?NumericQ,m_?NumericQ] := y[q,m] = Sqrt[(1 - a1)/b1]*(U - w1 (S - 1)/(2*S) - b1*R/(2*Sqrt[q]))*(1/(Sqrt[q] + a1*R));

fq1[q_?NumericQ, m_?NumericQ, w_?NumericQ] := fq1[q,m,w] = NIntegrate[Exp[-z^2/2]/Sqrt[2 π]*(ϕ[z])^S, {z, y[q,m]*a1 + x[q,m] - I*Sqrt[a1]*w, ∞}];
fq2[q_?NumericQ, m_?NumericQ, w_?NumericQ] := fq2[q,m,w] = NIntegrate[Exp[-z^2/2]/Sqrt[2 π]*(ϕ[z + y[q,m]])^S, {z, -y[q,m]*(1 - a1) + x[q,m] - I*Sqrt[a1]*w, ∞}];
fq3[q_?NumericQ, m_?NumericQ, w_?NumericQ] := fq3[q,m,w] = NIntegrate[Exp[-z^2/2]/Sqrt[2 π]*ϕ[z - y[q,m]]*(ϕ[z])^(S - 1), {z, y[q,m]*a1 + x[q,m]-I*Sqrt[a1]*w, ∞}];
fq[q_?NumericQ,m_?NumericQ] := fq[q,m] = (1 - a)/a1*NIntegrate[Exp[-w^2/2]/Sqrt[2 π]*fq1[q,m,w], {w, -∞, ∞}] + NIntegrate[Exp[-w^2/2]/Sqrt[2 π]*fq2[q,m,w], {w, -∞, ∞}] + (S - 1)*NIntegrate[Exp[-w^2/2]/Sqrt[2 π]*fq3[q,m,w], {w, -∞, ∞}];

fm[q_?NumericQ, m_?NumericQ] := fm[q, m] = 1/(1 - a1)*NIntegrate[Exp[-w^2/2]/Sqrt[2 π]*fq2[q, m, w], {w, -∞, ∞}] - fq[q, m]*a1 /(1 - a1);

FindRoot[{q - fq[q, m] == 0, m - fm[q, m] == 0}, {{q, 1}, {m, 1}}]

In particular it gives the errors

Numerical integration converging too slowly; suspect one of the following: singularity, value of the integration is 0, highly oscillatory integrand, or WorkingPrecision too small.
The integral failed to converge after 1012 integrand evaluations. NIntegrate

Any hints and suggestions are welcome.


text:
Q: How to get all data back in an ios parse query I have two tables each with one record(for testing and question purposes). These tables are Post and Comment. Post has a PFRelation called myComment (I know only one comment - lets call it a feature for now). If I query Post, how do I get the Post and Comment data back?
Can't find this anywhere using web search engines or Parse docs (not a complete answer at least).

A: Because Relation in Parse is just like its literal meaning, it does not contain any data. If you want to get the data back, you need to get that instance of Relation first. Then call query from that instance. After that, you just perform that query if you want to get all objects from this Relation. You can also add some constraints after getting the query from Relation.
If you use Pointer type, you can just get back the data by using includeKey:.


text:
Q: background images not found in GAE I have a bad problem when loading most of background pictures in my GAE front-end app.
"Failed to load resource: the server responded with a status of 404 (Not Found)".
My app is a simple website, with no GAE backend.
I am using Eclipse with Google AppEngine Plugin.
The background pictures are changed every 10 seconds using JQuery.
What I dont understand is that out of my 16 background pictures, the 3rd and 11th are always found,
whereas the rest are never. (And no, the name is not wrong I have checked that million of times..)
If there is some systematic error in the way I access the pictures, then shouldnt they all fail?
Now obviously I am missing something here but what? I have tried to google for answer but I dont get it, everything works fine locally.
Any other small pictures I have for icons and header always load perfectly. The problem is with the big background images. There is no difference between browsers.
Things I tried (with no success):

*

*I increased the stack size (-Xmx10m -Xss10m) to try to see if the deployment somehow failed.

*I do not have any app.yaml file, I tried to add a simple app.yaml file and telling the engine that my images are in "images" folder.

*i moved my background pictures from "images/background" into "images"

*Made a test in which I changed all the pictures really simple with just a single color background, and then all pictures were OK.. And later again all the pictures failed except the 3rd and 11th with no code changes.

Please, any idea what I am missing here? If things work locally, but not in GAE, is there a list somewhere what is the difference in terms of environment..?
Some of the code is below:
var photos = [ {
"image" : "p1.jpg",}, {
"image" : "p2.jpg",}, {
"image" : "p3.jpg",}, {
// pictures 4-10
    "image" : "p11.jpg",}, {
// pictures 12-15
    "image" : "p16.jpg",
        }
        ];

// Set the background image of the new active container
$("#backgroundimg" + activeContainer).css({
    "background-image" : "url(images/" + photoObject.image + ")",
    "display" : "block",
    "z-index" : currentZindex
});

// Fade out the current container
// and display the header text when animation is complete
$("#backgroundimg" + currentContainer).fadeOut(function() {
    setTimeout(function() {
        animating = false;
    }, 1000);
});

A: please try referencing your images absolutely, meaning from the document root rather than relatively.  relative reference, from the current directory:
url(images/" + photoObject.image + ")"

absolute reference, works regardless of current directory (which i'm wondering if somehow google app engine is altering dynamically given some other bit of code.
url(/images/" + photoObject.image + ")"

i'm also curious about the photos object.  given the small amount of context, this might be easier to work with:
var photos = ["p1.jpg", "p2.jpg", "p3.jpg", "p11.jpg", "p16.jpg"];

good luck!
`


text:
Q: Format 12h format timestamp string to TIME in iDB2 I need a iSeries DB2 SQL query which can transform this timestamp 1/1/1900 12:00:00 AM into 00:00:00 (handling the 12h to 24h time convertion). The scalar functions I've used don't handle this time format, the only way I managed to support this was with the following query:
SELECT (
    CASE
    WHEN LOCATE('PM', '1/12/1900 12:00:00 AM') = 0 THEN
    REPLACE(CHAR(TIME(TIMESTAMP_FORMAT('1/12/1900 12:00:00 AM', 'DD/MM/YYYY HH24:MI:SS'))) , '.', ':' )
    ELSE
    REPLACE(CHAR(TIME(TIMESTAMP_FORMAT('1/12/1900 12:00:00 AM', 'DD/MM/YYYY HH24:MI:SS')) + 12 HOURS) , '.', ':' )
    END)
FROM SYSIBM.SYSDUMMY1;

Is there a better way to achieve the objective ?
EDIT 6/JUN/2014
I've found that it might be possible to set the date format (ISO,USA, ...) in the connection string, which would solve all of the problems I'm currently having with this, but, I haven't found the correct parameter name to achieve that.

A: Assuming you have specified the correct values on the connection to indicate the correct date and time formats, if you can then convert/source the date and time values separately, you can then use the below query for conversion to your desired format:
select to_char( timestamp( date('12/12/1901') , time('12:00 PM') ),  'YYYY-MM-DD HH24:MI:SS')
from sysibm/sysdummy1;

A: The following expression should suffice for the purposes expressed by the OP; i.e. for obtaining just the TIME value in the character-string format HH:MM:SS [where HH represents 00 to 24], as derived from string values that are an effective timestamp in the format MM/DD/YYYY HH:MI:SS AM for which the single digit variants of both MM [i.e. just M] and DD [i.e. just D] must be supported. So for example, such that the column-name ts_str is VARCHAR(22):
char( time( insert( right( ts_str, 11 ), 6, 3, '' ) )
       + int( left( right( ts_str, 05 ), 2 ) ) seconds
      , JIS )

In the above expression, with the right-most eleven characters known to be the time portion in the format HH:MM:SS AM, from which the :SS is truncated by the INSERT scalar, thus leaving a valid *USA time-string value HH:SS AM, that string is converted to a TIME value with the TIME casting scalar. Then the second line picks out the SS value, casting that to an integer with the INT casting scalar, and that value is the duration in SECONDS added to the derived TIME. Finally that adjusted time value [i.e. with seconds added-back] is cast to character using the *JIS format which is HH:MM:SS [where HH is 00 to 24].
Now, about the TIMESTAMP_FORMAT:
The DB2 for IBM i 7.1 has, according to updated documentation IBM i 7.1-> Database-> Reference-> SQL reference-> Built-in functions-> Scalar functions-> TIMESTAMP_FORMAT, apparently with some level of Technology Refresh or cumulative level, there has been added support for the Meridian indicator [i.e. 'AM'] within a format-string. The following expression has been confirmed, albeit on IBM i 7.3, to properly convert the timestamp-like strings from the OP, into a TIMESTAMP:
to_date( ts_str, 'MM/DD/YYYY HH:MI:SS AM')

Thus that use of the TIMESTAMP_FORMAT [shown just above as TO_DATE], given ts_str represents the input values described in the OP, should be able to derive a TIMESTAMP directly from those input timestamp-strings, specifying nothing more than that scalar with a format-string as the second argument and the input-string as the first argument. Quite simple, if available.
Note: I do not know which, neither of a TR nor a cumulative PTF level on v7r1 on which the function becomes available on that release; perhaps look for "What's new as of April 2016" in the IBM i 7.1 Knowledge Center and/or the maintenance levels, both as alluded-to here: TO_CHAR VARCHAR_FORMAT enhancement for numeric editing format-string
The following script includes a setup and then tests two different expressions to verify the results; these are the previously/above noted expressions. This same setup is then used in later examples which show some alternatives if the TIMESTAMP_FORMAT [aka TO_DATE] enhancement is not available [e.g. on older v7r1 maintenance levels, or on v6r1 where the enhancement will not ever be seen], or like on prior releases where there is not even a TIMESTAMP_FORMAT function available, such as for v5r3 on which the latter three scripts were verified:
create table so24067379
( ts_str for ts varchar(26) /* `for ts`-short name ref'd later */
, ts_val timestamp
)
;
insert into so24067379 values
  (  '1/2/1900 12:00:00 AM', '1900-01-02-00.00.00.000000')
, ( '1/12/2012 12:00:00 AM', '2012-01-12-00.00.00.000000')
, ('12/12/1900 12:00:00 AM', '1900-12-12-00.00.00.000000')
, (  '1/2/2012 12:07:00 AM', '2012-01-02-00.07.00.000000')
, ( '7/12/1900 01:07:08 AM', '1900-07-12-01.07.08.000000')
, ( '12/2/2012 01:07:08 AM', '2012-12-02-01.07.08.000000')
, ('12/12/2012 01:07:08 AM', '2012-12-12-01.07.08.000000')
, ( '1/12/1900 12:13:14 PM', '1900-01-12-12.13.14.000000')
, (  '7/2/2012 12:13:14 PM', '2012-07-02-12.13.14.000000')
, ('12/12/1900 12:13:14 PM', '1900-12-12-12.13.14.000000')
, (  '1/2/2012 01:00:00 PM', '2012-01-02-13.00.00.000000')
, ('12/12/1900 01:14:15 PM', '1900-12-12-13.14.15.000000')
, (  '1/2/2012 07:20:21 PM', '2012-01-02-19.20.21.000000')
, ( '1/12/2012 07:20:21 PM', '2012-01-12-19.20.21.000000')
;
create view test0 as
( select m.*
   /* , to_date( ts_str, 'MM/DD/YYYY HH:MI:SS AM') */
       , TIMESTAMP
          ( date( to_date( ts, 'MM/DD/YYYY' ) )
          , time( insert( right( ts, 11 ), 6, 3, '' ) )
             + int( left( right( ts, 05 ), 2 ) ) seconds
          ) as ts_tst
  from so24067379 as m
)
; -- functional on v6r1 and above per no reference to Meridian enhancement
select * from test0
where ts_val <> ts_tst
; -- above query returns zero rows as verification of adjusted TIME

create view test1 ( ts_str, ts_val, ts_tst )  as
( select m.*
       , to_date( ts_str, 'MM/DD/YYYY HH:MI:SS AM')
  from so24067379 as m
)
; -- requires v7r1 **plus** Meridian enhancement
select * from test1 where ts_val <> ts_tst
; -- above query returns zero rows as verification of TO_DATE

The following two alternatives for which no TO_DATE is utilized are effectively the same, conceptually; each just choosing a different place for the same logic for adjusting the hours to the time.  The first is probably prettier, but repeats a larger amount of expressions, because the task is split first, into AM vs PM, before both generating the time-value and then an adjustment to the number of hours, depending on whether the first two digits are '12':
create view test2 ( ts_str, ts_val, ts_tst )  as
( select
    m.*  /* , to_date( ts_str, 'MM/DD/YYYY HH:MI:SS AM')  */
  , (TIMESTAMP
      ( date( left( ts, locate(' ', ts) - 1 ) )
      , case right( ts, 2 )
         when 'PM'
         then time( substr( ts, locate(' ', ts) + 1 , 8 )
                  ) + case substr( ts, locate(' ', ts) + 1 , 2 )
                        when '12' then 0 else 12 end  HOURS
         when 'AM'
         then time( substr( ts, locate(' ', ts) + 1 , 8 )
                  ) - case substr( ts, locate(' ', ts) + 1 , 2 )
                        when '12' then 12 else 0 end  HOURS
       end
      )
    ) as true_ts
  from so24067379 as m
)
;
select * from test2 where ts_val <> ts_tst
-- above query returns zero rows as verification of TO_DATE replacement

This variation takes advantage of the fact that all of the time values will be valid as HH:MM:SS [for HH 01 to 12], despite being incorrect pending adjustment per Meridian specification; that TIME value is calculated first, and then logic is employed to decide on how many hours to adjust that time value. The first test is for the time beginning with '12', for which 'AM' values must have 12 hours subtracted to make 00 hours, but for which 'PM' values no adjustment needs to be made; then for any other 'PM' values [i.e. 01 to 11], 12 hours must added, and finally for any other 'AM' values [i.e. 01 to 11] there are no adjustments to be made:
create view test3 ( ts_str, ts_val, ts_tst )  as
( select
    m.*  /* , to_date( ts_str, 'MM/DD/YYYY HH:MI:SS AM')  */
  , ( TIMESTAMP
        ( date( left( ts, locate(' ', ts) - 1 ) )
        , time( substr( ts, locate(' ', ts) + 1 , 8 ) )
           + case
               when substr( ts, locate(' ', ts) + 1 , 2 ) = '12'
               then case when right( ts, 2 ) = 'AM' then -12
                         else   0 /* must be 12:xx PM */ end
               when right( ts, 2 ) = 'PM' then 12
               else 0
             end       HOURS
        )
    ) as true_ts
  from so24067379 as m
)
;
select * from test3 where ts_val <> ts_tst
; -- above query returns zero rows as verification of TO_DATE replacement

While the following is much more succinct, and using the original expression offered to get the TIME in place of what the OP showed was being attempted, I put this example last, because although the expression is nice, the logic is just not very intuitively obvious as might be intuited from reading the prior expressions that used the CASE expressions:
create view test4 as
( select m.*
   /* , to_date( ts_str, 'MM/DD/YYYY HH:MI:SS AM') */
       , TIMESTAMP
          ( date( left( ts, locate(' ' , ts ) ) )
          , time( insert( right( ts, 11 ), 6, 3, '' ) )
             + int( left( right( ts, 05 ), 2 ) ) seconds
          ) as ts_tst
  from so24067379 as m
)
;
select * from test4
where ts_val <> ts_tst
; -- above query returns zero rows as verification of TO_DATE replacement


text:
Q: Why this mysql insert statement doesn't work? I am trying to insert an image into a longblob type field named 'img':
    include('config.php');

    $imgData =  mysqli_real_escape_string($conn, file_get_contents($_FILES['im_age']  ['tmp_name']));

    $qry="  insert into tblproducts(
    vendorid, prefix, overallsize, handlematerial, img, code, itemcost, shippingcost,
    profitpercentage, discountpercentage, caption, availability, quantity
    )
    values(
    $_POST[vendor_id],
    $_POST[pre_fix],
    $_POST[overall_size],
    $_POST[handle_material],
    $imgData,
    $_POST[co_de],
    $_POST[item_cost],
    $_POST[shipping_cost],
    $_POST[profit_percentage],
    $_POST[discount_percentage],
    $_POST[cap_tion],
    $_POST[avail_ability],
    $_POST[quan_tity]
    )
";

   $result = mysqli_query($conn, $qry) or die("Could not execute query!");

EDIT: I get the following error: 'Could not execute query'
How do I make the insertion of the image happen? Thanks in advance!

A: Your POST values aren't being interpolated properly. You shouldn't be using interpolation or concatenation to build your queries. Here's how to write a prepared statement to prevent against SQL injections:
$qry = "INSERT INTO tblproducts (
    vendorid, prefix, overallsize, handlematerial, img, code, itemcost, shippingcost,
    profitpercentage, discountpercentage, caption, availability, quantity
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";

$stmt = mysqli_prepare($conn, $qry);

mysqli_stmt_bind_param($stmt, 'sssssssssssss',
    $_POST['vendor_id'],
    $_POST['pre_fix'],
    $_POST['overall_size'],
    $_POST['handle_material'],
    $imgData,
    $_POST['co_de'],
    $_POST['item_cost'],
    $_POST['shipping_cost'],
    $_POST['profit_percentage'],
    $_POST['discount_percentage'],
    $_POST['cap_tion'],
    $_POST['avail_ability'],
    $_POST['quan_tity']
);

if (!mysqli_stmt_execute($stmt)) {
    echo 'Query failed.';
}

Of course there's more advanced techniques of error handling and using object-oriented things, but this should cover the very basics to get the query working.
You may have noticed the question mark parameters in the query. MySQLi does not support named parameters. If you would prefer using named parameters in your query like :vendor_id, try using PDO.

A: Regarding your query: none of the post data would be parsed into the query because you are just writing it. You need to either concatenate the values in or wrap the variables in {$var}. Also the key in $_POST should be wrapped in single quotes. Ex: $_POST['vendor_id'];
Use mysqli_prepare() and mysqli_bind_param() to make a more functional and more secure query.
Regarding images in MySQL, you can but it's not recommended. Check out this post for more info about it.

A: Its because you are munging the image datadirectly into the query text which is probably causing a bunch of issues.
Use mysqli_prepare and mysqli_stmt_bind_param instead. As Dai hinted at, this is much safer.


text:
Q: HQL for an any association I'm trying to write HQL for a Rental that has many-to-any association PaymentTypes.
from rental
where not exists(
    from PaymentTypes pt where pt.Owner = :rental and type = 'Visa'
)

Owner is a any association where OwnerId is rental.Id and OwnerType = 'Rental'
Unfortunately I can't use SetEntity as prefetching the rentals and then calling SetEntity will be very costly.

A: Why not trying a dynamic query like
from rental where not exists(from PaymentTypes pt where pt.Owner.id = " + rental.id + " and type = 'Visa')


text:
Q: angular-formly multiCheckbox Select All I have a multiselect field in angular-formly, with the following options:
vm.fields = [
    {
    key: 'fruits',
    type: 'multiCheckbox',
    className: 'multi-check',
    templateOptions: {
        label: 'Fruits:',
        options: [
            {
                "name": "ALL",
                "value":"ALL"
            },

            {
                "name": "apple",
                "value":"apple"
            },
            {
                "name": "orange",
                "value":"orange"
            },
            {
                "name": "pear",
                "value":"pear"
            },
            {
                "name": "blueberry",
                "value":"blueberry"
            },
        ],
    },

  },

];

When I select/unselect "ALL", I want all the options to be selected/unselected.
For Example. If ALL is checked, then all the fruits options( apple, orange, pear, blueberry) should be checked as well
If I unselect ALL, then none of the fruit options should be checked.
How do I  enable this behavior in angular-formly?
Here is the link to jsbin:
https://jsbin.com/xololi/edit?html,js,output

A: I wrote a working example here https://jsbin.com/dukewac/6/edit?js,output
The signature of templateOptions.onClick when a function is $modelValue, fieldOptions, scope, event.  This occurs when the ngModelAttrsTemplateManipulator is run.  I leveraged these variables in my function.
Some of it is a bit hacky but that partially has to do with how angular implements checkboxes and the workarounds that the multiCheckbox type in angular-formly-templates-bootstrap employs.
Gotchas
Nested Keys
This example will not work with nested keys but should if the multiCheckbox type was updated. This is because it is directly accessing the model using array access notation [see the code here] (https://github.com/formly-js/angular-formly-templates-bootstrap/blob/a69d69e5c3f6382ea6a6c028c1d8bf76a9b94db3/src/types/multiCheckbox.js).
Hardcoded "all" option
The code also assumes that the 'ALL' option is the first in the list and that its value is 'ALL'.  This could be fixed by adding a templateOption property that references what the index and value the all functionality is for.
Model contains 'ALL'
'ALL' will appear in your model.  A possible way to get around this would be to define a $parser for it.
No support for templateOptions.valueProp
templateOptions.valueProp is not taken into account but shouldn;t be too difficult to add.

A: Do you have any solution how to add defaultValue to multiCheckbox. I can add it and see it in model but on view (html) it is not displayed.
I'we made example on jsbin where I have all types of fields and also multiCheckbox... jsbin example
Thanks.

A: here is another working solution (actually updated ckniffty's code), which binds ng-click to formly multi checkbox field and then calls function in controller:
        ....
        ngModelElAttrs: {
          "ng-click": "update(this.option.value)"
        },
        controller: function ($scope) {
          $scope.update = function (val) {
            var all = 'ALL',
              // field key
              key = $scope.options.key,
              // if true - current checkbox is selected, otherwise - unselected
              selected = $scope.model[key].indexOf(val) !== -1,
              // index of 'ALL' checkbox within model array
              indexOfAll = $scope.model[key].indexOf(all);

            // 'ALL' checkbox clicked
            if (val === all) {
              // on select - select all checkboxes, on unselect - unselect all checkboxes
              $scope.options.value(selected ? $scope.to.options.map(function (option) {
                return option.value;
              }) : []);
            }
            // other then 'ALL' checkbox unselected, while 'ALL' is selected
            else if (!selected && indexOfAll !== -1) {
              // unselect 'ALL' checkbox
              $scope.model[key].splice(indexOfAll, 1);
            }
            // all checkboxes selected except of 'ALL'
      else if (selected && indexOfAll === -1 && $scope.model[key].length === $scope.to.options.length - 1) {
        // select 'ALL' checkbox
              $scope.model[key].push(all);
            }
          };
        }
        .....

plunker: https://plnkr.co/edit/LWRZSS6HuBmrzSG5fsH9


text:
Q: Order Dataframe in R based on Values in one column (strings) I have a dataset in R and would like to sort the whole Dataframe  by the values of one column.
The Values are strings and there are only three possible values in this column (Teenager, Twenties, 30+).
I want the Dataframe to be ordered in  this exact order.
The name of my dataframe is age, the name of the column is Category.
I already tried
> age[order(Category),]

which indeed orders the values but in this order: 30+, Teenager, Twenties.
Is it somehow possible to tell R the exact order I want to have?
Btw I am a beginner, obviously :) Thanks in advance!

A: You can use factor´s and the dplyr package for arranging your data. Factors can handle levels which can be ordered as you want. For example:
# load dplyr
library(dplyr)

# generate example df
age <- data.frame(Category=c("Teenager", "Twenties", "30+", "Teenager"),
                  stringsAsFactors = F)

# mutate the Category variable as factor with orderd levels
age <- age %>%
  mutate(Category=factor(Category,
                         levels=c("Teenager", "Twenties", "30+"),
                         ordered=T)) %>%
  arrange(Category)

By the way, here you can finde a introduction to dpylr. This is very usefull for data handling.
P.S.: Happy learning :-)

A: This will convert the column to the correct order.
Category <- factor(as.character(Category), levels = c("Teenagers", "Twenties", "30+"))

So now you can do
age[order(Category),]


text:
Q: How to change decimal operator according to the device culture in Windows Phone 8.1 RT? I need to show the number keypad with the appropriate decimal separator for the culture. For example, Keypad should show the comma for de-DE (German).
Changing the language and region does not help. The keypad is still en-US.
Is there any solution to this?


text:
Q: Using Gson to Parse JSonObject to Model I have the following model:
I am trying to parse the response from the server using GSon, with the following code:
   public class UserDetails
    {
      private final int ID;
      private final String user_email;

      public UserDetails(int ID, String user_email)
     {
        this.ID = ID;
        this.user_email = user_email;
    }

    public int getID()
    {
        return ID;
    }

    public String getUser_email()
    {
        return user_email;
    }

   }

   public void onResponse(Call call, Response response) throws IOException {
       String mMessage = response.body().string();
       if (response.isSuccessful()) {
         try {
            Gson gson = new Gson();

            UserDetails user_details = gson.fromJson(mMessage, UserDetails.class);
            Log.d("Success","The response from the server" + " " + user_details.getID()
               + " " + user_details.getUser_email().toString());
            Log.d("Success", " "+mMessage);
         }
       }
   }

However, when i place a break point to obtain the user details the values are always displayed as null.

A: You have a non default constructor, and you don't seem to have a no arguments (default) constructor, as per the docs:
Please add one to your pojo:
 public UserDetails()
 {

}

If you want to be sure your POJO is well structured use this site. It will generate the pojos based on your json structure.
This is roughly how it should look like:
public class UserDetail {

@SerializedName("ID")
@Expose
private Integer iD;
@SerializedName("user_email")
@Expose
private String userEmail;

public Integer getID() {
return iD;
}

public void setID(Integer iD) {
this.iD = iD;
}

public String getUserEmail() {
return userEmail;
}

public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}

}


text:
Q: Why does Scala compilation get stuck in IntelliJ IDEA 13.1.3? I'm using IntelliJ IDEA 13.1.3 and am trying to compile a Scala 2.10.4 project. It compiles for a while, then the compile process hangs.
I can compile and run my project from the sbt console.
I already invalidated caches, cleaned the project, reinstalled IntelliJ IDEA and all plugins.
Any ideas why Intellij behaves like this?

A: The problem was the Play Framework plugin. Uninstalling it did the trick.
Alternatively, you can try the Community Edition, as it does not have Play support at all.


text:
Q: How do you route root requests to a controller? I have a controller called Videos. I'd like my URLs to be like this:
http://website/1

Rather than this:
http://website/videos/1

I'd also like to keep the functionality of controlling its content via /videos/ (edit, new, destroy, etc). Basically the show action is the only one that would be responding from root.
Is there a way to do this without messing up with the other controllers?

A: Just add a /:id route, that links to videos#show:
get '/:id' => 'videos#show'

You'll need to put this near the bottom of your routes file so that it doesn't match requests for things like /videos.

A: You can create all RESTful routes for a controller, without its name in path by using

resources :videos, path: ""

This will create all routes for videos controller like (index, new, edit, create etc)
If you want only a specific route to serve as this then you can pass that  too with this like

resources :videos, path: "", only:[:show]

This will create only your desired path
http://website/1
and will not affect any other controllers.