text:
Q: Gradient descent not updating theta values Using the vectorized version of gradient as described at :
gradient descent seems to fail
theta = theta - (alpha/m *  (X * theta-y)' * X)';

The theta values are not being updated, so whatever initial theta value
this is the values that is set after running gradient descent :
example1 :
m = 1
X = [1]
y = [0]
theta = 2
theta = theta - (alpha/m .* (X .* theta-y)' * X)'

theta =

    2.0000

example2 :
m = 1
X = [1;1;1]
y = [1;0;1]
theta = [1;2;3]
theta = theta - (alpha/m .* (X .* theta-y)' * X)'

theta =

    1.0000
    2.0000
    3.0000

Is theta = theta - (alpha/m *  (X * theta-y)' * X)'; a correct vectorised implementation of gradient descent ?

A: theta = theta - (alpha/m *  (X * theta-y)' * X)'; is indeed the correct vectorized implementation of gradient-descent.
You totally forgot to set the learning rate, alpha.
After setting alpha = 0.01, your code becomes:
m = 1                # number of training examples
X = [1;1;1]
y = [1;0;1]
theta = [1;2;3]
alpha = 0.01
theta = theta - (alpha/m .* (X .* theta-y)' * X)'
theta =

   0.96000
   1.96000
   2.96000


text:
Q: How to view the contents cacerts.bks (Certificate file /system/etc/security/cacerts.bks) Does anybody know how to view the list of root certificates that an Android device supports?
I would like to see that information.
I found that /system/etc/security/cacerts.bks contains the root certificates information,
but I am not able to decode the contents using any available editors.
I have also tried KeyTool but couldn't succeed with that.
Please suggest how to decode this file's content.
Regards,
Durga

A: If you do not want to be an expert who always write scripts/codes to do what he want.
This is a recommended GUI keystore tool for you: http://www.keystore-explorer.org/downloads.html

A: You can get the list of installed certificates in an Android device from code: In your onCreate() method, include this code:
For devices pre IceCream Sandwich (API < 14):
TrustManagerFactory tmf;
    try {
        tmf = TrustManagerFactory.getInstance(TrustManagerFactory
                .getDefaultAlgorithm());

        tmf.init((KeyStore) null);

        X509TrustManager xtm = (X509TrustManager) tmf.getTrustManagers()[0];
        for (X509Certificate cert : xtm.getAcceptedIssuers()) {
            String certStr = "S:" + cert.getSubjectDN().getName() + "\nI:"
                    + cert.getIssuerDN().getName();
            Log.d(LOG_TAG, certStr);
        }
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

For devices with Android 4.0 and upwards (API >= 14):
try
    {
        KeyStore ks = KeyStore.getInstance("AndroidCAStore");
        if (ks != null)
        {
            ks.load(null, null);
            Enumeration aliases = ks.aliases();
            while (aliases.hasMoreElements())
            {
                String alias = (String) aliases.nextElement();
                java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) ks.getCertificate(alias);

                Log.d(LOG_TAG, cert.getIssuerDN().getName());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (java.security.cert.CertificateException e) {
        e.printStackTrace();
    }

A: keytool -list -v -keystore "cacerts.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "bcprov-jdk16-146.jar" -storetype BKS -storepass ""

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to store the JSON data into array(model class) in swift3? I got nils when I try to store the JSON data into array.
I want to get the JSON data correctly
This is the result of print(articles) on APIManager class
[AppName.Article(author: nil, description: nil, publishedAt: nil, title: nil, url: nil, urlToImage: nil), AppName.Article(author: nil, description: nil, publishedAt: nil, title: nil, url: nil, urlToImage: nil)]

I have three classes and API data below.
Article
import Foundation
import SwiftyJSON

struct Article {

var author: String!
var description: String!
var publishedAt: String!
var title: String!
var url: String!
var urlToImage: String!

init(json: JSON) {
    self.publishedAt = json["publishedAt"].string
    self.author = json["author"].string
    self.title = json["title"].string
    self.description = json["desctiption"].string
    self.url = json["url"].string
    self.urlToImage = json["urlToImage"].string
}

//    init(author: String, discription:String, publishedAt: String, title:    String,    url: String, urlToImage: String) {
//        self.author = author
//        self.discription = discription
//        self.publishedAt = publishedAt
//        self.title = title
//        self.url = url
//        self.urlToImage = urlToImage
//    }
}

APIManager
import Foundation
import Alamofire
import SwiftyJSON

class APIManager {

class func getArticle(handler: @escaping (Array<Article>?) -> ()) {
    Alamofire.request(
        "https://newsapi.org/v1/articles?source=techcrunch&apiKey=XXX"
    )
    .responseJSON { response in
        guard response.result.isSuccess else {
            print("Error while fetching jsondata: \(response.result.error)")
            return
        }

        guard let responseJSON = response.result.value else {
            print("Invalid jsondata received from the server")
            return
        }

        var articles: Array<Article> = []
        let json = JSON(responseJSON)
        //print(json)

        json.forEach {(_, json) in
            print(json)
            articles.append(Article(json: json))
            print(articles)
        }

        handler(articles)
    }
}
}

ViewController
    override func viewDidLoad() {
    super.viewDidLoad()

    APIManager.getArticle{ (articles: Array<Article>?) in
        if let data = articles?[0] {

            print(data)

        }
    }

API data
{
articles =     (
            {
        author = "Matthew Lynley";
        description = "Google reported mixed earnings for its fourth quarter today \U2014 but we're starting to see some flashes of improvement in its \"other bets\" category, which is..";
        publishedAt = "2017-01-26T20:09:05Z";
        title = "Alphabet\U2019s bets beyond search are starting to pay\U00a0off";
        url = "http://social.techcrunch.com/2017/01/26/alphabets-bets-beyond-search-are-starting-to-look-better/";
        urlToImage = "https://tctechcrunch2011.files.wordpress.com/2016/07/a3c4057e7d804c79b4bfb3278f4afced.jpg?w=764&h=400&crop=1";
    },

            {
        author = "Natasha Lomas";
        description = "An Executive Order signed by U.S. President Donald Trump in his first few days in office could jeopardize a six-month-old data transfer framework that enables..";
        publishedAt = "2017-01-26T15:41:33Z";
        title = "Trump order strips privacy rights from non-U.S. citizens, could nix EU-US data\U00a0flows";
        url = "http://social.techcrunch.com/2017/01/26/trump-order-strips-privacy-rights-from-non-u-s-citizens-could-nix-eu-us-data-flows/";
        urlToImage = "https://tctechcrunch2011.files.wordpress.com/2017/01/gettyimages-632212696.jpg?w=764&h=400&crop=1";
    },

sortBy = top;
source = techcrunch;
status = ok;
}

If you need more information, please let me know.
Thanks.

A: You need to access articles array from your JSON and loop through it to get the array of Article.
let json = JSON(responseJSON)
//Get the Array of articles(JSON)
let articleArray = json["articles"].arrayValue
//Now loop through this array.
articleArray.forEach {(json) in
    print(json)
    articles.append(Article(json: json))
    print(articles)
}


text:
Q: Sudden memory consumption jump resulting in out of memory exception while processing huge text file I need to process a very large text file (6-8 GB). I wrote the code attached below. Unfortunately, every time output file reaches (being created next to source file) reaches ~2GB, I observe sudden jump in memory consumption (~100MB to few GBs) and in result - out of memory exception.
Debugger indicates that OOM occurs at while ((tempLine = streamReader.ReadLine()) != null)
I am targeting .NET 4.7 and x64 architecture only.
Single line is at most 50 character long.
I can workaround this and split original file to smaller parts not to face the problem while processing and merge resuls back to one file at the end, but would like not to do it.
Code:
public async Task PerformDecodeAsync(string sourcePath, string targetPath)
    {
        var allLines = CountLines(sourcePath);
        long processedlines = default;
        using (File.Create(targetPath));
        var streamWriter = File.AppendText(targetPath);
        var decoderBlockingCollection = new BlockingCollection<string>(1000);
        var writerBlockingCollection = new BlockingCollection<string>(1000);

        var producer = Task.Factory.StartNew(() =>
        {
            using (var streamReader = new StreamReader(File.OpenRead(sourcePath), Encoding.Default, true))
            {
                string tempLine;
                while ((tempLine = streamReader.ReadLine()) != null)
                {
                    decoderBlockingCollection.Add(tempLine);
                }
                decoderBlockingCollection.CompleteAdding();

            }
        });
        var consumer1 = Task.Factory.StartNew(() =>
        {
            foreach (var line in decoderBlockingCollection.GetConsumingEnumerable())
            {
                short decodeCounter = 0;
                StringBuilder builder = new StringBuilder();
                foreach (var singleChar in line)
                {

                    var positionInDecodeKey = decodingKeysList[decodeCounter].IndexOf(singleChar);

                    if (positionInDecodeKey > 0)
                        builder.Append(model.Substring(positionInDecodeKey, 1));
                    else
                        builder.Append(singleChar);

                    if (decodeCounter > 18)
                        decodeCounter = 0;
                    else ++decodeCounter;
                }
                writerBlockingCollection.TryAdd(builder.ToString());
                Interlocked.Increment(ref processedlines);
                if (processedlines == (long)allLines)
                    writerBlockingCollection.CompleteAdding();
            }
        });
        var writer = Task.Factory.StartNew(() =>
        {
            foreach (var line in writerBlockingCollection.GetConsumingEnumerable())
            {
                streamWriter.WriteLine(line);
            }
        });
        Task.WaitAll(producer, consumer1, writer);
    }

Solutions, as well as advices how to optimize it a little more is greatly appreciated.

A: As the work you are doing is mostly IO bound, you aren't really gaining anything from parallelization. It also looks to me like (correct me if I'm wrong) that your transformation algorithm doesn't depend on you reading the file line-by-line, so I would recommend instead doing something like this:
void Main()
{
    //Setup streams for testing
    using(var inputStream = new MemoryStream())
    using(var outputStream = new MemoryStream())
    using (var inputWriter = new StreamWriter(inputStream))
    using (var outputReader = new StreamReader(outputStream))
    {
        //Write test string and rewind stream
        inputWriter.Write("abcdefghijklmnop");
        inputWriter.Flush();
        inputStream.Seek(0, SeekOrigin.Begin);

        var inputBuffer = new byte[5];
        var outputBuffer = new byte[5];
        int inputLength;
        while ((inputLength = inputStream.Read(inputBuffer, 0, inputBuffer.Length)) > 0)
        {
            for (var i = 0; i < inputLength; i++)
            {
                //transform each character
                outputBuffer[i] = ++inputBuffer[i];
            }

            //Write to output
            outputStream.Write(outputBuffer, 0, inputLength);
        }

        //Read for testing
        outputStream.Seek(0, SeekOrigin.Begin);
        var output = outputReader.ReadToEnd();
        Console.WriteLine(output);

        //Outputs: "bcdefghijklmnopq"
    }

}

Obviously, you would be using FileStreams instead of MemoryStreams, and you can increase the buffer length to something much larger (as this was just a demonstrative example). Also as your original method is Async, you use the async variants of Stream.Write and Stream.Read

A: Like I said, I'd probably go for something simpler first, unless or until it's demonstrated that it's not performing well. As Adi said in their answer, this work appears to be I/O bound - so there seems little benefit in creating multiple tasks for it.
publiv void PerformDecode(string sourcePath, string targetPath)
{
    File.WriteAllLines(targetPath,File.ReadLines(sourcePath).Select(line=>{
        short decodeCounter = 0;
        StringBuilder builder = new StringBuilder();
        foreach (var singleChar in line)
        {
            var positionInDecodeKey = decodingKeysList[decodeCounter].IndexOf(singleChar);
            if (positionInDecodeKey > 0)
                builder.Append(model.Substring(positionInDecodeKey, 1));
            else
                builder.Append(singleChar);

            if (decodeCounter > 18)
                decodeCounter = 0;
            else ++decodeCounter;
        }
        return builder.ToString();
    }));
}

Now, of course, this code actually blocks until it's done, which is why I've not marked it async. But then, so did yours, and it should have been warning about that already.
(You could try using PLINQ instead of LINQ for the Select portion but honestly, the amount of processing we're doing here looks trivial; Profile first before applying any such change)


text:
Q: Prove equivalence of relations - Complex Analysis when there exists $\delta > 0$ such that $f$ is differentiable on $D*(z_0; \delta)$. Given the following statement there exists $\delta > 0$ such that $f$ is differentiable on
$D*(z_0; \delta)$.
I have deduced here that:
$(i)$ ord$ (f; z0) = n$;
$(ii)$ there exist real numbers $\alpha, \beta > 0$ such that:
$\alpha|z - z_0|^n < |f(z)| < \beta|z -z_0|^n$
for $0 < |z - z_0| < \delta$.
Can someone help explain how these are equivalent?

A: I'll try and direct you in the correct way of proving this by pointing out the first few steps:
Allow the Laurent Series for $f$ at $z_0$ to be $\sum a_n(z-z_0)^n$
First, suppose ord $(f,z_0)=n$
Then, $(z-z_0)^{-n}f(z)=a_n+g(z)$, where $g(z) \rightarrow 0$ as $z \rightarrow z_0$
Given $\epsilon > 0$ there exists $\delta > 0$ such that
$|g(z)|<\epsilon|a_n|$ whenever $0<|z-z_0|<\delta$
From here I hope you can continue.


text:
Q: Laravel 9 auto increment string value with carbon i want to make code with 4 digit auto increment integer and current date format MMMyy that has to use carbon. Example: Oct22-0001, Set22-0002, Dec22-0003.
table producs
public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('nama_barang');
        $table->string('kode', 10);
        $table->double('harga');
        $table->integer('jumlah');
        $table->timestamps();
    });
}

ProductController
public function store(Request $request)
{
    $storeData = $request->all();
    $validate = Validator::make($storeData, [
        'nama_barang' => 'required|max:60|unique:products',
        'harga' => 'required|numeric',
        'jumlah' => 'required|numeric'
    ]);

    $lastValue = Product::orderBy('kode', 'desc')->first();
    $storeData = new Product();
    $date = Carbon::now();
    $storeData->kode = $date . '-' . str_pad($lastValue->kode, 4, '0', STR_PAD_LEFT) + 1;

    if($validate->fails())
        return response(['message' => $validate->errors()], 400);

    $product = Product::create($storeData);
    return response([
        'message' => 'Add product Success',
        'data' => $product
    ], 200);
}

i got error

"message": "Illuminate\Database\Eloquent\Builder::create(): Argument #1 ($attributes) must be of type array, App\Models\Product given, called in C:\Users\nana\test\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php on line 23",

A: There is a lot wrong in your code. Like already mentioned in the comments, you are trying to create a new Product by throwing an existing product model instance into the create method which causes the exception you're seeing.
This is bad enough, but there are other issues in your code as well.
Here is my quick (untested) refactoring:
public function store(Request $request)

    $validated = $request->validate([
        'nama_barang' => 'required|max:60|unique:products',
        'harga' => 'required|numeric',
        'jumlah' => 'required|numeric'
    ]);

    $date = now()->format('dy');

    DB::beginTransaction();

    $lastValue = Product::where('kode', 'like', "$date%")
        ->orderBy('kode', 'desc')
        ->first('kode');

    if ($lastValue) {
        $counter = (int)\Str::after($lastValue->kode, '-') + 1;

        $newKode = $date . '-' . str_pad($counter, 4, '0', STR_PAD_LEFT));
    } else {
      $newKode = "{$date}-0001";
    }

    $productData = $validated + ['kode' => $newKode];

    $product = Product::create($productData);

    DB::commit();

    return response([
        'message' => 'Add product Success',
        'data' => $product
    ], 200);
});

Explanation:
If you're using the validate method of the request, you don't have to explicitly return any errors, Laravel will do that automatically.
To get the proper format for the date like you mentioned in your example, you have to call the format method including the proper parameters. I always google what letters to use there, this time I found it here :)
I wrapped the database stuff into a transaction to try to prevent the aforementioned race conditions. Not sure if that is enough, but maybe it helps.
Then it's important to filter the products by the current month/year combination first before sorting them, otherwise it would always sort by the month first and then by the year, which would not be very helpful.
for the generation of the code I used the string helper class to get only the "interesting" part of the "kode", converted it to an integer and then directly incremented it by one. In your version you were trying to add one to a string, for which I actually don't know what would be the result there.
Then the actual product data ist created by merging the validated information from the request with the newly created "kode".
As I said; This is untested, but it should hopefully help you with your task.
I actually think that there is way too much happening in this controller and I would suggest to look how to fix this by moving the code into different places. For starters, you could look into form request validation.


text:
Q: Mysql SELECT / INSERT realtime VS Later + Securtiy [Q]uestion prepared Statements Mysql SELECT / INSERT realtime VS Later + Securtiy Question prepared Statements
Hello,
I wrote a small script unique in and out counter, where the timestamp + ip of the user and the referer gets added into a txt file and every 5 mins a cronjob calls a script to update the db which he gets the data from the txt file.
I found a the mysql function "INSERT DELAY" -  "SET UPDATE LOW_PRIORITY" im using the both commands in the cronjob, now im thinking, inserting the data straight to the DB with these both commands, would this increase the DB load? or is it better to make this every 5 mins.
About the script: Checks if ip exist if ip exists it drops insert, and deletes all ips which are older than 24h, if ip not exist it adds the ip and deletes the older than 24h and does some other things, in worst case it does 15 things to the db SELECT / INSERT / UPDATE / DELETE and OPTIMIZE TABLE for each ip
About the environment: Every 1 sec 5 user is coming, and in 5 mins i should have around 1500 ips in the txt file.
About the table: There will be arround 300k+ ips, which deletes / checks / inserts.
So would it be better to make it how i do it right now? Or is it possible to add the data in realtime to the db with insert delayed and so on?
Ok I want improve my script, and found out about prepared statements, I use MYSQLI Extension: Sample
$sql = "SELECT * FROM table WHERE row1 = ? AND row2 = ? AND row3 = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('sss', $var1, $var2, $var3);
$stmt->execute();
$stmt->close();

So I dont do anymore  mysqli->real_escape_string($var); So my Question is it still possible to do SQL Injections, with prepared statements? If yes how I can prevent this?
Thank you


text:
Q: How to Convert A Clojure/Java Date to Simpler Form I want to take
(str (Date.))
"Thu Feb 07 12:15:03 EST 2013"

and turn it into a string, so it can be input into an Informix date field mm/dd/yyyy.
02/07/2013

I have been looking at various posts, with no success. Here's the first thing I found, and tried, knowing I'd have to reverse the order of the date format. I just wanted to get it to work.
(defn str-to-date [date] (. (SimpleDateFormat. "yyyy-MM-dd") parse date))

I get this error
(str-to-date (str (Date.)))
ParseException Unparseable date:
"Thu Feb 07 12:44:41 EST 2013"  java.text.DateFormat.parse (DateFormat.java:354)

I have also tried this
 (.parse (SimpleDateFormat. "mm/DD/yyyy") (str (Date.)))
ParseException Unparseable date:
"Thu Feb 07 12:42:02 EST 2013"  java.text.DateFormat.parse (DateFormat.java:354)

with no success. Any documentation pointers or answers would be appreciated.

A: (def date (java.util.Date.))
date
=> #inst "2013-02-07T19:08:12.107-00:00"

You can directly format to desired format
(.format (java.text.SimpleDateFormat. "MM/dd/yyyy") date)
=> "02/07/2013"

But if starting from a string,
(str date)
=> "Thu Feb 07 13:08:12 CST 2013"

you must first parse using that string's format
(def df (java.text.SimpleDateFormat. "EEE MMM d HH:mm:ss zzz yyyy"))
(.parse df (str date))
=> #inst "2013-02-07T19:08:12.107-00:00"

and then back to the desired format
(.format (java.text.SimpleDateFormat. "MM/dd/yyyy") (.parse df (str date)))
=> "02/07/2013"

You might also want to look into some time and date libraries: What are the Clojure time and date libraries?.

A: .parse takes a string in the format specified in the SimpleDateFormat constructor and turns it into a Date object.  If you can just pass in the date, then use .format passing it the date to be formatted.  If you need to pass in a string, then you'll need 2 SimpleDateFormats.  One for the input format and one for the output format.  Call .parse using the input format and .format using the output format.


text:
Q: How to scrape the images from the website? How can we get all the images of this site: http://www.theft-alerts.com
We need the images of the 19 pages. Sow far we have this code, but it doesn't work yet. We want the images in a new map.
#!/usr/bin/python

import [urllib2][1]
from bs4 import BeautifulSoup
from urlparse  import urljoin

url = "http://www.theft-alerts.com/index-%d.html"
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page, "html.parser")

base = "http://www.theft-alerts.com"

images = [urljoin(base,a["href"]) for a in soup.select("td a[href^=images/]")]

for url in images:
    img = BeautifulSoup(urllib2.urlopen(url).read(),"lxml").find("img")["src"]
with open("myimages/{}".format(img), "w") as f:
    f.write(urllib2.urlopen("{}/{}".format(url.rsplit("/", 1)[0], img)).read())

A: IMAGE SCRAPING WITH PYTHON
This code will surely work for Scraping Google Images.
import os
import time
import requests
from selenium import webdriver
def fetch_image_urls(query: str, max_links_to_fetch: int, wd: webdriver,
sleep_between_interactions: int = 1):
    def scroll_to_end(wd):
        wd.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(sleep_between_interactions)

    # build the google query

search_url = "https://www.google.com/search?safe=off&site=&tbm=isch&source=hp&q=
{q}&oq={q}&gs_l=img"

# load the page
wd.get(search_url.format(q=query))

image_urls = set()
image_count = 0
results_start = 0
while image_count < max_links_to_fetch:
    scroll_to_end(wd)

    # get all image thumbnail results
    thumbnail_results = wd.find_elements_by_css_selector("img.Q4LuWd")
    number_results = len(thumbnail_results)

    print(f"Found: {number_results} search results. Extracting links from
{results_start}:{number_results}")

    for img in thumbnail_results[results_start:number_results]:
        # try to click every thumbnail such that we can get the real image behind it
        try:
            img.click()
            time.sleep(sleep_between_interactions)
        except Exception:
            continue

        # extract image urls
        actual_images = wd.find_elements_by_css_selector('img.n3VNCb')
        for actual_image in actual_images:
            if actual_image.get_attribute('src') and 'http' in
actual_image.get_attribute('src'):
                image_urls.add(actual_image.get_attribute('src'))

        image_count = len(image_urls)

        if len(image_urls) >= max_links_to_fetch:
            print(f"Found: {len(image_urls)} image links, done!")
            break
    else:
        print("Found:", len(image_urls), "image links, looking for more ...")
        time.sleep(30)
        return
        load_more_button = wd.find_element_by_css_selector(".mye4qd")
        if load_more_button:
            wd.execute_script("document.querySelector('.mye4qd').click();")

    # move the result startpoint further down
    results_start = len(thumbnail_results)

return image_urls

def persist_image(folder_path:str,url:str, counter):
    try:
        image_content = requests.get(url).content

    except Exception as e:
        print(f"ERROR - Could not download {url} - {e}")

    try:
        f = open(os.path.join(folder_path, 'jpg' + "_" + str(counter) + ".jpg"), 'wb')
        f.write(image_content)
        f.close()
        print(f"SUCCESS - saved {url} - as {folder_path}")
    except Exception as e:
        print(f"ERROR - Could not save {url} - {e}")

def search_and_download(search_term: str, driver_path: str, target_path='./images',
number_images=10):
    target_folder = os.path.join(target_path, '_'.join(search_term.lower().split('
')))

    if not os.path.exists(target_folder):
        os.makedirs(target_folder)

    with webdriver.Chrome(executable_path=driver_path) as wd:
        res = fetch_image_urls(search_term, number_images, wd=wd,
sleep_between_interactions=0.5)

    counter = 0
    for elem in res:
        persist_image(target_folder, elem, counter)
        counter += 1

# How to execute this code
# Step 1 : pip install selenium. pillow, requests
# Step 2 : make sure you have chrome installed on your machine
# Step 3 : Check your chrome version ( go to three dot then help then about google
chrome )
# Step 4 : Download the same chrome driver from here  "
https://chromedriver.storage.googleapis.com/index.html "
# Step 5 : put it inside the same folder of this code

DRIVER_PATH = './chromedriver'
search_term = 'iphone'
# num of images you can pass it from here  by default it's 10 if you are not passing
#number_images = 10
search_and_download(search_term=search_term, driver_path=DRIVER_PATH)

A: You need to loop over every page and extract the images, you can keep looping until the anchor with the text "Next" is in the code tag with the class resultnav:
import  requests

from bs4 import BeautifulSoup
from urlparse import urljoin

def get_pages(start):
    soup = BeautifulSoup(requests.get(start).content)
    images = [img["src"] for img in soup.select("div.itemspacingmodified a img")]
    yield  images
    nxt = soup.select("code.resultnav a")[-1]
    while True:
        soup = BeautifulSoup(requests.get(urljoin(url, nxt["href"])).content)
        nxt = soup.select("code.resultnav a")[-1]
        if nxt.text != "Next":
            break
        yield [img["src"] for img in soup.select("div.itemspacingmodified a img")]

url = "http://www.theft-alerts.com/"

for images in get_pages(url):
    print(images)

Which gives you the images from all 19 pages.


text:
Q: Promise to string - [object Object] or [object Promise]? I execute this code in FF and Chrome.
Object.prototype.toString.call(Promise.resolve())

Results:

*

*Firefox Nightly 44 - [object Promise]

*Chrome Canary 48 (with flag) - [object Promise]

*Chrome 46 - [object Object]
EcmaScript specification in chapter 25.4.4.5 Promise.resolve(x) quote:

The resolve function returns either a new promise resolved with the
  passed argument, or the argument itself if the argument is a promise
  produced by this constructor.

*

*Let C be the this value.

*If Type(C) is not Object, throw a TypeError exception.

*If IsPromise(x) is true,

*

*Let xConstructor be Get(x, "constructor").

*ReturnIfAbrupt(xConstructor).

*If SameValue(xConstructor, C) is true, return x.

*Let promiseCapability be NewPromiseCapability(C).

*ReturnIfAbrupt(promiseCapability).

*Let resolveResult be Call(promiseCapability.[[Resolve]], undefined, «x»).

*ReturnIfAbrupt(resolveResult).

*Return promiseCapability.[[Promise]].

So promiseCapability.[[Promise]] toString is the result in browser.
PromiseCapability Records have the fields listed in Table 57:

-------------------------------------------------------------------
| Field Name  | Value     | Meaning                               |
-------------------------------------------------------------------
| [[Promise]] | An object | An object that is usable as a promise |
-------------------------------------------------------------------

So [[Promise]] is a object and must be [object Object].

A: Yeah! Welcome to ES2015 :)
This is feature of Symbol implementation in browser. Symbol affect Object.prototype.toString.call by Symbol.toStringTag:

*

*Let tag be Get (O, @@toStringTag).

*ReturnIfAbrupt(tag)

*If Type(tag) is not String, let tag be builtinTag.

*Return the String that is the result of concatenating "[object ", tag, and "]".

So Symbol make the default string description of an object obj:
'[object '+obj[Symbol.toStringTag]+']'

Get more info about ES2015 aka ES6 Symbol from this article.


text:
Q: Cant access login popup window elements using Selenium Python When the login button is clicked a popup window which shows login with google. I need to access into the sign in with google button of the popup. I've shown some previous example to handle the popup using driver.switch_to_window method and iframe method. But cant access the element in the popup window.
The Below code is showing noSuchElementException
import time

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait

from time import sleep

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://shatkora.co/grocery")

main_window=None
while not main_window:
    main_window=driver.current_window_handle

join_btn=driver.find_element_by_xpath("/html/body/div[1]/div[1]/div/div[1]/div/header/div/button")
join_btn.click()

login_window=None;
while not login_window:
    for handle in driver.window_handles:
        if(handle!=main_window):
            login_window=handle
            break

# driver.switch_to(login_window)

driver.switch_to.window(login_window)

login_with_google_button=driver.find_element_by_xpath("/html/body/div[1]/div[1]/div/div[6]/div/div/div/div[1]/button")
login_with_google_button.click()

A: You do not need to switch to any windows, also use absolute xpath with explicit waits.
driver = webdriver.Chrome(driver_path)
driver.maximize_window()
driver.get("https://shatkora.co/grocery")
wait = WebDriverWait(driver, 20)

join_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Join']")))
join_btn.click()

time.sleep(5)

button = driver.find_element_by_xpath("//h3[text()='Welcome to Shatkora!']/following-sibling::button")
driver.execute_script("arguments[0].click();", button)

after this code you will have to switch to new windows, which can be done via below code :
handles = driver.window_handles
driver.switch_to.window(handles[1])


text:
Q: Alternate way to use 'INSERT tempTable EXEC storedProcedure' to get data I have a new stored procedure that contain of following script:
Insert into #tmpTable
Exec dbo.SP_GetData '2016-11-01'

and above script causes a SQL Server error message

An INSERT EXEC statement cannot be nested.

because there is another INSERT EXEC inside the SP_GetData stored procedure and according to a few hours of reading on this error message, I can't have two INSERT EXEC or I will get that error.
I found several alternatives such as using inline query to insert into temp table and modify the existing SP_GetData stored procedure but both way can't work for me. In my case, it's a must to depend on SP_GetData as it involve many complicated process and must not be changed.
I just need to retrieve all data from the SP_GetData in my new stored procedure and return.
Please let me know what is my alternatives on this.

A: DECLARE @Query VARCHAR(100),@Date VARCHAR(100)
SELECT @Date = '2016-11-01'
SELECT @Query = 'dbo.SP_GetData '''+@Date+''''
INSERT INTO #tmpTable
EXEC (@Query)


text:
Q: Disabling Listbox is not changing background color in style I have this simple style that does not change the ListBox Background when the ListBox is disabled:
<Style TargetType="ListBox" >
    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="True">
            <Setter Property="Background" Value="Red"/>
        </Trigger>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Background" Value="Orange"/>
        </Trigger>
    </Style.Triggers>
</Style>

Snoop does not help me on this one and I cannot figure a simple way without overriding templates.  Anyone have a simple way to get this working?  TIA.

A: The only way to do this is by overriding the template

A: You can change the background color of the listbox itself when the listbox is disabled by simply changing the colors that the built-in template is using.  You can do this via style resources.  Just paste the below code into your Listbox element and the background will be transparent when you disable the box.
<ListBox.Style>
    <Style TargetType="{x:Type ListBox}">
        <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent"/>
        </Style.Resources>
    </Style>
</ListBox.Style>

It is also very common to want to modify the background color of a single item when it's highlighted and when the box loses focus.. to change these, you can reference this post:
https://stackoverflow.com/a/7298301/1721136


text:
Q: The identity $a^n-b^n=(a-b) (\sum_{i=0}^{n-1}a^ib^{n-1-i})$ How do I use finite induction to prove that
$$a^n-b^n=(a-b) (\sum_{i=0}^{n-1}a^ib^{n-1-i}), \forall a,b\in \Bbb{R}\space \text{and} \space \forall n \in \Bbb{N}?$$
Ok, for $n=2$ it's fine. $a^2-b^2=(a-b)(b+a)=(a-b)(\sum_{i=0}^1a^ib^{n-1-i})$.
Right, then suppose the equality valid for n. But, how to handle with $a^{n+1}-b^{n+1}$? How to use the induction hypothesis here?
Need some help!
If this question has already been answered, please, give me the link... Sorry about that.

A: Hint:
Let $S{}={}\sum_{i=0}^{n-1}a^ib^{n-1-i}$. Compute $aS-bS$.


text:
Q: WorkManager Observer not receiving result I have a function with a worker that checks for internet when opening the app the function works ok so far.
Now that I'm upgrading the app for TIRAMISU, the Observable in the Worker is not triggering. In the logcat I can see the message:

I/WM-WorkerWrapper: Worker result SUCCESS for Work...

But the result is not delivered to the Observer in the getWorkInfoByIdLiveData.
This is the function that dispatches the Worker:
private void isInternetAvailable() {
        OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(InternetCheck.class).build();
        WorkManager workManager = WorkManager.getInstance(ActivitySplash.this);
        workManager.enqueue(workRequest);
        workManager.getWorkInfoByIdLiveData(workRequest.getId())
                .observe(ActivitySplash.this, workInfo -> {
                    if (!workInfo.getState().isFinished())
                        return;
                    if (workInfo.getState() == WorkInfo.State.SUCCEEDED) {
                        requestAdsConsent();
                    } else {
                        consentStatus = ConsentStatus.PERSONALIZED;
                        startActivity();
                    }
                });
    }

Quite simple and has been working fine until now, I guess I must have missed anything new regarding the WorkManager configuration in the latest releases.
I have checked that the Id of the worker is the same as the one in the logcat on SUCCESS.
Either if the Worker FAILS or SUCCEED the Observer is not being triggered, the result is not getting to the Observer.
Any ideas what am I missing here? I have the Latest version of WorkManager with compileSdkVersion 33
implementation 'androidx.work:work-runtime:2.7.1'

EDIT: I have made sure that the app has not changed its Lifecycle State, it is RESUMED.


text:
Q: Ending an infinite while loop I currently have code that basically runs an infinite while loop to collect data from users. Constantly updating dictionaries/lists based on the contents of a text file. For reference:
while (True):
    IDs2=UpdatePoints(value,IDs2)
    time.sleep(10)

Basically, my problem is that I do not know when I want this to end, but after this while loop runs I want to use the information collected, not lose it by crashing my program. Is there a simple, elegant way to simply exit out of the while loop whenever I want? Something like pressing a certain key on my keyboard would be awesome.

A: I think the easiest solution would be to catch the KeyboardInterrupt when the interrupt key is pressed, and use that to determine when to stop the loop.
except KeyboardInterrupt:
    break

The disadvantage of looking for this exception is that it may prevent the user from terminating the program while the loop is still running.

A: You could use exceptions. But you only should use exceptions for stuff that isn't supposed to happen. So not for this.
That is why I recommand signals:
import sys, signal
def signal_handler(signal, frame):
    print("\nprogram exiting gracefully")
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

you should put this on the beginning of your program and when you press ctrl+c wherever in your program it will shut down gracefully
Code explanation:
You import sys and signals.
Then you make a function that executes on exit. sys.exit(0) stops the programming with exit code 0 (the code that says, everything went good).
When the program get the SIGINT either by ctrl-c or by a kill command in the terminal you program will shutdown gracefully.

A: I use python to track stock prices and submit automated buy/sell commands on my portfolio. Long story short, I wanted my tracking program to ping the data server for info, and place trades off of the information gathered, but I also wanted to save the stock data for future reference, on top of being able to start/stop the program whenever I wanted.
What ended up working for me was the following:
trigger = True
while trigger == True:
 try:
  (tracking program and purchasing program conditions here)
 except:
  trigger = False

print('shutdown initialized')
df = pd.DataFrame...
save all the datas
print('shutdown complete')

etc.
From here, while the program is in the forever loop spamming away requests for data from my broker's API, using the CTRL-C keyboard interrupt function toggles the exception to the try loop, which nullifies the while loop, allowing the script to finalize the data saving protocol without bringing the entire script to an abrupt halt.
Hope this helps!
Resultant

A: You can try wrapping that code in a try/except block, because keyboard interrupts are just exceptions:
try:
    while True:
        IDs2=UpdatePoints(value,IDs2)
        time.sleep(10)
except KeyboardInterrupt:
    print('interrupted!')

Then you can exit the loop with CTRL-C.

A: I would suggest using the try, except syntax within a loop if you are running on an IPYNB file in Google Colab or Jupyter, like:
while True:
    try:
       IDs2=UpdatePoints(value,IDs2)
       time.sleep(10)
    except KeyboardInterrupt:
       break
    except:
       continue

the last except is for any other error if occurs the loop will resume

A: You can catch the KeyboardInterrupt error in Python:
try:
    while 1>0:
        IDs2=UpdatePoints(value,IDs2)
        time.sleep(10)
except KeyboardInterrupt:
    print('While loop ended!')

Also, instead of saying:
while True:

It looks more professional to use:
while 1>0:

To read more about Python Error handling (try, except, etc.):

https://www.w3schools.com/python/python_try_except.asp

or:

https://www.w3schools.com/python/gloss_python_try_finally.asp


text:
Q: Value of the integral $\int_{a}^{a}f(x)dx?$ I am confused about the value of the integral $\int_{a}^{a}f(x)dx,$ is it $0$ or not always? In Riemann integration case (i.e. $f$ is bounded ) its zero by definition. What about other cases for example $\int_{0}^{0}\frac{1}{x}? $ Is it zero? Please help. Thanks a lot.

A: It's always zero...except that there are some conventions in which this notation is used to denote something that's not zero.
So let me clarify "always": for the Riemann integral, and for the  Lesbegue integral with respect to the standard measure on the real line, and for functions $f: \mathbb R \to \mathbb R$, it's always zero. This property is very useful, for it helps ensure that
$$
\int_a^b + \int_b^c = \int_a^c
$$
in general.
So why do I say "except..."?
Well, for instance, if $f$ is a "delta function" (which isn't really a function, but instead a distribution), then this integral can denote something nonzero (or at least
$$
\int_{0^{-}}^{0^{+}} f(x) dx
$$
can be nonzero).
And if your measure "dx" on the real line happens to assign positive measure to the point $0$, then again the integral can denote something nonzero. But it'd be pretty odd to use "dx" to denote such a measure.

A: The heart of your question comes down to what we mean by the word integral. The most reasonable value for $\int_{0}^{0}\frac{1}{x}\,\mathrm{d}x$ is probably $0$, and for this reason nobody would object to you giving the value of this integral as $0$. I expound on this below.
Let $a<b$ be real numbers and let $f\colon[a,b]\to\mathbb{R}$. Broadly speaking, if $\int_{c-\epsilon}^{c+\epsilon}f(x)\,\mathrm{d}x$ is defined for all sufficiently small $\epsilon>0$, then we usually would define $\int_{c}^{c}f(x)\,\mathrm{d}x$ to be zero. This is simply because defining it any other way would be strange: our intuitive picture of what the integral means is "an area under a graph". It then makes intuitive sense that, if the area under the graph is a meaningful concept for some small interval around $c$ (that is, if the function is integrable on $[c-\epsilon,c+\epsilon]$ for some $c\in\mathbb{R}$ and some $\epsilon>0$), then the area under the graph (the value of the integral) should get smaller and smaller (tend to zero) as we make the interval smaller (as $\epsilon\to0$).
Ultimately, a fair amount of what is true in pure mathematics comes down to what we define to be true. We make the definitions ourselves according to what we consider to be "reasonable". Whether or not the statement above is actually true for any particular definition of "integral" depends on the definitions, either of the integral itself or just of integrals with these kinds of limits. My point is that most "reasonable" definitions of "integral" are called "reasonable" at least in part because this statement is true for them. If it weren't, they wouldn't (usually) be very good definitions of "integral".
This solves the problem in cases where the function is sufficiently integrable. In other cases, such as the example $\int_{0}^{0}\frac{1}{x}\,\mathrm{d}x$ that you give, whether or not the value is $0$ is again dependent on what we define it to be. If we wanted to, we could define $\int_{0}^{0}\frac{1}{x}\,\mathrm{d}x=\pi$ and see where that gets us, but we would never want to do this because this makes little sense. The most reasonable value would be $0$, for a couple of reasons.

*

*The integrand is an odd function, and we expect from our knowledge of "nice" situations that the integral of an odd function on an interval symmetric about $0$ should evaluate to $0$. Since $\{0\}$ is in a perverse sense "an interval symmetric about $0$", it makes sense to define the value of the integral based on this other result.

*A related way to come up with a reasonable definition is to take inspiration from other reasonable definitions, in this case the Cauchy principal value. The Cauchy principal value allows us to assign values to certain improper integrals by imagining the area under the graph as "expanding out from the origin". In this case, we may instead imagine the area as expanding in from outside the origin. With this picture in mind, we might define
$$\int_{0}^{0}\frac{1}{x}\,\mathrm{d}x = \lim_{\epsilon\to1^{-}}\left(\int_{-1}^{-1+\epsilon}\frac{1}{x}\,\mathrm{d}x + \int_{1-\epsilon}^{1}\frac{1}{x}\,\mathrm{d}x=0\right).$$
Now the calculation is easy: for any $\epsilon\in(0,1)$ we have $\int_{-1}^{-1+\epsilon}\frac{1}{x}\,\mathrm{d}x + \int_{1-\epsilon}^{1}\frac{1}{x}\,\mathrm{d}x=0$ by symmetry (either evaluate the integral or draw a diagram). Hence the limit is $0$.

The important thing to take away here is that if something is undefined, you may sometimes feel free to define it yourself; the important thing is that the definition should be mathematically reasonable. Of course, what is reasonable and what isn't reasonable is another question entirely! Figuring out the right answer to this question is often the main goal of much mathematical research.

A: You can say like this $$\int_0^0{1\over x}dx=\lim_{c\to0+}\int_{-c}^{c}{1\over x}dx=\lim_{c\to0+}\left[\ln|x|\right]_{-c}^c=\lim_{c\to 0+}\{\ln|c|-\ln|-c|\}=0$$


text:
Q: Need help with a script which copies all files from a folder to another based on time stamp I need to supply start time and end time .
i.e I want all files  from 3 am to 6 am on sep 10th
start time:2021091003
end time  :2021091006
Source folder has files as below

00:59 file.2021091000.log
01:59 file.2021091001.log
02:59 file.2021091002.log
03:59 file.2021091003.log
04:59 file.2021091004.log
05:59 file.2021091005.log

expected output in destination folder

03:59 file.2021091003.log
04:59 file.2021091004.log
05:59 file.2021091005.log

Please help.

A: Make use of wildcards:
cp -t destination/ *202109100[3-5].log

or if your cp does not support -t option:
cp *202109100[3-5].log destination/


text:
Q: Python random function I'm having problems with Python's import random function. It seems that import random and from random import random are importing different things. I am currently using Python 2.7.3
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> random()

Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
    random()
NameError: name 'random' is not defined
>>> random.randint(1,5)

Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
random.randint(1,5)
NameError: name 'random' is not defined
>>> import random
>>> random()

Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
random()

TypeError: 'module' object is not callable
>>> random.randint(1,5)
2
>>> from random import random
>>> random()
0.28242411635200193
>>> random.randint(1,5)

Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
random.randint(1,5)
AttributeError: 'builtin_function_or_method' object has no attribute 'randint'
>>>

A: The problem is that there are two things called random here: one is the module itself, and one is a function within that module. You can't have two things with the same name in your namespace so you have to pick one or the other.

A: import random

includes the module into the namespace under the name 'random'.
from random import random

includes the function'random' from the namespace 'random' into the global namespace.
So in the first example, you would call random.random, and in the second, you would call random.  Both would access the same function.
Similarly,
from random import randint

would import randint into the global namespace, so you could simply call randint instead of random.randint.

A: Well, yes, they import different things.  import random imports the random module, from random import random imports the random function from the random module.  This is actually a good example of why when designing an API in Python, it's often a good idea to try to avoid naming modules and their members the same thing.

A: import random imports the random module, which contains a variety of things to do with random number generation. Among these is the random() function, which generates random numbers between 0 and 1.
Doing the import this way this requires you to use the syntax random.random().
The random function can also be imported from the module separately:
from random import random

This allows you to then just call random() directly.

A: The random module contains a function named random(), so you need to be aware of whether you have imported the module into your namespace, or imported functions from the module.
import random will import the random module whereas from random import random will specifically import the random function from the module.
So you will be able to do one of the following:
import random
a = random.random()
b = random.randint(1, 5)
# you can call any function from the random module using random.<function>

or...
from random import random, randint   # add any other functions you need here
a = random()
b = randint(1, 5)
# those function names from the import statement are added to your namespace

A: The 'random' module is a package from the python standard library, as well as a function defined in this package.
Using 'import random' imports the package, which you can then use the function from this package: 'random.random()'. You can use any other function from the 'random' package as well.
You can also tell python to specifically import only the random function from the package random: 'from random import random'. Then you can only use the function 'random()', and should not specify the package it comes from. However you cannot use any other function from the random package, because they have not been imported if you use 'from random import random'.

A: If you use from random import random, you must call randint() like so: randint(1,5). If you use import random, you call it like so: random.randint(1,5).

A: If you are using PyDev or other clever IDE, make sure it did not import the module automatically, overriding your import. It can be especially confusing here, when module name is equal to a function name, because the error thrown is not a NameError. In my case I added
import random

and later used it:
r = random.radom()

but got:
AttributeError: 'builtin_function_or_method' object has no attribute 'random'

Only after searching I found that PyDev automatically added the line
from random import random

to the end of my imports, so I was in fact calling attribute random of method random. Solution is to delete the automatic import or use it and call the random() method directly.

A: You have to import the random function, from the random module before you can use it use it
In [1]: from random import random

In [2]: random()
Out[2]: 0.5607917948041573


text:
Q: PHP error_log function not working after upgrading to IIS 7.5 I'm using error_log which has been working fine for years under IIS 6. Recently I upgraded to IIS 7.5 (Windows 7) and the messages logged by error_log stop appearing.
In fact nothing is going to the log. If I call an incorrect function to force a real PHP error, it gets reported to the screen, but not to the file. My ini settings:
display_errors=On
error_log='C:\Work...\php_errors.log'
log_errors=on
error_reporting=E_ALL & !E_DEPRECATED

I've also added < httpErrors existingResponse="PassThrough" /> to the web.config file in my virtual directory but it doesn't work even after a restart.
Can anyone shed any light?

A: The problem eventually turned out to be access permissions for the folder where the error log was.  I had to give the IUSR user write access to that folder.
Al.


text:
Q: Vue.js, async await functions return empty results js project where I need to use await/async for getting data from my API.
My code
        const logsFc = async () => {
          let logs = [];
          for (let i = 0; i < this.data.length; i++) {
            const formData = new FormData();

            const getLogsFc = () => {
              getLogs.request(new URLSearchParams(formData), (response) => {
                if (response.status >= 200 && response.status < 300) {
                  localConsoleLog('getLogs', response);
                  return response.data.data;
                }
              });
            };

            let data = await getLogsFc();
            console.warn(data);
            logs.concat(data);
          }

          return logs;
        };

but logs are returned before getting response.
babel.config.js
module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        useBuiltIns: 'usage',
        corejs: 3.6,
        modules: false,
      },
    ],
  ],
};

"vue": "^2.6.0"
What am I doing wrong?

A: Don't run the callback of the request just return the response :
 const getLogsFc = async () => {
          let response = await getLogs.request(new URLSearchParams(formData));
            if (response.status >= 200 && response.status < 300) {
                  localConsoleLog('getLogs', response);
                  return response.data.data;
                }
            };

            let data = await getLogsFc();


text:
Q: Commutator of spacetime translation In Srednicki's textbook Quantum Field Theory, eq. (95.7) reads:
\begin{equation}
[\Phi (x, \theta, \theta^{*}), P^{\mu}] = -i\partial^{\mu}\Phi (x, \theta, \theta^{*}).
\end{equation}
where $\Phi (x, \theta, \theta^{*})$ is a superfield and $P^{\mu}$ is a generator of the Poincare group.
I don't quite understand this equation. To my understanding, the left-hand side is a commutator, so it should be
\begin{equation}
[\Phi (x, \theta, \theta^{*}), P^{\mu}] = i\Phi (x, \theta, \theta^{*})\partial^{\mu} -i\partial^{\mu}\Phi (x, \theta, \theta^{*}).
\end{equation}
Why is the first term on the right-hand side missing?

A: Remember! Those are operators, and as such they act on some state $\varphi$. The second term, when operating on this $\varphi$, includes in fact two components
$$P_{\mu}(\Phi\varphi)=(P_{\mu}\Phi)\varphi+\Phi(P_{\mu}\varphi)$$
Put this back into the commutator to get your answer.


text:
Q: Zend Framework Redirect and Routes, somehow not working I've been trying to wrap my head around routing and for that very reason build a small aplication to fiddle around with, but i've managed to stumble upon a problem.
The goal of the whole test was to hide the url 'hostname/content/index/add' and turn it into a url more understandable for a user like 'hostname/wms/content/add'.
But now for some odd reason i cannot redirect using the $this->url() methode. But somehow a normal link like somelink work.
I have build a few routes in the application.ini to test how it works. It's nothing fancy...
resources.router.routes.contentroute.route = "/wms/content"
resources.router.routes.contentroute.defaults.module = content
resources.router.routes.contentroute.defaults.controller = index
resources.router.routes.contentroute.defaults.action = index

resources.router.routes.vacaturesroute.route = "/wms/vacatures"
resources.router.routes.vacaturesroute.defaults.module = vacatures
resources.router.routes.vacaturesroute.defaults.controller = index
resources.router.routes.vacaturesroute.defaults.action = index

So when i type hostname/wms/content i get redirected to the content module's IndexController and it's IndexAction. This works fine for all the links in my views that point to the content module like this
 link

However it's not working for 3 links that actually redirect towards a specific action of the IndexController on that very page hostname/wms/content.
<a href="<?php echo $this->url(array('controller'=>'index','action'=>'add'));?>">Add new content

Instead of actually redirecting towards the add action in the IndexController i get redirected to hostname/wms/content, wich is the page i'm comming from.
Anyone have an idea why this is happening and possibly a way to solve this? Or am i totally approaching this the wrong way?

A: First, your route are static ones. You should replace them with:
resources.router.routes.contentroute.route = "/wms/content/:action/*"
resources.router.routes.contentroute.defaults.module = content
resources.router.routes.contentroute.defaults.controller = index
resources.router.routes.contentroute.defaults.action = index

Then, you should specify the name of your route and pass true in reset argument:
$this->url(
  array('module'=>'content', 'controller'=>'index','action'=>'add'),
  'contentroute',
  true
);

A: try this instead
<a href="<?php echo $this->url(array('controller'=>'index','action'=>'add','module'=>'xyz'),null,true);?>">Add new content

Replace xyz with your module name.


text:
Q: Multiple join conditions over a Many to Many relationship I'm writing an application that has three classes, Users, Posts and Groups.
A user may make a post, but can do so on behalf of themselves, and/or on behalf of one of their groups. Two or more users can also make a post in conjunction with each other, without a group. I'm trying to find a way to count the number of posts that a user is associated with, whether through themselves or one of their groups, and in the case where both assocations are present for only one post, it should only count as one.
User:
class User {
    /**
     * @ManyToMany(targetEntity="Post", inversedBy="users")
     */
    private $posts;

    /**
     * @ManyToMany(targetEntity="Group", inversedBy="users")
     */
    private $groups;

and the equivalent mappedBy on the other two entites.
I've written a MySQL query that seems to solve this
SELECT COUNT(DISTINCT posts.id), users.name FROM users
LEFT JOIN post_user ON post_user.user_id = user.id
LEFT JOIN group_user ON group_user.user_id = user.id
LEFT JOIN post_group ON post_group.group_id = group_user.group_id
LEFT JOIN posts ON
    posts.id = post_user.post_id OR
    posts.id = post_group.post_id
GROUP BY users.id

which gives me a list of users, and the amount of posts they're associated with.
I'm having trouble finding a way to write this kind of query into the ORM language. The problem comes from the necessity to join to the ManyToMany join tables, as opposed to the entities' tables themselves. In the past, I've been able to write a condtional join using the 'WITH' statement.
$qb = $this->createQueryBuilder('u')
    ->select('COUNT(DISTINCT p.id), u.name')
    ->leftJoin('u.groups', 'g')
    ->leftJoin('MyBundle:Post', 'p', 'WITH', 'p = u.posts OR p = g.posts')

This errors with
Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.

and it's clear the problem stems from 'u.posts' and 'g.posts' referencing tables instead of fields.
I'm not really sure if Doctrine is capable of doing this kind of query, and I would prefer this be done on the database side, because there may be a large dataset to deal with, and this will need to be ordered by the count from the resultset.
Is there any way to reference the join table itself using DQL? and if not, is there a different kind of relational architecture that might solve this?

A: In my opinion your primary concern should be the fact that you have many to many relationship in your database not the fact that the code does not work properly.
Create a view with a union of two queries. Gather the user id's from groups in one query and then gather the user id's from the independent users on the other query. Once you have the view you can do your counts.


text:
Q: Xcode won't use localization files despite matching IDs I have a bunch of elements in Xcode 5's Interface Builder which I need to translate. I'm using Object ID of those elements to localize, like this:
/* Class = "NSButtonCell"; title = "Automatically copy link to clipboard"; ObjectID = "eee-18-aaH"; */
"eee-18-aaH.title" = "Copier automatiquement le lien dans le presse-papier";

I checked IDs fifteen times and they match. However, Xcode won't pull those in when I test the app. Everything else is translated but strings based on Object IDs won't update.
Both Project → Clean and Window → Organizer → Projects → Derived Data → Delete didn't work.
What works is unchecking localization from the project and checking it again. After replacing text, Xcode starts localizing those strings.
But this means we need to update dozens of strings across 18 localizations. There has to be a better way to ask Xcode to obey. Ideas?


text:
Q: Are switch-case statements allowed for multiple conditions? I was going to do a complex number class, and I appear to have too many conditionals involving multiple statements on one of my functions. Here is a snippet of my program with a ToString() function:
public override string ToString()
{
    if (this.real == 0 && this.imaginary == 0)
    {
        return "0";
    }
    else if (this.real == 0 && this.imaginary == 1)
    {
        return "i";
    }
    else if (this.real == 0 && this.imaginary == -1)
    {
        return "-i";
    }
    else if (this.real == 0 && (this.imaginary != 1 && this.imaginary != -1))
    {
        return String.Concat(this.imaginary.ToString(), "i");
    }
    else if (this.real != 0 && this.imaginary == 0)
    {
        return String.Concat(this.real.ToString());
    }
    else if (this.real != 0 && this.imaginary == 1)
    {
        return String.Concat(this.real.ToString(), " + i");
    }
    else if (this.real != 0 && this.imaginary == -1)
    {
        return String.Concat(this.real.ToString(), " - i");
    }
    else if (this.real != 0 && this.imaginary < -1)
    {
        this.imaginary = -this.imaginary;
        return String.Concat(this.real.ToString(), " - ", this.imaginary.ToString(), "i");
    }
    return String.Concat(this.real.ToString(), " + ", this.imaginary.ToString(), "i");
}

Would switch statements be helpful for multiple conditions?

A: Make code more readable with eliminating redundant checks.
Use string interpolation instead of String.Concat
public override string ToString()
{
     if (real == 0)
     {
          if (imaginary == 0)
          {
              return "0";
          }

          if (imaginary == 1)
          {
              return "i";
          }

          if (imaginary == -1)
          {
              return "-i";
          }

          if (imaginary != 1)
          {
              return $"{imaginary}i";
          }
    }
    else
    {
         if (imaginary == 0)
         {
             return real.ToString();
         }
         if (imaginary == 1)
         {
             return $"{real} + i";
         }
         if (imaginary == -1)
         {
             return $"{real} - i";
         }
         if (imaginary < -1)
         {
              imaginary = -imaginary;
              return $"{real} - {imaginary}i";
         }
  }

  return $"{real} + {imaginary}i";
}

A: You cannot have more than one condition in switch, but it looks like this.real has only two possibilities, 0 or 1, so you can take that out an use a switch for this.imaginary.
Also it is probably better to use String.Format() or String Interpolation instead of String.Concat().
public override string ToString() {
    if (this.real == 0) {
        switch(this.imaginary) {
            case 0:
                return "0";
            case 1:
                return "i";
            case -1:
                return "-i";
            default:
                return $"{this.imaginary}i";
    }
    else {
        switch(this.imaginary) {
            case 0:
                return this.real.ToString();
            case 1:
                return $"{this.real} + i";
            case -1:
                return $"{this.real} - i";
            default:
                if (this.imaginary < -1) {
                    this.imaginary = -this.imaginary;
                    return $"{this.real} - {this.imaginary}i";
                }
        }
    }
    return $"{this.real} + {this.imaginary}i";
}

A: Your code is overcomplicated and redundant because you've come up with a separate branch for each possible situation. Your code will be a lot simpler if you break it down and do the following:

*

*Get the real part (if there is one) and the imaginary part (if there is one)

*Combine them together if there are two parts

The following will do this:
private string RealPartString()
{
    if (real == 0) { return imaginary == 0 ? "0" : null; }

    return real.ToString();
}

private string ImaginaryPartString()
{
    if (imaginary == 0) { return null; }

    var abs = Math.Abs(imaginary);
    var number = abs == 1 ? "" : abs.ToString();
    // Only include the sign here if there is no real part
    var sign = real == 0 && imaginary < 0 ? "-" : "";

    return sign + number + "i";
}

public override string ToString()
{
    var parts = new[] { RealPartString(), ImaginaryPartString() }.Where(s => s != null);
    var sign = imaginary < 0 ? " - " : " + ";

    return string.Join(sign, parts);
}


text:
Q: Flutter checkbox not deselecting after select I have an API with an array list of values that passes values to my Radio button successfully. When I select each the select value parses but I'm unable to deselect the select radio button. Below is my flutter code:

ListView.builder(    shrinkWrap:true,
                     physics:const NeverScrollableScrollPhysics(),
                     itemCount:dataOptions == null? 0: dataOptions.length,
                     itemBuilder:(BuildContext context,int index) {
                                                            return Container(
                                                                padding:
                                                                    const EdgeInsets
                                                                            .only(
                                                                        bottom:
                                                                            0.0),
                                                                child: Card(
                                                                  elevation: 0,
                                                                    child:
                                                                        ListTile(
                                                                  title: Text(
                                                                      dataOptions[index]['option_title']),
                                                                  leading:
                                                                      Radio(
                                                                    value: dataOptions[index]["option_price"],

                                                                        //below will be the default value.
                                                                        groupValue: dataOptions[index]["option_id"],
                                                                    onChanged: (value) {
                                                                      setState(
                                                                          () {
                                                                            dataOptions[index]["option_id"] = value;
                                                                        debugPrint("radioSel:$value");
                                                                      });
                                                                    },
                                                                    activeColor: Colors.green,
                                                                  ),
                                                                  trailing:
                                                                      Text(dataOptions[index]['option_price'].toString(), style:TextStyle(fontFamily: 'Montserrat',
                                                                      color: colorPink, fontWeight: FontWeight.bold,
                                                                      fontSize: 15,
                                                                    ),
                                                                  ),
                                                                )));
                                                          })

A: Since groupValue stores the currently selected value and you use the individual dataOptions[index]["option_id"] as groupValue all radio buttons are independent from each other.
If this is intended, check out checkboxes as they are meant to be used for this behavior.  CheckBox
To deselect a Radio widget if another one in the group is selected do the following.
//Set default option if prefered
String? _groupValue;

Radio(
  value: dataOptions[index]["option_price"],
  groupValue: _groupValue,
  onChanged: (value) {
    setState(() {
      _groupValue = value;
    });
  },
),

A: I added this and it worked.
toggleable: true,
reference: https://api.flutter.dev/flutter/material/Radio/toggleable.html


text:
Q: How to word-wrap headers in a vertical table (transposed table)? We are using the responsive tables as described here: http://dbushell.com/demos/tables/rt_05-01-12.html .

It transposes the table by creating a vertical table with a fixed left column. The transposed header row,
however, is not wrapped on white space and unnecessarily widens the table.

For transposing, the trick is to use display: inline-block; on the table rows and
  white-space: nowrap; on the table body.

Any solutions to enable wrapping in the header row?
JsFiddle link: http://jsfiddle.net/ckaodhz1/
Code for the above trick:
table thead { display: block; float: left; }
table tbody {
    display: block;
    width: auto;
    position: relative;
    overflow-x: auto;
    white-space: nowrap;
}
table thead tr { display: block; }
table th { display: block; }
table tbody tr { display: inline-block; vertical-align: top; }

A: You can use <th> tag for all the headers.
Then you can use word-wrap: break-word; for the <th> tag.

A: You can use ellipsis. try this
.graham tr td:first-child{
  text-overflow:ellipsis;
  overflow:hidden;
  white-space:nowrap;
  width:50px;
}


text:
Q: How can I get the result of ls into a variable in bash Script? I'm a novice at bash (more like less than a novice). Trying to get the results of this into a variable
ssh root@HOST "ls -tr /path/to/files/Backups | tail -1"

This is what I have
#!/bin/bash
STR=ssh root@HOST "ls -tr /path/to/files/Backups | tail -1"
echo $STR

It returns myscript.sh: command not found
Script is located in the ~/Desktop/scripts
I am running it in that directory by typing test.sh
How do I format the line for the variable?

A: str="$(ssh root@HOST "ls -tr /path/to/files/Backups | tail -1")"
to assign the result to the variable. However that is not the error that you are currently on. You are having trouble running your script. Use an absolute or relative path. e.g. ./my-script


text:
Q: Custom styling cell in react-table Material UI I have a issue with display value with custom style to Cell in react-table of MUI. (Align center text in cell)
This is code to render cell to table
<TableBody {...getTableBodyProps()}>
  {rows?.map((row) => {
    prepareRow(row)
    const { key, ...getRowProps } = row.getRowProps()
    return (
      <Row
        onClick={() => hasRowClick && onRowClick(row)}
        hasRowClick={hasRowClick}
        hover
        key={key}
        {...getRowProps}
      >
        {row.cells.map((cell) => {
          const { key, ...getCellProps } = cell.getCellProps()

          return (
            <Cell variant="body" key={key} {...getCellProps}>
              {cell.render('Cell')}
            </Cell>
          )
        })}
      </Row>
    )
  })}

  {!loading && !data.length && (
    <Row>
      <Cell colSpan={headerGroups[headerGroups.length - 1]?.headers.length}>
        <EmptyTable />
      </Cell>
    </Row>
  )}
</TableBody>

Below is code create column for this table:
export const EmployeeTimeOffFields = {
  listFields: [
    {
      Header: i18n.t('employee.date'),
      accessor: 'date',
      display: true
    },
    {
      Header: i18n.t('employee.number_of_minutes'),
      accessor: 'number_of_minutes',
      Cell: ({ value }: CellProps<TimeOff>) => {
        return minutesToDays(value, 'string')
      },
      display: true
    }
  ],
  searchFields: [
    {
      Header: i18n.t('employee.date'),
      accessor: 'date',
      type: 'text',
      grid: { xs: 12, sm: 6, md: 6 },
      display: true
    }
  ],
  quickSearchField: {
    Header: i18n.t('employee.date'),
    accessor: 'date',
    type: 'text',
    grid: { xs: 12, sm: 6, md: 6 },
    display: true
  }
}

And i found a block of code in codesanbox.io that describe exactly what i expected. But it written by javascript (my teams use typescript).
function MyCell({ value, columnProps: { rest: { someFunc } } }) {
  return
{value}

}
.
.
.
{
  Header: 'Profile Progress',
  accessor: 'progress',
  Cell: MyCell,
  getProps: () => ({ someFunc: () => alert("clicked")})
}

And only allow edit in listField, not allow edit inside return <TableBody.../> method.
(only write in this block):
  listFields: [
    {
      Header: i18n.t('employee.date'),
      accessor: 'date',
      display: true
    },
    {
      Header: i18n.t('employee.number_of_minutes'),
      accessor: 'number_of_minutes',
      Cell: ({ value }: CellProps<TimeOff>) => {
        return minutesToDays(value, 'string')
      },
      display: true
    }
  ],

Hope your help, thanks so much


text:
Q: ¿Cómo se logra ocultar parte del email en ASP.NET? C*****reo25@ejemplo.com Saludos,
¿Cómo se logra que un correo electrónico o cualquier otro campo oculte con * (asteriscos parte de la palabra)?
Por ejemplo así llega el siguiente correo.

.CS del envío de correo
 string username = string.Empty;
        string password = string.Empty;
        string constr = ConfigurationManager.ConnectionStrings["Web2017_test"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT Username, [Password] FROM Users WHERE Email = @Email"))
            {
                cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    if (sdr.Read())
                    {
                        username = sdr["Username"].ToString();
                        password = sdr["Password"].ToString();
                    }
                }
                con.Close();
            }
        }
        if (!string.IsNullOrEmpty(password))
        {
            MailMessage mailMsg = new MailMessage("webmaster@myFirstWeb.com", txtEmail.Text.Trim());

            mailMsg.Subject = "Su usuario es";
            string body = "Cuenta My Web Page
";
            body += string.Format("

Su usuario es: {0:}.

", username);
            body += "
haz clic en el siguiente enlace para iniciar sesión
»http://localhost/login.aspx
";
            body += "Si no reconoce la actividad en está cuenta, puede enviarnos un correo electrónico indicando que no es usted quien ha solicitado esta información.";

            mailMsg.Body = body;
            mailMsg.IsBodyHtml = true;

            SmtpClient servidor = new SmtpClient("smtp.gmail.com");
            servidor.Port = 587;
            servidor.EnableSsl = true;
            servidor.Send(mailMsg);

            lblMessage.ForeColor = Color.Green;
            lblMessage.Text = "El nombre de usuario solicitado se ha enviado a su cuenta de correo.";
            lblMessage.Font.Size = 15;
            Response.AddHeader("Refresh", "5; url=forgotUser.aspx");
        }
        else
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Atención!* La dirección de correo que ingresó no se encuentra registrada.";
            lblMessage.Font.Size = 10;
        }

A: Hay muchas posibles maneras de hacer lo que quieres. Yo te doy solo una posibilidad:
string usuario = "ejemplo123@ejemplo.com";
string[] separada = usuario.Split('@');
int inicio = 1; //Caracteres al inicio de la cadena que dejamos visibles
int final = 3; //Caracteres al final de la cadena que dejamos visibles
int longitud;
if (separada[0].Length > inicio+final)
    longitud = separada[0].Length - final - inicio;
else
    longitud = 1;

separada[0] = separada[0].Remove(inicio, longitud).Insert(inicio, new string('*', longitud));
usuario = String.Join( "@",separada);

Este código con "ejemplo123@ejemplo.com" da como salida "e******123@ejemplo.com". Probablemente se puede optimizar mas pero esto es sólo para que veas una posibilidad y lo ajustes a tus necesidades.


text:
Q: how to transfer netcdf to binary IN PYTHON I want to know how to translate a netcdf file to a binary file IN PYTHON. I have some timeseries data in a netcdf file. I want to change it to a binary file so that I can run TIMESAT to extract phenological metrics.
Has someone already solved this problem? Or can I use Arcmap to build models to do this process?

A: NCO converts netCDF to binary as illustrated here, e.g.,
ncks -C -O -v one_dmn_rec_var -b bnr.dat -p ~/nco/data in.nc out.nc

A: You can just use gdal_translate to convert from netcdf to binary.  See:
http://web.nateko.lu.se/timesat/timesat.asp?cat=5
and
http://www.gdal.org/gdal_translate.html
My favorite way to install gdal is with conda.  Download anaconda or miniconda and for free from https://www.anaconda.com/ and then do:
conda install -c conda-forge gdal


text:
Q: ip address not in network i'm using centos 5.7. my ip address is 192.35.251.225. when i start and login to my machine, i'm still on the network in which i'm still reachable on the ipmsg of our company. but after a few hours or so, i can no longer be accessible via ipmsg. on my local, my ip address displayed on the ipmsg is 127.0.0.1 and there's 0 member when i refreshed ipmsg.
when i execute
ifconfig eth0

the ip address is still there
inet addr:192.35.251.225

i have tried restarting my network
/sbin/service network restart

but still, i'm not connected to our company's network. this problem occurs when i'm doing a project which is to setup snmp service to another machine which a 64-bit machine so i was connecting to that machine via ssh. then i also execute restoreocon -Rv . on my local machine.
what should i do to solve this problem? any idea what's the cause of this one? please help.
btw, i have checked the /var/log/messages and i have this message
Can't open system message bus connection: Failed to connect to socket
/var/run/dbus/system_bus_socket: Connection refused

A: TL;DR It could be a company's firewall that blocks ipmsg communication after a time of inactivity.
Detailed: ipmsg depends upon UDP port 2425 (and TCP for attachment transfer). If there is a network device between you and your peer that performs network address translation (NAT) chances are that you simply fall off the conntrack table because of insufficient activity. This table becomes overfilled with tracked hosts (including UDP, as much as it is a connectionless protocol). From your question it seems that you are disconnected after some time of ipmsg inactivity.