text:
Q: How to have two bindings simultaneously to the same widget in Tkinter? I want to to perform a fuction when a certain entry gets focus AND a key is pressed (not just focus alone, nor just key is pressed alone)
I mean something like
entry.bind('<FocusIn>', '<Key>', myFunction)

I kow that I can check for focus first then apply the function when the key is pressed, but I was wondering if I can just make it like above in some way.

A: No there actually isn't a way to do this. I wasn't sure myself so i tried something like:
root.bind('<FocusIn-Key>',callback) #callback=print

and:
root.bind('<Key-FocusIn>',callback) #callback=print

but nothing worked. So I would say binding '<Key>'-sequence and checking for focus will be the best solution for you.

A: It might be possible to combine to bindings somehow using some tomfoolery, however, a combination of getting focus and a keyboard event is simply impossible because the widget only begins to look for keyboard events after it is in focus. If this was not the case, what you are asking for would be possible, but it would also mean that if you had multiple widgets bound to keyboard events, they would all activate when you type characters.
Like I said in the beginning, there might be ways to work it so that if you press two keys simultaneously you can run you desired function. But a mouse click and a keyboard event would only be possible after an initial mouse click (which is a little bit redundant).


text:
Q: Migrating old GUID (Symfony <= 5.2) to new UUID Component (Symfony >= 5.3) as Entity ID I started with Symfony 4 and used the Security Components from the "Get Started" tutorial. Everythings went fine. I don't like Integer as ID, so switched to UUID as the ID if the Entity.
Entity schema:
/**
     * @ORM\Id()
     * @ORM\Column(type="guid")
     * @ORM\GeneratedValue(strategy="UUID")
*/
private $id;

[...]

I did the updates till Symfony 5.2 and all components still work. My fault, I didn't saw the deprecated information about the changed UUID processes in a minor update...
After updating thru composer to 5.2 nothing works. I get some 503 errors with the hints, that the old way of creating a UUID is not longer working.
So I changed the old, deprecated components...
I change the PasswordEncoder to PasswordHasher...
I change the old guid type style in the entities to
+ use Symfony\Component\Uid\Uuid;
   /**
     * @ORM\Id()
   - * @ORM\Column(type="guid")
   - * @ORM\GeneratedValue(strategy="UUID")
   + * @ORM\Column(type="uuid", unique=true)
   */
    private $id;

[...]

  + public function __construct()
  +  {
  +      $this->id = Uuid::v4();
  +  }

  - public function getId(): string
  + public function getId(): Uuid
  +  {
  +     return $this->id;
  +  }

I tested the new process on a new, clean project. I'm able to log in, create a user etc. The relations of to entities works fine etc.
BUT i can't migrate my old data to the new binary(16) field, without ForeignyKey errors, or data failures (plain cropped UUID String in a BLOB field).
Long story, short: I searched three days for a migration path for the old GUID fields char(36) to the new binary(16) UUID fields, without double all tables or scripting a CSV ex-/import. Find nothing and my head is too empty for new searchqueries ;) Is there a migrationpath for old projects to the new UUID component on existing data?

redpajama_set_name: RedPajamaStackExchange


text:
Q: VSCode Extension: Get outline of function for custom outliner I'm trying to create a custom outliner for VSCode (currently only for python), but I don't find measures to get the information I needed.
I like to get information in this manner this:

*

*Array:

*

*[0]

*

*label: "foo"

*type: "Function"

*parameters: [...]

*Range: [...]

*innerDefinitions: [0]

*[1]

*

*label: "myclass"

*type: "Class"

*base_class: ""

*Range: [...]

*innerDefinitions:

*

*[0]:

*

*[...]

*[1]:

*

*[...]

Currently I try to get outline information via vscode.commands.executeCommand(     'vscode.XXX'
What I've tried:
Here is what commands I've tried and what result I received.

*

*vscode.executeImplementationProvider

*

*half usable: range of functionname. Other information is missing

*vscode.executeHoverProvider

*

*half usable: string of function head (including def keyword)

*vscode.executeDefinitionProvider

*

*half usable: range of complete function. Individual information must be "parsed out"

*vscode.executeTypeDefinitionProvider

*

*Never provided any result

*vscode.executeDeclarationProvider

*

*Never provided any result

*vscode.executeDocumentSymbolProvider

*

*Goes in a good direction. However
(1) Does only work on the whole document (not single function)
(2) Does only return first-level entities (i.e. class methods are not included in result)

Is there any API call I've overseen?
I wonder how the built-in outliner works, as it  contains all-level information.

A: *

*You need to use vscode.commands.executeCommand<vscode.Location[]>("vscode.executeDocumentSymbolProvider", uri, position)

*This will give you the full outline of one file. There is no way to receive a partial outline.

*Note: innerDefinitions are called children here.

*Regarding the detail of the outline:

*

*How detailed (and correct) an outline is going to be, depends on the implementation of the provider. Also, provider's information is no necessarily consistent among languages. This is very important to keep in mind!

*

*At the moment (2021/03), the standard SymbolProvider for...

*

*... Python will have a child for each parameter and local variable of a function. They will not be distinguishable

*... C++ will contain no children for parameters. But it will have the parameter types in its name. (e.g. name of void foo(string p) will be foo(string): void.

*As you can see, both act differently with their own quirks.

*You could create and register a DocumentSymbolProvider yourself, that would return a level of detail you need (see VSCode Providers)

Also see: https://stackoverflow.com/a/66486297/6702598


text:
Q: Extending Wightman axioms to gauge theories I understand that Wightman axioms were defined for scalar quantum field theories. However, what prevents axiomatization of non-scalar quantum field theories, such as gauge theories, even for free field?

A: Well, nothing prevents a generalization of Wightman's axioms in case of free gauge theories. This, however, requires in turn a generalization of Hilbert spaces, known as Krein Spaces. The only lucid and thorough presentation I know of is Chapter #10 of BLOT. I hope this boook is available to you.

A: As @DanielC Pointed out, Krein spaces are the main ingredient to generalise Wightman axioms to free gauge theories. There is a framework, which you might be looking for: the Strocchi Wightman framework. You can find a detailed description in chapter 7 of the following notes:
https://www-m5.ma.tum.de/foswiki/pub/M5/Allgemeines/WojciechDybalski/Notes-QFT41.pdf


text:
Q: Rust conflict with error-chain and websocket crates I'm trying to use error-chain with the websocket crate, but running into an issue that I'm not sure how to resolve. WsUpgrade::accept has the following signature:
fn accept(self) -> Result<Client<S>, (S, IoError)>

Note that the Err variant is a tuple. I want to configure error-chain to handle calls to this method, so I tried to do so as follows in the relevant consuming module:
mod errors {
    error_chain! {
        foreign_links {
            WebSock((::std::net::TcpStream, ::std::io::Error));
        }
    }
}

This results in the following error, seemingly related to the presence of the tuple.
error: expected identifier, found `(`
  --> src/lib/websock.rs:23:21
   |
23 |             WebSock((::std::net::TcpStream, ::std::io::Error));
   |                     ^

How can I resolve this? Hopefully I've missed something simple.

A: A simple solution would be to introduce a type alias:
mod errors {
    type WebSocketError = (::std::net::TcpStream, ::std::io::Error);
    error_chain! {
        foreign_links {
            WebSock(WebSocketError);
        }
    }
}

However, this type does not implement traits required by error-chain (such as Error and Display), so it can't be used there.
I think the simplest solution is to convert the error manually using Result::map_err before passing the value to error-chain. For example, the following construction will produce Result<Client<S>, IoError>:
x.accept().map_err(|e| e.1)


text:
Q: How do I reformat column/row placement in pandas? I have a pandas dataframe as shown:

I would like to remove the 'Category_2' and 'Category_1' from the dataframe. I would also like the dataframe to look like a table, rather than how it is now (state and primary_or_piggyback are both numpy arrays). How would I go about achieving this goal?

A: Categories one and two are the names of the  index and columns objects respectively.
variations_tab.rename_axis(None).rename_axis(None, 1)


text:
Q: How to skip saturday and sunday in a cron expression? Hi I want to create a cron expression excluding saturday and sunday.

A: Try this:
# run every two hours at the top of the hour Monday through Friday
0 */2 * * mon-fri <command>

A: Begin the line with 0 0 * * 1,2,3,4,5 <user> <command>. The first fields are minutes and hours. In this case the command will run at midnight. The stars mean: for every day of the month, and for every month. The 1 to 5 specify the days. monday to friday. 6=saturday 0=sunday.


text:
Q: Windows Phone 7 - Deselecting ListBoxItem in nested ListBoxes I have a ListBox with dates.
Each ListBoxItem (date) have another ListBox with that date's events.
When I select an event it gets highlighted (SelectedIndex/SelectedItem) and I navigate to another Pivot. This works fine.
My problem is that every ListBox has it's own SelectedItem. I want to clear the SelectedItem from each ListBox, but I cannot get it to work!
Here's my try:
    //Store a reference to the latest selected ListBox
    public ListBox SelectedListBox { get; set; }

    private void SelectionChangedHandler(object sender, SelectionChangedEventArgs e)
    {
        ListBox lstBox = ((ListBox)sender);

        //This row breaks the SECOND time!!
        var episode = (Episode)lstBox.SelectedItem;

        episodeShowName.Text = episode.Show; //Do some code
        episodeTitle.Text = episode.Name; //Do some code
        episodeNumber.Text = episode.Number; //Do some code
        episodeSummary.Text = episode.Summary; //Do some code

        resetListBox(lstBox); //Do the reset !

        pivot1.SelectedIndex = 1;
    }

    private void resetListBox(ListBox lstBox)
    {
        if (SelectedListBox != null)
            SelectedListBox.SelectedIndex = -1;

        //If I remove this line, the code doesn't break anymore
        SelectedListBox = lstBox; //Set the current ListBox as reference
    }

var episode is null the second time. How come?

A: I found the problem!
private void resetListBox(ListBox lstBox)
{
    if (SelectedListBox != null)
        SelectedListBox.SelectedIndex = -1;

    //If I remove this line, the code doesn't break anymore
    SelectedListBox = lstBox; //Set the current ListBox as reference
}

When I set the previous selected ListBox's SelectedIndex to -1, the SelectionChangedHandler event gets triggered again (of course) and screws up ! :D
Easy fix:
    private void SelectionChangedHandler(object sender, SelectionChangedEventArgs e)
    {
        ListBox lstBox = ((ListBox)sender);
        if (lstBox.SelectedIndex < 0)
            return;


text:
Q: How do I stop scripts from accessing the mouse wheel in Firefox? I'm using Firefox 16.0.2 on Mac OS X 10.6.8, including the NoScript 2.5.9 plugin. Sometimes when browsing, a web site will have an embedded map or the like within it, and when scrolling down the page with the mouse wheel, once the cursor is over the map the wheel switches to zooming in and out rather than scrolling. Even on a dedicated mapping site, I find it unintuitive that the scroll wheel does something other than scrolling, and I can't imagine a scenario where I'd want scripts to be able to hijack it.
Is there some way to prevent scripts from receiving the mouse wheel events? I'm assuming that there's just something obvious in about:config or the NoScript options that I'm missing. The analogous option for stopping scripts from getting right clicks is in Options / Content / Enable Javascript Advanced / Disable or replace context menus.
Thank you!


text:
Q: How to show a tabpage with button click from other form private void btnLogin_Click(object sender, EventArgs e)
{
  Form1 frm = new Form1();
  string sql = "SELECT * From Admin WHERE UserName='" + txtUserName.Text + "' And Password='"+txtPassword.Text+"'";

  if (conn2.State != ConnectionState.Open)
  {
    conn2.Open();
  }

  command = new SqlCommand(sql, conn2);
  SqlDataReader reader = command.ExecuteReader();
  reader.Read();

  if (reader.HasRows)
  {
    if(reader[0]==txtUserName.Text   && reader[1]==txtPassword.Text)
    {
      // I want the code in this section
    }
  }
}

I want to activate the "edit tabpage" when the login suceeds . The "edit page " is in other form.

A: This might do the trick for you.
int indexyouwant = 1; // Suppose 1 is your Edit Page Tab.
Form1 frm = new Form1();
// SQL
if (reader.HasRows)
{
    if(reader[0]==txtUserName.Text   && reader[1]==txtPassword.Text)
    {
        frm.YourTabControlName.SelectedIndex = indexyouwant;
    }
}

It is suggested that you should use Parameterized Query to prevent SQL Injection.


text:
Q: How to get a list of files for a package I haven't installed yet? apt-cache search returns list of available packages. In my case I would like to look at  the list of files that would be installed on my PC in case I install the package usb-creator-gtk.
Something like dpkg-query -L does for an already installed package.
Thanks for help.

A: You've got at least these two options.
First one, use apt-file for packages you haven't installed yet.
$ sudo apt-get install apt-file
$ sudo apt-file update
$ apt-file list usb-creator-gtk
usb-creator-gtk: /usr/bin/usb-creator-gtk
usb-creator-gtk: /usr/lib/python2.7/dist-packages/usbcreator/frontends/gtk/__init__.py
usb-creator-gtk: /usr/lib/python2.7/dist-packages/usbcreator/frontends/gtk/frontend.py
[...]

Second one, use the packages.ubuntu.com website to locate the package, then all the way down on the page in the "Download" section, you'll find a link [list of files]. Example for your package in Bionic (18.04) is here.
Either way, please remember that packages might install more files in their install scripts!


text:
Q: Limit number of result in SOLR by score My catalog has a lot of products, so sometimes there are a lot of search results by some queries. Solr have its own field 'score', and our customer wants to limit search results by limiting 'score' value. For example, if we set 'limit score value' to 500, then in search result should be only products which score > 500. (I know this is a bad practice).
I tried google a lot on it, tried to edit edismax and etc.
So my question, how can i do this?

A: This will not work because the scores are not consistent. They only make sense within a single query and do not have good absolute representation. They are not even consistent between different cores that form a single collection in SolrCloud. You will not be able to find the meaningful number to use.
You need to go back to the business and ask what they mean in business terms and then see how the Solr can answer that. In some cases that may even mean different indexing strategy.


text:
Q: How to kill a thread in PHPmyadmin I have a thread showing in PHPmyadmin under processes. However, when I click kill, I get the error:
phpMyAdmin was unable to kill thread 148. It probably has already been closed.

Why does this thread still then show as active? How can I remove it entirely?

A: Open mysql client and type
mysql> show processlist;
+-----+------+-----------+------+---------+------+-------+------------------+-----------+---------------+-----------+
| Id  | User | Host      | db   | Command | Time | State | Info             | Rows_sent | Rows_examined | Rows_read |
+-----+------+-----------+------+---------+------+-------+------------------+-----------+---------------+-----------+
| 106 | root | localhost | NULL | Query   |    0 | NULL  | show processlist |         0 |             0 |         0 |
+-----+------+-----------+------+---------+------+-------+------------------+-----------+---------------+-----------+
1 row in set (0.00 sec)

you'll see processes with ID, than you can do this:
mysql> kill 106;

and your process (id = 106) will be killed.

A: Between the time that phpMyAdmin received the list of processes and the time you clicked to kill one of them, this process had finished by itself.
See also https://sourceforge.net/p/phpmyadmin/feature-requests/1490/.

A: This phenomenon is caused by the connection used to access PHPmyadmin itself, hence it doesn't show on the direct MySQLQuery. It can't be killed, as it would close the PHPmyadmin connection.


text:
Q: pattern is the topic i am not getting the answer E
E D
E D C
E D C B
E D C B A

print using for loop
public class t3 {
    public static void main(String[] args) {

        int n=5;

        for(int i=1;i<=n;i++){

            for(char j='E'-i;j<='E';j++){
              System.out.print(j);
            }

            System.out.println();

        }
    }

}

A: I got it working with this code:
public class ForLoop {
    public static void main(String[] args) {
        int n = 4;
        for(int i = 0; i <= n; i++){
            for(char j = (char) ('E' - i); j <= 'E'; j++) {
                System.out.print(j);
            }
            System.out.println();
        }
    }
}

Here is the output:
% java ForLoop.java
E
DE
CDE
BCDE
ABCDE

I cast the value 'E' - i to a char after the subtraction is performed.
The value 'E' - i is an int because i is an int and we need an int to store the result. We can cast 'E' - i to a char explicitly to avoid a compilation error.
Let's open jshell to see what happens when we cast a really big int.
% jshell
|  Welcome to JShell -- Version 17.0.1
|  For an introduction type: /help intro

jshell> char c1 = 0x41
c1 ==> 'A'

jshell> int i = 0xab000041
i ==> -1426063295

jshell> char c2 = (char) i
c2 ==> 'A'

You can see that the cast (char) i truncates the integer i and makes it fit into the space of a char. The integer i has a decimal value of -1426063295. The char c2 has a decimal value of 65.
In Java, a char is a 16-bit Unicode character, and an int is a 32-bit signed integer.
A signed integer can be positive, negative, or zero; an unsigned integer can be positive or zero.
The notation 0x is hexadecimal; sometimes it is easier to write numbers in hexadecimal because eight hexadecimal digits is always four bytes, and an int consists of four bytes.
The number 41 in hexadecimal is equal to 65 in decimal.

Some notes on hexadecimal
A byte can always be represented by two hexadecimal digits, so it is sometimes easier to write numbers in hexadecimal.
For example, the byte 255 can be represented by the hexadecimal digits 0xFF, but it cannot be represented by two decimal digits.
(The largest number that can be represented by two decimal digits is 99.)
It is often easier to translate hexadecimal into binary and vice versa, than it is to translate decimal into binary.
It is often more efficient to store binary numbers in hexadecimal, since we only need two digits (0x00-0xFF) instead of three (0-255).


text:
Q: Is there a way to get a Set/Array of minutes and hours in iOS? I'm trying to populate my picker view with minutes and hours in the simplest way possible. I'm implementing a custom picker so using UIDatePicker with it's mode set to UIDatePickerModeTime is out of the question.
Is there a function available in iOS to retrieve the data set or do I just have to initialise the array with hardcoded values from 0-12 (12 hour system) and 0-60 for the hours and minutes respectively with say a for loop?
I'm currently populating the array like so:
#pragma mark - Lazy Loading
-(NSArray *)hourValues{
    if(!_hourValues){
        NSMutableArray *hours = [[NSMutableArray alloc] init];
        for(int i = 0; i < 12; i++){
            [hours addObject:[NSNumber numberWithInt:i]];
        }
        _hourValues = hours;
    }
    return _hourValues;
}
-(NSArray *)minuteValues{
    if(!_minuteValues){
        NSMutableArray *minutes = [[NSMutableArray alloc] init];
        for(int i = 0; i < 60; i++){
            [minutes addObject:[NSNumber numberWithInt:i]];
        }
        _minuteValues = minutes;
    }
    return _minuteValues;
}
-(NSArray *)amPmValues{
    if(!_amPmValues){
        _amPmValues = @[@"am", @"pm"];
    }
    return _amPmValues;
}

I don't like the hardcoded values.
Ideally, I would like to be able to do something like this:
hours = [NSDate NS12HourSetArray];
minutes = [NSDate NS60MinuteArray];

A: I think you have 3 options:

*

*Write a script/automate creating textual data and load it at runtime, you can easily do that in python/bash and plist.

*do it manually using the good old for loop. I recommend that.

*or You can create an index set from whatever range you want using NSIndexSet and NSRange objects respectively.
for example:
NSIndexSet *minutesIndexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 60)];

Then you ether make your UI load form the index set directly, or again enumerate the index set and fill an array with its indexes.
In both ways what you are ultimately doing is iterating through a loop to fill your arrays manually. the only one that does only the load is the first one.

A: There is no built-in methods that you can call like this. Personally, I don't really see an issue with hard-coding things like "the number of minutes in an hour" because it's well-defined and you can be relatively sure that it won't ever change. You could hide it from yourself a little bit by making a category on NSDate if that's where you expect the API to exist.
@interface NSDate (ConvenientArrays)
+ (NSArray *)minutesInAnHourArray;
+ (NSArray *)hourRepresentationsPerDay:(BOOL)use24Hour;
@end

@implementation NSDate (ConvenientArrays)
+ (NSArray *)minutesInAnHourArray {
  return @[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,
           10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
           20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
           30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
           40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
           50, 51, 52, 53, 54, 55, 56, 57, 58, 59];
}
+ (NSArray *)hourRepresentationsPerDay:(BOOL)use24Hour {
  if (use24Hour) {
    return @[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,
             10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
             20, 21, 22, 23];
  }
  return @[     1,  2,  3,  4,  5,  6,  7,  8,  9,
           10, 11, 12];
}
@end


text:
Q: K means clustering mahout I am trying to cluster a sample dataset which is in csv file format. But when I give the below command,
user@ubuntu:/usr/local/mahout/trunk$ bin/mahout kmeans -i /root/Mahout/temp/parsedtext-seqdir-sparse-kmeans/tfidf-vectors/ -c /root/Mahout/temp/parsedtext-kmeans-clusters -o /root/Mahout/reuters21578/root/Mahout/temp/parsedtext-kmeans -dm org.apache.mahout.common.distance.CosineDistanceMeasure -x 2 -k 1 -ow --clustering -cl

I am getting the following error, saying there is no input clusters available and to check the -c cluster argument. Can anybody help me please>
Here is the error which I got for the above command:
16/05/11 16:09:15 INFO compress.CodecPool: Got brand-new decompressor [.deflate]
Exception in thread "main" java.lang.IllegalStateException: No input clusters found in /root/Mahout/temp/parsedtext-kmeans-clusters/part-randomSeed. Check your -c argument.
at org.apache.mahout.clustering.kmeans.KMeansDriver.buildClusters(KMeansDriver.java:213)
at org.apache.mahout.clustering.kmeans.KMeansDriver.run(KMeansDriver.java:147)
at org.apache.mahout.clustering.kmeans.KMeansDriver.run(KMeansDriver.java:110)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
at org.apache.mahout.clustering.kmeans.KMeansDriver.main(KMeansDriver.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:71)
at org.apache.hadoop.util.ProgramDriver.run(ProgramDriver.java:144)
at org.apache.hadoop.util.ProgramDriver.driver(ProgramDriver.java:152)
at org.apache.mahout.driver.MahoutDriver.main(MahoutDriver.java:195)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
at org.apache.hadoop.util.RunJar.main(RunJar.java:136)

A: Let me copy the error message for you:

No input clusters found in /root/Mahout/temp/parsedtext-kmeans-clusters/part-randomSeed. Check your -c argument.

Have you considered checking or removing your -c argument?
But Mahout k-means is really low-quality. Use something else. apt-get install elki and try that instead, it's much faster.


text:
Q: How to get the name of color by RGB values from dataframe? I'm creating a program that reads an image and prints its name. I have csv file with about 900 colors with RGB values. How can I compare RGB values of the image in my program and compare them to dataframe to get the name of a color?
from webbrowser import Mozilla
from wsgiref import headers
from matplotlib import image
import numpy as np #needed to work with matrix of an image
import pandas as pd #needed to work with color.csv
import cv2 #needed to work with image
import matplotlib.pyplot as pl #needed to work with plotting
import urllib.request#needed to work with image url

#step 1. Read csv file with name, RGB and HEX values.
#step 2. Set color detection function. Get value of pixels in a NumPy array
#step 3. Compare RGB value of a pixel with dataframe.
#step 4. Save the name and RBG value inside a file.

#global values
#image from url
def url_to_image(url): #doesn't get file, need to work upon this
    resp = urllib.request.urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype='uint8')
    image = cv2.imdecode(image,cv2.COLOR_BGR2RGB)
    return image

#dataframe with 864 colors
index = ['color', 'color_name', 'hex','R','G','B']
csv = pd.read_csv('colors.csv', names = index, header = None)

def getColor(R,G,B):
    minimum = 10000
    for i in range(len(csv)):
        distance = abs(R-int(csv.loc[i, 'R'])) + abs(G-int(csv.loc[i, 'G'])) + abs(B-int(csv.loc[i,'B']))
        if(distance<=minimum):
            minimum = distance
            color_name = csv.loc[i, 'color_name']
        return color_name

#passes image from open source, don't pass images from sources, which considered my attempt as DDOS atack
img = url_to_image("https://htmlcolorcodes.com/assets/images/colors/purple-color-solid-background-1920x1080.png")
B,G,R = img[100,100] #BGR value of a pixel in x row and y column
print(getColor(R,G,B))

A: You can use this function to get the color with the smallest distance to your input R, G, B values. You can also specify a maximum value – if the closest value in the color dataframe is too far, no color name is returned:
def get_color(red, green, blue, max_distance=10_000):
    # Make a copy of the dataframe to avoid changing the original
    df = csv.copy()
    df["distance"] = (
        (df["R"] - red).abs() +
        (df["G"] - green).abs() +
        (df["B"] - blue).abs()
    )
    # Select row with smallest distance
    top_row = df.sort_values("distance").iloc[0]

    if top_row.distance <= max_distance:
        return top_row.color_name

    return None


text:
Q: TextView with editable parts I would like to have a TextView, where certain "empty spaces" can be edited, but the rest is constant. I'm aware of that this is easy for prefixes and suffixes, but in my case most of the text is fixed, and the editable parts can be anywhere.
I plan to parse text like this (just longer):
Blah blah blah ______ text text
text _____ text text blah blah

This should create a view like a TextView, but the parts where there are underscores should be editable.
Is there some kind of View in the SDK that could help me with this? If not, how would I go about implementing it?

A: EditText is a TextView. Use a TextView:
textView.setCursorVisible(true);
textView.setFocusableInTouchMode(true);
textView.setInputType(InputType.TYPE_CLASS_TEXT);
textView.requestFocus(); //triggers soft keyboard to show up

Then add TextWatcher:
textView.addTextChangedListener(new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        // This method is called to notify you that, within s, the count characters beginning at start are about to be replaced by new text with length after.
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        //
    }

    @Override
    public void afterTextChanged(Editable s) {

        //
    }
});

Then you can set the characters to be fixed or blank.


text:
Q: Monitor and copy to and from multiple locations Trying to automatically copy files from one PC (not on network) to a network location using a bridging PC with two network cards.
I have managed to put together this script from a previous post on the subject. This works great!
The issue I have is that I need to monitor and copy files from two locations on the PC to two separate locations on the bridging PC
C:\Source → C:\Destination
and
C:\Source2 → C:\Destination2
I tried running 2 PowerShell scripts with different sources and destinations however it wont allow the second to run while the first is running. The following error message occurs:

Register-ObjectEvent : Cannot subscribe to the specified event. A subscriber
with the source identifier 'FileCreated' already exists.
At ****\PowerShell\movePowerhell - Copy.ps1:8 char:14
+ ... onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileC ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (System.IO.FileSystemWatcher:FileSystemWatcher) [Register-ObjectEvent], ArgumentException
    + FullyQualifiedErrorId : SUBSCRIBER_EXISTS,Microsoft.PowerShell.Commands.RegisterObjectEventCommand

I assume I need to monitor both locations and copy to both destinations in the same script?
I have tried creating a array with both sources and destinations and looping through the code twice but I get the same error as above.
$folder = "C:\Source"
$filter = "*.*"
requirements
$destination = "C:\Destination"
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
    IncludeSubdirectories = $true
    NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
    $path = $Event.SourceEventArgs.FullPath
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated

    Move-Item $path -Destination $destination -Force -Verbose # Force will overwrite files with same name
}

A: When in doubt, read the documentation (emphasis mine):

-SourceIdentifier
Specifies a name that you select for the subscription. The name that you select must be unique in the current session. The default value is the GUID that Windows PowerShell assigns.

The simplest way to avoid the issue is to not specify a source identifier. If you omit the parameter PowerShell will automatically set a GUID as the source identifier, which will avoid name collisions.


text:
Q: PHP headers putting everything that was output to screen into downloaded file I have the following PHP code using headers to download a file from the server:
$file = 'Order.txt';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);

This code works fine, however I have it in a file with the HTML form and it is ran using an if isset all of the HTML code is placed in the file, as well as anything I echo out in PHP; and the data I actually want in the file is there at the end.
I can't figure out what in the headers is causing it to write everything that is on screen to the file when downloaded. The file on he server isn't changed and is how it should be.
Thanks for any help.
Heres all the code...
    <form action="<?=$_SERVER['PHP_SELF'];?>" method="post"><br>
Order Number: <input type="number" name="orderNo" size="10"/>
<input type="submit" name="Download" value="Download" />
</form>

</body>
</html>

<?php
if(isset($_POST['Download'])){download();}

function download()
{
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('amazondb', $conn);
 $result = mysql_query("SELECT ID, PurchaseDate, BuyerName, ShipCity, ShipState, ShipPostalCode, ShipCountry,
                          ShipAddress1, ShipAddress2, ShipAddress3 FROM imported_orders");
$orderNo = $_POST['orderNo'];
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($orderNo>0&&$orderNo<=count($row))
{
    $file = fopen('Order.txt', 'w');
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
    if($row['ID']==($orderNo))
        {
        echo "Hello";
        fwrite($file, $row['BuyerName'].PHP_EOL .$row['ShipAddress1'].PHP_EOL .$row['ShipAddress2'].PHP_EOL  .$row['ShipAddress3'].PHP_EOL  .$row['ShipCity'].PHP_EOL      .$row['ShipState'].PHP_EOL  .$row['ShipPostalCode'].PHP_EOL  .$row['ShipCountry'].PHP_EOL);
        }
    }
    fclose($file);
$file = 'Order.txt';
header("Cache-Control: private");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
}
 else{echo "Please enter a valid Order Number"; echo $orderNo;}
}

A: move this code at very begin of file, so you will have:
<?php
if (your condition to output file) {
    $file = 'Order.txt';
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");
    readfile($file);
    die();
}
the rest of your file....

another solution, at the very top of file add:
<?php
ob_start() or die('Cannot start output buffering');
... your page

and just before the first header add:
$file = 'Order.txt';
ob_end_clean();
header("Cache-Control: public");
...
readfile($file);
die();


text:
Q: Python pandas - Possible issue with multi indexing column names of different types The following code leads to the exception: KeyError: u'the label [37,5 cl ] is not in the [columns]'.
df = pd.read_csv('https://raw.githubusercontent.com/AntoineGautier/Data/master/new.txt')
df.rename({'1': 1, '3': 3, '0':0}, axis=1, inplace=True)
df.set_index(list(df.columns[:3]), inplace=True)
df.sort_index(inplace=True)
for idx in df.index:
    tmp = df.loc[idx]

No exception if all column names are strings.

A: If you are iterating over an multiindex, idx is a tuple, therefore you should use df.loc[list(idx)], this gives the expected result:
In [22]: df.loc[list(idx)]
Out[22]:
                                            5_x    5_y _merge  id_stock
1    3        0
1949 37,5 cl  Château LAFITE ROTHSCHILD   759.0  798.0   both        35
              Château LAFITE ROTHSCHILD   798.0  759.0   both        36

EDIT: You can also do the same with df.loc[slice(idx)], compare Multiindexing in the docs.
EDIT2: Compare the following ones:
In [38]: tuple(idx)
Out[38]: (1949, '37,5 cl ', 'Ch\xc3\xa2teau LAFITE ROTHSCHILD ')

In [39]: (idx)
Out[39]: (1949, '37,5 cl ', 'Ch\xc3\xa2teau LAFITE ROTHSCHILD ')

In [40]: list(idx)
Out[40]: [1949, '37,5 cl ', 'Ch\xc3\xa2teau LAFITE ROTHSCHILD ']

In [41]: [idx]
Out[41]: [(1949, '37,5 cl ', 'Ch\xc3\xa2teau LAFITE ROTHSCHILD ')]

The two first ones don't work while the last two does.


text:
Q: Crystal Reports not returning data from some Oracle views using Oracle driver I'm using Crystal Reports 2013 and have Oracle ODAC 32 and 64 bit versions installed. If I create a new report and use the "Oracle Server" data source, I can select from any tables to which I have access. However, I find I retrieve no data from some, not all, views.
The queries work fine in SQL Plus or SQL Developer. The queries retrieve data in Crystal Reports using outdated drivers like OLE DB and ODBC.
I can't find a commonality between the views that do or don't work. All the views I've tested with belong to the same schema. they all involve tables that belong to a third schema -- that is, I log in as USER1, query from a view belonging to USER2, which pulls data from tables belonging to USER2 and USER3. In order to create a view on a table and make that view available to others, Oracle requires SELECT WITH GRANT OPTION permission, which is in place. Again, the queries work fine in other SQL tools.
UPDATE: I've tried logging in as the owner of the views and was unable to query them. I've tried querying the underlying tables as the view owner (user2) and as the Crystal Reports owner (user1). Both users are able to query the underlying tables. The view itself seems to be the problem.
I'm studying the differences between the views that work and the views that don't work. I was optimistic when I found that the views that don't work were all using ORDER BY clauses that referenced column position (ex: ORDER BY 2, 1). I tried rewriting the ORDER BY to use column names. Didn't work. Tried removing the ORDER BY clauses. Didn't work. Back to the drawing board.

A: I found that the problem was that the Oracle view was using Oracle-specific, non-standard SQL. In addition to the ORDER BY 2, 1 mentioned above, there was an implicit date conversion in the WHERE clause e.g.
WHERE date_col = '01-JAN-2016'

When I added the TO_DATE function:
WHERE date_col = TO_DATE ('01-JAN-2016', 'dd-MON-yyyy')

Crystal Report was able to query the view.


text:
Q: C#: Radio Button doesn't have definition .IsChecked? I am writing a program to run a testing tool that has two cameras, named Pias and DinoLite.  The operator can select which camera is to be active by two radio buttons.  I am trying to implement an exception where if an operator tries to select a camera which is not connected, the program will ask if they want to restart with the correct camera installed.  If the operator says no, I would like the radio buttons to revert to the previous camera.  However, for some reason, the .IsChecked method for radio buttons is not available.  Is there a property I must change first?  I've seen other posts about using .IsChecked and I couldn't find a similar issue.
Here is my code for the radio button (forgive me if it's appalling, I'm a mechanical engineer by training):
    private void pias_mode_CheckedChanged(object sender, EventArgs e)
    {
        MessageBox.Show("Please ensure the correct camera is installed.  Press OK when finished.", "Camera Switch", MessageBoxButtons.OK);
        if (pias_mode.Checked)
            Mode_Indicator.Text = "Pias Mode";
    }

    private void dino_mode_CheckedChanged_1(object sender, EventArgs e)
    {
        if (dino_mode.Checked)
            Mode_Indicator.Text = "DINO Mode";
            measuringZ = 100;
            try //detects if DinoLite camera is connected
            {
                axDNVideoX1.Connected = true;
                axDNVideoX1.Preview = true;
            }
            catch (Exception)
            {
                DialogResult dialogresult = MessageBox.Show("Could not find DinoLite camera.  Would you like to connect DinoLite camera?  This will require the program to exit.", "Device not Found", MessageBoxButtons.YesNo);
                if (dialogresult == DialogResult.Yes)
                {
                    Close();
                }
                else if (dialogresult == DialogResult.No)
                {
                    pias_mode.IsChecked = true;
                }
            }
    }

Visual studio tells me there is no definition for '.IsChecked'
Here is what it looks like:

A: You can not change the value of IsChecked. Instead use the Checked property of the RadioButton.


text:
Q: python requests: post and big content I am sending a CSV file to a server using a POST request.
I am using a file-like object with requests.post
Will there be a problem if the CSV file is quite big and I have limited memory or the fact that I use a file-like object will never load the whole file in memory? I am not sure about that.
I know there is the stream option but it sounds like it's more for getting the response and not sending data.
headers = {
    'content-type': 'text/csv',
}
csvfile = '/path/file.csv'
with open(csvfile) as f:
    r = requests.post(url, data=f, headers=headers)

A: This will not load the entire file into memory, it will be split into chunks and transmitted a little at a time. You can see this in the source code here.

A: Using an open file object as the data parameter ensures that requests will stream the data for you.
If a file size can be determined (via the OS filesystem), the file object is streamed using a 8kb buffer. If no filesize can be determined, a Transfer-Encoding: chunked request is sent sending the data per line instead (the object is used as an iterable).
If you were to use the files= parameter for a multipart POST, on the other hand, the file would be loaded into memory before sending. Use the requests-toolbelt package to stream multi-part uploads:
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

csvfile = '/path/file.csv'
with open(csvfile) as f:
    m = MultipartEncoder(fields={'csv_field_name': ('file.csv', f, 'text/csv')})
    headers = {'Content-Type': m.content_type}
    r = requests.post(url, data=m, headers=headers)


text:
Q: How to add vertical tabs (like the product page) to a custom magento admin form There are many tutorials to adding extra tabs to the product page but I am struggling to find information on how I can create tabs on a new form from scratch. I have looked at the following resources but the information presented doesn't seem to be very clear or my magento isn't good enough to understand it yet:

*

*http://www.excellencemagentoblog.com/module-development-series-magento-admin-module-part3

*how to create multiple tab in magento custom module?
I am trying to emulate the tab system that runs vertically down the left side of the product section but on a custom form.
Are there any references out there on how this should be done (similar to the official magento one explaining how to create an admin module)?
p.s I haven't posted code as anything I have is directly from the tutorials.

A: I ended up working through the excellencemagentoblog version and have successfully got tabs working. The examples given aren't exactly straight forward unless you understand the magento structure really well but the information within the article is adequate enough to work through.


text:
Q: "this.props.dispatch" dispatching wrong action I'm exporting a component without mapping dispatch to props like this, in order to make dispatch available by default to props.:
export default connect(
    mapStateToProps
)(Radium(ClientList));

I have the following action creator:
export function organizeDownloadableClientCustomerData(downloadableClientCustomerData) {
    return {
        type: 'ORGANIZE_DOWNLOADABLE_CLIENT_PAGE_DATA',
        downloadableClientCustomerData: downloadableClientCustomerData
    }
}

When I dispatch it:
componentDidMount() {
    this.props.dispatch(this.fetchCustomerData());
}

It dispatches the first action I've defined on actions.js:
export const navigate = eventLink => {
    return {
        type: 'NAVIGATE',
        eventLink: eventLink
    }
}

Which makes no sense at all. I know I should be making API requests far away from componentDidMount with fancy redux-saga, but I'm getting there. Funny thing is, if I dispatch it like this:
componentDidMount() {
    this.props.dispatch({
        type: 'ORGANIZE_DOWNLOADABLE_CLIENT_PAGE_DATA',
        downloadableClientCustomerData: downloadableClientCustomerData
    });
}

It works like a charm. Why it dispatches a wrong action if it's through an action creator???
EDIT (fetchCustomerData):
fetchCustomerData() {
    return dispatch => {
        dispatch({ type: 'FETCH_DOWNLOADABLE_CLIENT_CUSTOMER_DATA_BEGIN' });
        return fetch(`${backendAddress}/fetch_customers/?acquirer=${this.props.storeState.currentAcquirer}`)
            .then(res => res.json())
            .then(responseData => {
                dispatch({
                    type: 'FETCH_DOWNLOADABLE_CLIENT_CUSTOMER_DATA_SUCCESS',
                    responseData: responseData
                });
                this.fitDataIntoPages(this.props.storeState.downloadableClientCustomerData.responseData);
                return true;
            })
            .catch(error => {
                dispatch({
                    type: 'FETCH_DOWNLOADABLE_CLIENT_CUSTOMER_DATA_ERROR',
                    payload: { error }
                });
                return false;
            });
    };
}

EDIT2:
fitDataIntoPages(data) {
    ...
    let downloadableClientCustomerData = {
        responseData: data,
        organizedData: organizedData,
        customerElements: customerElements,
        totalItems: totalItems,
        numberOfPages: Math.ceil(totalItems / this.props.storeState.downloadableClientCustomerData.pageCount)
    }
    this.props.dispatch(organizeDownloadableClientCustomerData(downloadableClientCustomerData));
}

A: I can't believe it!!! I've changed the import just to test the luck after @Ryan Cogswell asked, from import organizeDownloadableClientCustomerData from "../../actions.js"; to import { organizeDownloadableClientCustomerData } from "../../actions.js"; and just bloody worked!!! (It dispatched the correct action) I've lost almost a whole day of work because of this.


text:
Q: auto_increment index depends other table I have two tables:
Friends :
id  name
1   jhon
2   peter

Teammates:
id  name
3     juan

i am looking for a way two auto increment the id of the second table (teammates) according to the first table ( Friends ).
When I add a new register to Teammates it never match with an id of Friends

A: I think this is not good practice. If you do so, you are introducing an implicit functional dependency between both tables outside of the declared design. If you want to it anyway, you can use a trigger to asign the value instead of making the column autoincrement.
I would suggest to have a table for all people with the real autoincrement id, then you can use several approaches:
i) Make your two actual tables take id values as foreign keys of this new table, with the corresponding integrity constraint.
ii) Simply create 2 views of the table: One for friends, other for teammates.
Table_Friends: (id, name, role)
View_Friends: Select id, name from table_Friends where role = value_for_friend_role
View_Mates: Select id, name from table_Friends where role = value_for_teammate_role


text:
Q: MOSS 2007 SqlDataSource could you please help, where can I find information, how can I set ODBC SqlDataSource on an aspx page, if I cannot edit the Web.Config file probably due to security reasons?
Is there any inline-code which can help configuring connection without Web.Config?
I have looked around, I could find post with possibly the similar problem here /however, without answer/:
http://ms-sharepoint.itags.org/q_sharepoint_173844.html

A: If by .aspx page you mean something like a web part page, maybe the fastest would be to create a DataSource in your site, using SharePoint Designer and consume data via web parts.
See example here http://office.microsoft.com/en-us/sharepoint-designer-help/add-a-database-as-a-data-source-HA010355745.aspx


text:
Q: When was the Defiant engine room set last seen/torn down? The set for the engine room of the DS9 USS Defiant was built at the end of season 3 as a permanent set. In later seasons the engine room was seen increasingly less, and I wonder when it was last seen / when the set was torn down.
I found here that 'in later years' the set was 'torn down to make room for a Klingon starship interior and generic Cardassian setting.'
I also found here that

At the end of DS9 Season 5, the Defiant-class engineering set was
deemed to be taking up much-wanted room in the swing set area of the
Paramount sound stages used by Star Trek: Deep Space Nine. This
resulted in the set for an overhead flying rig – originally built and
used for Season 2 installment "Melora" – to be removed from that
stage.

I'm not sure if the latter quote means that the engine room set was removed, or that just the overhead flying rig was removed. The engine room appears in season 6 episode 14 'One Little Ship', so that seems to indicate that the quote above was just about the overhead flying rig. Or did they rebuild the set just for that season 6 episode? (Note: I haven't watched DS9 s7 yet)
Anyway, my question: when was the Defiant engine room set last seen?

A: The Sound of Her Voice (Season 6 - Episode 25) https://memory-alpha.fandom.com/wiki/The_Sound_of_Her_Voice_(episode)
Without watching the episode again I believe the final time is a scene in Engineering where O'Brien and Kasidy are in Engineering. O'Brien is working on the com line and he's chatting with Kasidy about the Defiant having civilians aboard then the crashed Captain on the other end of the com link is suddenly able to hear them chatting


text:
Q: Check if a website's form is submitting to a database General question: Assuming someone has normal viewing access to a form/survey (say a google form as an example), what would be the ways to tell if the form is actually using the data you imputed and doing something with it rather than just pretending it was submitted?
I have a specific case like this where I think that I'm looking at a fake form that doesn't submit to any database, etc. but I'm not entirely sure what I would be looking for to confirm that.
I initially looked to see what the form submitted to and it goes to another html page, and I viewed the code on that page too, and it has only html and no PHP or JS. Is it still possible that it submits to a database?

A: You cannot know what, if anything the server will do with the submitted values unless you have access to the code running on that server.


text:
Q: ssis 2008 transactions I am using SSIS 2008 for the loading of data from txt file to sql. In this scenario I want to revert all the data if package failes in any component for that I used transaction: required at package level and transaction: supported at all data flow levels but it is not giving the desired results. Could any one give possible solutions to it.
Thanks
prav

A: Package:
TransactionOption = Required
Containers:
TransactionOption = Supported;  FailPackageOnFailure = True; ForceExecutionResult = None

A: Another option would be
A) IF Upload TextFile to SQL Package Success --> Do Step "X" ("X" is NEXT Step for example)
B) IF Upload TextFile to SQL Package FAILS --> Delete/Truncate Your Table Data --> Do Step "X" ("X" is NEXT Step for example)


text:
Q: Mysqld Crashes immediately on running on Windows 7...? I am trying to run MySql 5.1 on Windows 7 Home Premium 64 bit. I have downloaded the MSI installer from the MYSql website and installed it. The installation is successful, but the service does not start.
If I try to run MySql manually using the mysqld executable, it crashes immediately on running (error: mysqld.exe has stopped working).
Earlier mysql was running on the machine, but I had some problem with it (wasn't executing big queries) and installed it again which somehow broke the program. I had installed it to work as a service which started giving me this isse, and now it won't work even if  I don't install it as a service.
I have tried removing the mysql folder and re-installing. Is there somewhere else where Mysql saves configuration info or other data?
Has anyone else found this problem and solved it?
How can I find out why the process is failing to run?

A: Or you can try and run the mysqld.exe as administrator.

A: See the Debugging a MySQL Server in your MySQL reference manual.

*

*download the noinstall (zip archive) version of MySQL corresponding exactly to the version that is already installed on your system

*extract the .pdb symbols files to your existing MySQL installation's bin directory

*start Dr. Watson

*start mysqld-debug in standalone mode

*capture the list of all moduled (i.e. loaded DLLs) with their full path from DrWatson

*capture the stack trace from DrWatson

*examine the MySQL log files (including mysqld.trace) to see what went on immediately prior to the crash


text:
Q: Get local variable from ssh call in shell I have a script called global.sh which copies a shell script called my_local_script.sh on a remote machine.
scp my_local_script.sh host@user_a:remote_directory

Then i connect to that ssh host and execute it like this
ssh host@user "
                cd remote_directory
                ./my_local_script.sh
              "

So far so good and everything is ok, the problem is that i want to get a local variable inside my_local_script.sh to global.sh. I tried doing this
ssh host@user "
                cd remote_directory
                my_arg=$(./my_local_script.sh)
              "

But this does not work and the even the call of my local script does not work properly anymore. Any suggestions how can i overcome this issue.
PS : Copying the variable to a temporary file is not an option. I am looking for a shell solution for this if possible.

A: You are using a command substitution, which is necessary, but it is in the wrong place. You should place it around the entire SSH command:
my_var=$(ssh host@user "cd remote_directory; ./my_local_script.sh")

This is assuming that the variable you want to capture is being outputted by my_local_script eg by echo or printf.


text:
Q: If watts is power and amps is current, what is volts I know power is measured in the terms of watts, current is measured in amps, so is there an X for voltage?

A: Voltage is the difference in energy between two points in an electric field, expressed per unit of charge. A Volt is a Joule per Coulomb: \$V = J/C\$.  The voltage between two points tells us how much energy each electron will gain or lose when it moves between those two points.
The separation of opposite charges stores energy. If we separate charges such that there is one volt between them, that represents less energy than if we separate the same charges such that there are two volts between them.  And of course we store more energy by separating more charges at the same voltage.
This is why power is related to both current and voltage.

A: *

*power is measured in watts

*current is measured in amps

*electric potential is measured in volts

A: \$1V=\dfrac{1J}{C}\$
\$1A=\dfrac{1C}{s}\$
\$\therefore P=IV=\dfrac{C}{s}\dfrac{J}{C}=\dfrac{J}{s}=W\$
Any of the different formulas for power can be derived using these relationships.

A: Victorian textbooks had an excellent take on this, introducing electricity for engineers more used to hydraulics or steam...

*

*Power is the equivalent of hydraulic power;

*Current is the equivalent of current;

*and Voltage is the equivalent of pressure.

In fact up until about the 1920s you will see textbooks talking about "electrical pressure, measured in Volts".
It is a really good analogy in that the concepts translate perfectly, and really make understanding the difference between voltage and current, and how circuits work.

A: Voltage is an electric potential energy difference. Think of it like gravity but for the force between electrons rather than the attractive force between two objects with mass.
Google defines it as

The SI unit of electromotive force, the difference of potential that
  would carry one ampere of current against one ohm resistance.


text:
Q: Instantiate newRequestQueue Volley I have a new class where I try to Instantiate a new newRequestQueue with the with the Volley.
I try to Instantiate It like this:
RequestQueue queue = Volley.newRequestQueue(this);

And have an error:,
newRequestQueue (android.content.Context) in Volley cannot be applied to (pawel.cooker.API)

Here's code of my class:
package pawel.cooker;

import com.android.volley.*;
import com.android.volley.toolbox.Volley;

public class API {

    protected String ServerURL;
    protected String GET;
    protected String POST;
    RequestQueue queue =  Volley.newRequestQueue(this);

    public API(){
        setServerURL("http://localhost:63424");
        setGET("http://localhost:63424");
        setPOST("http://localhost:63424");

    }

    //Logowanie
    public boolean CheckLogin (String Login, String Password){
        setGET(getGET()+"/api/user");

        if (){
            return true;
        }
        else{
            return false;
        }

    }

    public String getServerURL() {
        return ServerURL;
    }

    public void setServerURL(String ServerURL) {
        ServerURL = ServerURL;
    }

    public String getGET() {
        return GET;
    }

    public void setGET(String GET) {
        this.GET = GET;
    }

    public String getPOST() {
        return POST;
    }

    public void setPOST(String POST) {
        this.POST = POST;
    }

}

I was also trying this solution:
 Volley.newRequestQueue(getActivity().getApplicationContext());

But still have same problem. How can I instantiate it right?

A: I think you have 2 problems here.

*

*You are passing in (this) which you can't do at that point.  (this) hasn't been created yet because the constructor hasn't been called yet.

*(this) is of type API which is the wrong type to pass in. You need to pass in the type android.content.Context

A: Okey I find solution.
First

*

*Add 'extends Application' in class

*Then queue = Volley.newRequestQueue(getApplicationContext());


text:
Q: Magento223: How to Import CSV during module installation I have custom module in which i am importing csv file upon button click.
I want to import the csv during module installation, i don't know how to implement it in install data file.
Any help will be appreciated.

A: You can find examples of import CSV files during installation on Magento 2 Sample data module https://github.com/magento/magento2-sample-data/blob/2.3-develop/app/code/Magento/CatalogSampleData/Setup/Installer.php


text:
Q: InfoBright MYSQL Daily crashes for the last 4 days
From last 4 days we are facing frequent database crashes with mysql infobright engine, there is no recent changes on production environment and no updates.
  Currently we are using the version 5.1.40.

Find the below dump, can any one help to figure out the issue.
170520 21:12:08 - mysqld got signal 11 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.
We will try our best to scrape up some info that will hopefully help diagnose
the problem, but since we have already crashed, something is definitely wrong
and this may fail.

key_buffer_size=1677721600
read_buffer_size=1048576
max_used_connections=75
max_threads=1000
threads_connected=54
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 3696548 K
bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

thd: 0xc2a4bd000
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
stack_bottom = 0x7fc0d0bede58 thread_stack 0x80000
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0xaef849]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0x412e13]
/lib64/libpthread.so.0(+0xf7e0) [0x7fc0d48c77e0]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0xb10635]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0xb1f123]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0x9a9693]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0x76ae0c]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0x76b594]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0x767ab3]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0x7694ea]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0x72902b]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0x422325]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0x427573]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0x42b38c]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0x42c227]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0x42cb05]
/usr/local/infobright-4.7.1-x86_64/bin/mysqld() [0x41f06d]
/lib64/libpthread.so.0(+0x7aa1) [0x7fc0d48bfaa1]
/lib64/libc.so.6(clone+0x6d) [0x7fc0d460caad]
Trying to get some variables.
Some pointers may be invalid and cause the dump to abort...
thd->query at 0xc2da5e410 = SELECT   DATE_FORMAT(DATETIME,'%Y%m%d')  AS YEAR_MONTH_DAY_SK  ,HOUR(DATETIME)  AS HOUR_SK,  IFNULL(DESTINATION,'0') AS DESTINATION,  IFNULL(DATETIME,'1970-01-01 00:00:00') AS DATETIME,  IFNULL(CLIENTID,'0') AS CLIENTID,  IFNULL(GROUPID,'0') AS GROUPID,  IFNULL(TEAMID,'0') AS TEAMID,  IFNULL(SERVICEID,'0') AS SERVICEID,  IFNULL(CHANNELID,'0') AS CHANNELID,  IFNULL(STATUSID,'0') AS STATUSID,  CASE REASONCODE WHEN '' THEN NULL WHEN NULL THEN NULL ELSE REASONCODE END  AS REASONCODE,  CASE REASONDESC WHEN '' THEN NULL WHEN NULL THEN NULL ELSE REASONDESC END  AS REASONDESC,  IFNULL(ACTIONTYPE1ID,'0') AS ACTIONTYPE1ID,  CASE ACTIONTYPE1DESC WHEN '' THEN NULL WHEN NULL THEN NULL ELSE ACTIONTYPE1DESC END  AS ACTIONTYPE1DESC,  IFNULL(ACTIONTYPE2ID,'0') AS ACTIONTYPE2ID,  CASE ACTIONTYPE2DESC WHEN '' THEN NULL WHEN NULL THEN NULL ELSE ACTIONTYPE2DESC END  AS ACTIONTYPE2DESC,  IFNULL(ATTACHMENT,'0') AS ATTACHMENT,  CASE MIMETYPE WHEN '' THEN NULL WHEN NULL THEN NULL ELSE MIMETYPE END  AS MIMETYPE,  CASE VOICEFLOWNAME WH
thd->thread_id=35918
thd->killed=NOT_KILLED
The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.
170520 21:12:08 mysqld_safe Number of processes running now: 0
170520 21:12:08 mysqld_safe mysqld restarted
tcmalloc: large alloc 1365172224 bytes == 0x4518000 @
Loading configuration for Infobright instance ...
Option: AllowMySQLQueryPath, value: 1.
Option: AutoConfigure, value: 0.
Option: CacheFolder, value: /usr/local/infobright-4.7.1-x86_64/cache.
Option: ControlMessages, value: 0.
Option: IBEngineRevision, value: IEE_4.7.1_r30553_31737.
Option: InternalMessages, value: 0.
Option: InternalMessagesFlushPeriod, value: 60.
Option: KNFolder, value: BH_RSI_Repository.
Option: KNLevel, value: 99.
Option: LicenseCheckInterval, value: 0.
Option: LicenseExpireWarningDays, value: 0.
Option: LicenseFile, value: <unknown>.
Option: LicenseServerIPAddr, value: .
Option: LicenseServerType, value: .
Option: LicenseServerWarningNumber, value: .
Option: LoaderMainHeapSize, value: 800.
Option: PushDown, value: 1.
Option: ServerMainHeapSize, value: 48000.
Option: UseMySQLImportExportDefaults, value: 0.
Option: bherrLogLevel, value: 1.
Infobright instance configuration loaded.
tcmalloc: large alloc 40265318400 bytes == 0x687c8000 @
tcmalloc: large alloc 10066329600 bytes == 0x9cff48000 @
170520 21:12:09 [ERROR] Can't start server: Bind on TCP/IP port: Address already in use
170520 21:12:09 [ERROR] Do you already have another mysqld server running on port: 5029 ?
170520 21:12:09 [ERROR] Aborting

170520 21:12:09 [Note] /usr/local/infobright-4.7.1-x86_64/bin/mysqld: Shutdown complete

    170520 21:12:09 mysqld_safe mysqld from pid file /data/infobright/data/SH-UMP-CINFBRT2.pid ended


text:
Q: Getting values of fields in XML I have the folling XML (as string)
xml = '''
<?xml version="1.0" encoding="utf-8"?>
<Response total="00:00:00.2130175">
  <Result>
    <Channel name="test">
      <TotalCount ignoringpaging="2">2</TotalCount>
      <Products>
        <Product id="8050" ecommerceproduct="Productname">
          <Fields>
            <Field name="pid">8050</Field>
            <Field name="ProductName">Productname</Field>
            <Field name="ProductCategorie" culture="nl-NL">Category</Field>
            <Field name="Titel" culture="nl-NL">Product Titel</Field>
            <Field name="ProductHoogte">74</Field>
            <Field name="ProductVerstelbaarheid">Vast</Field>
            <Field name="ProductDikte">25</Field>
            <Field name="ProductMateriaal">Gemelamineerd spaanplaat</Field>
            <Field name="ProductLijn">0</Field>
            <Field name="prodId">63258518</Field>
          </Fields>
          <Variants>
            <Variant id="8060" ecommerceproduct="Productname">
              <Fields>
                <Field name="ProductName">Productname / Black</Field>
                <Field name="PID">8060</Field>
                <Field name="Zichtbaar">Y</Field>
                <Field name="articleCode">123456</Field>
                <Field name="priceExcl">469</Field>
                <Field name="ProductBreedte">180</Field>
                <Field name="ProductDiepte">80</Field>
                <Field name="ProductHoogte">74</Field>
                <Field name="varId">121655579</Field>
                <Field name="visible">Y</Field>
              </Fields>
            </Variant>
          </Variants>
        </Product>
                <Product id="8051" ecommerceproduct="Productname 2">
          <Fields>
            <Field name="pid">8051</Field>
            <Field name="ProductName">Productname 2</Field>
            <Field name="ProductCategorie" culture="nl-NL">Category</Field>
            <Field name="Titel" culture="nl-NL">Product Titel 2</Field>
            <Field name="ProductHoogte">74</Field>
            <Field name="ProductVerstelbaarheid">Vast</Field>
            <Field name="ProductDikte">25</Field>
            <Field name="ProductMateriaal">Gemelamineerd spaanplaat</Field>
            <Field name="ProductLijn">0</Field>
            <Field name="prodId">63258520</Field>
          </Fields>
          <Variants>
            <Variant id="8061" ecommerceproduct="Productname 2">
              <Fields>
                <Field name="ProductName">Productname 2 / White</Field>
                <Field name="PID">8061</Field>
                <Field name="Zichtbaar">Y</Field>
                <Field name="articleCode">234567</Field>
                <Field name="priceExcl">499</Field>
                <Field name="ProductBreedte">180</Field>
                <Field name="ProductDiepte">80</Field>
                <Field name="ProductHoogte">74</Field>
                <Field name="varId">216555798</Field>
                <Field name="visible">N</Field>
              </Fields>
            </Variant>
          </Variants>
        </Product>
      </Products>
    </Channel>
  </Result>
</Response>'''

with xml.etree I can iterate over the Products, but how can I get all the values of the fields and variants fields.
  root = ET.fromstring(xml)

  for p in root.iter('Product'):
    print(p.attrib)

the output I get is:
{'id': '8050', 'ecommerceproduct': 'Productname'}
{'id': '8060', 'ecommerceproduct': 'Productname 2'}
So this seems to work, but whatever I try to get the values from the fields, I get no response.


text:
Q: What is the difference between adding and multiplying fixed effects in linear mixed-effects models such as lme4 Short question – What is the difference between these two linear mixed-effects models:
lme4::lmer(duration ~ stress*city*run + (1 | participantID),
           s2data)

lme4::lmer(duration ~ stress + city*run + (1 | participantID),
           s2data)

Detailed question:
I have a dataset from a virtual user study where participants performed a route-following task from an origin to a destination. Every participant conducted two runs in two different cities in a counterbalanced order. The route in the two cities were of different lengths. Half of the participants were tested under the influence of an additional stressor.
My goal is to determine if a learning effect can be found with increasing task experience, either across all participants or across one of the two stress groups. Here is a glimpse at the data structure:
participantID, stress, city, run, duration

I came up with the two different linear mixed-effects models, using lme4-package in RStudio (see Short question).
When multiplying all fixed effects, there is no significant difference between the different runs.
However, when using stress + city*run, there is a significant difference between the different runs.
Can anyone tell me the differences between these two approaches and which approach makes more sense to determine a potential learning effect with increasing task experience? Thank you in advance!


text:
Q: SAP .net Connector 3.0 item not showing up in visual studio 08, 10, etc I got the new SAP .net connector 3.0 that is supposed to work for visual studio 2008 and 2010.  I just tried to create a C# console application and I went to the project menu to add a "new item" but I do not see an SAP Proxy item.  What am I missing ?
I am aware of the .net connector 2.0 but I do not want the 2.0 version.  I've already seen the code project article etc etc so please do not post a link to an article referencing the 2.0 version.  The whole purpose of SAP .net connector 3.0 is to utilize vs 2010.
I've also taken the 2 dll files from C:\Program Files\SAP\SAPDotNet (sapnco.dll, and sapnco_utils.dll) and referenced those files in my C# application.  I also have a reference to System.Web.Services.
I should be now able to right click my project and "Add Item" and one of those items should be an SAP Proxy object item...

A: The 3.0 connector doesn't work this way. From the documentation:

With the .NET Connector 2.0, the NCo design time would generate a "proxy method"
  for each ABAP function module you want to call, and one specific class for each
  structure or table type that this function module is referencing. You had to create
  objects from these structure/table classes and pass them into the proxy method
  corresponding to the function module.
Now with the .NET Connector 3.0, there is no longer any kind of generated code.

Good:

*

*No Visual Studio version dependency.

*Small changes in SAP function doesn't break the client.

*No generated code.

Bad:

*

*No auto completion. You have to read the function and datatype declarations. In SAP or in the debugger.

Documentation and samples.


text:
Q: How do I correct my htaccess for proxying search engine crawl requests? I have built a website with React at the front end and WordPress as the backend. For search engine crawlers to see my site, I have set up prerendering at the server side, and am trying to set up htaccess to proxy requests coming from search engines so that they are served pre-rendered pages.
For testing, I am using the "Fetch as Google" tool in Google Webmasters.
Here is my attempt:
<IfModule mod_rewrite.c>
    RewriteEngine On
    <IfModule mod_proxy_http.c>
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteCond %{HTTP_USER_AGENT} googlebot [NC,OR]
    RewriteCond %{QUERY_STRING} _escaped_fragment_
    # Proxy the request ... works for inner pages only
    RewriteRule ^(?!.*?)$ http://example.com:3000/https://example.com/$1 [P,L]

    </IfModule>
</IfModule>
# BEGIN WordPress
<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /
   RewriteRule ^index\.php$ - [L]
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule . /index.php [L]
</IfModule>
# END WordPress

My problem is that this directive doesn't work for my home page, and works only for inner pages (http://example.com/inner-page/):
RewriteRule ^(?!.*?)$ http://example.com:3000/https://example.com/$1 [P,L]

When I change this line to the following line, the home page request is indeed proxied correctly, but the inner pages stop working.
RewriteRule ^(index\.php)?(.*) http://example.com:3000/https://example.com/$1 [P,L]

Could you help me fix the rewrite rule so that my home page is also proxied correctly for the googlebot?

A: Change the RewriteRule to:
RewriteRule ^(.*)/?$ http://example.com:3000/https://example.com/$1 [P,L]

A: First avoid the repetetions
<IfModule mod_rewrite.c>
    RewriteEngine On
    <IfModule mod_proxy_http.c>
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteCond %{HTTP_USER_AGENT} googlebot [NC,OR]
    RewriteCond %{QUERY_STRING} _escaped_fragment_
    # Proxy the request ... works for inner pages only
    RewriteRule ^(?!.*?)$ http://example.com:3000/https://example.com/$1 [P,L]
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

    </IfModule>
</IfModule>

Then change ^(?!.*?)$ to ^.*$ or with a good pattern like [a-zA-Z0-9-.]*. Don't forget to use 0 or more flag (*) there.
The correct code will be
<IfModule mod_rewrite.c>
    RewriteEngine On
    <IfModule mod_proxy_http.c>
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteCond %{HTTP_USER_AGENT} googlebot [NC,OR]
    RewriteCond %{QUERY_STRING} _escaped_fragment_
    # Proxy the request ... works for inner pages only
    RewriteRule ^(.*)$ http://example.com:3000/https://example.com/$1 [P,L]
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

    </IfModule>
</IfModule>


text:
Q: trouble using an api on heroku from a rails app for a project at school I am trying to use the Bandsintown api to display upcoming concerts for artists that a user follows on my site.  I am able to use the api the way I want to in development but when it comes to my heroku site in production nothing displays and I receive no errors, in fact I just receive an empty array.  Perhaps you need permission from Bandsintown to use their api on heroku?  I tried contacted them but have not heard a response yet.
My question, why am I able to get a response from Bandsintown on development but not in production?  New to web dev in general, so I haven't come across this before..
Here is my code:
calendar_controller.rb
class CalendarController < ApplicationController
  require 'uri'

  def index
    @user = current_user
    @hash_version_array = []

    @user.follows.each do |follow|
      response = HTTParty.get("http://api.bandsintown.com/artists/#{URI.escape(follow.artist_name)}/events/search.json?api_version=2.0&app_id=#{app_id}&location=use_geoip")
      @hash_version = JSON.parse(response.body)

      @hash_version_array << @hash_version if @hash_version != []
    end

    @hash_version_array
  end
end

calendar/index.html.erb

<%= @user.name %>'s Calendar

<%= link_to "Calendar" %>

<%= link_to "List" %>

<%= link_to "Map" %>

<% @hash_version_array.each do |date| %>

<%= date[0]["formatted_datetime"] %>

  <% date[0]["artists"].each do |info| %>

<%= info["name"] %>

    <%= image_tag("#{info['thumb_url']}", class: 'artist_img') %>
  <% end %>

  <%= date[0]["venue"]["name"] %>

  <%= date[0]["formatted_location"] %>, <%= date[0]["venue"]["country"] %>

  Tickets <%= date[0]["ticket_status"].titleize %> <%= link_to("Buy", "#{date[0]['ticket_url']}") %>

<% end %>

Response from Bandsintown while working in development:
From: /Users/jasonquaccia/Sites/code/projects/capstone/the-music-project/app/controllers/calendar_controller.rb @ line 15 CalendarController#index:

     4: def index
     5:   @user = current_user
     6:   @hash_version_array = []
     7:
     8:   @user.follows.each do |follow|
     9:     response = HTTParty.get("http://api.bandsintown.com/artists/#{URI.escape(follow.artist_name)}/events/search.json?api_version=2.0&app_id=el_proyecto_de_la_musica&location=use_geoip")
    10:     @hash_version = JSON.parse(response.body)
    11:
    12:     @hash_version_array << @hash_version if @hash_version != []
    13:   end
    14:
 => 15:   binding.pry
    16:   @hash_version_array
    17: end

[1] pry(#<CalendarController>)> @hash_version_array
=> [[{"id"=>10847723,
   "title"=>"Metallica @ AT & T Park in San Francisco, CA",
   "datetime"=>"2016-02-06T19:00:00",
   "formatted_datetime"=>"Saturday, February 6, 2016 at 7:00PM",
   "formatted_location"=>"San Francisco, CA",
   "ticket_url"=>"http://www.bandsintown.com/event/10847723/buy_tickets?app_id=el_proyecto_de_la_musica&artist=Metallica&came_from=67",
   "ticket_type"=>"Tickets",
   "ticket_status"=>"available",
   "on_sale_datetime"=>"2015-11-06T10:00:00",
   "facebook_rsvp_url"=>"http://www.bandsintown.com/event/10847723?app_id=el_proyecto_de_la_musica&artist=Metallica&came_from=67",
   "description"=>"CBS RADIO's The Night Before with Metallica and Cage the Elephant",
   "artists"=>
    [{"name"=>"Metallica",
      "mbid"=>"65f4f0c5-ef9e-490c-aee3-909e7ae6b2ab",
      "image_url"=>"https://s3.amazonaws.com/bit-photos/large/4304043.jpeg",
      "thumb_url"=>"https://s3.amazonaws.com/bit-photos/thumb/4304043.jpeg",
      "facebook_tour_dates_url"=>"http://www.bandsintown.com/Metallica/facebookapp?came_from=67",
      "facebook_page_url"=>nil,
      "tracker_count"=>2341049,
      "url"=>"Metallica",
      "website"=>"http://metallica.com"}],
   "venue"=>{"name"=>"AT & T Park", "city"=>"San Francisco",     "region"=>"CA", "country"=>"United States", "latitude"=>37.7784059, "longitude"=>-122.3894401}}]]

A: Found out why I am not getting anything while in production on Heroku, has to do with location=use_geoip on this line:
response = HTTParty.get("http://api.bandsintown.com/artists/#{URI.escape(follow.artist_name)}/events/search.json?api_version=2.0&app_id=#{app_id}&location=use_geoip")

This works locally because it can reference my location and then search Bandsintown for the correct information.  However, on Heroku it does not know how to correctly reference a location.  Therefore I don't receive any results.


text:
Q: Warning while loading the BertModel I load a BERT model using the following code snippet:
        name = "bert-base-uncased"

        from transformers import BertModel
        from transformers import BertTokenizer

        print("[ Using pretrained BERT embeddings ]")
        self.bert_tokenizer = BertTokenizer.from_pretrained(name, do_lower_case=lower_case)
        self.bert_model = BertModel.from_pretrained(name)
        if fix_emb:
            print("[ Fix BERT layers ]")
            self.bert_model.eval()
            for param in self.bert_model.parameters():
                param.requires_grad = False
        else:
            print("[ Finetune BERT layers ]")
            self.bert_model.train()

But I get the following error:
Some weights of the model checkpoint at bert-base-uncased were not used when initializing BertModel: ['cls.seq_relationship.weight', 'cls.predictions.transform.dense.bias', 'cls.predictions.transform.dense.weight', 'cls.seq_relationship.bias', 'cls.predictions.bias', 'cls.predictions.transform.LayerNorm.weight', 'cls.predictions.decoder.weight', 'cls.predictions.transform.LayerNorm.bias']
- This IS expected if you are initializing BertModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
- This IS NOT expected if you are initializing BertModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).

What is going wrong here?

A: These might help.
you're loading the bert-base-cased checkpoint (which is a checkpoint that was trained using a similar architecture to BertForPreTraining) in a BertForSequenceClassification model.
This means that:
The layers that BertForPreTraining has, but BertForSequenceClassification does not have will be discarded
The layers that BertForSequenceClassification has but BertForPreTraining does not have will be randomly initialized.

This is expected, and tells you that you won't have good performance with your BertForSequenceClassification model before you fine-tune it.


text:
Q: Get Safari current URL's in a list to Google Chrome Im trying to run AppleScript on Python to get all my current url in safari windows, so a create the following code:
from asyncio import subprocess
import os
import webbrowser as wb

cmd = """osascript -e 'tell application \"Safari\" to get the URL of every tab of every window'"""

def url():
    os.system(cmd)

url()

I need to save it in a list to import the URL to another web browser, Google Chrome for example.


text:
Q: uWSGI run on exit I'm running a Flask app via uWSGI. I have some cleanup code that I need to run when my app exits (to shut down some external processes). I installed signal handlers for SIGTERM and SIGINT to run the script using the python signal module. These work when I just run the app using python and hit for example Ctrl+C. However, for whatever reason, these don't get run when I do /etc/init.d/uwsgi-emperor stop, so they must be being bypassed by uWSGI code. What's the best way to get a function to be run on exit?

A: Do not override UNIX signals in uWSGI workers, it is the path to an infinite stream of problems. As already suggested use python atexit module, the uwsgi.atexit python hook, or the more general uwsgi hooks (the ones you define from options, like --exec-as-user-atexit)


text:
Q: Python not able to compare the dates in dateframes I have a dataframe df['Latest date'] as below
45      01.12.2015 - 13:35:23
46      01.12.2015 - 13:36:27
                ...
4355    09.07.2018 - 07:54:22
4356    09.07.2018 - 07:52:03
4357    24.07.2018 - 16:00:36
4358    09.07.2018 - 07:53:19
4359    09.07.2018 - 11:40:22
4369    23.07.2018 - 09:13:34
4370    16.07.2018 - 13:02:28
4371    23.07.2018 - 09:14:13
4372    23.07.2018 - 09:14:44
4374    23.07.2018 - 09:15:35
4378    23.07.2018 - 09:15:58
4379    23.07.2018 - 09:16:24
4380    23.07.2018 - 09:16:41
4381    23.07.2018 - 09:17:16
4383    23.07.2018 - 09:17:53
4387    23.07.2018 - 09:18:28
4389    23.07.2018 - 09:19:25
4393    23.07.2018 - 09:20:08
4394    25.07.2018 - 14:25:20
4395    18.07.2018 - 10:10:58
4396    18.07.2018 - 10:10:18
4398    18.07.2018 - 10:10:42
4399    16.07.2018 - 11:09:21
4400    16.07.2018 - 11:27:23
4401    23.07.2018 - 09:21:16
4407    18.07.2018 - 10:11:15
4417    24.07.2018 - 11:56:14
4418    25.07.2018 - 11:05:11

I want to filter for the rows with date> 22/07/2018
I tried df=df[(df["Latest date"]>"22/07/2018")]
however the new df returns entries not necessarily after 22/07/2018. I wonder if it is not understanding the dates are in "dd/mm/yy" formats.

A: You need first parse dates to datetimes by to_datetime with parameter format, see also http://strftime.org/ if different formating:
df["Latest date"] = pd.to_datetime(df["Latest date"], format='%d.%m.%Y - %H:%M:%S')
#slowier solution without defined format
#df["Latest date"] = pd.to_datetime(df["Latest date"])

print (df["Latest date"].dtype)
datetime64[ns]

[30000 rows x 1 columns]
df = pd.concat([df] * 1000, ignore_index=True)

In [204]: %timeit df["Latest date1"] = pd.to_datetime(df["Latest date"], format='%d.%m.%Y - %H:%M:%S')
163 ms ± 3.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [205]: %timeit df["Latest date2"] = pd.to_datetime(df["Latest date"])
5.09 s ± 55.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So now is possible filtering:
df=df[(df["Latest date"]>"22/07/2018")]
print (df)
             Latest date
4357 2018-07-24 16:00:36
4369 2018-07-23 09:13:34
4371 2018-07-23 09:14:13
4372 2018-07-23 09:14:44
4374 2018-07-23 09:15:35
4378 2018-07-23 09:15:58
4379 2018-07-23 09:16:24
4380 2018-07-23 09:16:41
4381 2018-07-23 09:17:16
4383 2018-07-23 09:17:53
4387 2018-07-23 09:18:28
4389 2018-07-23 09:19:25
4393 2018-07-23 09:20:08
4394 2018-07-25 14:25:20
4401 2018-07-23 09:21:16
4417 2018-07-24 11:56:14
4418 2018-07-25 11:05:11

EDIT:
Another possible solution if input data are in csv is use parse_dates parameter by position of column or by column name:
df = pd.read_csv(file, parse_dates=['Latest date'])
#e.g. third column, pandas counts from 0
#df = pd.read_csv(file, parse_dates=[2])


text:
Q: Is a separate Data Layer necessary when using Linq to Entities? When using Linq to Entities, is it still necessary to abstract database access using a separate Data Layer, or is it acceptable (or even recommended) to make Linq queries directly from code-behind (Since the Get, Add, Update, and Delete functionality is already built into the Entity Framework)?

A: We use Linq to EF and we still have a separate data layer.
Partly because what happens in the future if we don't want to use EF any more, or if we need to support a database that EF doesn't support. Part of the point of abstraction is that every layer can be changed without effecting the others.
But also because our data layer is a little more complex than just plain loading and saving of data objects. After objects are loaded from EF they are fully disconnected from the EF data context and translated into business objects. The EF generated data objects are never exposed above the data layer. (This is done because of EF's poor support for disconnected client-server applications, so we have to manage that part ourselves)

A: Linq-to-Entities is an implementation detail. A data layer is intended to abstract the implementation away from interactions with the data. This ensures robustness in your system should you discover that Linq-to-entities is not the right fit and you have to change the implementation. Therefore, yes, you still need a data layer.

A: In my opinion, the Entity framework is a DAL.  Although in some applications I have wrapped it because it's still a specific technology and I try abstract specific technologies from the application as a whole. So if there was a need to go to a different one or change how the business objects are created you can do that without affecting the rest of your application.
It's going to be interesting some of the responses you get since this really applies to all OR/M tools.

A: It depends on how close the dead line is, how big is the application you wish to develop and probably many more.
I would say yes, do implement a data layer. For example: what if the application would need to run using an Oracle database (some time in the future).. things sure would get ugly very quick.


text:
Q: Evaluating $\int\frac{x^4+1}{x^6+1}dx$ I have problem with this integral:
$$\int\dfrac{x^4+1}{x^6+1}dx$$
I guess it is easy, but I was trying for quite a long time and the only thing I got is headache.
Thanks for help

A: Try
$$
\frac{x^4+1}{x^6+1}=\frac{x^4-x^2+1}{x^6+1}+\frac{x^2}{x^6+1}
=\frac1{x^2+1}+\frac{x^2}{x^6+1}.
$$
The first term is a table integral. The second term reduces to it with the substitution $t=x^3, dt=3x^2\,dx$.

A: hint
$$\frac{x^4+1}{x^6+1}=\frac{2}{3(x^2+1)}+\frac{x^2+1}{3(x^4-x^2+1)}$$
And proceed to the next step in decomposing the second fraction of the RHS

A: $\bf{My\; Solution:: }$ Let $$\displaystyle I = \int\frac{x^4+1}{x^6+1}dx = \int \frac{(x^2+1)^2-2x^2}{(x^2+1)\cdot (x^4-x^2+1)}dx$$
$$\displaystyle I  = \int\frac{x^2+1}{x^4-x^2+1}dx-2\int\frac{x^2}{(x^3)^2+1}dx = \int\frac{\left(1+\frac{1}{x^2}\right)}{\left(x-\frac{1}{x}\right)^2+1}dx-\frac{2}{3}\int\frac{3x^2}{(x^3)^2+1}dx$$
For First Integral put $$\displaystyle \left(x-\frac{1}{x}\right)=t\;\;,$$ Then $$\left(1+\frac{1}{x^2}\right)dx =dt$$
And for Second Integral Put $$x^3=u\;\;, 3x^2dx=du$$
So We Get $$\displaystyle I = \int\frac{x^4+1}{x^6+1}dx = \tan^{-1}\left(x-\frac{1}{x}\right)-\frac{2}{3}\tan^{-1}(x^3)+\mathcal{C}$$


text:
Q: Cyclic Groups - $a^k = e \text{ iff } n|k$ I saw this proof in the book on Abstract Algebra. Here is part of it:
Let $G$ be a cyclic group of order $n$ and $a$ is the generator of $G$. Then $a^k = e \iff n|k$
Proof: Suppose $a^k=e$. By the division algorithm, $\exists q,r \text{ such that } k=nq+r$ where $0\le r < n$. So $e=a^k = a^{nq+r} = a^{nq}a^r = ea^r = a^r$
My question is: is this circular, because we are already assuming that $a^{nq} = e$?

A: Exponent laws still work in groups, so we can prove that $a^{nq}=e$ by noting:
$$a^{nq}=\left(a^n\right)^q=e^q=e$$
where the first two expressions both expand to $$\underbrace{a\cdot a\cdot a\cdot \ldots\cdot  a \cdot a}_{nq\text{ times}}$$
and the next follows from replacement with $a^n=e$.
Moreover, notice that the statement $a^{nq}=e$ is exactly the same as

$n|k$ implies $a^k=e$

whereas the proof you present aims to show the converse:

$a^k=e$ implies $n|k$

So it's not actually circular - the premise it is taking is distinct from what it is proving and can be proven separately.


text:
Q: how to fix Out of memory error in c# I created dll from c function and importing into c#
When I call the dll function I am getting error:
Unable to load DLL 'subFunction.dll': Not enough storage is available to process this command. (Exception from HRESULT: 0x80070008).

How to fix it.

A: I am inclined to say you look at it from the wrong side - this is not a C# issue, it is a simple as it is error in C++. I suggest you put up a native C++ command line test and check whether this happens there too, then you go on and fix your code.
Without debugging we are sort of guessing what you made wrong - and that will never work. BUt this seriously looks like C# is totally irrelevant for the question and it is a pure C level issue.


text: Q: Invision Power Board Invision Power Board (abbreviated IPB, IP.Board or IP Board) is Internet forum software produced by Invision Power Services, Inc. It is written in PHP and primarily uses MySQL as a database management system. The software is commercially sold under a propriety license.


text: Q: prohibiting float to double conversion I'm learning C programming, so during writing my code, one question emerged in my head. I'm writing program which works with numbers featuring floating point, but it does not require so big mantissa as double variable provides. As far as I know, due to latest standards, C compilers automatically convert float variables to double. So I was wondering if C syntax that prohibits converting my variables defined as float, to double exist. Is it compiler defined functionality or C syntax features such conversion definition? I'm using GCC by the way, if it matters.


text:
Q: Client side changes of div title are not being reflected in C# code behind I have a problem with my div element title. The following is my div element:

The following is my javascript:
function div_Click(btn) {
    if (btn.title == "any") {
        btn.title = "on";
        btn.style.background = "url('sample1.png')";
    }
    else if (btn.title == "on") {
        btn.title = "off";
        btn.style.background = "url('sample2.png')";
    }
    else if (btn.title == "off") {
        btn.title = "any";
        btn.style.background = "url('sample3.png')";
    }
    return false;
}

and after changing the title to "on" or "off" from client side, the value of Attributes["title"] from c# code behind is still "any"!! Any help guys...

A: What are you trying to do? Since title is attribute it is never posted back to server. Only input element are posted back to server. There fore you are unable to get the changed value.
To bypassthis restriction you will have to add hiddenfield with runat server tag. update hiddenfield value to the div title before post and recover the value in your code behind by using hiddenfield. value.
Hope this is clear.

A: Try this, this will help you
$('#sampleDiv').click(function() {
    if ($(this).prop('title') == "any") {
        $(this).prop('title',"on");
        $(this).prop('background,url(sample1.png)');
    }
    else if ($(this).prop('title') == "on") {
         $(this).prop('title',"off");
        $(this).prop('background,url(sample2.png)');
    }
    else if ($(this).prop('title') == "off") {
         $(this).prop('title',"any");
        $(this).prop('background,url(sample3.png)');
    }
});

fiddle  Here

A: Better to use a switch statement here. It will break if there is a match
 function div_Click(btn) {
     btn=$(btn);
     switch(btn.attr('title'))
        {
        case 'any':
          btn.attr('title','on');
          btn.css('background','url(sample1.png)');
          break;
        case 'on':
          btn.attr('title','off');
          btn.css('background','url(sample2.png)');
          break;
        case 'off':
          btn.attr('title','on');
          btn.css('background','url(sample3.png)');
          break;
        default:
          //default code if no match
        }
    }


text:
Q: PDO Statement does not return full array I cant figure out why i only get 1 entry in the returning array, when the table has 4 entries in total.
My PDO code is:
$stmtkat = $this->db->prepare("SELECT * FROM kategorie");
$stmtkat->execute();
$katarray=$stmtkat->fetch(PDO::FETCH_ASSOC);
var_dump($katarray);

The return array i get:
 array(2) { ["id"]=> string(1) "1" ["kategorie"]=> string(12) "Coaching" }

The table has 4 rows, why do i get only the first row into the array?
What i am doing wrong? Obviously i am new to PDO.
Ty for your time.

A: You are only fetching one of the result rows produced by your query
If you use ->fetch() to get result rows one at a time you do it in a while loop like this
$stmtkat = $this->db->prepare("SELECT * FROM kategorie");
$stmtkat->execute();
while ( $katarray=$stmtkat->fetch(PDO::FETCH_ASSOC) ) {
    var_dump($katarray);
}

Or use fetchAll() to return all rows into a local array from a single call to the PDO Stmt object
$stmtkat = $this->db->prepare("SELECT * FROM kategorie");
$stmtkat->execute();
$katarray=$stmtkat->fetchAll(PDO::FETCH_ASSOC) ) {

var_dump($katarray);

A: You get only one row in return because:

PDOStatement::fetch — Fetches the next row from a result set

Use fetchAll() instead to get full array() of result or use fetch() inside while() loop.
Example with fetch() and while():
while ($stmtkat->fetch(PDO::FETCH_ASSOC)) {
  var_dump($katarray);
}

Example with fetchAll():
$result = $stmtkat->fetchAll(PDO::FETCH_ASSOC)
var_dup($result);


text:
Q: How to show this tensor is not decomposable Let $V$ a vector space over $\mathbb{F}$ with basis $B=\{e_1,\dots, e_n \}$ and $B'=\{e^1,\dots,e^n \}$ adjoint basis in $V^*$, Consider the following tensor:
$$t^{ij}=(i+j) $$
I need to see that is not decomposable. This is the proof of my professor:
$\delta=\sum_{i,j=1}^{n}(i+j)(e_i\otimes e_j), $ suppose $\delta=\left(\sum_{i=1}^{n}x_ie_i\right) \otimes \left(\sum_{i=1}^{n}y_j e_j \right)$. As $n\geq 2$, we have $x_1y_1=2$,$x_1y_2=3$, so $y_1/y_2=2/3$, but $x_2y_1=3$, $x_2y_2=4$ and $y_1/y_2=3/4$ that is a contradiction.
I am not sure why this numbers are related with the fact that is decomposable, tensors are pretty hard to me, can you help me to understand this?

A: Let $\delta=\sum_{i,j=1}^n(i+j)(e_i\otimes e_j)$, as you have. By definition, a decomposable element of $V\otimes V$ is one of the form $v\otimes w$, for some $v,w\in V$. To show that $\delta$ is not decomposable, we therefore need to show that $\delta\neq v\otimes w$, for any $v,w\in V$. On the other hand, since $B$ is a basis of $V$, every element of $V$ is of the $\sum_{i=1}^nx_ie_i$, for some $x_i\in \mathbb{F}$. Thus it suffices to show that $\delta\neq\left(\sum_{i=1}^nx_ie_i\right)\otimes\left(\sum_{j=1}^ny_je_j\right)$ for any $x_i,y_i\in\mathbb{F}$.
Assume for contradiction therefore that $\delta$ is of that form, for some $x_i$ and $y_i$. We can expand the second expression as follows, using the bilinear and $\mathbb{F}$-balanced properties of the tensor product: \begin{align}
\left(\sum_{i=1}^nx_ie_i\right)&\otimes\left(\sum_{j=1}^ny_je_j\right)=\sum_{i=1}^n\left(x_ie_i\otimes \sum_{j=1}^ny_je_j\right)
\\ &=\sum_{i,j=1}^n(x_ie_i\otimes y_je_j)=\sum_{i,j=1}^n(x_iy_j)(e_i\otimes e_j).
\end{align}
If this equals $\delta=\sum_{i,j=1}^n(i+j)(e_i\otimes e_j)$, then – because $\{e_i\otimes e_j\}_{i,j\leqslant n}$ is a basis for $V\otimes V$ – we must have $x_iy_j=i+j$ for every $i,j\leqslant n$.
In particular, we have

            $\bullet$ $x_1y_1=1+1=2$                         $\bullet$ $x_2y_1=1+2=3$
            $\bullet$ $x_1y_2=2+1=3$                         $\bullet$ $x_2y_2=2+2=4$

This gives  that $$\frac{y_1}{y_2}=\frac{x_1y_1}{x_1y_2}=\frac{2}{3}\ \ \ \ \ \ \ \ \text{ and }\ \ \ \ \ \ \ \ \frac{y_1}{y_2}=\frac{x_2y_1}{x_2y_2}=\frac{3}{4},$$ which gives the desired contradiction.
(In dividing by $3$ and $4$, we are assuming here that $\mathbb{F}$ does not have characteristic $3$ or $2$. I suspect you are probably assuming that $\mathbb{F}$ has characteristic $0$, so I assumed this too. However, do correct me if I'm wrong; the result still holds no matter what $\operatorname{char}(\mathbb{F})$ is, we just need a tiny bit of extra casework in the case where it equals $2$ or $3$.)


text: Q: tf.keras to exe problems i've installed anaconda and trained a neural network using (tf) keras on a windows machine. i'm able to use model.predict within the environment (anaconda navigator and visual code), communicating with the outside world via input and output file. however, none of the tools i tried to create an exe work. pyinstaller complains that there is "no module keras", py2exe mentions something is "beyond top level", while cxfreeze refers to "intel mkl threads". any hints other than to visit the astrologer to tell me when and where to buy a new computer?


text:
Q: Illegal String Offset in Models Codeigniter Pls help me i having trouble, i have models and error, pls help me
 public function website_footer() {
   $data = '';
    $settings = $this->check_settings_exist(13);
    if ($settings != false) {
        $setting_details = $this->objectToArray(json_decode('[' . $settings . ']'));
        $i = 1;
        foreach ($setting_details[0] as $key => $value) {
            if ($i == count($setting_details[0])) {
                $data[$key] = $value;
            } else {
               $data[$key   ] = $value;
            }
            ++$i;
        }
        return $data;
    } else {
        return '';
    }
}

Error :

A PHP Error was encountered
Severity: Warning
Message: Illegal string offset 'website_footer'
Filename: models/Write_setting_model.php
Line Number: 97