text:
Q: crawl site that has infinite scrolling using python I have been doing research and so far I found out the python package that I will plan on using its scrapy, now I am trying to find out what is a good way to build a scraper using scrapy to crawl site with infinite scrolling. After digging around I found out that there is a package call selenium and it has python module. I have a feeling someone has already done that using Scrapy and Selenium to scrape site with infinite scrolling. It would be great if someone can point towards to an example.

A: You can use selenium to scrap the infinite scrolling website like twitter or facebook.
Step 1 : Install Selenium using pip
pip install selenium

Step 2 : use the code below to automate infinite scroll and extract the source code
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import sys

import unittest, time, re

class Sel(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "https://twitter.com"
        self.verificationErrors = []
        self.accept_next_alert = True
    def test_sel(self):
        driver = self.driver
        delay = 3
        driver.get(self.base_url + "/search?q=stackoverflow&src=typd")
        driver.find_element_by_link_text("All").click()
        for i in range(1,100):
            self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(4)
        html_source = driver.page_source
        data = html_source.encode('utf-8')

if __name__ == "__main__":
    unittest.main()

The for loop allows you to parse through the infinite scrolls and post which you can extract the loaded data.
Step 3 : Print the data if required.

A: This is short & simple code which is working for me:
SCROLL_PAUSE_TIME = 20

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

posts = driver.find_elements_by_class_name("post-text")

for block in posts:
    print(block.text)

A: from selenium.webdriver.common.keys import Keys
import selenium.webdriver
driver = selenium.webdriver.Firefox()
driver.get("http://www.something.com")
lastElement = driver.find_elements_by_id("someId")[-1]
lastElement.send_keys(Keys.NULL)

This will open a page, find the bottom-most element with the given id and the scroll that element into view. You'll have to keep querying the driver to get the last element as the page loads more, and I've found this to be pretty slow as pages get large. The time is dominated by the call to driver.find_element_* because I don't know of a way to explicitly query the last element in the page.
Through experimentation you might find there is an upper limit to the amount of elements the page loads dynamically, and it would be best if you wrote something that loaded that number and only then made a call to driver.find_element_*.

A: For infinite scrolling data are requested to Ajax calls. Open web browser --> network_tab --> clear previous requests history by clicking icon like stop--> scroll the webpage--> now you can find the new request for scroll event--> open the request header --> you can find the URL of request ---> copy and paste URL in an seperare tab--> you can find the result of Ajax call --> just form the requested URL to get the data page until end of the page

A: Great Question!
The Challange
When working with an infinite scroll page (or dynamically loading site), there's no way to really know how long new items will take to load, as such it is hard to know how long to wait before new items load and we can hit page-down.
Additionally, even if we can solve the first problem, we want to make sure that we're scrolling enough to actually reach the bottom of the page, so we want hit page-down enough times to actually reach the bottom of the page.
TLDR;If the site isn't so fast or for whatever reason data takes a while to load, we don't want to exit too early.
My Solution

*

*First, define a scroll_down function which takes a driver and a positive integer n as input.

*The function contains a for-loop which hits page down n times waiting .01 seconds (this can be changed) between page-downs

*Store the current window height in a variable named prev_height

*Within a for-loop utilize a predefined function to scroll down.

*Within each iteration, take a significant pause allowing more items to load (I waited 10 seconds)

*After the pause, compare prev_height with the current height. If they are the same, then exit, otherwise continue.

Code
Scroll function:
def scroll_down(elem, num):
    for _ in range(num):
        time.sleep(.01)
        elem.send_keys(Keys.PAGE_DOWN)

Main code:
    driver = <load driver etc.>
    SCROLL_PAUSE_TIME = 10
    elem = driver.find_element_by_tag_name("body")
    prev_height = elem.get_attribute("scrollHeight")

    for i in range(0, 500):
        # note that the pause between page downs is only .01 seconds
        # in this case that would be a sum of 1 second waiting time
        scroll_down(elem,100)
        # Wait to allow new items to load
        time.sleep(SCROLL_PAUSE_TIME)

        #check to see if scrollable space got larger
        #also we're waiting until the second iteration to give time for the initial loading
        if elem.get_attribute("scrollHeight") == prev_height and i > 0:
            break
        prev_height = elem.get_attribute("scrollHeight")

Note: The actual numbers I used within my program may not work for you. But I do believe the solution itself is a reliable approach. Additionally, while the solution has been quite reliable for me, it is also one which takes time.


text:
Q: Check if update push is succesfull I update an existing document with the code below. Its working fine.
foreach($jArray as $value){
!!some code!!
    try {
        $collection->update(array("tablename"=>$tablename),array('$push' => array("inventar" => $new_data)));
        echo json_encode($collection);
    }
    catch ( MongoConnectionException $e ) {
        echo '
Update failed
';
        exit();
    }
}

JSON response:
{"w":1,"wtimeout":10000}{"w":1,"wtimeout":10000}

(2 values are tried to update)
Even if no tablename matched, means no update happend, the result is w = 1.
Why? No update happend and w is 1/true?

A: There seems to be a little confusion here. The JSON response you are looking at is not the actual return value from the update operation. What you did was JSONifying the collection itself, which has the integer attributes w and wtimeout (see source code here). Those attributes are in no way related to the result of the update operation itself.
So, the right way to go seems to be changing the lines inside the scope of your try statement to:
$result = $collection->update(array("tablename"=>$tablename),array('$push' => array("inventar" => $new_data)));
echo json_encode($result);

For more information about what is returned from the update method, refer to these docs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap accordion aria-expanded doesnt work i am using bootstrap 4 accordion. i want as initial state to have all the cards collapsed. I set aria-expanded to false but all the cards appeared expanded.

                        <button class="btn btn-link" data-toggle="collapse" aria-expanded="false" data-bind="text:name, attr: { 'data-target': '#collapsible' +  $index(),'aria-controls': 'collapsible' +  $index() }"></button>

                        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

What i am doing wrong?

A: You need to update the classes as they are in the collapsed state.
1) Add class collapsed with btn btn-link in the button element
2) Remove class show from collapse show in the div element
I have updated the code with the above changes. It should keep the accordion in collapsed state initially.

                        <button class="btn btn-link collapsed" data-toggle="collapse" aria-expanded="false" data-bind="text:name, attr: { 'data-target': '#collapsible' +  $index(),'aria-controls': 'collapsible' +  $index() }"></button>

                        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.


text:
Q: What's the meaning of this last run on sentence? Vincent speaks about the sky:

Vincent: But, the sight of the stars always makes me dream.
Why I say to myself should those spots of light in the firmament be
inaccessible to us? Maybe we can take death to go to a star
and to die peacefully of old age would be to go there on foot.

What's the meaning of this last run on sentence?
That's a weird sentence to me, I think it's something like "Maybe we go into the stars when we die, and dying of old age is just getting to the stars slower".

A: This line from the movie (I assume) is adapted from one of Vincent's letters (which Fumblefingers has found)
The meaning is there in the shortened version for the movie, but it is clearer in the full letter.  The extra information from the letter is in brackets []
Stars are spots of light [just like towns on a map are spots of black, we can go to towns when we are alive] perhaps our "soul" visits the stars when we are dead. [We can go to a town by rail, horse, or slowly by walking, the quick ways then to get to the stars are diseases like cancer.] Going to the stars by dying of old age is like walking [to a distant town]
It is rather morbid, and melancholic. Van Gogh is known to have had exaggerated mood swings, typical of a bipolar disorder.
Note. That is not a run-on sentence this sentence is a run-on sentence. A run-on sentence is not just a long one.  It is one that fuses two clauses without a conjunction or proper punctuation.

A: It is a scrambled metaphor.
It starts by comparing death to a vehicle:

Maybe we can take a ride on the mode of stellar transportation called death to go to the stars.

A bit weird. Then the metaphor changes:

Death has now become the terminal from which we journey to the stars. And travel "by foot" indicates traveling slowly.

If we die of old age, we traveled to the star transit terminal called death the slow way.

So, you got the thought despite how strange the metaphors were.

Maybe we go to the stars when we die, so dying of old age delays the trip.


text:
Q: Generate YML file from YML.dist I'm building my own micro-framework using Silex and I can't solve one problem: how can I autogenerate parameters.yml file from .dist file when composer install command is run (like in Symfony)?
What packages or components should I use?
Tnx


text:
Q: Angular: Get ng-model by ng-attr-id? Is there a way to get ng-model value by ng-attr-id ?
I'm making a Comment/Reply box and I would like to get the value of the current reply.
Here is my html--

                {{comment.content}}

                Reply

                <textarea ng-model="replytxt" ng-attr-id="{{'replytxt-'comment.id}}"></textarea>

                    <button type="button" ng-click="sendReply(comment.id)">
                        Publier
                    </button>

Here is the angularjs--
$scope.sendReply = function(commentId){
    var elm = document.getElementById('replytxt-'+commentId);
    console.log(elm);
}

The above function show this in console:
<textarea ng-model="replytxt"  ng-attr-id="{{'replytxt-'+comment.id}}" class="ng-pristine ng-valid ng-touched" id="replytxt-31"></textarea>

A: You don't need to retrieve element value by its selector. Do pass replytxt value inside sendReply function itself on click.
ng-click="sendReply(comment.id, replytxt)"

$scope.sendReply = function(commentId, replytxt){

Suggestion: rather than having replytxt there independently as ng-model, you can put it on comment level property like comment.replytxt, so that you don't need to take care of passing replytxt value separately to server.
ng-click="sendReply(comment)"

Code
$scope.sendReply = function(comment){
    console.log(comment.id, comment.replytxt);
}


text:
Q: npm run dev failing on Mac due to webpack serve command failing I am trying to run the "npm run dev" on my Mac but facing the below errors. I have already fixed the webpack installation, npm installation, etc. required but am stuck here.
MacBook-Air:Exercise workhouse$ npm run dev

> @ dev /Users/workhouse/Desktop/Personal Projects/3JS/Lesson 4/Exercise
> webpack serve --config ./bundler/webpack.dev.js

[webpack-cli] Unable to load '@webpack-cli/serve' command
[webpack-cli] TypeError: devServerFlags is not iterable
    at /Users/workhouse/Desktop/Personal Projects/3JS/Lesson 4/Exercise/node_modules/@webpack-cli/serve/lib/index.js:28:43
    at WebpackCLI.makeCommand (/Users/workhouse/Desktop/Personal Projects/3JS/Lesson 4/Exercise/node_modules/webpack-cli/lib/webpack-cli.js:98:31)
    at ServeCommand.apply (/Users/workhouse/Desktop/Personal Projects/3JS/Lesson 4/Exercise/node_modules/@webpack-cli/serve/lib/index.js:10:19)
    at loadCommandByName (/Users/workhouse/Desktop/Personal Projects/3JS/Lesson 4/Exercise/node_modules/webpack-cli/lib/webpack-cli.js:378:35)
    at Command.<anonymous> (/Users/workhouse/Desktop/Personal Projects/3JS/Lesson 4/Exercise/node_modules/webpack-cli/lib/webpack-cli.js:694:23)
    at Command.listener [as _actionHandler] (/Users/workhouse/Desktop/Personal Projects/3JS/Lesson 4/Exercise/node_modules/webpack-cli/node_modules/commander/index.js:426:31)
    at Command._parseCommand (/Users/workhouse/Desktop/Personal Projects/3JS/Lesson 4/Exercise/node_modules/webpack-cli/node_modules/commander/index.js:1002:14)
    at Command.parse (/Users/workhouse/Desktop/Personal Projects/3JS/Lesson 4/Exercise/node_modules/webpack-cli/node_modules/commander/index.js:801:10)
    at Command.parseAsync (/Users/workhouse/Desktop/Personal Projects/3JS/Lesson 4/Exercise/node_modules/webpack-cli/node_modules/commander/index.js:828:10)
    at WebpackCLI.run (/Users/workhouse/Desktop/Personal Projects/3JS/Lesson 4/Exercise/node_modules/webpack-cli/lib/webpack-cli.js:711:28)
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ dev: `webpack serve --config ./bundler/webpack.dev.js`
npm ERR! Exit status 2

A: This is an issue with the latest @webpack-cli/serve v1.6 version. You can find temporary solutions here: https://githubmemory.com/repo/webpack/webpack-cli/issues/2990?page=1


text:
Q: "Not even" as a conjunction or for contrast Is this sentence fine?
It was pitch black, not even the stars could be seen.
I know that you can use a comma before not even and then a noun for contrast, but can it still work with a sentence?

A: Technically these are two sentences, so should be separated by a semicolon or perhaps a dash would do.
Grammatically this would then make sense. For me it's a bit jarring logically, as in my experience the less (artificial) light there is in spot, the more stars tend to be visible. This may not be what you're asking about, though.


text:
Q: DNS and IP settings I have a question regarding the settings for IP address and DNS servers. I use a VPN and also Heimdal Pro security. The problem is that Heimdal Pro doesn't allow customized settings for either. (127.0.0.1) is used instead, and my VPN wants to use (192.168.1.x) format for IP. So what happens is my internet connection constantly goes off and back on repeatedly. Is there a way to make these addresses be interchangable? Something like 127.0.0.1 would get forwarded to my computer IP and vice-versa? I'm looking for a way to continue with Heimdal Pro, but as of right now, its uninstalled and a shame to disregard it if there's a solution, even if it means doing manual extra steps. Thank you for any advice on this delimna.

A: If you are using a VPN solution in combination with Heimdal V2, our application doesn't understand this automatically and it needs a backdoor for Heimdal to bypass it. For this, we recommend configuring an exception in your VPN solution like in this guide:
https://support.heimdalsecurity.com/hc/en-us/articles/207385449-Using-Heimdal-with-Cisco-Anyconnect-VPN
If you still need further assistence, just contact us directly on our webpage.
Best regards,
Răzvan Crâznic - Ionuț
Senior Support Technician (English & German)
Heimdal Security A/S & Heimdal Security SRL
The Cyberthreat Security suite. We protect what other endpoint solutions can't
http://www.heimdalsecurity.com/


text:
Q: C: Implementation of a Quicksort algorithm with pointers I'm trying to implement a Quicksort algorithm in C language with pointers, but I found that I get problems in the function:
int partition(int *a[], int start, int end, int pivot_idx)

For example, if I want to sort an array of 3 items:
4 3 2

when I enter the function partition in the while:
while  (a[high_idx]>pivot)

with high_idx = 2, a[high_idx] = 2, pivot = 3, the condition 2 > 3 results in true, and so the execution continues, but it shouldn't be like this. I think that I should resolve the problem with the function malloc, but I'm fledgling with pointers and I need your help.
Can anyone help me?
void swap (int **ptr_s1, int **ptr_s2)
{
    int *temp;
    temp=*ptr_s1;
    *ptr_s1=*ptr_s2;
    *ptr_s2=temp;
}

int partition (int *a[], int start, int end, int pivot_idx)
{
    int low_idx=0, high_idx=0;
    int *pivot;

    pivot= a[pivot_idx];
    swap(&a[pivot_idx], &a[start]);
    low_idx=start+1;
    high_idx=end;
    while(low_idx<=high_idx){
        while(a[high_idx]>pivot){
            high_idx--;
        }
        while((a[low_idx]<=pivot)&&(low_idx<=high_idx)){
            low_idx++;
        }
        if(low_idx<high_idx){
            swap(&a[low_idx], &a[high_idx]);
            low_idx++;
            high_idx--;
        }
    }
    swap(&a[high_idx], &a[start]);

    return high_idx;
}

void sort (int *a[], int start, int end)
{
    int pivot_idx, new_pivotidx;
    if(start<end){
        pivot_idx = (start+end)/2;
        new_pivotidx = partition(a, start, end, pivot_idx);
        sort(a, start, new_pivotidx-1);
        sort(a, new_pivotidx+1, end);
    }
}


text:
Q: Javascript to disable popup blocker I am new to javascript i want to know pop up blockers is disabled or not. If Enabled i want for users to throw an message saying that to Disable the pop up and if user accepts to disable the pop up it will allow user to proceed further if not, User will be on the same page. Please help me with the code so that it will run in all the browser(IE, Mozilla, Chrome n safari)

A: It is there to stop them and you can not turn it off. Best you can do is:
winpop = window.open("asdf.html");
if(!winpop || winpop.closed)alert("foobar");


text:
Q: Swift 3 - Trying to cast a dictionary to CFDictionary When I'm trying to create an array as a CFDictionary, I'm getting an error (shown bellow).
This is the code:
let attrs = [kCVPixelBufferCGImageCompatibilityKey:kCFBooleanTrue,  kCVPixelBufferCGBitmapContextCompatibilityKey:kCFBooleanTrue] as CFDictionary

But the weird thing is that I'm using the same line of code in another project, without receiving any errors. What does the error mean?

Error: Contextual type 'CFDictionary' cannot be used with dictionary literal

A: You can use below code to convert the dictionary to CFDictionary as mention below:
let attrs = [kCVPixelBufferCGImageCompatibilityKey as String :kCFBooleanTrue,
             kCVPixelBufferCGBitmapContextCompatibilityKey as String:kCFBooleanTrue] as
        CFDictionary

Hope This will helps


text:
Q: How to get info if any Monitoring tool (DB performance Analyzer) stops working? What is the Reason behind if SQL monitor for Production stopped working? what is the reason for this? I checked on Licensing, SQL server permissions, No Updates/Patching and Remote admin connections everything is alright. It might be cause of over load or OS issues effect SQL monitor? Any specific reason?

A: You are encountering THREADPOOL waits, which occurs when the instance has run out of available worker threads. New logins will be denied, and lots of queries will be just waiting.
To troubelshoot THREADPOOL waits, connect with the Remote DAC and check current activity. You'll likely see huge blocking chains. You'll need to resolve or reduce the blocking to resolve the THREADPOOL waits.
Some Microsoft engineers will say to increase worker threads on the instance, but that doesn't help in my experience. It just means it'll take longer before THREADPOOL is encountered.
Things that might resolve THREADPOOL waits:

*

*Adjusting Max Degree of Parallelism and Cost Threshold for Parallelism so that less queries go parallel and thus fewer worker threads are needed

*Adding indexes

*Refactoring queries

*RCSI

*etc

For more information on THREADPOOL waits, check out these links (disclaimer: I work for Brent Ozar Unlimited):
https://www.brentozar.com/archive/2014/05/connections-slow-sql-server-threadpool/
https://www.sqlskills.com/help/waits/threadpool/
http://www.sqlpassion.at/archive/2011/10/25/troubleshooting-threadpool-waits/


text:
Q: How to force user to input a fixed amount of numbers for int? I want to force the user to input a number with 5 lengths long (
no more and no less) and store them inside an int variable, this includes a leading 0.
For example, the program should allow the user to input:
12345
04123
00012

But it should not work for:
123456
4123
001

I tried...
  if(int x < 99999){
  //continue with code
  }

This would work only if the user input more than 5 lengths but it doesn't resolve the issue of the user putting in an int length less than 5

A: I think you should take input in string not in int then if the validation goes right you can parse it into integer like the following:
import java.util.Scanner;

public class main {

public static void main(String[] args) {
    /// take input
    String userInput = "";
    Scanner sc = new Scanner(System.in);
    userInput = sc.nextLine();
    int input ;
    // validation test
    if(userInput.length() == 5) {
        input = Integer.parseInt(userInput);
    }else {
        // you can display an error message to user telling him that he should enter 5 numbers!
    }
}

}

but you have to know that after parsing it into int if there's a leading zeros it could be gone.

A: Something crazy simple like this. Lacks edge case handling (Read: Negative values)
boolean matchesLength(int n, int lengthLim){
    char[] charArr = (n + "").toCharArray();
    return (charArr.length == lengthLim);
}

A: Two functions. First, to verify the input:
static boolean is_valid_number(String x) {
    // returns true if the input is valid; false otherwise
    if(x.length != 5 || Integer.valueOf(x) > 99999) {
        // Check that both:
        //    - input is exactly 5 characters long
        //    - input, when converted to an integer, is less than 99999
        // if either of these are not true, return false
        return false;
    }
    // otherwise, return true
    return true;
}

and second, to get user input:
static int get_user_input() {
    // Create a scanner to read user input from the console
    Scanner scanner = new Scanner(System.in);
    String num = "";
    do {
        // Continuously ask the user to input a number
        System.out.println("Input a number:");
        num = scanner.next();
        // and continue doing so as long as the number they give isn't valid
    } while (!is_valid_number(num));
    return Integer.valueOf(num);

You might also have to do some error-handling, in case the given input isn't an integer at all. You could implement is_valid_number() concisely like this:
static boolean is_valid_number(String x) {
    try {
        return (x.length == 5 && Integer.valueOf(x) <= 99999);
    } catch (NumberFormatException e) {
        // Integer.valueOf(x) throws this when the string can't be converted to an integer
        return false;
    }
}


text:
Q: Parse JSON into Hashtable How do I parse the following JSON into hashtable in PowerShell? I want to pair car name ("BMW") as key and color ("Dark Gray") as value in the hashtable.
{
  "Car": [
    {"BMW": "Dark Gray"},
    {"Audi": "Yellow"}
  ]
}

A: Like this:
$json = @'
{
  "Car": [
    {"BMW": "Dark Gray"},
    {"Audi": "Yellow"}
  ]
}
'@

$ht = @{}

ConvertFrom-Json $json | Select-Object -Expand 'Car' | ForEach-Object {
    $ht[$_.PSObject.Properties.Name] = $_.PSObject.Properties.Value
}

If you're stuck with PowerShell v2, but have at least .Net Framework 3.5 you could do something like this instead:
$json = @'
...
'@

$ht = @{}

[void][Reflection.Assembly]::LoadWithPartialName('System.Web.Extensions')
$serializer = New-Object Web.Script.Serialization.JavaScriptSerializer
$serializer.DeserializeObject($json).Values.GetEnumerator() |
    ForEach-Object { $_ } |
    ForEach-Object { $ht[($_.Keys -join '')] = ($_.Values -join '') }

If that also isn't possible, but your key/value pairs are always on one (separate) line, you could extract the data with a regular expression (although I wouldn't recommend that approach):
$json = @'
...
'@

$ht = @{}

$json -split "`n" | Where-Object {
    $_ -match '\{"(.*?)": "(.*?)"\}'
} | ForEach-Object {
    $ht[$matches[1]] = $matches[2]
}

Otherwise you'll have to write a JSON parser yourself.

A: In Powershell v6 it's built-in with ConvertFrom-Json:
$hashtable = '{ "key1":"value1", "key2":"value2" }' | ConvertFrom-Json -AsHashtable

For example:
PS> $hashtable["key1"]
value1


text:
Q: Android FB logInWithReadPermissions and registerCallback WITHOUT login button Getting mad with this. I try to login into FB and at the same time retrieve user information.
The FB login works fine, the app changes to FB, shows what permission the app is asking for and after pressing Accept, goes back to my app. BUT the registerCallback is never called. Where is my mistake? here my code:
        FacebookSdk.sdkInitialize(getApplicationContext());
        CallbackManager mCallbackManager = CallbackManager.Factory.create();
        LoginManager.getInstance().logInWithReadPermissions(
                this,
                permissionNeeds);

        LoginManager.getInstance().registerCallback(mCallbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        Log.e("dd", "SUCCESS");

                        GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {

                                    @Override
                                   public void onCompleted(JSONObject json, GraphResponse response) {
                                        if (response.getError() != null) {
                                            System.out.println("ERROR");
                                        } else {
                                            System.out.println("Success");
                                            try {
                                                String jsonresult = String.valueOf(json);
                                                System.out.println("JSON Result" + jsonresult);
                                                String str_email = json.getString("email");
                                                String str_id = json.getString("id");
                                                String str_firstname = json.getString("first_name");
                                                String str_lastname = json.getString("last_name");
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                }).executeAsync();
                    }

                    @Override
                    public void onCancel() {

                        Log.e("dd", "facebook login canceled");

                    }

                    @Override
                    public void onError(FacebookException e) {

                        Log.e("dd", "facebook login failed error");

                    }
                });

A: EDIT:
found it, the following code was missing, now I am getting the user information after login
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    mCallbackManager.onActivityResult(requestCode, resultCode, data);
}


text:
Q: Validate form and prevent submission Using html5 form validation with required attributes.
When submit button is clicked, I only want to validate, not submit the form.
<input type="submit" id="calculate">

A: To trigger the form html5 validation you can use
$('#myForm')[0].checkValidity();

A: It can be done by using buttoninstead of input, as:
<button type="button" id="submitButton">Submit</button>

And use JavaScript to validate the form for submission, as:
$('#submitButton').click(function() {
    //Validate form
    if(formValidated()) {
        $('#formId').submit ();
    }
});

If you don't wanna submit just remove, $('#formId').submit ();.

A: Just as an idea/demonstration, here's a way to validate without using the required attribute -- it gives you a little more control over the validation process, and as you can see it's quite simple.
Begin by creating an array containing the IDs of all input fields to check. (You can have groups of like fields that must be evaluated in the same way... one array/for-loop for input fields, another for checkboxes, another for text fields, etc.)
When you return false; form submission is aborted.

var arr = ['em','fn','ln'];
$('#myForm').submit(function(){
  for (var n=0; n<arr.length; n++){
     $('#'+arr[n]).removeClass('errorField');
     if ( arr[n] == 'em'){
        if  ( $('#'+arr[n]).val() == 'Bob' ){
           //eval email field differently
           alert('Hi Bob - you cannot complete this form');
           return false; //error condition, so abort submit
        }
     }else if ( $('#'+arr[n]).val() == ''){
        $('#'+arr[n]).addClass('errorField').focus();
        return false; //error condition, so abort submit
     }
  }

  alert("Form will now submit"); return false; //FOR DEMO ONLY
  //Submit continues
});
.errorField{background:yellow;}

<form id="myForm" action="process.php" method="post" >
  First Name: <input type="text" id="fn" name="fn" />

  Last Name: <input type="text" id="ln" name="ln" />

  Non-Required: <input type="text" id="nr" name="nr" />

  Email: <input type="text" id="em" name="em"  />

  <input type="submit" id="mybutt" value="Submit" />

</form>


text:
Q: how to implement search engine on existing mvc page Suppose I have MVC application with some static and dynamic web pages. How to add search feature for such site?
I dont want to create simple page searching for the data contained in database, I want to be able to index whole pages as they are displayed to customer.
Any solution for ASP.NET MVC4/5?
Shell I use existing solution (which?) or create my own one ?

A: Disclaimer: it's the product of the company I work for.
You can use SearchUnit for indexing/searching MVC web sites.  There's a free Community version, and a more powerful paid version.
I don't know the specifics of what you need, but it's easier to use and more rounded (eg. includes spell checking, many document format parsers) than other options such as Lucene (IMHO, let me know if you disagree).
MVC specifics are here.


text:
Q: axis2 xmlbeans code stops without exception I'm in the process of setting up a web service client using Axis2 with XML beans.
My code is exiting my calculateTest function without throwing an exception. If you look at my code below, the code exits at the line "AuthHeader authHeader = authHeaderDocument.addNewAuthHeader();"
public class ClientTest {
    private static final int IDLE_CONNECTION_TIME = 0;

    private ServiceStub serviceStub;
    private MultiThreadedHttpConnectionManager connectionManager;

    public ServiceStub getServiceStub() {
        return serviceStub;
    }
    public void setServiceStub(ServiceStub serviceStub) {
        this.serviceStub = serviceStub;
    }

    public static void main(String[] args) {
        try {
System.out.println("STARTING");
            ClientTest a = new ClientTest();
            a.initServiceClient("https://XXXXXXX.asmx?WSDL");
            a.calculateTest();
System.out.println("FINISHED");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initServiceClient(String targetEndpoint) throws Exception {
        try {
            org.apache.axis2.context.ConfigurationContext myConfigContext = org.apache.axis2.context.ConfigurationContextFactory.createDefaultConfigurationContext();
            this.connectionManager  = new MultiThreadedHttpConnectionManager();
            HttpConnectionManagerParams params = new HttpConnectionManagerParams();
            params.setStaleCheckingEnabled(true);
            params.setDefaultMaxConnectionsPerHost(100);
            this.connectionManager.setParams(params);
            HttpClient httpClient = new HttpClient(this.connectionManager);
            myConfigContext.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
            myConfigContext.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Boolean.TRUE);

            if(targetEndpoint != null){
                serviceStub = new DACALCServiceStub(myConfigContext,targetEndpoint);
            }else{
                serviceStub = new DACALCServiceStub(myConfigContext);
            }
            ServiceClient sc = serviceStub._getServiceClient();

            Options options = sc.getOptions();
            options.setProperty(HTTPConstants.SO_TIMEOUT, 30000);
            options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, 30000);
            options.setProperty(HTTPConstants.AUTO_RELEASE_CONNECTION, true);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public String calculateTest() throws Exception {
System.out.println("Inside calculateTest");

        String output = null;
        try {
System.out.println("1.");
            String authenticationUsername = "XXXX";
            String authenticationPassword = "XXXX";
            String errorMsg = "";
System.out.println("1a.");

            AuthHeaderDocument authHeaderDocument = AuthHeaderDocument.Factory.newInstance();

System.out.println("1a1.");
            AuthHeader authHeader = authHeaderDocument.addNewAuthHeader();
System.out.println("1a2.");
            authHeader.setUserName(authenticationUsername);
System.out.println("1a3.");
            authHeader.setPassword(authenticationPassword);
System.out.println("1a4.");
            authHeader.setErrorMessage(errorMsg);
System.out.println("1b.");

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            serviceStub._getServiceClient().cleanupTransport();
            this.connectionManager.closeIdleConnections(IDLE_CONNECTION_TIME);
            return output;
        }
    }
}

The output I'm seeing is:
STARTING
Inside calculateTest
1.
1a.
FINISHED

No exceptions are thrown. Why would the code be silently failing on this line?

A: I removed the try/catch in calculateTest and an exception was thrown (strange how it wasn't being caught by the generic Exception handler).
It turns out that I wasn't including some required files in my resources directory. Once I added that, everything worked.

A: I guess that by "exiting without throwing an exception" you actually mean exiting without executing the code in your catch block. The explanation is that you are catching Exception, not Throwable. This means that exceptions that extend Error will not be caught.


text:
Q: left join and sum and group by - odd behavior I have these two tables:
student attendance table - student_id, campus_section
campus table -  campus_section, number_of_students, campus_name

Sample Data:
Student Table:
Student_Id, campus_section
1, ddr1
2, ddr1
3, ddr2
4, ddr3
5, ddv1
6, ddv2
7, ddv6

Campus Table
Campus_Section, Number_Of_Students, Campus_Name
ddr1, 10, ddr
ddr2, 5, ddr
ddr3, 5, ddr
ddv1, 5, ddv
ddv2, 10, ddv
ddv3, 10, ddv
ddv6, 10, ddv

So the expected rows would be
Campus, current_students, campus_students
ddr, 4, 20
ddv, 3, 35

There can be multiple campus_section rows per campus_name. The following query lists campus name along with number of students attending in that campus and total number of students in that campus.
select d.[campus_name] as campus_name,
       cast(count(s.student_id) as int) as current_students,
       sum(cast (d.[number_of_students] as int)) as campus_students
from campus d
left join student s
on s.campus_section = d.campus_section
group by d.[campus_name]

For some campus_name's, the result in section_students column is greater than this:
select d.[campus_name] as campus_name,
           sum(cast (d.[number_of_students] as int)) as section_students
    from campus d
    group by d.[campus_name]

It means left join is doing something that it should not be for certain rows. Or maybe the second query is incorrect.
Edit: For example, the first query would give 18 for a certain campus name while the second query would give 10.
Can anybody shed some light on what is going on?  It's sql server 2008.

A: with left join, sum(cast (d.[number_of_students] as int)) will be number_of_students*number_of_students in a campus. Get rid of group by statement, you will find out why.
select d.[campus_name] as campus_name,
       s.student_id,
       d.[number_of_students]
from campus d
left join student s
on s.campus_section = d.campus_section

So the right way is:
select d.[campus_name] as campus_name,
       cast(count(s.student_id) as int) as current_students,
       cast (d.[number_of_students] as int) as section_students
from campus d
left join student s
on s.campus_section = d.campus_section
group by d.[campus_name],cast (d.[number_of_students] as int)

UPDATE
According to the data OP posted on later, need to group by campus first to get sum of section_students number, then join students table and group by campus_name to get the current_students number.
with campus_t as (select d.[campus_name] as campus_name,
       sum(cast (d.[number_of_students] as int)) as campus_students
     from campus d
     group by d.[campus_name])
select d.campus_name,
       d.campus_students,
       cast(count(s.student_id) as int) as current_students,
from campus_t d
left join campus section
on section.campus_name = d.campus_name
left join student s
on s.campus_section = section.campus_section
group by d.campus_name,d.campus_students

Note: not tested yet. pleas check it.
Your problem came from the denormalized design. The campus table should be split to two campus and campus_section tables. That's why I have to add a CTE table named campus_t to get information of  campus entity. Your original campus table's data represents campus_section entity. If you normalize the model into three tables, that should be easier to query.

A: Sections can have more than one student. Consequently, when the tables are joined, rows in Campus can become duplicated, which skews your results if you try to aggregate everything in one go.
Therefore, try doing it in two steps: first do the student counts per campus section:
SELECT
  campus_section,
  number_of_students,
  campus_name,
  COUNT(s.student_id)
FROM
  dbo.Campus AS c
LEFT JOIN
  dbo.Student AS s
ON
  c.campus_section = s.campus_section
GROUP BY
  campus_section,
  number_of_students,
  campus_name

then aggregate section results per campus:
SELECT
  campus_name,
  current_campus  = SUM(current_section),
  campus_students = SUM(number_of_students)
FROM
  (
    SELECT
      c.campus_section,
      c.number_of_students,
      c.campus_name,
      current_section = COUNT(s.student_id)
    FROM
      dbo.Campus AS c
    LEFT JOIN
      dbo.Student AS s
    ON
      c.campus_section = s.campus_section
    GROUP BY
      campus_section,
      number_of_students,
      campus_name
  ) AS sub
GROUP BY
  campus_name
;


text:
Q: How to get static page dropdown in OctoberCMS with get page tree? I am open this based from my question in my own comment from Static page dropdown within static page in OctoberCMS.
I have problem when adding $pageList->getPageTree(true). The child pages did not display. My current code is repeating foreach from $pageObject->subpages which is not a good practice.
Below here is my code example:
Plugin.php
<?php namespace MyPlugin\CustomPlugin
use System\Classes\PluginBase;
public function boot() {
    \RainLab\Pages\Classes\Page::extend(function($model) {
        $model->addDynamicMethod('getPageOptions', function() {
            $theme = \Cms\Classes\Theme::getEditTheme();
            $pageList = new \RainLab\Pages\Classes\PageList($theme);
            $pages = [];
            foreach ($pageList->getPageTree(true) as $name => $pageObject) {
                $pages[$pageObject->page->url] = $pageObject->page->title;
                if ($pageObject->subpages) {
                    foreach ($pageObject->subpages as $name => $pageObject) {
                        $pages[$pageObject->page->url] = '   ' . $pageObject->page->title;
                        if ($pageObject->subpages) {
                            foreach ($pageObject->subpages as $name => $pageObject) {
                                $pages[$pageObject->page->url] = '      ' . $pageObject->page->title;
                            }
                        }
                    }
                }
            }
            return $pages;
        });
    });
}

Appreciate if anyone could help.

A: may be this will help you.
function onStart() {
    $theme = \Cms\Classes\Theme::getEditTheme();
    $pageList = new \RainLab\Pages\Classes\PageList($theme);
    $treePageList = $pageList->getPageTree(true);
    $pages = [];
    $this->getRecursivePage($pages, $treePageList);
    dd($pages);
}

function getRecursivePage(&$pages, $subpages, $level = 0) {
    $level++;
    foreach($subpages as $pageArr) {
        $pages[$pageArr->page->url] =
               str_repeat('-',$level) . ' ' . $pageArr->page->title;
        if(count($pageArr->subpages) > 0) {
            $this->getRecursivePage($pages, $pageArr->subpages, $level);
        }
    }
}

Output

array:9 [▼
  "/content" => "- Content"
  "/content/pages" => "-- Static Pages"
  "/content/content" => "-- Content"
  "/content/models" => "-- Models"
  "/content/urls" => "-- URLs"
  "/content/urls/tesets" => "--- tesets"
  "/test-sp" => "- test-sp"
  "/test-sp/oks" => "-- oks"
  "/test" => "- test"
]

here you can just replace - to   or just remove that part [ I added because you had that in code so, may be useful to you. ]

For your code

public function boot() {
  \RainLab\Pages\Classes\Page::extend(function($model) {
      $model->addDynamicMethod('getPageOptions', function() {
          $theme = \Cms\Classes\Theme::getEditTheme();
          $pageList = new \RainLab\Pages\Classes\PageList($theme);
          $treePageList = $pageList->getPageTree(true);
          $pages = [];
          $this->getRecursivePage($pages, $treePageList);
          return $pages;
      });
  });
}

public function getRecursivePage(&$pages, $subpages, $level = 0) {
    $level++;
    foreach($subpages as $pageArr) {
        $pages[$pageArr->page->url] =
               str_repeat('-',$level) . ' ' . $pageArr->page->title;
        if(count($pageArr->subpages) > 0) {
            $this->getRecursivePage($pages, $pageArr->subpages, $level);
        }
    }
}

If any doubt please comment.


text:
Q: Grant AKS access to Postgres database in Azure via VNet Trying to figure out how to best give my AKS cluster access to a Postgres database in Azure.
This is how I create the cluster:
az group create \
  --name $RESOURCE_GROUP \
  --location $LOCATION

az aks create \
  --resource-group $RESOURCE_GROUP \
  --name $CLUSTER_NAME \
  --node-vm-size Standard_DS2_v2 \
  --node-count 1 \
  --enable-addons monitoring \
  --enable-managed-identity \
  --generate-ssh-keys \
  --kubernetes-version 1.19.6 \
  --attach-acr $ACR_NAME \
  --location $LOCATION

This will automatically create a VNet with a subnet that the node pool uses.
The following works:

*

*Find the VNet resource in Azure

*Go to "subnets" -> select the subnet -> Choose "Microsoft.SQL" under "Services". Save

*Find the Postgres resource in Azure

*Go to "Connection Security" -> Add existing virtual network -> Select the AKS VNet subnet. Save

So I have two questions:

*

*Is it recommended to "fiddle" with the VNet subnet automatically created by az aks create? I.e adding the service endpoint for Micrsoft.SQL

*If it's ok, how can I accomplish the same using Azure CLI only? The problem I have is how to figure out the id of the subnet (based on what az aks create returns)


text:
Q: Should I use Upsert IAction method or Edit and Create separately? I'm new and learning how to build an MVC application and while implementing CRUD operations and I'm wondering if the logic from Edit and Create should be placed inside one single method as some tutorials seem to suggest.
Is this a good practice, and why?
Does this respect SOLID principles?
Thank you so much in advance <3

A: You could use the same request model for both create and update methods; however, they should still be separate endpoints for a few key reasons:

*

*Security: You may want to implement additional controller logic around the editing of existing entities.

*Different input required: To update an existing entity, you need to know the ID of the entity to be updated.  Generally, this is passed in the form of a URL parameter in a PUT request.  For example, to update user 2, you would send a PUT request to /api/users/2 with a request body containing the JSON of your create/edit user request model.

*Clearer logging: By utilizing separate request types, it is much easier to interpret basic access logs.  For example, if you see several 500 response codes in access logs for PUT requests, you are able to focus your investigation on the update logic.

With that said, there isn't really one right way.  However, most development teams (including one-person teams) will opt for separate methods for some of the reasons above.


text:
Q: PHP Maximum execution time exceeded - sign of attack? We were facing a very high CPU load on our web server today. Our application was freezing and not reaction. We could reduce the load by setting the maximum execution time from 180 to 90 seconds.
However, the log files are now full of the following error:
Maximum execution time of 90 seconds exceeded  {"exception":"[object] (Symfony\\Component\\ErrorHandler\\Error\\FatalError(code: 0):

And about every 10 seconds, there is a new error of this type in the log.
None of our application's forms and scripts should take this amount of execution time. Therefore my question is, if this error logs could be the sign of an attack (e.g. DDoS)? In addition, is there a chance to find out the IP address of the client that triggered the error?

A:
However, the log files are now full of the following error:

You've told PHP to kill all scripts that run longer than 90 seconds, so this is what you get.

None of our application's forms and scripts should take this amount of execution time.

Theory and practice sometimes diverge. You should seriously debug the problem - pinpoint the long-running script and find out why it's doing that - deep log and URL/cookies/headers analysis, possibly with increased log level.

So it doesn't seem to be a problem with the application itself.

That is a very dangerous assumption. Quite possibly there's an attack still going on. Currently, there might still be time to fix the problem before the attacker actually finds a security hole (high load can cause race conditions which in turn can open loop holes). At the very least, your website will get some hardening against DoS.

A: You have to debug the script, place timing elements and add to some debug log.  I doubt its an attack, its probably some loop, in the script that was unanticipated.  I have written scripts where an error condition was not trapped and created an unanticipated loop.  My educated guess, is that is exactly what is going on.

A: Given that your application is perfect and there's no way to idenfify what is causing the problem your only hope is a commecrial uptime preservation service like Akamai or Cloudflare.


text:
Q: How to make number in first line of file as variable? I have a file with a list of number like this:
10
15..135
140..433
444..598
600..783
800

The first and last lines are always single number without "..". So the problem is that, how to edit the first and last line to be like this:
1..10
15..135
140..433
444..598
600..783
800..900

For the first line.. I need to put "1.." in front of the number IF THE NUMBER IS NOT 0. If the number is already 0, no "1.." need to be there.
For last line.. I always want to edit (in this case I add "..900"). Can somebody give me some idea?

A: perl -pi -e '($.==1)?s/^/1../:((eof)?s/$/..900/:1);' your_file

PS: This does an in place replacement of the file


text:
Q: How to display data in my JSON array as separate lines using handlebars Im having trouble getting my json array from my database to display each sentence in the array on a new line.
Json code in MongoDB database
{
"_id" : ObjectId("5a9546659f96044402c2403a"),
"title" : "Asthma",
"description" : [
    "1. Help the person sit in a comfortable position and help them take their medicine.",
    "2. Reassure the person.",
    "3. If the attack becomes severe, they dont have their medication or they dont improve call the emergency services."
],
"image" : "https://danu7.it.nuigalway.ie:8710/images/asthma.jpg"

}
I have looked up ways to do this and tried some out to no avail. I want the sentences to print out at follows.

*

*

*

*
Currently this is what my code looks like handlebar file
  {{#each tutorials}}

{{description}}

{{/each}}

and this is how it is displaying on my webpage output
Any help would be greatly appreciated!!!

A: For me it looks like you're printing the whole description array at once.
So improve the line
{{description}} to
{{#each description}}{{this}}
{{/each}} and all description elements will be printed in a new line.


text:
Q: Get script location from server before angular is loaded I need dynamically add script in my index.html page depending on the application version. I have a controller that returns app version and tried to do this using angularjs:
    var resourceLoader = angular.module('MyTabs', []);
    resourceLoader.controller('ResourceLoaderController', ['$scope', '$http', function ($scope, $http) {
        $scope.getVersion = function() {
            $http.get('/version/get').then(function (response) {
                $scope.version = response.data;
                var link = document.createElement("link");
                link.setAttribute("type", "text/css");
                link.setAttribute("rel", "stylesheet");
                link.setAttribute("href", '/r/' + $scope.version +'/css/app.css');
                document.getElementsByTagName("head")[0].appendChild(link);

                var script = document.createElement("script");
                script.setAttribute("type", "text/javascript");
                script.setAttribute("src", '/r/' + $scope.version +'/js/app.js');
                document.getElementsByTagName("head")[0].appendChild(script);
            });
        };

        $scope.getVersion();
    }]);

It works but there are angular controllers in app.js, and I get an error in runtime that AuthController, used in index.html, is undefined.
Is there any way to get application version from server and include script before angularjs starts processes the web page?

A: How AngularJS works is it creates the app and builds all controller/directives/services dictionaries when you include the .js files.
By adding another script after AngularJS has finished building those, the controllers won't get added to the app.
You need to look up how to add controllers dynamically: Loading an AngularJS controller dynamically
Your other choice is getting the version and script BEFORE your html references and builds the AngularJS dependency. This way by the time AngularJS starts doing its magic, the scripts already will be loaded.

A: interesting question.
You could, get the version in a normal script tag in the head of the HTML document, making sure it is loaded synchronously, which is the default I believe (script tags I believe are loaded synchronously even when async operations are performed within them). That script would add a CSS class onto head to represent the version number.
Then afterwards you could load angular in a script tag and then do ...
<script ng-if="version==='something'" src='/somePath'></script>

for conditional script tags.
Hope that helps.
Alternatively use Node's grunt or gulp to start a server which makes an HTTP request to get the version and then writes the index.html page according to the version and then starts the server.
Worth noting that Node's wiredep auto includes script tags into index.html based on bower components.
I feel that the grunt or gulp approach is the more natural although it still seems that 60+% of the webdev community are still living in the web's dark ages and have never used or heard of Node or grunt or gulp. lol.

A: Thank you for answers. I fixed problem this way:
<script>
    var xmlhttp;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLXTTP");
    }

    function getVersion() {
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var version = xmlhttp.responseText;
                var link = document.createElement("link");
                link.setAttribute("type", "text/css");
                link.setAttribute("rel", "stylesheet");
                link.setAttribute("href", '/r/' + version +'/css/app.css');
                document.getElementsByTagName("head")[0].appendChild(link);

                var script = document.createElement("script");
                script.setAttribute("type", "text/javascript");
                script.setAttribute("src", '/r/' + version +'/js/app.js');
                document.getElementsByTagName("head")[0].appendChild(script);
            } else if (xmlhttp.status != 200) {
                console.log("Something went wrong. HTTP Status: " + xmlhttp.status);
            }
        };
        xmlhttp.open("GET", "version/get" , true);
        xmlhttp.send();
    }
    getVersion();
</script>


text:
Q: Heroku Push- Several solutions failed Full disclosure- I am a new to coding.
Initially when I tried the command $ git push heroku master -I received the following error, "uninitialized constant Devise".
I moved the gem devise(Gemfile) from (group :development, :test do)  to (group :production do) to no avail. I even tried it moving outside the previously mentioned groups. This was returned as a result: failed to push some refs to 'https://git.heroku.com.
Following that I ran the push commands again and received this error 'FileNotFound: couldn't find file 'bootstrap-sprockets' with type'application/javascript.' I removed the bootstrap-sprockets from your application.js subsequently. That failed also. I moved everything back to its original place and tried to push again and this what returned:
Counting objects: 229, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (208/208), done.
Writing objects: 100% (229/229), 41.31 KiB | 0 bytes/s, done.
Total 229 (delta 66), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Ruby app detected
remote: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-2.0.0
remote: -----> Installing dependencies using bundler 1.9.7
remote:        Running:

    bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deploymen
    remote:        Fetching gem metadata from https://rubygems.org/...........
    remote:        Fetching version metadata from https://rubygems.org/...
    remote:        Fetching dependency metadata from https://rubygems.org/..
    remote:        Rubygems 2.0.14 is not threadsafe, so your gems must be installed one at a time. Upgrade to Rubygems 2.1.0 or higher to enable parallel gem installation.
remote:        Installing rake 10.4.2
remote:        Installing i18n 0.7.0
remote:        Installing json 1.8.3
remote:        Installing minitest 5.7.0
remote:        Installing thread_safe 0.3.5
remote:        Installing tzinfo 1.2.2
remote:        Installing activesupport 4.2.1
remote:        Installing builder 3.2.2
remote:        Installing erubis 2.7.0
remote:        Installing mini_portile 0.6.2
remote:        Installing nokogiri 1.6.6.2
remote:        Installing rails-deprecated_sanitizer 1.0.3
remote:        Installing rails-dom-testing 1.0.6
remote:        Installing loofah 2.0.2
remote:        Installing rails-html-sanitizer 1.0.2
remote:        Installing actionview 4.2.1
remote:        Installing rack 1.6.1
remote:        Installing rack-test 0.6.3
remote:        Installing actionpack 4.2.1
remote:        Installing globalid 0.3.5
remote:        Installing activejob 4.2.1
remote:        Installing mime-types 2.6.1
remote:        Installing mail 2.6.3
remote:        Installing actionmailer 4.2.1
remote:        Installing activemodel 4.2.1
remote:        Installing arel 6.0.0
remote:        Installing activerecord 4.2.1
remote:        Installing bcrypt 3.1.10
remote:        Installing coffee-script-source 1.9.1.1
remote:        Installing execjs 2.5.2
remote:        Installing coffee-script 2.4.1
remote:        Installing thor 0.19.1
remote:        Installing railties 4.2.1
remote:        Installing coffee-rails 4.1.0
remote:        Installing orm_adapter 0.5.0
remote:        Installing responders 2.1.0
remote:        Installing warden 1.2.3
remote:        Installing devise 3.5.2
remote:        Installing multi_json 1.11.1
remote:        Installing jbuilder 2.2.16
remote:        Installing jquery-rails 4.0.3
remote:        Installing pg 0.17.1
remote:        Using bundler 1.9.7
remote:        Installing sprockets 3.2.0
remote:        Installing sprockets-rails 2.3.1
remote:        Installing rails 4.2.1
remote:        Installing rails_serve_static_assets 0.0.4
remote:        Installing rails_stdout_logging 0.0.4
remote:        Installing rails_12factor 0.0.2
remote:        Installing rdoc 4.2.0
remote:        Installing sass 3.4.14
remote:        Installing tilt 1.4.1
remote:        Installing sass-rails 5.0.3
remote:        Installing sdoc 0.4.1
remote:        Installing turbolinks 2.5.3
remote:        Installing uglifier 2.7.1
remote:        Bundle complete! 16 Gemfile dependencies, 56 gems now installed.
remote:        Gems in the groups development and test were not installed.
remote:        Bundled gems are installed into ./vendor/bundle.
remote:        Post-install message from rdoc:
remote:        Depending on your version of ruby, you may need to install ruby rdoc/ri data:
remote:        <= 1.8.6 : unsupported
remote:        = 1.8.7 : gem install rdoc-data; rdoc-data --install
remote:        = 1.9.1 : gem install rdoc-data; rdoc-data --install
remote:        >= 1.9.2 : nothing to do! Yay!
remote:        Bundle completed (86.26s)
remote:        Cleaning up the bundler cache.
remote: -----> Preparing app for Rails asset pipeline
remote:        Running: rake assets:precompile
remote:        rake aborted!
remote:        Sprockets::FileNotFound: couldn't find file 'bootstrap' with type 'application/javascript'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/app/assets/javascripts/application.js:17
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/resolve.rb:64:in `resolve!'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:399:in `resolve'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:207:in `process_require_directive'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:180:in `block in process_directives'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:178:in `each'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:178:in `process_directives'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:83:in `_call'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/directive_processor.rb:68:in `call'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:75:in `call_processor'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:57:in `block in call_processors'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:56:in `reverse_each'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:56:in `call_processors'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:86:in `load_asset_by_uri'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:45:in `block in load'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:155:in `fetch_asset_from_dependency_cache'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:38:in `load'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/cached_environment.rb:20:in `block in initialize'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/cached_environment.rb:47:in `yield'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/cached_environment.rb:47:in `load'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/bundle.rb:23:in `block in call'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/utils.rb:183:in `dfs'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/bundle.rb:24:in `call'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:75:in `call_processor'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:57:in `block in call_processors'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:56:in `reverse_each'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/processor_utils.rb:56:in `call_processors'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:86:in `load_asset_by_uri'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:45:in `block in load'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:155:in `fetch_asset_from_dependency_cache'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/loader.rb:38:in `load'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/cached_environment.rb:20:in `block in initialize'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/cached_environment.rb:47:in `yield'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/cached_environment.rb:47:in `load'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/base.rb:63:in `find_asset'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/base.rb:70:in `find_all_linked_assets'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/manifest.rb:138:in `block in find'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/legacy.rb:114:in `block (2 levels) in logical_paths'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/path_utils.rb:223:in `block in stat_tree'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/path_utils.rb:207:in `block in stat_directory'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/path_utils.rb:204:in `each'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/path_utils.rb:204:in `stat_directory'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/path_utils.rb:222:in `stat_tree'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/legacy.rb:105:in `each'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/legacy.rb:105:in `block in logical_paths'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/legacy.rb:104:in `each'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/legacy.rb:104:in `logical_paths'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/manifest.rb:136:in `find'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/sprockets/manifest.rb:162:in `compile'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-rails-2.3.1/lib/sprockets/rails/task.rb:70:in `block (3 levels) in define'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-3.2.0/lib/rake/sprocketstask.rb:147:in `with_logger'
remote:        /tmp/build_b8ba7c7f8f9b9d6606dccf954e43d1c0/vendor/bundle/ruby/2.0.0/gems/sprockets-rails-2.3.1/lib/sprockets/rails/task.rb:69:in `block (2 levels) in define'
remote:        Tasks: TOP => assets:precompile
remote:        (See full trace by running task with --trace)
remote:  !
remote:  !     Precompiling assets failed.
remote:  !
remote:
remote:  !     Push rejected, failed to compile Ruby app
remote:
remote: Verifying deploy....
remote:
remote: !       Push rejected to (app_name).
remote:
To https://git.heroku.com/app_name.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/app_name.git'
_________________________________________________________________________

I have tried several solutions. I cannot figure it out. Everything was moving along swimmingly. Any idea what I need to do to resolve this issue? App_name is just a replacement for the original name by the way.
Any help is much appreciated. Thanks in advance.

A: It doesn't seem to be installing bootstap in production. Make sure you have bootstrap included in your Gemfile correctly and not only included in development.


text:
Q: Packaging EJBs in Java EE server I have deployed an enterprise app in an EAR and a standalone web app in WAR (out side of the EAR) to the same Java EE server.
Question is can I access the local interface of the session bean in the EAR from the standalone WAR? if so can I use dependency injection (DI)?

A: Section 3.2.2 of the EJB 3.1 specification explicitly states that this is not portable:

Access to an enterprise bean through
  the local client view is only required
  to be supported for local clients
  packaged within the same application
  as the enterprise bean that provides
  the local client view. Compliant
  implementations of this specification
  may optionally support access to the
  local client view of an enterprise
  bean from a local client packaged in a
  different application. The
  configuration requirements for
  inter-application access to the local
  client view are vendor-specific and
  are outside the scope of this
  specification. Applications relying on
  inter-application access to the local
  client view are non-portable.

In general, the solution will require at a minimum:

*

*Some mechanism for allowing both the EAR and WAR class loaders to have visibility to the same interface class.

*Some mechanism for looking up a local interface from another application.  For example, java:global.

A: The answer anyway to both your questions is yes.
Since both the ear and war are in the same JVM, a local interface can be used. To get an instance of the session bean, you would use the global JNDI name of said bean to do either a JNDI lookup or use with the mappedName property on the @EJB annotation. Those names are standardized via the following pattern:
java:global[/<app-name>]/<module-name>/<bean-name>[!<fully-qualified-interface-name>]
Lookup would thus be if the name of your ear is my_app, your bean is MyBean.java and its local interface is com.foo.SomeBeanLocal:
InitialContext ctx = InitialContext();
SomeBeanLocal someBean = (SomeBeanLocal) ctx.lookup("java:global/my_ear/SomeBean/com.foo.SomeBeanLocal");

Injection would be:
public SomeManagedClass {

    @EJB(mappedName="java:global/my_ear/SomeBean/com.foo.SomeBeanLocal")
    SomeBeanLocal someBean;
}

There are two catches however:
Non-standard naming
Older Java EE implementations (e.g. JBoss AS 5.1, Glassfish 2, Websphere) used their own naming pattern. E.g. JBoss AS 5.x would use:
<app-name>/<bean-name>/local|global
E.g. with the same names as the previous example, the global JNDI name of that bean in JBoss AS 5.1 would be:
my_app/MyBean/local
As said, other old application servers might use other names.
Startup-order
Especially with injection you have to assure somehow that the application you want to inject from has been started before the application you want to inject into. I.e. in your case that the EAR has been started before the standalone WAR. There are no standard mechanisms for this. You might be just lucky that it happens to be in the right order for you. This order might be influenced by time-stamps, alphabetical order of application names, or something else entirely.
JBoss AS for example uses <depends> tags in many of its proprietary configuration files, which is perfectly suited for this although it can be hard to find out what exactly you need to depend on (the syntax can be very cryptic).


text:
Q: Type Error "Map" is not a function while using react hooks I am new to react and I am building a component thats going to be displayed within the profile page for a specific type of user of the app that I am working on "podcaster". I am trying to display their podcasts in a responsive list but I keep getting this typeError. I have looked at different examples here on SO but I have not been able to find the problem.
I am using 2 hooks to get this info [useState & useEffect] yet I am not able to fully understand why I am getting this error.
import { FC, useState, useEffect, Fragment } from 'react'
import ResponsiveList from '../ResponsiveList'

const UserProfilePodcaster: FC = () => {
const {
  user: { id, accountType },
    } = useAuth()
const [podcasts, setPodcasts] = useState<any[]>([])
const [showModal, setShowModal] = useState(false)
const [currentPodcast, setCurrentPodcast] = useState<any>({})
const [isLoading, setIsLoading] = useState(true)
const [categories, setCategories] = useState<{ name: string; code: string }[]>([])

 useEffect(() => {
;(async function () {
  const categories = await getCategories()
  const podcasts = await getPodcast(id)

  setCategories(categories)
  setPodcasts(podcasts)
  setIsLoading(false)
  })()
  }, [id])

  <ResponsiveList
      data={podcasts.map((podcast: any) =>
        podcast.name({
          ...podcast,
          edit: (
            <Button
              variant="contained"
              color="primary"
              fullWidth
              onClick={() => handleEditPodcast(podcast)}
            >
              Edit
            </Button>
          ),
        })
      )}
      keys={[
        { key: 'podcasts', label: 'Podcast Name' },
        { key: 'categories', label: 'Podcast Categories' },
        { key: 'description', label: 'Podcast Niche' },
        { key: 'Reach', label: 'Podcast Reach' },
        {
          key: 'edit',
          label: 'Edit',
        },
      ]}
      emptyMessage="It seems that you have not created a podcast yet, go out and start one  "
    />

A: map is a function of the Array prototype. If map is not a function, it means your podcasts is not an array. This might happen due to bugs in programming or as a result of podcasts being the result of e.g. an API call which is not there yet (is undefined) on first render as the API call has not resolved yet.
There are many ways to go about the latter case. You could e.g. write
data={podcasts?.map(...)}

and make sure the <ResponsiveList/> handles undefined data well, or you could render a loader for as long as the data is not there yet.

A: You can use lodash package. lodash will handle this type of errors
import _ from 'lodash';

.
.
.
data={_.map(podcasts, pod =>  {pod['key_name']})}


text:
Q: Sql: determine an event's active period from start date and end date split in 2 tables Sql problem: determine an event's active period from start date and end date split in 2 tables
This is an adhoc report that I need to produce. I was provided 2 extract files pertaining to events (csv). I intend to insert these extracts to a single sql table #temp_events.
File 1:
event, start date
Core training, 01Jan2011
Certification reviews, 23Feb2011
Core training, 15May2011
Abc Event, 24Nov2011

File 2:
event, end date
Core training, 05Jan2011
Certification reviews, 24Feb2011
Core training, 18May2011
Abc Event, 30Nov2011

I want to insert into a #temp_events, wherein an entry will define an event's active period. Note that there is no FK, as this is the primary problem at hand... the only way to relate data is via event name however there could be multiple occurrences of an event. An event's end cannot be calculated since there is no data that defines how long an event is. These are the restrictions that I need to deal with as extract provider has stipulated, unfortunately.
Can anyone provide suggestions for the logic that I need to code, so that I can reliably link event's in File 1 to File 2 even though there is no natural key/id/FK? Any obvious loophole that I may run into?

A: There you go:
CREATE TABLE eventstart
        ( event VARCHAR NOT NULL
        , zdate date
        );
INSERT INTO eventstart(event,zdate) VALUES
 ( 'Core training' , '2011-01-01' )
,( 'Certification reviews' , '2011-02-23' )
,( 'Core training' , '2011-05-15' )
,( 'Abc Event' , '2011-11-24' )
        ;

CREATE TABLE eventend
        ( event VARCHAR NOT NULL
        , zdate date
        );
INSERT INTO eventend(event,zdate) VALUES
 ('Core training' , '2011-01-05' )
,('Certification reviews' , '2011-02-24' )
,('Core training' , '2011-05-18' )
,('Abc Event' , '2011-11-30' )
        ;

WITH    s AS (
        SELECT ss.event, ss.zdate
        , ROW_NUMBER() OVER( PARTITION BY ss.event ORDER BY ss.zdate) AS zrnk
        FROM eventstart ss
        )
        ,e AS (
        SELECT ee.event, ee.zdate
        , ROW_NUMBER() OVER( PARTITION BY ee.event ORDER BY ee.zdate) AS zrnk
        FROM eventend ee
        )
SELECT s.event
       , s.zdate AS sdate
       , e.zdate AS edate
FROM s
LEFT JOIN e ON e.event = s.event AND s.zrnk = e.zrnk
WHERE s.zdate <= COALESCE(e.zdate , s.zdate) -- safety valve ;-)
        ;

Note: the above query is very rude. It relies on the borderconditions given by the OP, that there will be a matching end-record for every start record. If not: YMMV
Result:
CREATE TABLE
INSERT 0 4
CREATE TABLE
INSERT 0 4
         event         |   sdate    |   edate
-----------------------+------------+------------
 Abc Event             | 2011-11-24 | 2011-11-30
 Certification reviews | 2011-02-23 | 2011-02-24
 Core training         | 2011-01-01 | 2011-01-05
 Core training         | 2011-05-15 | 2011-05-18
(4 rows)


text:
Q: How to parse file with array of objects gets turned into string I have a text file containing a an array of objects in the following format:
[{
            "symbol": "MSFT",
            "side": "BUY",
            "price": 120,
            "quantity": 100
        },
        {
            "symbol": "KPMG",
            "side": "SELL",
            "price": 88,
            "quantity": 10
        }]

However, when I upload the file into my application, and store it as a variable, it gets stored as a string. Does anyone know how I can avoid doing this?
I want to be able to read the file in (which I can already do) and store that as an array. So I can go like data[1] and get access to
  {
        "symbol": "KPMG",
        "side": "SELL",
        "price": 88,
        "quantity": 10
    }

I also want to be able to go like:
data[1].side

and retrieve the field


text:
Q: ¿Cómo puedo mostrar tres gráficas en un plot donde hay varias gráficas? Cordial saludo compañeros, tengo algunos inconvenientes con el siguiente código, sucede que en la primera gráfica necesito mostrar tres funciones seno desfasadas pero no se como añadirlas al código pues siempre me da error.
otro detalle es que las gráficas aparecen muy juntas, me gustaría separarlas mas para que las etiquetas no se estorben entre ellas, muchas gracias por su ayuda. la imagen muestra las dos gráficas que están muy pegadas entre ellas, por lo que me gustaría separarlas un poco mas, subir la gráfica de la curva seno, y pues el aspecto mas importante es que deben mostrarse 3 ondas en la primera gráfica pero me da error cuando intento return en la función y graficar, realmente no se como mostrarlas, un saludo.
import math
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider

#Funcion que define la accion de los controles deslizantes
def sliders_on_changed(val):
    line1.set_ydata(FuncionTorque(r2_slider.val, AMP_slider.val))
    line2.set_ydata(FuncionSeno(AMP_slider.val))
    fig1.canvas.draw_idle()

#funcion de la tension trifasica.
def FuncionSeno(A):

    x = np.arange(0.0, 2*np.pi, 0.0001)
    V1 = A*np.sin(x)
    #V2 = A*np.sin(x+(120*np.pi)/180)
    #V3 = A*np.sin(x+(240*np.pi)/180)
    return V1

#funcion para calcular el torque de la maquina.
def FuncionTorque(r2, AMP):

    #valores requeridos del programa

    r1 = 0.641 #resistencia del estator.
    x1 = 1.106 #reactancia del estator.
    x2 = 0.464 #reactancia del rotor.
    xm = 26.3 #reactancia del circuito tanque.

    voltaje_fase = AMP/math.sqrt(3)
    n_sincronismo_rad = 188.5

    #Calcuamos el voltaje e impedancia de Thevenin.

    vth = voltaje_fase * (xm /math.sqrt(r1**2 + (x1 + xm)**2))

    zth = ((xm*1j)*(r1 + x1*1j)) / (r1 + (x1 + xm)*1j)
    rth = zth.real
    xth = zth.imag

    #Calculamos la caracteristica par vs velocidad.
    torque = ((3*vth**2*r2)/s) / (n_sincronismo_rad*((rth + (r2)/s)**2 + (xth + x2)**2))
    return torque

#Codigo general

axis_color = 'lightgoldenrodyellow'
fig1 = plt.figure("CURVA PAR VS VELOCIDAD")

ax1 = fig1.add_subplot(224)
plt.title("Curva Par vs Velocidad")
plt.xlabel("Velocidad sincrona - RPM", fontsize = 7)
plt.ylabel("Torque inducido - N.M", fontsize = 7)
plt.grid(True)

ax2 = fig1.add_subplot(222)
plt.title("Onda trifasica de la tension")
plt.xlabel("Variacion en el tiempo - S", fontsize = 7)
plt.ylabel("Tension de entrada - V", fontsize = 7)
plt.grid(True)

#valores iniciales del programa.
A = 460
r2 = 0.332
s = np.arange(0.001,1,0.001)
n_sincronismo = 1800
nm = (1 - s)*n_sincronismo
x = np.arange(0.0, 2*np.pi, 0.0001)

#Ajuste del espacio de ubicacion de las graficas.
fig1.subplots_adjust(left=0.05, bottom=0.25)

#Creacion de la grafica a modificar
[line1] = ax1.plot(nm, FuncionTorque(r2,A), linewidth= 1, color='r')
[line2] = ax2.plot(x, FuncionSeno(A), linewidth = 1)

#controles deslizantes

#Definimos el control deslizante para la resistencia rotorica
r2_slider_ax1  = fig1.add_axes([0.25, 0.1, 0.55, 0.03], facecolor= axis_color)
r2_slider = Slider(r2_slider_ax1, 'R2', 0.001, 1.5, valinit= r2)

#Definimos el control deslizante para la amplitud de la tension
AMP_slider_ax1 = fig1.add_axes([0.25, 0.05, 0.55, 0.03], facecolor=axis_color)
AMP_slider = Slider(AMP_slider_ax1, 'AMP', 0.001, 500.0, valinit= A)

#activacion del control deslizante.
r2_slider.on_changed(sliders_on_changed)
AMP_slider.on_changed(sliders_on_changed)

plt.show()

A: Para la gráfica del seno desfasada, imagino que el desfase que quieres es el que hay en las líneas comentadas V1 y V2, lo que puedes hacer es por ejemplo lo siguiente:
Añades un nuevo parametro a la función que indique el desfase que quieres:
def FuncionSeno(A, desfase):
    x = np.arange(0.0, 2 * np.pi, 0.0001)
    V = A * np.sin(x + (desfase * np.pi) / 180)
    return V

En la parte en la que creas las gráficas añades las siguientes líneas:
# Creacion de la grafica a modificar
[line1] = ax1.plot(nm, FuncionTorque(r2, A), linewidth=1, color='r')
[line2] = ax2.plot(x, FuncionSeno(A, 0), linewidth=1)
[line3] = ax2.plot(x, FuncionSeno(A, 120), linewidth=1)
[line4] = ax2.plot(x, FuncionSeno(A, 240), linewidth=1)

Con esto ya habrías solucionado la parte de añadir las tres funciones del seno.
Para la parte del solapamiento entre gráficas puedes pasarle un parámetro más a subplots_adjust(). Al pasarle hspace le indicas el espacio vertical que quieres dejar entre gráficas (he puesto 1, prueba cambiandolo). Por lo que modificando la línea así:
# Ajuste del espacio de ubicacion de las graficas.
fig1.subplots_adjust(left=0.05, bottom=0.25, hspace=1)

Conseguirías dejar las gráficas ya listas:

Por último, no sé si tenías pensado añadir más gráficas, porque tal y como lo tienes ahora está distribuido para tener 4 (por eso las dos que has hecho te salen tan a la derecha).
Si no vas a añadir más, cambia estas líneas:
ax1 = fig1.add_subplot(212)
ax2 = fig1.add_subplot(211)

El primer numero (2) son las filas, el segundo (1) las columnas y el tercero (1 y 2) el índice. Así te saldrá como lo tenías pero centrado, y si cambias el margen izquierdo para que no salga cortado ya lo tendrás del todo:
fig1.subplots_adjust(left=0.2, bottom=0.25, hspace=1)

Actualización
Para hacer que los Sliders sigan funcionando, lo más rápido sería poner estas líneas en la función sliders_on_changed, así haces que las tres funciones se actualicen:
line2.set_ydata(FuncionSeno(AMP_slider.val, 0))
line3.set_ydata(FuncionSeno(AMP_slider.val, 120))
line4.set_ydata(FuncionSeno(AMP_slider.val, 240))


text:
Q: Smart Lock request always RESOLUTION_REQUIRED with single account I only have a single credential saved in my app using Smart Lock, but I still get the account resolution alert every time:

Smart Lock docs seem to imply this alert should only appear if the user has multiple options to choose from.
Why am I seeing this alert with only one credential saved? More specifically, when I call Auth.CredentialsApi.request, why is my credentialRequestResult status RESOLUTION_REQUIRED with only one stored credential?

A: Check Settings > Google > Smart Lock for Passwords and ensure that Auto Sign-In has not be disabled for any of the accounts on the device (use account selector at the top to check each account, or check this account setting at passwords.google.com for each account on the device).
And of course, make sure that the disableAutoSignIn has not be called for the app on this device (we track that state in Play Services); and you need to do a save or selection to clear that state (or clear Play Services data)


text:
Q: Ideal way to handle F2PY compiler with multiple Fortran files I'm using F2PY to compile my Fortran codes, but it's a little confusing how I can sort out the dependency between files.
For example, there are file A.f90 and B.f90, that B.f90 uses a module in A.f90. How would I compile these to get a dynamic library? My approach is
with open('A.f90') as fh:
    source = fh.read()
with open('B.f90') as fh:
    source += fh.read()
f2py.compile(source, ...)

But I don't think it's a good practice. I believe there will be better approaches for this. I would like to compile those independently but use modules from A as a dynamic library when compiling B. Any advice would be appreciated!

A: You can send the fortran files with dependencies through the extra_args option within the f2py.compile module.
Your code would then look like
with open('B.f90') as fh:
    source = fh.read()
f2py.compile(source,....,extra_args=path_to_A.f90)


text:
Q: Can't connect to memcached from PHP CentOS version 6.8.
All things installed from yum.
php version 5.6.
memcached service installed and running.
also installed php-memcached module (not memcache).
When i try run this code from bash - it works well. When I try run it trough apache as a php page - it even not connect to the memcached server and not return any errors.
Code:
<?php
   $m = new Memcached();
   $m->addServer('localhost', 11211);

   $m->set('test_key','test_value');

   print_r($m->get('test_key'));
?>

Memcached server is running in verbose mode (memcached -vv -m64 -l127.0.0.1). When I execute the code above from console, memcached server log is:
<28 new auto-negotiating client connection

28: Client using the ascii protocol

<28 set test_key 0 0 10

>28 STORED

<28 get test_key

>28 sending key test_key

>28 END

<28 quit

<28 connection closed.

When I run it as trough apache - no any log messages in verbose console at all.


text:
Q: How to filter two arrays? How to filter two arrays?
I have two arrays where allBrands are all brands and userBrands are brands that the user has already selected, I'm trying to filter allBrands in such a way that it doesn't show the brands already selected by the user
  const allBrands = [
    { id: 0, title: "Apple" },
    { id: 1, title: "bmw" },
    { id: 2, title: "mercedes" },
    { id: 3, title: "samsung" }
  ];
  const userBrands = [
    { id: 0, title: "Apple" },
    { id: 1, title: "mercedes" }
  ];

  const filtered = allBrands.filter(({ title }) => {
    return userBrands.map((item) => item.title !== title);
  }); // need bmw, samsung

A: We can use find inside the filter instead of map to find if the brand is already selected by the user. If brand is found in userBrands then return false, else return true inside filter.

const allBrands = [
  { id: 0, title: "Apple" },
  { id: 1, title: "bmw" },
  { id: 2, title: "mercedes" },
  { id: 3, title: "samsung" }
];
const userBrands = [
  { id: 0, title: "Apple" },
  { id: 1, title: "mercedes" }
];

const filtered = allBrands.filter(({ title }) => {
  return !userBrands.find((item) => item.title === title);
}); // need bmw, samsung

console.log(filtered);

A:

const allBrands = [
    { id: 0, title: "Apple" },
    { id: 1, title: "bmw" },
    { id: 2, title: "mercedes" },
    { id: 3, title: "samsung" }
  ];
  const userBrands = [
    { id: 0, title: "Apple" },
    { id: 1, title: "mercedes" }
  ];

  const filtered = allBrands.filter(({ title:title1 }) => !userBrands.some(({ title:title2 }) => title1 === title2));

  console.log(filtered)

A: If you are thinking of filtering the allBrands Array so that it does not contain the brands already selected by the user. You can try making 2 for loops and nesting one in the other and cycling through the allBrands array to check if it contains the brand already selected by the user.
Example:

const allBrands = [
    { id: 0, title: "Apple" },
    { id: 1, title: "bmw" },
    { id: 2, title: "mercedes" },
    { id: 3, title: "samsung" }
  ];
  const userBrands = [
    { id: 0, title: "Apple" },
    { id: 1, title: "mercedes" }
  ];

 //Filtering Part
 for(let i = 0; i < allBrands.length; i++) {
  for(let j = 0; j < userBrands.length; j++) {
    if(allBrands[i] === userBrands[j]) {
        allBrands.slice(i, 1);
    }
  }
}


text:
Q: Como transferir de uma ComboBox para outra (C#) A ideia é, existem uma ComboBox Principal, cada um com um cliente de 4 cidades diferentes, eu queria selecionar um cliente na ComboBox, apertar o botão e remover dessa ComboBox e inserir na cidade correspondente dela.
Resumindo: Quero tirar um item, remove-lo e colocar na ComboBox pré selecionada.
Eu tentei usando IF, ja que cada ComboBox começa com 0, mas ao adicionar na ComboBox, ela retorna um valor que contem algo la dentro, mas não mostra nenhum texto.
(Exemplo do que tentei)
if (cboClientes.SelectedIndex == 0 || cboClientes.SelectedIndex == 2 || cboClientes.SelectedIndex == 3 ||
{
    cboVarginha.Items.Add(cboClientes.SelectedIndex);
    cboClientes.Items.RemoveAt(cboClientes.SelectedIndex);
}

A: Pelo que eu entendi, vc quer selecionar um item na ComboBox, apertar um botão e move-lo para outro ComboBox.
Montei um esquema aqui... espero que sirva.
Imagem:

Código Utilizado:
        private void Form2_Load(object sender, EventArgs e)
        {
            for (int i = 1; i < 5; i++)
                comboBox1.Items.Add($"Item {i}");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!comboBox1.SelectedIndex.Equals(-1))
            {
                comboBox2.Items.Add(comboBox1.SelectedItem);
                comboBox2.Sorted = true;

                Resultado.Text = $"O Elemento {(string)comboBox1.SelectedItem} foi transferido para o Destino";
                Resultado.Left = (Resultado.Parent.Width / 2) - (Resultado.Width / 2);

                comboBox1.Items.RemoveAt(comboBox1.SelectedIndex);
                Resultado.Visible = true;
            }
        }

Existe também a possibilidade de usar o evento SelectedIndexChanged da ComboBox e mandar direto para Segunda ComboBox no ato da seleção do Item na Primeira.


text:
Q: Как сделать переданные props состоянием компонента? У меня есть 2 компонента
Первый PageExample - это контейнер который ходит в api за данными, пришедшие по апи данные пишутся в state.
Второй MyModal - обычный компонент в который через пропсы передаются данные из родительского this.state
Как в MyModal правильно присвоить переданные props в локальный state.
То есть я хочу чтобы переданные пропсы стали состоянием MyModal.
Возможно ли это? Если да то в каком методе это правильнее делать, в конструкторе или в componentDidMount и т.п.? Спасибо

A: Да, можно все это сделать, как вы и хотите. Вот к примеру в родительском PageExample вы передаете посредством props данные, которые получили из API и записали в dataAPI стэйта, в MyModal компонент.
Предположим, что в PageExample есть такая функция, в которой получаем данные и кладем в стэйт:
loadDatafromAPI() {
  // тут какой-то код получения данных (к примеру)
  let data = ...

  // и запись этих данных в state
  this.setState({
     dataAPI: data
  });
}

А уже потом внутри PageExample вы создаете свой MyModal компонент, в который передаете эти данные посредством props:
<MyModal data={this.state.dataAPI} />

а уже внутри вашего MyModal, в конструкторе, можно их присвоить в локальный стэйт:
constructor(props) {
  super(props);

  this.state = {
    dataAPI: props.data
  }
}

По поводу componentDidMount - можно и в нем, к примеру вот тут: componentDidMount() рекомендуют загружать данные с удаленной конечной точки (для сетевых запросов) именно внутри него. Однако вызов setState({..}) в этом методе вызовет дополнительный рендеринг, но это произойдет до того, как браузер обновит экран.  Я бы писал в конструторе.