text:
Q: How to make elasticsearch scoring take field-length into account I created a very simple test index consisting on the following 5 entries:
{    "tags": [        { "topics": "music festival dance techno germany"}    ]}
{    "tags": [        { "topics": "music festival dance techno"}    ]}
{    "tags": [        { "topics": "music festival dance"}    ]}
{    "tags": [        { "topics": "music festival"}    ]}
{    "tags": [        { "topics": "music"}    ]}

Then I performed the following query:
{
  "query": {
    "bool": {
      "should": [
        { "match": { "tags.topics": "music festival"}}
      ]
    }
  }
}

Expecting to obtain the following order in the results:
1)  "music festival"
2)  "music festival dance"
3)  "music festival dance techno"
4)  "music festival dance techno germany"
5)  "music"
Accounting for field-length normalization.
However I got the following:
{
    "took": 4,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 5,
        "max_score": 0.5753642,
        "hits": [
            {
                "_index": "testindex",
                "_type": "entry",
                "_id": "1",
                "_score": 0.5753642,
                "_source": {
                    "tags": [
                        {
                            "topics": "music festival dance techno germany"
                        }
                    ]
                }
            },
            {
                "_index": "testindex",
                "_type": "entry",
                "_id": "3",
                "_score": 0.5753642,
                "_source": {
                    "tags": [
                        {
                            "topics": "music festival dance"
                        }
                    ]
                }
            },
            {
                "_index": "testindex",
                "_type": "entry",
                "_id": "4",
                "_score": 0.42221835,
                "_source": {
                    "tags": [
                        {
                            "topics": "music festival"
                        }
                    ]
                }
            },
            {
                "_index": "testindex",
                "_type": "entry",
                "_id": "2",
                "_score": 0.32088596,
                "_source": {
                    "tags": [
                        {
                            "topics": "music festival dance techno"
                        }
                    ]
                }
            },
            {
                "_index": "testindex",
                "_type": "entry",
                "_id": "5",
                "_score": 0.2876821,
                "_source": {
                    "tags": [
                        {
                            "topics": "music"
                        }
                    ]
                }
            }
        ]
    }
}

Whose order seems absolutely random, except for the lowest score that matched only one word.
What could be causing this and, what could I change (during mapping, indexing or searching), to get the expected order?
Note: The same goes for non-perfect matching queries. Searching "music dance" should still produce the 3 word entry as a first result, so using or boosting term queries seems out of the question.

A: As I described in this answer scoring/relevance is not the easiest topic in Elasticsearch.
I was trying to figure out solution for you and currently I have something like that.
Documents:
{ "tags": [ { "topics": ["music", "festival", "dance", "techno", "germany"]} ], "topics_count": 5 }
{ "tags": [ { "topics": ["music", "festival", "dance", "techno"]} ], "topics_count": 4 }
{ "tags": [ { "topics": ["music", "festival", "dance"] } ], "topics_count": 3 }
{ "tags": [ { "topics": ["music", "festival"]} ], "topics_count": 2 }
{ "tags": [ { "topics": ["music"]} ], "topics_count": 1 }

and query:
{
  "query": {
    "bool": {
      "should": [
        {
          "function_score": {
            "query": {
              "terms_set": {
                "tags.topics" : {
                  "terms" : ["music", "festival"],
                  "minimum_should_match_script": {
                    "source": "params.num_terms"
                  }
                }
              }
            },
            "script_score" : {
              "script" : {
                "source": "_score * Math.sqrt(1.0 / doc['topics_count'].value)"
              }
            }
          }
        },
        {
          "function_score": {
            "query": {
              "terms_set": {
                "tags.topics" : {
                 "terms" : ["music", "festival"],
                 "minimum_should_match_script": {
                    "source": "doc['topics_count'].value"
                  }
                }
              }
            },
            "script_score" : {
              "script" : {
                "source": "_score * Math.sqrt(1.0 / doc['topics_count'].value)"
              }
            }
          }
        }
      ]
    }
  }
}

It is not perfect. Still needs some improvements. It works well (tested on ES 6.2) for ["music", "festival"] and ["music", "dance"] on this example but I'm guessing that on other results it will work not 100% as you expected. Mostly because of the relevance/scoring complexity. But you can now read more about things I used and try to improve it.


text:
Q: Trigger python script with Django user input I am trying to trigger a pyfirmata script that will load onto an arduino device when a user checks a  checkbox on a django view. I am trying to implement some comparison code in my view that will check if user submitted check box is true then trigger pyfirm.py.
Background: Py firmata will drive the arduino pins directly without needing an arduino IDE.
Should I hard code my pyfirmata in my view or can I trigger a full script some how?
Iam using a raspberry pi as a single board computer that is connected to arduino as a device driver. I am considering the pi device as a user.
Any tips on this?
I have my check box working and i am printing the POST results to the terminal. just need to check if box is true and trigger script some how.
Haven't had any luck triggering a script. I see a couple questions related to this but i am curious for pyfirmata specific directions on this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Path finding Algorithm for changeable environments I am having trouble adapting the A* algorithm to handle changing environments. As a minimum example, consider this rogue-like map:
######
#!   #
###  #
#S   #
##+###
##F###
######

The goal is to get from S to F, but in order to do so the player must step on ! to open the door.  The problem I'm having is that in A* once a grid point is visited it becomes "closed" and cannot be reentered.  How can I modify the algorithm to solve this puzzle?

A: You can run A* twice:

*

*First find shortest path to the switch (!) where the door is like
a wall

*Then find shortest path to the end from the switch, where the door
is blank tile.

The shortest path will be the combination of these two paths.

A: In your problem, it is not true that in A* when you visit a point (x,y cord) you won't visit again the same point.
The reason is that in your problem, state is position in the grid and for each door its state (open or close).
So at the beginning, in your example, the initial state is (3,1,{false}). (false means the door is closed).
When you reach the '!' position, the new state will be (1,1,{true}) so now when you reach the door you will pass the door.


text:
Q: Why is my program glitching and lagging out on me? I'm working on a drawing app in python, and I recently added in a mousedrag function to make it so that you could drag the turtle and it would draw. It often gets a little bit laggy, and can go in other directions when I'm dragging it. Here's the code:
    import sys
import turtle
from tkinter import *

wn = turtle.Screen()
wn.title('Drawing Function!')
wn.bgcolor('blue')
ashton = turtle.Turtle()
ashton.pencolor('lime')
ashton.shape('turtle')

def turtleWrite():
    pass

def turtleForward():
    ashton.forward(30)

def turtleLeft():
    ashton.left(45)

def turtleRight():
    ashton.right(45)

def closeWindow():
    wn.bye()

def penup():
    ashton.penup()

def pendown():
    ashton.pendown()

def clear():
    ashton.clear()

def stamp():
    ashton.stamp()

def undo():
    ashton.undo()

ashton.ondrag(ashton.goto)

wn.onkey(turtleForward, 'Up')
wn.onkey(turtleLeft, 'Left')
wn.onkey(turtleRight, 'Right')
wn.onkey(closeWindow, 'q')
wn.onkey(penup, 'u')
wn.onkey(pendown, 'd')
wn.onkey(clear, 'c')
wn.onkey(stamp, 's')
wn.onkey(undo, 'BackSpace')

wn.listen()
wn.mainloop()

Does anyone have any ideas why this is happening, and if so, how I can fix them?
Thanks!

A: The turtle documentation is a little oversimplified when it suggests turtle.ondrag(turtle.goto) to draw freehand.  To make it work you need to define your own event handler that immediately disables drag events on entry, moves the turtle and then reenables drag events on exit:
import turtle

wn = turtle.Screen()
wn.title('Drawing Function!')
wn.bgcolor('blue')

ashton = turtle.Turtle()
ashton.pencolor('green')
ashton.shape('turtle')

def drag_handler(x, y):
    ashton.ondrag(None)  # disable event inside event handler
    ashton.goto(x, y)
    ashton.ondrag(drag_handler)  # reenable event on event handler exit

ashton.ondrag(drag_handler)

wn.onkey(lambda: ashton.forward(30), 'Up')
wn.onkey(lambda: ashton.left(45), 'Left')
wn.onkey(lambda: ashton.right(45), 'Right')
wn.onkey(lambda: wn.bye(), 'q')
wn.onkey(lambda: ashton.penup(), 'u')
wn.onkey(lambda: ashton.pendown(), 'd')
wn.onkey(lambda: ashton.clear(), 'c')
wn.onkey(lambda: ashton.stamp(), 's')
wn.onkey(lambda: ashton.undo(), 'BackSpace')

wn.listen()
wn.mainloop()

My system blew up with pen color 'lime' ("TurtleGraphicsError: bad color string: lime") so I had to substitute 'green' for this example.


text:
Q: Sharepoint 2007 Site Actions IE9 doesnt work We have a public facing website which is custom branded. Up until viewing the website in IE9 all standard Sharepoint functionality worked such as Site Actions.
All browsers work with it. Recently when we updated to IE9 the second level drop down has stopped working. I considered it to be a CSS related issue on our end, so I cleared the possibility of that by disabling it and it still didnt work.
I haven't managed to find a solution which works so wondered if anyone can shed a light on this problem.

A: There are some known issues with IE9 and SharePoint 2007's JavaScript, etc.  You might set the IE Compatibility Mode meta tag in the master page so that it forces IE 9 to render in IE 7 or 8 mode:
i.e: < meta http-equiv="X-UA-Compatible" content="IE=7" / >
http://msdn.microsoft.com/en-us/library/cc288325(v=VS.85).aspx

A: If its not a JavaScript issue, I would also suggest to try to launch IE9 with no addons. If it works, then you should find the respective addon that is creating the problem and disable it.

A: You should make sure that JavaScript is enabled on your browser, Fast way to do this:
While in IE9, hit the F12 key on the keyboard
You will see the Developer tools appear at the bottom of the screen. From the Disable menu, confirm that 'Script' is not ticked.
If this doesn't work, make sure there are no JavaScript errors occurring on the page.
Hope this helps.


text:
Q: Using Bubble Sort with JOptionPanes I want to bubble sort an array that could be any number with values from the user. But the first method is not working. I really want to use JOptionPanes, but I don't even know if that is the problem. It compiles correctly, but doesn't run properly. This is my current code:
import javax.swing.*;
import java.io.*;
import java.util.*;

public class Gates_sortingBubble{

public static void main(String[] args)throws IOException{

  String amountS;
  amountS = JOptionPane.showInputDialog(null, "How many numbers would you like to sort?",
        "Sorting Arrays", JOptionPane.INFORMATION_MESSAGE);
  int amount = Integer.parseInt(amountS);

  JOptionPane.showMessageDialog (null, "Please enter " + amount + " numbers you wish to sort.",
        "Sorting Arrays", JOptionPane.INFORMATION_MESSAGE);

  int[] numbers = new int [amount];

  for(int i = 1; i <= amount; i++){
     String tempS = JOptionPane.showInputDialog("Number " + i + ": ");
     int temp = Integer.parseInt(tempS);
     numbers[i] = temp;
  }

  sort(numbers);

}

public static void sort(int[] tosort){

  int[] original  = tosort.clone();

  int j;
  boolean flag = true;     //set flag to true to begin first pass
  int temp;       //to hold the variable

  while(flag){
     flag= false;   //set flag to false awaiting a possible swap
     for( j=0;  j < tosort.length -1;  j++ ){
        if ( tosort[ j ] < tosort[j+1] ){
           temp = tosort[ j ];     //swap the array elements
           tosort[ j ] = tosort[ j+1 ];
           tosort[ j+1 ] = temp;
           flag = true;       //shows a swap occurred
        }
     }
  }

  print(tosort, original);
}

public static void print(int[] sorted, int[] unsorted){

  JOptionPane.showMessageDialog (null, "Your original five numbers are: "
           + Arrays.toString(unsorted) + ". \nYour new five numbers are: "
           + Arrays.toString(sorted) + ".", "Sorted Arrays", JOptionPane.INFORMATION_MESSAGE);
}

}

A: Your for loop in the main method goes from 1 to amount, but the array indexes of the numbers array range from 0 to amount-1. So in that loop, change:
numbers[i] = temp;

To:
numbers[i - 1] = temp;

And it will work.


text:
Q: How to run an installed file after installation? I have a setup project in c#. i want that setup run 2 exe file from the installed files after installation. How can i set which file to be run after installation.
Any suggestion would be highly appriciated

A: Add a custom action as below...

After the install complete, it should run the application automatically.
Launching Your Application After Install using Visual Studio


text:
Q: Angular ng build --watch seems to be broken in angular version 11 During development of angular libraries, I build the libraries on-the-fly using the ng build <lib> --watch. Setup is according to the official Angular docs at: https://angular.io/guide/creating-libraries  I am symlinking the libraries into my project with npm link. My angular 11 project is compiled using the Ivy compiler. My library is using the View  Engine compiler. The ng serve command uses ngcc to add the Ivy specific extras to the library (the build artifact in dist)
However, this approach does not work anymore for a new Angular 11 project. Everytime that the library gets rebuilt by the watcher, the application served by ng serve loses track and needs to be restarted afresh.
I tried downgrading angular to 10.x and sychronized the typescript compiler version in the library and the application project.
Restarting the ng serve of the project leads to: Tried to overwrite *.component.d.ts.__ivy_ngcc_bak with an ngcc back up file, which is disallowed. all the time. Only thing that helps in that case is restarting the ng build <lib> --watch process.
It seems to me that the in-limbo status of Ivy has thoroughly broken the library development experience using npm link.
Has anyone ideas about what has changed in Angular 11 that causes this problem?

A: I came across a nice solution that did not work for Angular 11, however, after downgrading to Angular 10, this works. The idea is to add an extra build configuration to the library for compiling in Ivy mode. Even ng build <lib> --watch is possible with this approach.
The solution is described here: https://github.com/angular/angular/issues/33395#issuecomment-693306453


text:
Q: How to retrieve GPS location from videos captured by iOS devices using Swift? I have been trying to extract GPS metadata from video captured by iphone. The following code produces the following result:
let asset = AVAsset(url: videoURL)
let allFormats = asset.availableMetadataFormats
allFormats.forEach {
    let metadataItems = asset.metadata(forFormat: $0)
    metadataItems.forEach {
        print("key: \($0.key!)")
        print("data: \($0.value!)")
        print("---------")
    }
}

Result is:
key: com.apple.quicktime.make
data: Apple
---------
key: com.apple.quicktime.model
data: iPhone 7
---------
key: com.apple.quicktime.software
data: 13.3
---------
key: com.apple.quicktime.creationdate
data: 2019-12-03T16:10:08+0300
---------

It means for me that AVFoundation gives only poor metadata information. But how to get GPS metadata? I know that captured videos contain geotags because exiftool extracts GPS metadata. Similar questions have already been raised here. But I could not find the answers on the merits.


text:
Q: Counting the amount of users or executions of an application. I made a program that gets the data from the clipboard and saves it in a string variable. Then it looks for specific words in that string and generates several URLs. Afterwards it open the browser and shows each URL in an own tab.
Some of my friends already use this program frequently and I want to have some statistics about how often. I simple counter variable would be enough but I need to get access to it.
I came up with two options that could work:

*

*I could send an email to a specific adress every time my app is executed. Then I can track the amount of uses by manually or automaticly counting the amount of emails in the postbox. I think this would be a Vers dirty solution.

*I could create and publish a website containing a counter. This counter could be refreshed by my application. This solution is a bit better I think but a lot more work for just one single counter.
Do you have better ideas to solve my problem or is one of mine already a good one?
Thank you in advace!

A: You can use Measurement Protocol Overview. This provides you statistics of usage your application compared with Google Analytics. You can see even a geo statistic, version distribution, crash reports. It is easy to use it from .net. It is just about requesting http request to google.


text:
Q: Is there a way to export functions in C static library? i am testing some C code in Rust, but rust only links to C static libraries on windows.
The problem is that the exported C functions are only exported to a Dynamic Library, and not to a Static one, since I can't use dlls in rust, i can't really link to the library with no exported symbols (if I try to, rust complains about unresolved references).
Some things I tried:

*

*Normal linking: these worked for a compilation one time, but I lost it, and since all the other normal ones go wrong.

*Static lib linked with Dynamic lib: sure, but it did not work, nor did the exported symbols appear in dumpbin /exports, or did the static lib rely on the dynamic lib.

*Static linked to Object linked to Dynamic: what
Code:
C:
// Note this is compiled with CMake to generate both a DyLib and a Static Lib.

#define EXPORT __declspec (dllexport)

EXPORT int my_func (void) {
    return 3;
}

Rust:
// build.rs:

fn main () {
    println!("cargo:rustc-link-search=native=path/to/my/lib");
}

// lib.rs:

#[cfg (test)]
mod tests;

// No *-sys crate for simplicity
pub mod sys {
    #[link (name = "my_lib")] // since Windows msvc linking is based on static libs, no matter what it is going to search for a static lib anyway...
    extern {
        pub fn my_func () -> i32; // libc::c_int is an alias to i32 on my machine
    }
}

// tests.rs:

use crate::sys;

#[test]
fn my_func_works () {
    assert_eq!(3, unsafe { sys::my_func () });
}

A: In your build script, you're telling cargo where to look for your library, but you never tell it to actually use the library. You need to add this to your build.rs:
println!("cargo:rustc-link-lib=native=my_lib.lib");

Note that the cargo docs have this to say about rustc-link-search (emphasis mine):

The rustc-link-search instruction tells Cargo to pass the -L flag to the compiler to add a directory to the library search path.

and about rustc-link-lib:

The rustc-link-lib instruction tells Cargo to link the given library using the compiler's -l flag.

A: It is way out of scope for this answer, but this is why attributes and declspecs are such an anathema to making software work.
If you have a library; that library has some names which have a global scope.  For example, you could have a procedure called ShaveMyBall for grooming a football pre-game.  In a library, ShaveMyBall might just exist, but you might have some requirements about linking with externals, so that ShaveMyBall might need to be prefixed with MyHairyBits_.
This opposing requirements can readily be solved by symbol manipulation utiities rather than a grotesque infrastructure between programming languages.   A few simple object file manipulations can change ShaveMyBall into MyHairyBits_ShaveMyBall.
But, if you insist on using odd, poorly defined, and even worse, partially defined by a standards committe, you will end up with something that may work on occasion, which outside of setting you up for a microsoft buyout, is typically the death knell for any company.


text:
Q: Hide parent element if img src = null I would like to hide the td containing the image if the image src inside of the td is null.
I tried the following, but it would hide more than just the td i was trying to target:

$('td').each(function() {
    if($(this).find('img').attr('src') == "null"){
        $(this).css('display', 'none');
    }
    });

          <input name="test" value="1" type="radio">

          <input name="test" value="1" type="radio">

          <input name="test" value="1" type="radio">

          <input name="test" value="1" type="radio">

Any help would be greatly appreciated, still learning :)

A: The simplest solution using jQuery:
$('td:has(img[src="null"])').hide();

or slightly faster:
$('td').has('img[src="null"]').hide();

A: You could also try with this

A: Should be a short line like this: $('img[src="null"]').parents('td:first').hide();
If need to target all of the parent td ancestors  $('img[src="null"]').parents('td').hide();  remove pseudo :first selector,


text:
Q: How to use python to write to s3 bucket I have a postgres database in aws that I can query from just fine using python and psycopg2. My issue is writing to an s3 bucket. I do not know how to do that. Supposable, you have to use boto3 and aws-lambda but I am not familiar with that. I've been trying to find something online that outlines the code but one link doesn't seem to have asked the question correctly: how do I send query data from postgres in AWS to an s3 bucket using python?. And the other, I don't understand how this example works A way to export psql table (or query) directly to AWS S3 as file (csv, json).
Here is what my code looks like at the moment:
import psycopg2
import boto3
import os
import io
#setting values to read

os.environ['AWS_ACCESS_KEY_ID'] = "XXXXXXXXXXXXX"

os.environ['AWS_SECRET_ACCESS_KEY'] = "XXXXXXXXXXXX"

endpoint = "rds_endpoint"
username = 'user_name'
etl_password = 'stored_pass'
database_name = 'db_name'
resource = boto3.resource('s3')
file_name = 'daily_export'
bucket = "my s3 bucket"

copy_query = '''select parent.brand as business_type
                , app.business_name as business_name
            from hdsn_rsp parent
            join apt_ds app
            on parent.id = app.id'''

def handle(event, context):

    try:
        connection = psycopg2.connect(user= username
                                        , password= etl_password
                                        , host= endpoint
                                        , port="5432"
                                        , database= database_name)

        cursor = connection.cursor()
        cursor.execute(copy_query)
        file = io.StringIO()
        #cursor.copy_expert(copy_query, file)
        #resource.Object(bucket, file_name+'.csv').put(Body=file.getvalue())

    except(Exception, psycopg2.Error) as error:
        print("Error connecting to postgres instance", error)

    finally:
        if connection:
            cursor.close()
            connection.close()

    return("query has executed and file in bucket")

If leave the commented part in then my code executes just fine(running from local machine), but when I uncomment it, remove the handler and put it in a function, I get my success back but nothing is in my s3 bucket. I thought I had permissions issue so I created a new user and didn't give permissions to that bucket so it would fail and it did, so permissions aren't an issue. But, I don't get what is going on with #cursor.copy_expert(copy_query, file) #resource.Object(bucket, file_name+'.csv').put(Body=file.getvalue()) because it's not placing the file in my bucket.
I'm new here and new to writing code in aws so please be patient with me as I am not entirely sure how to ask the question properly. I know this is a big ask, but I am so confused as to what to do. Could someone please assist me on what corrections I need to make?


text:
Q: angular material mat-accordion on click event top scroll in not working Angular Material -  while click the expansion panel header will call the onExpand function in that time window scroll  to top (or) change the position  not working
onExpand(){
    window.scrollTo(0,0);
}

<mat-accordion>
  <mat-expansion-panel class="Alert" [expanded]="false" #Completed>
    <mat-expansion-panel-header (click)="Completed.expanded?onExpand():onCollapse()">
      <mat-panel-title>

        Completed
      </mat-panel-title>
    </mat-expansion-panel-header>

    <mat-card *ngFor="let alrt of alerts" style="display: inline-block;border:0.6px solid #80808063;">

{{alrt.nudge_entity_name}}

{{alrt.nudge_amount | currency:"INR":'symbol':'1.0-0'}}

          <mat-progress-bar mode="determinate" value="40"></mat-progress-bar>

{{alrt.nudge_msg}}

    </mat-card>
  </mat-expansion-panel>
</mat-accordion>

A: If you want to scroll to the top of the page after you clicked a mat-expansion-panel header, then I suggest you use afterExpand as described in the Angular Material documentation:

@Output() afterExpand: EventEmitter
An event emitted after the body's expansion animation happens.

Here is a quick stackblitz I threw together that shows it in action. Just scroll a bit down and click on a expansion panel header, it will open the panel and immediately scroll to the top of the page.
app.component.html
<mat-expansion-panel *ngFor="let i of largeArray" (afterExpand)="scrollToTop()">

</mat-expansion-panel>

app.component.ts
scrollToTop() {
  window.scrollTo(0, 0);
}


text:
Q: Origin of "hating on" What is the origin of the slang phrase hating on?
Google Trends suggests that the phrase did not enter the lexicon until early 2009. I'm curious where the phrase originated.

As Stefano Palazzo noted, it appears that the Google Trends data is suspect. I did a search on a lyrics search engine and found a reference to a 2003 song named Hatin' On You by American R&B singer-songwriter Amerie, released July 30, 2002. So the phrase goes back at least that far, and probably farther.

A: Trawling USENET, the earliest reference I found was a review posted from a website to rec.music.hip-hop 19th August 1996:

Jay-Z "Can't Knock the Hustle" (Roc-A-Fella)
O-D.U.B.: Man...and I thought "Ain't No N-" was radio-friendly...guess Jay
  Z one upped himself on this aimed-for-plat-status single.  I'm not hating on it
  either...it flows well...I'd dance to it in a club and Mary J sounds good. It's
  not a hip hop classic by any means, that's for sure... Take it for what it's
  worth...

This also matches up with Sam's answer pointing to a track recorded between 1997 and 1999, and pointing out "most early references to this phrase seem to come out of hip-hop and rap culture".

Edit: Found an earlier reference in alt.rap to "hatin on" from 18th July 1996, again about Jay-Z:

Yo...
       I could bet my life...that blahzay blahzay new album Blah, Blah,
    Blah Will be The SHIT!!!! Thats all i gota say...
    And for all you NaS haters...Yo... you all just dont know good shit when
    it comes out your ass...so fuck you all
       And...JZ's lyrics are alright...but i think his beats are wack as hell...
    I dont like his style...its bullshit..
    Peace
    "How you like me now...i go PoW!!!!"

Well 2 outta 3 aint too bad, but take another listen to Jay-Z and peep
  his ability to flow with the track while effortlessy damn near
  speaking to you person to person.  But if you your just hatin on his
  material rap style, I can unserstand that cause that shit has more
  than had its turn.
  Peace

Again from rap/hip-hop culture and interesting to see the nearby haters.

A: It depends on what you regard as the same phrase.  For example, Shakespeare's sonnet 149 ends

But, love, hate on, for now I know thy mind,
     Those that can see thou lov'st, and I am blind.

This is an intransitive use.  The transitive use where X is hating on Y seems to mean X hates Y is more modern (and unnecessary).  Here is an example from the letters page of the April 2000 edition of Vibe

Why are people hating on Cash Money? I understand what Shaleena Smith means, but come on, let them experience their five minutes of success. Let them express their happiness.  Don't hate the playas, hate the game. - Janae Podgett, Jamaica, NY

There are several uses (with a g) in Raaid Khan's poem Stop Da Hatin from September 2004.

A: It may be fair to assume that there's just no data prior to 2009, as suggested by Wikipedia:

Originally, Google neglected updating Google Trends on a regular basis. In March 2007, internet bloggers noticed that Google had not added new data since November 2006, and Trends was updated within a week. Google did not update Trends from March until July 30, and only after it was blogged about, again.[2] Google now claims to be "updating the information provided by Google Trends daily; Hot Trends is updated hourly."
— (Google Trends)

Note that it says "Google did not update Trends from March until July 30 [2007][1]", i.e. it's missing slightly less than one and a half years. But as we can't study the inner workings of Google Trends, lack of data still seems more likely than the phrase suddenly springing into existence. A period of 1½ years for it to pick up seems somewhat reasonable.
1: although the phrasing is slightly ambiguous, the source, by its date of publication, suggests 2007
Note: this argument is of course flawed, and further evidence is needed to verify it - please take it as just an hypothesis.

A: As others have shown, Google Trends is simply inaccurate on this.  If you do a Google News search for "hating on" you'll find several entries from before 2009. The earliest I saw was from 2001.
The earliest reference I could find was on Dr. Dre's album The Chronic 2001. From the song Some L.A. Niggaz:

Anybody hatin on us can [do something unpleasant]

According to Wikipedia, the album was recored between 1997 and 1999, so it existed at least at that point.  Most early references to this phrase seem to come out of hip-hop and rap culture.

A: Actually I first heard it as a kid on an NYC subway in 1992 (I would have been about nine.) The phrase is at least as old as that and probably a bit before; it's origin is from Black American English, not rap music itself (the words out of the hooker's mouth in Taxi Driver are a variant.)

A: I cannot help with the direct history of this phrase, but the form seems similar to:

Pile on the hate
They keep on hating

In terms of prepositions, on seems to be only real candidate. I find all of the following awkward:

Stop hating at me
Stop hating to me
Stop hating by me
Stop hating up me
Stop hating with me

While you could suggest that the preposition is unneeded ("Stop hating me"), using hating this way changes the connotation from an emotion to an action. "Hating on" something is more akin to ranting or raging than simply stewing in invisible disgust.
As such, I wouldn't be surprised to find that this phrase has no common starting point or, if it does, it will be ridiculously difficult to find. Henry's answer regarding Shakespeare is a good example of how hard this will be to track down.
I found plenty of older uses using NGrams. Here are two from before 1900:

Well I knew The purport of his message, now declared; 'Tis such a one as foe might send to foe; The torture well becomes the Torturer! Then let him wreak his utmost hate on me, Loose all his stores of wrath; on me be thrown

The hit was in a review of Medwin's "Prometheus Bound" (translated from Aeschylus) which was first published in 1832.
The second was published in Frank Leslie's Pleasant Hours Volume 30. The book bears the date 1881.

You have looked scorn and hate on me often with these handsome eyes, you have railed at me often with these handsome lips, and now I will take righteous vengeance upon both.

However, both of these are much close to the idea that someone is piling on or actively causing hate to someone than "hating on" implies. But stepping from this to "hating on" seems reasonable.

A: It comes from black culture. Artists like Betty Davis referred to "haters" in her song "if I'm in luck" and it was repopularized in Bay Area Street lexicon back in the early nineties with artists like MC pooh and Spice 1 "Playa hatas". After the explosion of a favorite disparaging phrase calling some one a Playa Hater, for lack of appreciations for slick behavior, Hater resurfaced as the quick direct aggressive retart to someone disapproving of your idea or approach or your I'll gotten gains. All in all, black culture is the reason.

A: The practice of using the preposition "on" as in "peace on you" or "love on him" goes back to the 70s at least.  (I remember my college roommate being fond of the use.)  Saying "hate on Fred Flibber" to suggest you wish Fred ill would not be at all inconsistent with this practice, and likely has been done on occasion all along.
And the use of the adverb "on" to indicate a continuing condition, as in "love on" or "boogie on", has been well established for decades as well.  (The song "Boogie On" was recorded by Alvin Lee and Company in 1969 and released in 1972.)
The use of the gerund form of a verb such as "hurt" or "hate" to replace the equivalent noun, as a sort of emphasis, is also a well-established practice in urban vernacular.  I can't guess at an origin date, but there's no reason to believe it does not go back 50 years or more, given that it's a perfectly legitimate construction.
And there's certainly nothing "shocking" to this 66-year-old white Midwesterner in "Don't be hatin'!"
All in all, there's nothing remarkable about "hating on".  If it has obtained some sort of recent popularity it's likely due to a use in popular music or in a movie, but this would merely be briefly pumping up a construct that has lurked in the language for decades.

A: The two earliest matches for "hate on"/"hatin' on" that Elephind newspaper database searches turn up are from the same San Francisco Bay Area publication, in 1998 and 1999.
From Earl Vanbuskirk, Jr., "They Want It All: LOX," in the [Pittsburg, California] Los Medanos College Experience (February 27, 1998):

As for all of you that are still caught up in this East Coast/West Coast drama, let it rest in peace with Pac and Biggie. Stop hatin' on Bad Boy and show love where love is due and give The LOX their props. After all it's all music, right?

And from Keyairra Patterson, "United We Stand Divided We Fall," in the [Pittsburg, California] Los Medanos College Experience (November 6, 1999):

The problem here if you haven't noticed, there is no community unity or at least not enough and it is accompanied with two sicknesses which make it even worse. These sicknesses are hate and discrimination and whether you accept it or not, those are sicknesses. You may not agree with a lot of things people do or even say but that doesn't give you the right to hate them or hate on them. You may despise the things that people do or the way people live, but hate is a strong word and you really should be careful when you use it because it promotes bad carma.

The second instance quoted above is interesting because it indicates that—even at that early date—the writer sees a clear distinction between "hating" and "hating on." Regrettably, she doesn't spell out exactly what that distinction is.
Evidently, the expression was firmly in place in the Bay Area by the end of the 1990s. It is not at all clear, however, where the expression originated. Hugo's citations of USENET occurrences from 1996 indicate that there was plenty of time for the expression to have originated elsewhere in the United States and migrated to the Bay Area by 1998.

A: A line from the movie Malibu's Most Wanted that appeared widely in the previews was "Don't be hatin". It got traction and I suspect morphed into "hatin on".

A: The movie Taxi Driver showed a scene where some black hookers are fighting and one of them yells "Don't be hating". It was so random and I was shocked  to hear the phrase. It seems to me that this was a common phrase in the culture at that time and it made its way back into the mainstream.


text:
Q: How to make systemd message not show in /var/log/message Custom applications in the systemd how to customize the log path, the default to / var/log/message

A: I have solved this problems by using
ExecStart=/bin/sh -c '/apppath/appname > /filepath/filename 2>&1'

https://www.freedesktop.org/software/systemd/man/systemd.service.html


text:
Q: Can I animate my mapView like with SatNav I'm using MapKit to load a MKMapView and loading KML files to display a route with polylines between the designated points. I've seen a similar Android app using Google Maps that animates the route and runs it from start to finish.
I've been through the MapKit Framework documentation and I can't find anything that suggests I can do the same thing using Apple Maps.
If I'm wrong and it is possible I would be grateful for any information

A: The only way to resolve this issue is import the Google maps framework, which works perfectly well alongside MKMapkit.
There is a facility within Google Maps that enables the developer to animate their route.


text: Q: ¿Como extraer el fragmento de una cadena de texto que es variable? tengo una columna en SQL pero que tiene un formato parecido a JSON. Quisiera extraer unicamente el valor de ReportName : ""ReportName"":""Comercial - Direccion Sectores 2019"". El problema es que el ReportName nunca se llama igual. Estoy trabajando con Integration Services y se me ocurre hacerlo con una columna derivada pero sinceramente no se que expresión o función utilizar.


text:
Q: Loki::Factory throwing an exception on program exit I'm trying to use Loki::Factory in a project which is compiled with VC8 (I'm not allowed to switch to a newer compiler). I'm having an issue when the program exits, which I can reproduce with this basic code (which is the very least you might want to achieve when using a factory)
#include "stdafx.h"
#include <loki/Factory.h>

struct Base{};
Loki::Factory< Base, int> factory;

struct Derived : public Base{};
Base* buildDerived(){
    return new Derived();
}
namespace {
    bool registeredD = factory.Register(1, buildDerived);
}

int _tmain(int argc, _TCHAR* argv[])
{
    system("pause");
    return 0;
}

everything is fine up to when the system gets to a pause asking for the use to press a key (as for system("pause")); when I press the key, however, the program aborts, because of an unhandled exception, thrown from within the function
~auto_ptr()
{   // destroy the object
delete (_Ty *)_Myptr;
}

which can be found in the visual studio file "memory". The exception is an access violation and the stack starts with:
compmgr.dll!std::auto_ptr<Loki::FunctorImpl<Interface2D::IElement *,Loki::NullType,Loki::SingleThreaded> >::~auto_ptr<Loki::FunctorImpl<Interface2D::IElement *,Loki::NullType,Loki::SingleThreaded> >()  Riga 718 + 0x32 byte  C++
    compmgr.dll!Loki::Functor<Interface2D::IElement *,Loki::NullType,Loki::SingleThreaded>::~Functor<Interface2D::IElement *,Loki::NullType,Loki::SingleThreaded>()  + 0x2b byte    C++

I couldn't find any reference to the use of std::auto_ptr from Loki on the internet.
How can the problem be solved?

A: Since i always wanted to look at Loki libraries i used this chance. Well, to start, the issue is not connected with MSVC versions, i did run the same example on VS2008 and Loki libraries build with VS2008 and had the same results. Second:
#include "stdafx.h"
#include <loki/Factory.h>
#pragma comment(lib, "loki_D.lib")
struct Base{};

struct Derived : public Base{};
Base* buildDerived(){
    return new Derived();
}

int _tmain(int argc, _TCHAR* argv[])
{
    Loki::Factory< Base, int> factory;
    bool registeredD = factory.Register(1, buildDerived);
    //system("pause");
    return 0;
}

This works fine. I examined the crash at your example and seems that the Factory is deleting the association container where the functor you created is supposed to be after it is already destroyed. Seems to me that this is because Loki is hooking up atexit() and deleting some stuff there (not sure why, I guess to handle Singleton objects), that is where your Functor gets deleted, and then after the the destructor of your factory is called and then the erase call on the association container fails. Well - if it's not a huge deal, don't make the factory a global object. If it is a huge deal, try to debug and find why Loki is doing the stuff it does in atexit, maybe you need to set up something more. But at least as far as I can see, this is another bad case of undefined behaivor for destruction of global objects.
EDIT: Loki Factory-Singleton throws "dead reference detected" in try-catch-block on ARM , the macro LOKI_FUNCTOR_IS_NOT_A_SMALLOBJECT could be relevant, since I would guess that triggers the destrcution, maybe without this the object will not get in the list of objects destroyed in atexit but still, my knowledge about Loki libraries is not good enough. Maybe you need to define a policy of lifetime of the singleton or something like that.

A: The problem is with lifetime management. I report the solution here for reference:
#include "stdafx.h"
#include <loki/Factory.h>
#include <loki/Singleton.h>

struct Base{
    virtual ~Base(){};
};
typedef Loki::SingletonHolder< Loki::Factory<Base, int> > Factory;

struct Derived : public Base{};
Base* buildDerived(){
    return new Derived();
}
namespace {
    bool registeredD = Factory::Instance().Register(1, buildDerived);
}

int _tmain(int argc, _TCHAR* argv[])
{
    system("pause");
    return 0;
}


text:
Q: Wix DTF Custom Action Equivalent of WcaAddTempRecord I am trying to use Wix DTF custom action to write MSI runtime session values to registry.
This i wanted to achieve by adding temporary record to "Registry" table in the database.
Since c++ had a WcaAddTempRecord method to achieve this, really wanted to know is there any equivalent method in DTF.
Note: I tried using Session.Database.OpenView to insert the record, but consistently i am getting update failed error, due to session database readonly property.
Can someone please suggest the best approach for this situation?

A: The MSI database is read-only during the installation. So you cannot add permanent rows. However, you can insert temporary rows. Once you get the View back from the Session.Database.OpenView() then use the InsertTemporary() method on the View object to add temporary rows.
That's how WcaAddTempRecord() gets the Temp in its name. :)

A: This is my "go to" helper method:
private static void InsertTempRecord(Session session, string tableName, Object[] objects)
{
  Database db = session.Database;
  string sqlInsertSring = db.Tables[tableName].SqlInsertString + " TEMPORARY";
  session.Log("SqlInsertString is {0}", sqlInsertSring);
  View view = db.OpenView(sqlInsertSring);
  view.Execute(new Record(objects));
  view.Close();
}

For more information see:
Dynamic Windows Installer UI


text:
Q: pyDrake import Error: cannot import name 'DrakeVisualizer', ClippingRange, DepthRange, et al I am using the latest pydrake docker image and trying to visualize some of my results. Everything else in pydrake imports and works really well. Specifically packages in the pydrake.geometry cannot be imported correctly for some reason. I need to use a number of methods related to DepthRenderCamera. Another colleague is able to import everything just fine in the same setup. The code is similar to the the pydrake tutorial here. https://notebooks.gesis.org/binder/jupyter/user/robotlocomotion-drake-qtseq8o3/notebooks/tutorials/rendering_multibody_plant.ipynb
Any pointers or help is appreciated!
from pydrake.geometry.render import (
ClippingRange,
DepthRange,
DepthRenderCamera,
RenderCameraCore,
RenderLabel,
MakeRenderEngineVtk,
RenderEngineVtkParams,
)

A: The ClippingRange binding wasn't added to pydrake until:
commit 9b7a97b302214002a320088761b4d76196503618
Author: Eric Cousineau <eric.cousineau@tri.global>
Date:   Wed Oct 21 18:24:51 2020 -0400

Your 20201013064707 revision is too old (2020-10-13).


text:
Q: Looking for help converting a plot in R into a binary (or other) string I'm fairly new to R, so I may be missing something obvious...but so far my Google-fu has utterly failed me and my attempt to solve this problem has resulted in the coding equivalent of printing something out, sending a fax, and then drawing a picture from the fax.
So, for example, if the plot was a picture of a smiley face (that's not my plot, but I was trying to have fun with it while pulling my hair out.  I was hoping to have something that works off of the image created by R but is fairly image agnostic) then I'm trying to return something like this...either in a single string or one for each row. (it could be any characters reflecting on and off, I was assuming binary would be the easiest)
000000000000000000000000000
000000000000000000000000000
000000000000000000000000000
000001100001100000000000000
000001100001100000000000000
000000000000000000000000000
000000000000000000000000000
000000000000000000000000000
000000000000000000000000000
000000000000000000000000000
000110000000001100000000000
000011000000011000000000000
000001111111110000000000000
000000000000000000000000000
000000000000000000000000000
000000000000000000000000000
000000000000000000000000000

That's the general idea, and so far my only near success has involved printing to disk and then re-reading it...which I'm 100% sure is a bad approach. I'm good with SQL and formulas, but R is a whole new world for me.
The reasoning behind this is that I'm delivering the information to a box that only can handle text and is designed to receive a string, but I can shrink the text down to a font size of '2'and essentially create a grid of pixels.  I've already added some semi-graphical text (bar charts with a repeat function, waffle charts with a bit more effort, that sort of thing)...and this is just me following the logical progression (and also, hopefully, saving a LOT of screen real estate)
I'm suspecting this is a lot easier than I'm making it, as it's essentially the step R goes through in the process of making a plot...but I've clearly failed.
Any help would be hugely appreciated!

A: I think that using gridGraphics package as in this thread, you might be able to achieve just that.
maybe some other libraries allow you to access the parameters of the plot as well...


text:
Q: In R phantomJS ran with Rselenium hangs after several iterations I'm using phantomJS to collect data from different sites. During data scrapping process I experience a lot of crashes when parsing sites or sites elements. Unfortunately nor phantomJS nor RSelenium don't provide any information or bag report in the console. Script just hangs without any warnings. I see that it is executing, but actually nothing happens. The only way to stop script from executing is to manually restart R. After several test I found that phantomJS usually hangs on executing remDr$findElements() commands. I tried to reran my code using firefox and RSelenium - it works normally. So the problem is in how phantomJS works.Does anyone experience anything similar when running phantomJS? Is it possible to fix this misbehavior?
I'm using:

*

*Windows 7

*Selenium 2.0

*R version 3.1.3

*phantomjs-2.0.0-windows

My code:
# starting phantom server driver
phantomjsdir <- paste(mywd, "/phantomjs-2.0.0-windows/bin/phantomjs.exe", sep="" )
phantomjsUserAgent <- "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36 OPR/28.0.1750.48"
eCap <- list(phantomjs.binary.path = phantomjsdir, phantomjs.page.settings.userAgent = phantomjsUserAgent )
pJS <- phantom(pjs_cmd = phantomjsdir)
remDr <- remoteDriver(browserName = "phantomjs", extraCapabilities = eCap)
remDr$open(silent = FALSE)

mywords <- c("canon 600d", "sony 58k","nikon","nikon2","nikon 800","nikon 80","nikon 8")
timeout <- 3

#'
#' Exceuting script
#'

for (word in mywords) {

  print(paste0("searching for: ",word))
  ss.word <- word
  remDr$navigate("http://google.com")

  webElem <- remDr$findElement(using = "class", "gsfi")
  webElem$sendKeysToElement(list(enc2utf8(ss.word),key = "enter"))
  Sys.sleep(1)

  print (remDr$executeScript("return document.readyState;")[[1]])
  while (remDr$executeScript("return document.readyState;")[[1]]!= "complete" && totalwait<10) {
    Sys.sleep(timeout)
  }

  print(paste0("search completed: ",ss.word))
  elem.snippet <- remDr$findElements(using="class name",value = "rc")

  for (i in 1:length(elem.snippet)) {

    print(paste0("element opened: ",ss.word,"  pos",i))
    print(elem.snippet[[i]])
    ss.snippet.code  <- elem.snippet[[i]]$getElementAttribute('innerHTML')
    print(paste0("element element innerHTML ok"))
    elemtitle <- elem.snippet[[i]]$findChildElement(using = "class name", value = "r")
    print(paste0("element title ok"))

    elemcode <- elemtitle$getElementAttribute('innerHTML')
    print(paste0("element innerHTML ok"))

    elemtext <- elem.snippet[[i]]$findChildElement(using = "class name", value = "st")
    ss.text <- elemtext$getElementText()[[1]]
    print(paste0("element loaded: ",ss.word,"  pos",i))

    elemloc <- elem.snippet[[i]]$getElementLocation()
    elemsize <- elem.snippet[[i]]$getElementSize()
    print(paste0("element location parsed: ",ss.word,"  pos",i))

  }

  print(paste0("data collected: ",ss.word))
}


text:
Q: jQuery UI Autocomplete bug with ie9 in ASP.MVC3 View Hi I'm using jQuery UI Autocomplete 1.8.11 in a ASP.MVC3 web app.
In the view, I have the following javascript code:
 $("#textUsername" + UserNameCounter).autocomplete({
        minLength: 2,
        source: function (request, response) {
            var params = {
                q: 5,
                term: request.term
            };
            var jsonData = JSON.stringify(params, null, 2);
            $.ajax({
                url: '@Url.Action("GetUsernames", "Controller")', type: "POST", dataType: "json",
                contentType: 'application/json; charset=utf-8',
                data: jsonData,
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            id: item.id,
                            label: item.label,
                            value: item.value
                        }
                    }));
                }
            });
        }
    });

This works neat in Chrome and FF, but it behavies strangely in IE9:
when I start typing words and while autocomplete is showing the results it just deletes the results and the focus in the textbox is lost..
While googling around I realized that this pluging should work in IE9, and that most of the problems peeps post on forums are quite different from mine and are mostly related to syntax errors or something alike. Does anyone have any idea why the plugin is behaving like this on the view I'm working on?
Thanks in advanced.


text:
Q: pure javascript auto scroll to bottom of a page then back up This script works fine if you are using jquery:
$('html, body').animate({ scrollTop: $(document).height() - $(window).height() }, 1000, function() {
    $(this).animate({ scrollTop: 0 }, 1000); });

However, I need this in pure JS. I assume this is possible. I need the page to scroll to the bottom, then back up and repeat like in this demo: http://jsfiddle.net/QUCWe/
Many thanks.

A: This is a quick mock up, hope it helps you get started. I got the easing equations from here.
Link to JSFiddle
var wrapper = document.getElementById("wrapper"); //get div
var h = wrapper.offsetHeight; //get height

scrollTo(h);

function scrollTo(x) {
    //elapsed
    var e;
    //duration in milli seconds
    var d = 1000;
    //b as in begin, where to start (you could get this dynamically)
    var b = 0;
    //start time, when the animation starts
    var s = (new Date()).getTime(); //start time
    //the magic
    var t = setInterval(function () {
        //calculate elapse time
        e = (new Date()).getTime() - s;
        //check if elapse time is less than duration
        if (e < d) {
            //animate using an easing equation
            window.scrollTo(0, ease(e, b, x, d));
        } else {
            //animation is complete, stop interval timer
            clearInterval(t);
            t = null;
        }
    }, 4);
}

//Info about the letters (I think)
//t = elapse time
//b = where to begin
//c = change in comparison to begin
//d = duration of animation
function noease(t, b, c, d) {
    t /= d;
    return b + c * (t);
}

function ease(t, b, c, d) {
    return Math.round(-c * Math.cos(t / d * (Math.PI / 2)) + c + b);
}

A: function scroll(speed) {

    document.body.scrollTop = $(document).height() - $(window).height();
    setTimeout(function(){
    document.body.scrollTop = 0;
    },1000);
}

speed = 1000;

scroll(speed)
setInterval(function(){scroll(speed)}, speed * 2);

http://jsfiddle.net/QUCWe/664/


text:
Q: Spring Roo 2.0, release date, 2016? Any  news about next release or roo 2.0-m2 or even better 2.0 m3? According informations from spring roo pages it could be probably in May but the project doesnt seemed to be very active. And what about milestone 3, is it going to be release in close future?looking-ahead-to-spring-ro0-2
I would like to start new project and it is difficult to choose old roo version, which wont be probably in future supported, or new untested roo.
It could help me to decide which way to go.

A: Take a look to the Roo 2.0 roadmap. Next release is Roo 2.0.0.M2


text:
Q: How to get values from IXLCells (OpenXML) I want to find the cell in an Excel sheet that contains a certain text using closedXML. I use the following command:
IXLCells RefCells =PortfolioWorksheet.Search(strInternalReference, CompareOptions.None, false);
Accoridng to the Watch window in Visual Studio, RefCells does contain the correct cell address: C8 in my case.
I tried obtaining this value with:
RefCells.First().GetValue<string>()
Unfortunately I get the string I searched for and not the cell address.
Hope you can help!
Bas

A: GetValue() returns the content (value) of the cell. To get the address use Address.ToString() to get the full address or Address.RowNumber and Address.ColumnLetter (or Address.ColumnNumber) to get its parts.


text:
Q: I am having 2 java spring micro services from one microservice service I am uploading a file using open feign client and from the other end I am trying to download the same file by invoking the second service from a different JVM, Is there a complete example of file upload and download using open feign client.
Service 1 runs on open feign (1 jvm) and calls service on another jvm which downloads the file without using open feign


text:
Q: Regex does not remove the special chars in split function I am using a regex to split a string into an array of substrings
Input: mark bill #special# #special method# johni
import re
re.split('[ #, #]+', 'mark bill #special# #special method# johni')

When I execute this command the result is: ['mark', 'bill', 'special', 'special method' 'johni']
That's right, but in string 'special' I don't want to remove the special chars #
I want this result:: ['mark', 'bill', '#special#', #special method#, 'johni']
Is it possible?
Thanks.

A: Rather than split you should use findall:
print re.findall(r'#[^#]*#|\S+', 'mark bill #special# #special method# johni')

Output:
['mark', 'bill', '#special#', '#special method#', 'johni']


text:
Q: Gmail Api integartion with Salesforce using Rest Api I want to send email from gmail.
Implementation will be like this.
In lightning component we will have a button named "Send", once someone click on it will trigger an email.
Is it possible? I have checked Trigger and workflow is not supported.
also in API documentation I can see they do not support all programming languages and need library as well.
Can anyone please help on this?
Thanks in advance.
Regards,
Pinaki


text:
Q: Trouble with OxyPlot Heatmap Windows 8.1 Universal App VS 2015: Plot won't draw When I run the program in the debugger all I get is the big gray "X"
However this is only happens with Heatmaps. I AM able to draw line plots.
I'm completely new to OxyPlot (I love it already) and I'm hoping there's something I'm leaving out that is required to draw HeatMaps.
The documentation for OxyPlot heatmaps is a little thin.
What am I missing?
Here's my MainPage.xaml:
    <Page
...
    xmlns:oxy="using:OxyPlot.Windows"
    mc:Ignorable="d">
    <Page.DataContext>
        <local:MainViewModel/>
    </Page.DataContext>
    <Grid x:Name="LayoutRoot" Background="White">
               <oxy:PlotView x:Name="MyHeatMap"   Model="{Binding plotModel1}"/>
    </Grid>

</Page>

And in MainPage,xaml.cs I say:
...
        namespace App1
    {
        using OxyPlot;
        using OxyPlot.Series;

        public class

MainViewModel
    {
        public MainViewModel()
        {
            this.plotModel1 = new PlotModel { Title = "Example 1" };

            this.plotModel1.Axes.Add(new OxyPlot.Axes.LinearColorAxis
            {
                Position = OxyPlot.Axes.AxisPosition.Right,
                Palette = OxyPalettes.Jet(500),
                HighColor = OxyColors.Gray,
                LowColor = OxyColors.Black
            });
            var heatMapSeries1 = new OxyPlot.Series.HeatMapSeries
            {
                X0 = 0.0,
                X1 = 1.5,
                Y0 = 0.0,
                Y1 = 4.0,
                Data = new Double[,] { { 0.1, 0.2 }, { 0.4, 0.1 }, { 0.3, 0.2 } }

            };

            this.plotModel1.Series.Add(heatMapSeries1);

        }
        public PlotModel plotModel1 { get; private set; }

    } ...

A: I got the same problem today. Everything is working except the Heatmaps. When using a Heatmap, the program is freezing. I tried the examples and debugged the OxyPlot source code to get an idea what causes this error. It turned out, that the problem occurs when converting a MemoryStream to an IRandomAccessStream. This is the source code which is doing this:
        private static async Task<IRandomAccessStream> ConvertToRandomAccessStream(MemoryStream memoryStream)
        {
           var randomAccessStream = new InMemoryRandomAccessStream();
           var outputStream = randomAccessStream.GetOutputStreamAt(0);
           var dw = new DataWriter(outputStream);
           var task = Task.Run(() => dw.WriteBytes(memoryStream.ToArray()));
           await task;
           await dw.StoreAsync();
           await outputStream.FlushAsync();
           return randomAccessStream;
        }

The program freezes when var task = Task.Run(() => dw.WriteBytes(memoryStream.ToArray())); is called. But I don't know why this does not work... as a workaround I moved the dw.WriteBytes(memoryStream.ToArray()) and doing this without Threading which then works fine and the Heatmaps are  displayed as intended. You then just have to wait for the ConvertToRandomAccessStream(MemoryStream memoryStream) call when setting the source of the BitmapImage.
Does anyone know why the WriteBytes method of the DataWriter causes the freeze when running inside a Task?
EDIT: I'am using OxyPlot Version 2015.1.893.0 for an Windows Store app


text:
Q: How can I make work ViewPager with RecyclerView inside NestedScrollView I am using NestedScrollView with ViewPager. NestedScrollView has a LinearLayout inside with some TextViews, TabLayout and ViewPager at the end. TextViews occupy most of the space and for ViewPager left a little space. ViewPager using two fragments, in one of them there is a few TextViews and ImageViews and in another fragment there is a RecyclerView.
When I set ViewPager's height to WRAP_CONTENT it takes only space that left and I can't scroll to see the rest of the first fragment, and the second fragment scoll inside little ViewPager.
When I set ViewPager's height to 1000dp for example, I am able to scroll down on first fragment, but the second fragment still scrolling inside little ViewPager. And after I scroll in fragment with RecyclerView scoll in the first Fragment not working anymore.
How can I fix scrolling problem and make ViewPager work with WRAP_CONTENT?
Here is my code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_scrollFlags="scroll"
        android:fillViewport="true">

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/mainBackground"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="SOME TEXT" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="SOME TEXT" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="SOME TEXT" />

            <android.support.design.widget.TabLayout
                android:id="@+id/tabLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <android.support.v4.view.ViewPager
                android:id="@+id/viewPager"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>

A: @StevenZhang's solution almost worked for me but there was a problem when two tabs have different heights, the smaller tab takes the height of the bigger tab.
Based on this answer about how to make a dynamic height ViewPager I made a solution in Kotlin
Custom View Pager
class CustomViewPager: ViewPager {
    constructor(context: Context) : super(context)
    constructor(context : Context, attrs : AttributeSet) : super(context, attrs)

    private var currentView : View? = null

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {

        currentView?.let {
            it.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
            val h = it.measuredHeight
            val height = if (h > 0) h else 0
            val newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
            super.onMeasure(widthMeasureSpec, newHeightMeasureSpec)
            return
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    fun measureCurrentView(currentView: View?) {
        this.currentView = currentView
        requestLayout()
    }
}

In your custom PagerAdapter override setPrimaryItem
private var currentPosition = -1

override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) {
    super.setPrimaryItem(container, position, `object`)
    if (position != currentPosition) {
      val fragment = `object` as Fragment
      val pager = container as CustomViewPager
      if (fragment.view != null) {
         currentPosition = position
         pager.measureCurrentView(fragment.view)
      }
   }
}

You may also need to set isNestedScrollingEnabled of your RecyclerView to false
recyclerView.isNestedScrollingEnabled = false

A: I think you should override ViewPager like this:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int height = 0;
    for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        int h = child.getMeasuredHeight();
        if (h > height) height = h;
    }
    heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

A: maybe you can try :
 NestedScrollView scrollView = (NestedScrollView) findViewById (R.id.nest_scrollview);
    scrollView.setFillViewport (true);

such as:https://stackoverflow.com/a/33385207/4035627


text:
Q: How to pass nextPage variable value from child to parent's router-link? Trying to set the value of <router-link :to="{nextPage}">from a child component to make the router-link dynamic.
Some of the research I did talked about adding a prop, but I'm not too sure where that should go. In <router-view :next-page="">?
When I do this I have two problems:
Problem 1: solved
Problem 2: an error message "The data property "nextPage" is already declared as a prop. Use prop default value instead."
App.vue
<template>

    <router-view :nextPage="['/']"></router-view>

    <router-link class="prev-slide" :to="'/'">
      Restart
    </router-link>
    <router-link class="next-slide" :to="nextPage">
      Next
    </router-link>

</template>

Welcome.vue

A: you need to use computed. if you don't know anything about this; let me give you an example:

new Vue({
  el: '#app',
  props: {
    current: {
      type: Number,
      default: 1
    }
  },
  computed: {
    next() {
      return this.current  + 1
    }
  }
})

{{current}}
|
{{next}}

if you need get current page from route:

new Vue({
  el: '#app',
  computed: {
    current() {
      return this.$route.params.page
    }
  }
})

{{current}}


text:
Q: Using Baer's criterion for abelian groups. I am currently working through the chapters on injectivity in Donald Passman's A Course in Ring Theory, and have run into conceptual difficulty while attempting one of the exercises. I am trying to prove that a group homomorphism $\sigma:A\to B$, with both groups abelian, is injective or surjective iff $\hat\sigma:B^*\to A^*$ is surjective or injective respectively. For any abelian group $G$ we define $G^*=\operatorname{Hom}(G,\mathbb Q/\mathbb Z)$. We define $\hat\sigma(\theta)=\theta\sigma$ (function composition). For notational convenience let us here define $D:=\mathbb Q/\mathbb Z$
I have been able to prove most directions, but have not quite completed proving that $\sigma$ being injective means that $\hat\sigma$ is surjective. To that end I fixed some $\theta\in A^*$. Now as $\sigma$ is injective, $\sigma^{-1}:\sigma(A)\to A$ is well defined. Thus we can define the map $\phi:=\theta\sigma^{-1}:\sigma(A)\to D$. If we can extend $\phi$ to a map $\tilde\phi$ acting on all of $B$ then we'd be done, for $\hat\sigma \tilde\phi=\theta$. (In fact $\hat\sigma\phi=\theta$, but we do not know whether $\phi\in B^*$). Now I suspect that somehow I can use Baer's criterion to get the desired extension, because $D$ is a divisible group, hence injective. The crux of my problem lies in the fact that to use it in the form presented in Passman, I need $\sigma(A)$ to be somehow identified with a right ideal of the ring $\mathbb Z$, and $B$ with $\mathbb Z$ itself, but I am unsure how to do that. I would appreciate help in knowing why I can extend $\phi$.

A: If you know that $D$ is injective, then you know that $\operatorname{Hom}_{\mathbb{Z}}(-,D)$ is an exact functor.
Thus if $0 \to A \to B$ is exact, then $B^* \to A^* \to 0$ is exact.

A: I am going to take the liberty of using $\sigma^*$ instead if $\hat{\sigma}$.
Since you mentioned Baer's criterion, I am assuming you know about injective modules. If $\sigma$ is injective then you can use the fact that $\mathbb{Q}/\mathbb{Z}$  is injective $\mathbb{Z}$-module. Namely, given $\theta \in A^*$, there exists $\theta'\in B^*$ such that $\theta = \theta'\sigma = \sigma^*(\theta')$.


text:
Q: How to make a database request in Uniface 9.7 How to make a database request in Uniface 9.7 with an Informix database?
Example:
I like to query a person with the id = 5 from the database with the columns 'name' and 'age'.


text:
Q: Handle android TextView's link click So i have a textView and sometimes my textView contains links, currently when i click in this link an intent with a list of downloaded browsers opens. now what i want is, i wanna open this link inside the current app, say in a WebView. how can i do this?
we do have multiple articles/questions  on same topic but i have no idea what this articles/questions are really about.
like this one https://gist.github.com/ksoichiro/3394338 gave me an ClassCastException
android.text.style.URLSpan cannot be cast to pb.myPackage.LinkUtils$SensibleUrlSpan
or this one handle textview link click in my android app
is there's any straight simple way to achieve this? please let me know.

A: You could use Chrome Custom Tabs, this is faster than a webview in loading webpages and is pretty simple to customize.
First include the Library:
dependencies {
    ...
    compile 'com.android.support:customtabs:25.1.1'
}

Then in your Activity when you call the method to open a browser add these lines of java:
String url = ¨https://google.com/¨;
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent intent = builder.build();
intent.launchUrl(this, Uri.parse(url));

Refer to it's docs for more customization at:
https://developer.chrome.com/multidevice/android/customtabs


text:
Q: ServerError unknown error: cannot get automation extensionfrom unknown error My wdio configuration file
      args: [
            '--enable-automation',
            '--start-maximized',
            '--disable-gpu',
            '--headless',
            '--no-sandbox',
            '--test-type',
            '--disable-infobars',
            '--test-type=browser',
          ],

I have such error.
30 passing (191.50s)
3 pending
1 failing

1) [p] starts stage for students:
unknown error: cannot get automation extensionfrom unknown error: page could not be found: chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
running
Error: unknown error: cannot get automation extensionfrom unknown error: page could not be found: chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
    at new ErrorHandler.RuntimeError (node_modules/webdriverio/lib/utils/ErrorHandler.js:93:12)
    at Request._callback (node_modules/webdriverio/lib/utils/RequestHandler.js:59:33)
    at Request.self.callback (node_modules/webdriverio/node_modules/request/request.js:373:22)
    at Request.<anonymous> (node_modules/webdriverio/node_modules/request/request.js:1318:14)
    at IncomingMessage.<anonymous> (node_modules/webdriverio/node_modules/request/request.js:1266:12)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)

Exited with code 1

Chrome last stable version from official Google repository
webdriver last version 2.30


text:
Q: How to get a universal binary with both architectures from Homebrew on Mavericks I need to install Cairo for the use of a 32-bit application on Mavericks.
After first uninstalling libpng, I have succeeded in forcing a complete recompile of Cairo and all its dependents (libpng, fontconfig, pixman, glib) using
brew install --build-from-source cairo

Showing the brew info on these libraries indicates they were built from source, and built as a universal binary.  However lipo -info reports the architecture only as x86_64.
How can I get Homebrew to install Cairo and all its dependents with both i386 and x86_64 architectures?
Thanks for the help.


text:
Q: In there a way in Vue v-for to access two elements in each iteration? I want to show two ConditionCardComponents per slide.
I have added two, but I only have access to one(1) condition item in each iteration.
The outcome should look like we have two ConditionCardComponents in one slide.
This is with the outcome with one card. Imagine the desired outcome as two of these card in each slide.
 <template v-for="(condition, index) in dealData.Conditions" :key="index">
        <q-carousel-slide :name="index" class="row no-wrap slide-card">
          <ConditionCardComponent
            class="full-height full-width"
            :condition-details="condition.Details"
            :condition-status="condition.Status"
          />
          <ConditionCardComponent
            class="full-height full-width"
            :condition-details="condition.Details"
            :condition-status="condition.Status"
          />
        </q-carousel-slide>
      </template>

It is easy to do this with a finite number of hardcoded cards. All I would do is put every two card in one slide and give it a 'col-6' style.
The issue is when I am reading from an object.

A: v-for can't handle this case natively, you will have to create your own data structure for this.
You can create a computed property being an array of tuples like: [[condition1, condition2], [condition3, condition4], ...]
<script setup>
const slides = computed(() => {
  const slides = []
  for(let i = 0; i < dealData.Conditions.length; i += 2) {
    slides.push([dealData.Conditions[i], dealData.Conditions[i+1]])
  }
  return slides
})
</script>

<template>
  <template v-for="(conditionsTuple, index) in slides" :key="index">
    <q-carousel-slide :name="index" class="row no-wrap slide-card">
      <ConditionCardComponent
         class="full-height full-width"
         :condition-details="conditionsTuple[0].Details"
         :condition-status="conditionsTuple[0].Status"
       />
       <ConditionCardComponent
          class="full-height full-width"
          :condition-details="conditionsTuple[1].Details"
          :condition-status="conditionsTuple[1].Status"
       />
    </q-carousel-slide>
  </template>
</template>

A: I've never heard of that behavior before, but I think the easiest way would be to customize your array for your needs. For example, in your script you could do something like this:
export default: {
 data(){
  myArray : ['1','2','3','4','5','6']
 },
 computed: {
  myCustomizedArray(){
    return this.myArray.reduce((myFinalArray, item, index, wholeArray)=>{
     if(index%2===0){
      return [...myFinalArray, [item, wholeArray[index+1]]]
     }
     return myFinalArray
    }, [])
  }
 }
}

This computed method myCustomizedArray() will return an array of arrays like so
[[1, 2],[3, 4]]

If the length of the array is an odd number it will return last nested array with an undefined value, but I'll leave that task to you. This is the way I would do it


text:
Q: Add line segments to histogram in ggplot2 with radar coordinates I am trying to make a polar histogram in ggplot2 with annotation lines which are not radial lines.
The simple approach with coord_polar gives curved lines:
library(ggplot2)

d = data.frame(x=rep(seq(0, 350, 10), times=1:36))
lines = data.frame(x = c(40, 90, 150, 220, 270),
y = c(20, 20, 20, 20, 20),
xend = c(115, 165, 225, 295, 345),
yend = c(5, 5, 5, 5, 5))

ggplot(d, aes(x)) +
  geom_histogram(binwidth = 10) +
  geom_segment(data = lines,
               aes(x, y, xend = xend, yend = yend),
               color = 'red') +
  coord_polar() +
  scale_x_continuous(limits=c(0, 360))

Second try uses coord_radar, from various sources on StackOverflow and mail lists:
coord_radar <- function (theta = "x", start = 0, direction = 1)
{
 theta <- match.arg(theta, c("x", "y"))
 r <- if (theta == "x")
        "y"
      else "x"
 ggproto("CoordRadar", CoordPolar, theta = theta, r = r, start = start,
      direction = sign(direction),
      is_linear = function(coord) TRUE)
}

ggplot(d, aes(x)) +
  geom_histogram(binwidth = 10) +
  geom_segment(data = lines,
               aes(x, y, xend = xend, yend = yend),
               color = 'red') +
  coord_radar()

This fails completely:

I can get the lines to draw if I use grouped lines instead of segments:
lines2 = data.frame(x = c(40, 115, 90, 165, 150, 225, 220, 295, 270, 345, 330, 45),
y = c(20, 5, 20, 5, 20, 5, 20, 5, 20, 5, 20, 5),
group = c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6))

ggplot(lines2, aes(x, y, group = group)) +
  geom_line(color = 'red') +
  coord_radar() +
  scale_y_continuous(limits = c(0, 36)) +
  scale_x_continuous(limits = c(0, 360))

but I still need the histogram...
Any ideas?

A: I just answered a similar question on the geom_segment portion. The long and short of it is this: the draw_panel function of the ggproto Geom objects behind geom_segment / geom_histogram have two different methods of drawing the respective geoms, depending on whether the ggplot object's coordinate system is linear or non-linear.
coord_polar is non-linear (we can run CoordPolar$is_linear() to confirm this), so the geoms are drawn correctly using the methods associated with non-linear coordinate systems. coord_radar is linear, so the linear methods are used instead, and cause havoc.
We can get around this by defining tweaked versions of relevant Geoms that only include the non-linear methods, and geom_* functions that call on them instead of the original Geoms.
geom_segment2:
GeomSegment2 <- ggproto("GeomSegment2",
                        GeomSegment,
                        draw_panel = function (data, panel_params, coord, arrow = NULL,
                                               arrow.fill = NULL, lineend = "butt",
                                               linejoin = "round", na.rm = FALSE) {
                          data <- remove_missing(data, na.rm = na.rm,
                                                 c("x", "y", "xend", "yend", "linetype",
                                                   "size", "shape"),
                                                 name = "geom_segment")
                          if (ggplot2:::empty(data))
                            return(zeroGrob())
                          # remove option for linear coordinate system
                          data$group <- 1:nrow(data)
                          starts <- subset(data, select = c(-xend, -yend))
                          ends <- plyr::rename(subset(data, select = c(-x, -y)),
                                               c(xend = "x", yend = "y"),
                                               warn_missing = FALSE)
                          pieces <- rbind(starts, ends)
                          pieces <- pieces[order(pieces$group), ]
                          GeomPath$draw_panel(pieces, panel_params, coord, arrow = arrow,
                                              lineend = lineend)
                        })

geom_segment2 <- function (mapping = NULL, data = NULL, stat = "identity",
                           position = "identity", ..., arrow = NULL, arrow.fill = NULL,
                           lineend = "butt", linejoin = "round", na.rm = FALSE,
                           show.legend = NA, inherit.aes = TRUE) {
  layer(data = data, mapping = mapping, stat = stat,
        geom = GeomSegment2, # instead of GeomSegment
        position = position, show.legend = show.legend, inherit.aes = inherit.aes,
        params = list(arrow = arrow, arrow.fill = arrow.fill,
                      lineend = lineend, linejoin = linejoin, na.rm = na.rm,
                      ...))
}

geom_histogram2:
library(grid)

GeomBar2 <- ggproto("GeomBar2",
                    GeomBar,
                    draw_panel = function (self, data, panel_params, coord,
                                           width = NULL) {
                      # copy over GeomRect's draw_panel function for the non-linear portion
                      aesthetics <- setdiff(names(data),
                                            c("x", "y", "xmin", "xmax", "ymin", "ymax"))
                      polys <- plyr::alply(data, 1, function(row) {
                        poly <- ggplot2:::rect_to_poly(row$xmin, row$xmax, row$ymin, row$ymax)
                        aes <- as.data.frame(row[aesthetics],
                                             stringsAsFactors = FALSE)[rep(1, 5), ]
                        GeomPolygon$draw_panel(cbind(poly, aes), panel_params, coord)
                      })
                      ggplot2:::ggname("bar", do.call("grobTree", polys))
                    })

geom_histogram2 <- function (mapping = NULL, data = NULL, stat = "bin",
                             position = "stack", ..., binwidth = NULL,
                             bins = NULL, na.rm = FALSE, show.legend = NA,
                             inherit.aes = TRUE) {
  layer(data = data, mapping = mapping, stat = stat,
        geom = GeomBar2, # instead of GeomBar
        position = position, show.legend = show.legend, inherit.aes = inherit.aes,
        params = list(binwidth = binwidth, bins = bins, na.rm = na.rm,
                      pad = FALSE, ...))
}

Usage:
ggplot(d, aes(x)) +
  geom_histogram2(binwidth = 10) +
  geom_segment2(data = lines,
                aes(x, y, xend = xend, yend = yend),
                color = 'red') +
  coord_radar() +
  scale_x_continuous(limits = c(0, 360))


text:
Q: Using python with windows command prompt An integral part of Tensorflow guides are windows shell commands that control python. Unfortunately I do not know how to use it correctly, resulting in me not being able to proceed in the Tensorflow guide. Is there a guide on how to use snippets like:

Source: https://www.tensorflow.org/tutorials/images/image_recognition

A: First open up your terminal by Pressing Windows+R on your Keyboard, then typing in cmd and then pressing enter.
Then type in the commands, press enter and they should get executed.
Was this you question?

A: cd changes directories, so it's just changing the current directory you're in.  Those commands change directories to the "imagenet" folder then runs python on an included program.


text:
Q: Stringstream delimeter I am parsing a CSV file, which has a known structure of string,int,int,double.
I am writing a function that parses a CSV file line-by-line.  I am trying to design it so that it looks something like this:
void foo(const string& csvline){
  std::stringstream csvStream(csvline);
  std::string s; int i1; int i2; double d;
  csvline >> s;
  csvline >> i1;
  csvline >> i2;
  csvline >> d;
}

Is there a way to do this for CSV files?
I know that if they were separated by spaces, this will work out of the box. But what about for a CSV file (or an arbitrary delimiter, for that matter)?

A: You cannot specify a delimiter with operator>>. Use std::getline() to read a delimited value into a temp std::string, then use a std::istringstream to parse the string.
void foo(const std::string& csvline)
{
    std::istringstream csvStream(csvline);
    std::string s, tmp;
    int i1, i2;
    double d;

    std::getline(csvStream, s, ',');

    std::getline(csvStream, tmp, ',');
    std::istringstream(tmp) >> i1;

    std::getline(csvStream, tmp, ',');
    std::istringstream(tmp) >> i2;

    std::getline(csvStream, tmp);
    std::istringstream(tmp) >> d;
}


text:
Q: Complex sub-string replace query SQL I have the following table containing path info:
I need to replace the DIRECTORY_NAME value in the PATH field with the NEW_DIR_NAME value recursively.
sample table:
PATH                                                  |DIRECTORY_NAME                   |NEW_DIR_NAME
...............................................................................................................
\folder1\folder2\2a                          | folder2\2a                                  | folder2/2a
\folder1\folder2\2a\folder3              | folder3                                       | folder3
\folder1\folder2\2a\folder4              |   folder4                                       | folder4
\folder1\folder2\2a\folder4\2a\2b    | 2a\2b                                         | 2a/2b
...............................................................................................................
The result would look like this:
* changes are in bold
NEW_PATH
...............................................................................................................
\folder1\ folder2/2a
\folder1\ folder2/2a\folder3
\folder1\ folder2/2a\folder4
\folder1\ folder2/2a\folder4\ 2a/2b
...............................................................................................................
database is Oracle.
using the select replace(PATH, DIRECTORY_NAME, NEW_DIR_NAME) function will yield the folowing (not the solution):
\folder1\ folder2/2a
\folder1\folder2\2a\ folder3
\folder1\folder2\2a\ folder4
\folder1\folder2\2a\folder4\ 2a/2b

A: Please tell me your field name isn't really STRING. Anyways, here's the code you need, based on the supplied field names.
SELECT REPLACE(STRING,REFERENCE,REPLACE_WITH)

A: Your problem is your data.  Your table posits a one-to-one relationship between PATH and DIRECTORY_NAME, and hence with NEW_DIR_NAME.  But according to your required output this is clearly not so.  The DIRECTORY_NAME appears in multiple values of PATH.
So what you need to do is run the replace() statement for every combination where  DIRECTORY_NAME != NEW_DIR_NAME
for lrec in ( select DIRECTORY_NAME, NEW_DIR_NAME
              from your_table
              where DIRECTORY_NAME != NEW_DIR_NAME )
loop

    update your_table
    set  path = replace(PATH, lrec.DIRECTORY_NAME, lrec.NEW_DIR_NAME)
    ;
end loop;

This is not a particularly efficient approach but presumably this is a one-off exercise.


text:
Q: Grails and JQuery, how to use local storage to handle session timeout dialog with mutiple tabs I have a grails application which I would like to show a session timeout dialog based on local storage, so that multiple browser tabs are covered. resetting the timeout as different tabs are accessed. Do you have an example of this, preferably in JQuery.

A: Followup: I ended up doing the below to solve this:
WebIl.Session = [];
var sess_pollInterval = 60000;
var sess_intervalID;
var sess_expirationMinutes;

WebIl.Session.setupExpiration = function (timeout) {
   sess_expirationMinutes = Math.floor(timeout/60);
  initSession();
};

function initSession() {
  localStorage.timeout = new Date();
  sessSetInterval();
  $(document).ajaxStart(function (ed, e) {
    sessKeyPressed(ed, e);
  });
}
function sessSetInterval() {
  sess_intervalID = setInterval('sessInterval()', sess_pollInterval);
}
function sessClearInterval() {
  clearInterval(sess_intervalID);

}
function sessKeyPressed(ed, e) {
  localStorage.timeout = new Date();
}

function sessInterval() {
  //stop the timer
  now = new Date();
  diff = now - Date.parse(localStorage.timeout);
//  alert("now: " + now + "  local: " + Date.parse(localStorage.timeout) );
//alert("diff: "+ diff);
  diffMins = (diff / 1000 / 60);
//  alert("before timed out dif mins: " + diffMins + "  sess timeout: " + sess_expirationMinutes );
  if (diffMins > sess_expirationMinutes) {
    sessClearInterval();
    //show dialog
    openMessage('Session has timed out. All unsaved changes have been lost.'+
            ' You will be automatically logged back in through the single sign-on process', 'notice');
  }
}


text:
Q: How can I get song previews from Spotify or any other API without user auth I've tried to retrieve a song's 30s preview but it gives me error 401, I have to authenticate the user.
How can I manage to play the preview without any authentication?

A: To access Spotify content, you have to create an application at https://developer.spotify.com/. You will have to get Authorization token (which are a bit complicated).
After doing that, you will access Spotify data, including preview.
I don't think you can do that without authentication.


text:
Q: how to use services in angularjs to share data across multiple controllers? I want to share data across multiple controllers in angularjs without using $rootScope. I am learning to use services for the same. What is wrong with the following code?
This is my controllers.js :
function Ctrl1(shareData) {
  shareData.setValue("my_data");
}

function Ctrl2($scope, shareData) {
  $scope.value = shareData.getvalue();
}

This is my services.js :
angular.module('connectionsServices').
  factory('shareData', function() {
  var shareVar = 'undefined';
    return {
              getValue: function() {
          return shareVar;
          },

              setValue: function(value) {
          shareVar = value;
          }
       }
       });

But it is not working.

A: You can't bind service variable to controller variable, your code is changing shareVar but you are unable to see it, you can update the view like this:
HTML:

{{ value }}

            <button type="button" ng-click="change(); update();">Change me!</button>

JS:
angular.module('testApp', []).factory('shareData', function ($window) {
    var shareVar = 'undefined';
    return {
        getValue: function () {
            return shareVar;
        },

        setValue: function (value) {
            shareVar = value;
        }
    };
});

function Ctrl1($scope, $window, shareData) {
        $scope.change = function () {
            shareData.setValue("my_data");
        };
    }

    function Ctrl2($scope, shareData) {
        $scope.value = shareData.getValue();

        $scope.update = function () {
            $scope.value = shareData.getValue();
        };
    }

A:
Services provide an easy way for us to share data and functionality
  throughout our app. The services we create are singletons that can be
  injected into controllers and other services, making them the ideal
  place for writing reusable code.

Follow its link https://thinkster.io/a-better-way-to-learn-angularjs/services


text:
Q: Is there a way to change the background of an option menu in tkinter? I'm having trouble with changing the background color of tkinter's option menus. When I say background, I am not talking about the color of the option menu, but the color of its actual background. My tkinter window's background is gray, so when I add an option menu, it is surrounded by a few wite pixels. This doesn't happen with button or anything else that I'm aware of. Is there a way to fix this ?
Here is an image of the problem:

A: This can be done quite simply by
root.configure(background='black')

Assuming root is the name of your window.
This question has been asked and answered before here on stackoverflow. Please, try searching the site before asking for future questions, if you still can't find the answer, go ahead and post. :-)

A: Okay everyone I found out how to do it by printing the option menu's config and looking through all the parameters. Turns out I had to add this:
<widget ref>.config(bg = "gray", highlightthickness = 0)


text:
Q: Como funciona un Arreglo 2D con doble puntero en C Como funciona y como se puede hacer un arreglo bidimensional a partir de un doble apuntador en C?
int **a;

A: Te puedo mostrar un ejemplo que quizás te ayude:
/*
    Crea una matriz dinámica , la rellena de ceros y 1 en su diagonal.
    Matriz identidad .- Pascual Martínez Cruz

    Modifiqué este código porque estaba incompleto y con cosas innecesarias. -Zeugirdor

    Entre esas cosas, tenía los bucles incompletos y faltaba código necesario para
    que mostrara la matriz identidad de n filas por n columnas. Además, lo "adapté"
    a Windows, ya que tenía partes del código muy cortas pero de linux.

    El código tal cual estaba está en esta página, por ahora, online:

    http://m68455pagpersonal.galeon.com/pdoblec.html

*/

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

int * asignar_matriz(int x); // asigna la memoria de la matriz
void diagonal_matriz(int **array,int x); // rellena de 1s la diagonal
void imprimir_matriz(int **array,int x); // imprime la matriz

void main(void){

    int n; // dimensión de la matriz
    int i,j; // contadores
    int **matriz=NULL; // puntero doble para la matriz dinámica
    system("cls");
    printf("Introduce el tamanyo de la matriz:\n");
    scanf("%d",&n);
    matriz=asignar_matriz(n);
    diagonal_matriz(&*matriz,n); // paso de la matriz a funciones
    imprimir_matriz(&*matriz,n); // paso de la matriz a funciones
    printf("\n\n");
    system("pause");
}

// asigna la memoria de la matriz

int * asignar_matriz(int x){
    int i,j;
    int **array;
    array=(int **)calloc(x,sizeof(int *)); // se reserva memoria  para la matriz de x filas que contiene direcciones de memoria a las segundas dimensiones.
    for (i=0;i<x;i++){
        array[i]=(int *)calloc(x,sizeof(int *)); // se reserva memoria para las segundas dimensiones , x columnas
    }
    // en memoria ya tenemos reservado espacio para una matriz de x por x --> array[x][x]
    return &*array; // retorno de un puntero doble
}

// rellena de 1s la diagonal y de 0 lo demas

void diagonal_matriz(int **array,int x){
    int i,j;
    for (i=0;i<x;i++){
        for (j=0;j<x;j++){
            if (i==j){
                array[i][j]=1;
            }
            else{
                array[i][j]=0; // esto no lo tenía el código original.
            }
        }
    }
}

// imprime la matriz

void imprimir_matriz(int **array,int x){
    int i,j;
    printf("\nIMPRIMIENDO MATRIZ\n");
    printf("\n==================\n");
    // manejo del puntero doble recibido como si fuese una matriz
    for (i=0;i<x;i++){
        printf("\n");
        for (j=0;j<x;j++){
            printf("%d ",array[i][j]);
        }
    }
}


text:
Q: JS regex - get word after certain characters I have string which goes like this:
"teamA @ teamB" 2) "teamA vs. teamB"

I need to get word following @ or vs.. How can I do this in javascript?

A: Use a regular expression like
(?:@ |vs\. )(\w+)

The word after it will be stored in the first group. Now just use JavaScript to create the RegEx and search a text with it.


text:
Q: WordPress Search Appear with welcome to WordPress I have created a website and when I search the website name in google under my URL links there's a message call " Welcome to WordPress. This is your first post. Edit or delete it, then start writing! January 24, 2023. Got any book recommendations? Get In Touch " how can I remove this ??
I just delete all the posts
and corrected data's along with google index and Yoast SEO so on.
i need a solution to correct it.


text:
Q: Why isn't my Node package being imported? I'm learning Node.js and am using a Node-based Azure Function.
I'm trying to bring in Chalk, to log coloured messages to the console.
However, all of the below fail (in my main index.js file).
One
module.exports = async (ctx, req) => {
    const chalk = require('chalk');
    return console.log(chalk.blue('Hello world!'));

Despite being the approach recommended in this answer, this results in a console error that says:

Exception: require() of ES Module C:...\node_modules\chalk\source\index.js from C:...\index.js not supported.
Instead change the require of C:...\chalk\source\index.js in C:...\index.js to a dynamic import() which is available in all CommonJS modules.

Two
If I do as the error suggests, and use
const chalk = async import('chalk')

...I then get

Exception: chalk.blue is not a function

...even though console.log(chalk) does seem to show the Chalk API and its various properties.
Three
The Chalk docs themselves recommend this:
module.exports = async (ctx, req) => {
    import chalk from 'chalk'
    return console.log(chalk.blue('Hello world!'));

That yields an error saying I can't use import outside of a module (but surely I'm in one?)
Four
Same as three ^^ but moving the import outside module.exports:
import chalk from 'chalk'
module.exports = async (ctx, req) => {
    return console.log(chalk.blue('Hello world!'));

...yields the same error.
I'm sure this is a basic error but I can't find what I'm doing wrong so I'd be so grateful if someone could help. Thank you!

A: When you import something using import as a function(lazy import), It'll return an object with a default property and all exported properties. That you should use to access the module.
const module = async import('chalk')
const chalk = module.default
console.log(chalk.red('Hello world!'))