text:
Q: Rewrite URLs for static content I have problems with static files url rewriting in current .htaccess setup on apache2.
My app structure is:
/siteroot
/siteroot/app
/siteroot/lib
/siteroot/...
/siteroot/public <- all the static files (images, js, etc.) stored here
/siteroot/index.php
/siteroot/.htaccess

So, i need to rewrite url like /css/style.css to /public/css/style.css. I did that in really simple way, but when the file is not found it causing 10 internal redirects, which is bad. I need somehow to return 404 code if file not found, or just pass it to the next rule. And i dont have any access to site configuration file. Only .htaccess.
The reason why i`m asking this question is that the site was running on nginx and i need to rebuild the same configuration on apache.
Here is my .htaccess file.
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.+\.(jpg|jpeg|gif|png|ico|css|js|swf)$ /public/$0 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

A: Test if a redirect is reasonable:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/public/$0 -f
RewriteRule ^.+\.(jpg|jpeg|gif|png|ico|css|js|swf)$ /public/$0 [L]

A: If the number of prefixes is limited, you could add another group to your regex:
RewriteRule ^(css|js|images|etc)/.+\.(jpg|jpeg|gif|png|ico|css|js|swf)$ /public/$0 [L]


text:
Q: Google Maps Won't appear using Jquery Mobile I have a content which is contain maps but it won't appear. I'm using jquery mobile and run it on localhost. I've tried to re-load it for a couple times but still it won't work. I'm getting stuck.
So, this is the code:
    <link rel="stylesheet" href="<?php echo base_url('assets/jquerymobile/jquery.mobile.structure-1.2.0.css'); ?>" />
<link rel="stylesheet" href="<?php echo base_url('assets/jquerymobile/jquery.mobile-1.2.0.css'); ?>" />
<link rel="stylesheet" href="<?php echo base_url('assets/jquerymobile/jquery.mobile.theme-1.2.0.css'); ?>" />
<link rel="stylesheet" href="<?php echo base_url('assets/mobileicon/original/jqm-icon-pack-2.0-original.css'); ?>" />
<link rel="stylesheet" href="<?php echo base_url('assets/mobileicon/original/jqm-icon-pack-1.1.1-original.css'); ?>" />

I've put onload= initialize() on body. Function calcRoute was put on , but still not working.
HTML Code:

<form action="transportation.html" onSubmit="calcRoute();return false;" id="routeForm">

            <input type="text" name="from" id="from" placeholder="From" maxlength="300" style="width:100%;" data-mini="true"/>

            <input type="text" name="to" id="to" placeholder="To" maxlength="300" style="width:100%;" data-mini="true"/>

            <fieldset data-role="controlgroup" data-mini="true">
            <legend>Travel Mode:</legend>
                <input type="radio" name="travelMode"  id="rchoice1" value="DRIVING" checked="checked" />
                Driving

                <input type="radio" name="travelMode" id="rchoice2" value="BICYCLING"  />
                Cycling

                <input type="radio" name="travelMode" id="rchoice3" value="TRANSIT"  />
                Public transport

                <input type="radio" name="travelMode" id="rchoice4" value="WALKING"  />
                Walking
            </fieldset>

            <input type="submit" name="submit" data-theme="c" data-mini="true" value="Get directions"/>

</form>

Please, help me anyone. Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to avoid python script code mess and optimization? I have created a Python script that builds a calendar (.xlsx file) with people assigned to rewrite and overhaul the lessons of my college professors.
The code, however, is rather "wordy" and, almost certainly, not optimized. How can I proceed? Do you have any advice (including any texts that I could read to increase my knowledge)?
Here's my script:
import xlsxwriter
#use xlsxwriter functions to initializate\create .xlsx file
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
#Defining start informations
day = 24 #first day of the calendar
nday = 1 #nday stands for the week day (1=monday, ..., 7=sunday)
month = 10 #month number
trentuno = [1, 3, 5, 7, 8, 10, 12] #array that defines month that have 31 days
settimana = [1, 2, 3, 4 , 5] #array that defines working days
i=0
f=open('test.txt') #inside this file we have the names (one per line) of people that is going to be in the calendar
lines=f.readlines()
array = [] #void array that is going to be "the excel table"
array.append(["data", "ora", "sbobinatore", "controllore"])
festa = ["1/11", "8/12", "26/12", "27/12", "28/12", "29/12", "30/12", "2/1", "3/1", "4/1", "5/1", "6/1"] #holidays
due = ["9/1", "10/1", "11/1", "12/1", "13/1", "16/1", "17/1", "18/1", "19/1", "20/1"] #days with only 2h lessons
while i < len(lines):
    data = "%d/%d" % (day,month)
    if nday in settimana and not data in festa:
        ora = "[9:00-11:00]"
        sbobinatore1 = lines[i] # "sbobinatore" is the person who writes the lesson
        controllore1 = lines[i+1] # "controllore" is the person who check the rewrited lesson
        array.append([data, ora, sbobinatore1, controllore1])
        i = i+2
        ora2 = "[11:00-13:00]"
        sbobinatore2 = lines[i]
        controllore2 = lines[i+1]
        array.append([data, ora, sbobinatore2, controllore2])
        i = i+2
        if month in trentuno:
            if day == 31:
                day = 1
                nday = nday+1
                month = month+1
            else:
                day = day+1
                nday = nday+1
        elif month == 2:
            if day == 28:
                day = 1
                month = month+1
                nday = nday+1
            else:
                day = day+1
                nday = nday+1
        else:
            if day == 30:
                day = 1
                month = month+1
                nday = nday+1
            else:
                day = day+1
                nday = nday+1
#if the day is not a working day
    else:
        if month in trentuno:
            if day == 31:
                day = 1
                if nday == 7:
                    nday = 1
                else:
                    nday = nday+1
                month = month+1
            else:
                day = day+1
                if nday == 7:
                    nday = 1
                else:
                    nday = nday+1
        elif month == 2:
            if day == 28:
                day = 1
                month = month+1
                if nday == 7:
                    nday = 1
                else:
                    nday = nday+1
            else:
                day = day+1
                if nday == 7:
                    nday = 1
                else:
                    nday = nday+1
        else:
            if day == 30:
                day = 1
                month = month+1
                if nday == 7:
                    nday = 1
                else:
                    nday = nday+1
            else:
                day = day+1
                if nday == 7:
                    nday = 1
                else:
                    nday = nday+1
#repeating the while with role invertion
i=0
while i < len(lines):
    data = "%d/%d" % (day,month)
    if nday in settimana and not data in festa:
        ora = "[9:00-11:00]"
        sbobinatore1 = lines[i+1]
        controllore1 = lines[i]
        array.append([data, ora, sbobinatore1, controllore1])
        i = i+2
        ora2 = "[11:00-13:00]"
        sbobinatore2 = lines[i+1]
        controllore2 = lines[i]
        array.append([data, ora, sbobinatore2, controllore2])
        i = i+2
        if month in trentuno:
            if day == 31:
                day = 1
                nday = nday+1
                month = month+1
            else:
                day = day+1
                nday = nday+1
        elif month == 2:
            if day == 28:
                day = 1
                month = month+1
                nday = nday+1
            else:
                day = day+1
                nday = nday+1
        else:
            if day == 30:
                day = 1
                month = month+1
                nday = nday+1
            else:
                day = day+1
                nday = nday+1
#if the day is not a working day or holiday
    else:
        if month in trentuno:
            if day == 31:
                day = 1
                if nday == 7:
                    nday = 1
                else:
                    nday = nday+1
                month = month+1
            else:
                day = day+1
                if nday == 7:
                    nday = 1
                else:
                    nday = nday+1
        elif month == 2:
            if day == 28:
                day = 1
                month = month+1
                if nday == 7:
                    nday = 1
                else:
                    nday = nday+1
            else:
                day = day+1
                if nday == 7:
                    nday = 1
                else:
                    nday = nday+1
        else:
            if day == 30:
                day = 1
                month = month+1
                if nday == 7:
                    nday = 1
                else:
                    nday = nday+1
            else:
                day = day+1
                if nday == 7:
                    nday = 1
                else:
                    nday = nday+1
#sight check
print(array)
#defining starting point for the creation of the table inside the xlsx worksheet
row = 0
col = 0
#actual creation of the table
for a, b, c, d in (array):
    worksheet.write(row, col, a)
    worksheet.write(row, col + 1, b)
    worksheet.write(row, col + 2, c)
    worksheet.write(row, col + 3, d)
    row += 1

workbook.close()


text:
Q: android webview: website controls not working I have created android webview application.
But links or buttons on the webpage doesnt work.
I can saythat it doesnt load properly.
You can find the MainActivity.java here
package com.tunghuynh.comparotel;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.res.Configuration;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class MainActivity extends Activity {

    private WebView webView;
    private ProgressBar progress;
    private RelativeLayout splash;
    //private RelativeLayout imgSplash;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        splash = (RelativeLayout) findViewById(R.id.webview);
        //imgSplash = (RelativeLayout) findViewById(R.id.imgSplash);
        splash.setVisibility(View.INVISIBLE);

        webView = new WebView(this);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                MainActivity.this.setValue(newProgress);
                super.onProgressChanged(view, newProgress);
                try {
                    if (newProgress >= 100) {
                        splash.setVisibility(View.VISIBLE);
                        splash.addView(webView);
                        progress.setVisibility(View.INVISIBLE);
                    }
                } catch (Exception e) {
                }
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        progress = (ProgressBar) findViewById(R.id.progressBar);
        progress.setMax(100);
        String url = Global.urlComparotel;
        switch (Global.type) {
        case 0:
            url = Global.urlComparotel;
            break;
        case 1:
            url = Global.urlHotelcito;
            break;
        case 2:
            url = Global.urlHotelinha;
            break;
        case 3:
            url = Global.urlHotelomat;
            break;
        case 4:
            url = Global.urlOtelcik;
            break;
        default:
            url = Global.urlComparotel;
        }
        openWeb(url);

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setContentView(R.layout.activity_main);
    }

    private void openWeb(String url) {
        webView.loadUrl(url);
        MainActivity.this.progress.setProgress(0);
    }

    public void setValue(int progress) {
        this.progress.setProgress(progress);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;// super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub

        switch (item.getItemId()) {
        case R.id.item1:
            webView.reload();
            break;
        case R.id.item2:
            shareTextUrl();
            break;
        case R.id.item3:
            Intent int1 = new Intent(MainActivity.this, AboutUs.class);
            startActivity(int1);
            break;
        case R.id.item4:
            rateApp();
            break;
        case R.id.item5:
            finish();
            break;
        }
        //shareTextUrl();
        return false;// super.onOptionsItemSelected(item);
    }

    private void rateApp() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("market://details?id=" + this.getPackageName()));
        if (!MyStartActivity(intent)) {
            intent.setData(Uri
                    .parse("https://play.google.com/store/apps/details?id="
                            + this.getPackageName()));
            if (!MyStartActivity(intent)) {
                Toast.makeText(
                        this,
                        "Could not open Android market, please install the market app.",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean MyStartActivity(Intent aIntent) {
        try {
            startActivity(aIntent);
            return true;
        } catch (ActivityNotFoundException e) {
            return false;
        }
    }

    private void shareTextUrl() {
        Intent share = new Intent(android.content.Intent.ACTION_SEND);
        share.setType("text/plain");
        share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        share.putExtra(Intent.EXTRA_TEXT,
                "https://play.google.com/store/apps/details?id=" + this.getPackageName());
        startActivity(Intent.createChooser(share, "Share application!"));
    }
}

http://www.a2b4.net/MainActivity.java
How we can resolve the problem.

A: Since your website needs javascript you should enable javascript execution in your webview:
 webview.getSettings().setJavaScriptEnabled(true);

see also documentation
Update: You can suppress the warning message Warning: Using setJavaScriptEnabled can introduce XSS vulnerabilities into you application by adding:
 @SuppressLint("SetJavaScriptEnabled") // add this
 @Override
 protected void onCreate(Bundle savedInstanceState) {

above the onCreate method.


text:
Q: unable to open primary document entity I'm new at Ubuntu please anyone can help me to figure out this problem?
Whenever i run this command
7z x -so SwissProt.xml.7z | xqilla -i /dev/stdin q.xq

It displays error "unable to open primary document entity" like this one.


text:
Q: cell animation, uitableview cell I was downloading an Pizza pizza application for IPhone. There is very cool animation for a cell.
If you click on particular cell, it will expand down and show you more controllers.
Please look at link1 (first state ) and at link2 (second state when you are clicking on the cell)
Question : what is the right way to achieve this animation.
Please advice me on this issue. Any comments are welcomed

A: There is nothing new about this animation. Its pretty straight forward, and it will just depend on how you want to effect this change.
For example, start off with the cells as shown in your first image. Touching a cell will call the -didSelectRowAtIndexPath, and you will need to increase the size of the cell, and provide the new cell (which is the image of the second link). Call tableView reloadData to effect this change.  UseUIAnimation that will animate the cell from your first state to second state for a period of 0.5 seconds (how fast you want it to be)
Make sure that during the animation period, your cell is NOT selectable.
cell.userInteractionEnabled = NO
You can do this with other animation frameworks, but UIAnimation should do the trick. (Refer to examples of UIAnimation if you need help with it)

A: Every cell you see is a section Header View with button.When you touch the button,the table reload data in this section,then you can see the real cell view in this section. The cell view is a custom view with a lot of controllers.


text:
Q: Removing single/double quotes from beginning/end of string, only if they enclose it I'm trying to use regular expressions in PHP to strip single or double quotes from the beginning and end of string, but we only want to remove them if they exist at each end of the string. That way, quotes used as measurements won't be lost.
for example:
"3' 7"" - would remove quotes
3' 7" - would not remove

I can easily do this with substr and trim logic, but I'd love to do it all at once with regex.

A: To replace single or double quotes and ensure that they must match:
preg_replace('/^([\'"])(.*)\\1$/', '\\2', $value);

A: preg_replace('/^"(.*)"$/', '$1', '"3' 7""');

A: preg_replace('/^"(.*)"$/', '$1', '"3\' 7""');

A: The regular expression way of doing it is to capture the quote and then refer back to it later. The stuff inside the quotes should also be captured, so that it can be used as the replacement:
$x = array('3\' 7"', '\'3\' 7"\'', '"3\' 7""');
foreach ($x as $y)
    echo preg_replace('/^(["\'])(.*)\\1$/', '$2', $y), '
';
die;

Now, the regular expression way is okay, but doing it "manually" is probably a little easier to understand and to maintain in the future:
function remove_quotes($string)
{
    $length = strlen($string);

    if ($length > 2)
    {
        foreach (array('\'', '"') as $quote)
        {
            if ($string[0] === $quote && $string[$length-1] === $quote)
            {
                $string = substr($string, 1, -1);
                break;
            }
        }
    }
    return $string;
}
$x = array('3\' 7"', '\'3\' 7"\'', '"3\' 7""');
foreach ($x as $y)
    echo remove_quotes($y), '
';
die;


text:
Q: Bootstrap Modal Window not recognize all the variations of YouTube URLs On the Internet I found a jQuery code that works very well to open YouTube video in modal form. I change some dteails and everything was fine until I realized that do not recognize all the variations of YouTube URLs.
All I need is to extract the YouTube ID and put it in the right place. I wrote a regex and combined several versions but does not work with every URL.
This is my code:
$('a[href^="https://www.youtu"]').on('click', function(e){

        var YouTube=$(this).attr('href').replace(/feature=player_embedded[&\w]*(?!['"][^<>]*>|<\/a>)/ig, "").replace(";", "");  // replace player_embedded
            preg=/(?:http|https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=))([\w\-]{10,12})\b[?=&\w]*(?!['"][^<>]*>|<\/a>)/ig,
            youtubeID=YouTube.replace(preg, '$1');
        if (youtubeID!="" && (YouTube.indexOf('v') > -1 || YouTube.indexOf('embed') > -1))
        {
            // Prevent opening of external page
            e.preventDefault();
            // Variables for iFrame code. Width and height from data attributes, else use default.
            var width = $(window).width(),
                vidWidth = 800, // default
                vidHeight = 450; // default
            if ( $(this).attr('data-width') ) { vidWidth = parseInt($(this).attr('data-width')); }
            if ( $(this).attr('data-height') ) { vidHeight = parseInt($(this).attr('data-height')); }
            // responsive debug
            var vidWidth =  (width>vidWidth?800:(width-60));
            var iFrameCode = '

';

            // Replace Modal HTML with iFrame Embed
            $('#mediaModal .modal-body').html(iFrameCode);
            // Set new width of modal window, based on dynamic video content
            $('#mediaModal').on('show.bs.modal', function () {
                // Add video width to left and right padding, to get new width of modal window
                var modalBody = $(this).find('.modal-body'),
                    modalDialog = $(this).find('.modal-dialog'),
                    newModalWidth = vidWidth + parseInt(modalBody.css("padding-left")) + parseInt(modalBody.css("padding-right"));
                newModalWidth += parseInt(modalDialog.css("padding-left")) + parseInt(modalDialog.css("padding-right"));
                newModalWidth += 'px';
                // Set width of modal (Bootstrap 3.0)
                $(this).find('.modal-dialog').css('width', newModalWidth);
            });

            // Open Modal
            $('#mediaModal').modal();
        }
    });

Thanks!


text:
Q: Div scrolling in Firefox I use this code for scrolling my div
mydiv.addEventListener('mousewheel', function(e)
    {
    var col = 255;
    if(e.wheelDelta/120 > 0)
        {
        if(col < 245)
            {
            col+=10;
            }
        this.scrollTop = this.scrollTop-25;
        }
    else
        {
        if(col > 10)
            {
            col-=10;
            }
        this.scrollTop = this.scrollTop+25;
        }
    });

It run without problems in Opera, in Firefox it make nothing, and at the first, no errors, so that I don't know where the problem is.

A: Firefox does not support the mousewheel event at this point in time.
It instead supports the DOMMouseScroll event.
http://www.sitepoint.com/html5-javascript-mouse-wheel/


text:
Q: workingdirectory does not work when verb is used Using Start-Process, when Verb is used, the Workingdirectory option does not work, the new powershell always start in C:\WINDOWS\system32. Why is this? How can I do this without an extra cd command?
PS C:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.14393.0
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.0
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

PS C:\> Start-Process -FilePath powershell.exe -Verb Runas -WorkingDirectory C:\ws\

# the new ps shell always in system32:

Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

PS C:\WINDOWS\system32> pwd

Path
----
C:\WINDOWS\system32

A: As for the why - see the bottom of this answer.
As for an effective workaround (which does, however, require use of cd (Set-Location)):
Start-Process -FilePath powershell.exe -Verb Runas `
  -ArgumentList '-NoExit -Command "cd C:\ws"'

To avoid quoting headaches you can also pass the arguments individually, except for the command string itself:
Start-Process -FilePath powershell.exe -Verb Runas `
  -ArgumentList '-NoExit', '-Command', 'cd C:\ws'

Venryx points out that if you want to apply this technique to calling a script file that is normally called with -File rather than -Command, you must switch to a -Command approach (given that the two parameters cannot be combined) that changes the location first and then (;) invokes (&) the script, script.ps1 in the new location, this example:
Start-Process -FilePath powershell.exe -Verb Runas `
  -ArgumentList '-Command', 'cd C:\ws; & .\script.ps1'

For a more complex example involving nested quoting, see this answer.

In practice - and the docs do not mention that - the -WorkingDirectory parameter is not respected if you start a process elevated (with administrative privileges, which is what -Verb RunAs - somewhat obscurely - does): the location defaults to $env:SYSTEMROOT\system32 (typically, C:\Windows\System32).
Note that this is not the -Verb parameter per se that's the problem, but its specific RunAs argument.
The only case in which -WorkingDirectory is respected in combination with -Verb RunAs is if the program being started is PowerShell Core, namely pwsh.exe - whether you call from Windows PowerShell or PowerShell Core.
Whether there is a good technical reason for this behavior or whether this is a bug, I have no clue.
Do let us know if you do.
In all other scenarios:

*

*running as the current user as-is (the default)

*impersonating a different user with -Verb RunAsUser (with an invariably interactive credentials prompt)

*running non-interactively as a different user with -Credential <PSCredential>
the -WorkingDirectory parameter is respected.
However, if the (different) target user lacks the permissions to access the implied (current location) or explicitly specified working directory (via -WorkingDirectory), the current location defaults to C:\ in case (2), and results in failure of the Start-Process command in case (3).


text:
Q: An inequality for $1+\cos(x-x_0)-\cos(\delta)$ in Trigonometric Series by Zygmund On page 12 it's written that the function ($\delta>0$) $t(x)=1+\cos(x-x_0)-\cos(\delta)$ satisfies the following: $t(x)\ge 1$ in $I$ where $I = (x_0-\delta,x_0+\delta)$ $t(x)>1$ where $I'$ is some interior interval to $I$, and $|t(x)| \le 1$ outside of $I$.
My question how is it possible that there would be equality $t(x)=1$ in $I$ I mean it doesn't include the endpoints of the interval, I mean $t(x= x_0+\delta)=t(x_0-\delta)=1$ but $I$ doesn't include the endpoints of the interval.
Perhaps I should add also that $I\subset (-\pi , \pi)$.

A: When $|x-x_0|<\delta\le \pi$, we have
$$t(x)=1+\cos(x-x_0)-\cos(\delta)>1$$
by the monotonicity of cosine. Apparently, the author does not need strict inequality here: $t(x)\ge 1$ is enough for his purpose.
Writing $t(x)\ge 1$ does not mean that the equality is attained: it means not bothering to think whether it may be attained. This is a matter of writing style. Some mathematicians prefer using $\le $ and $\ge$ as "default mode" of inequalities, reserving $<$ and $>$ only for the situations when strictness matters. Benefits include not changing the inequality when passing to limits, or multiplying by $|x|$, etc.


text:
Q: Caching Compiled Expression Delegates Backstory: Throughout our project we constantly find ourselves using the System.ComponentModel.DataAnnotations.Validator object as well as attributes to validate properties passed in to our API. The Validator object requires passing in the property name as well as the value, which is fair, but we are all a little grossed out by the [constantly-increasing] number of magic strings being passed around for these property names. Not only this entails the risk of mistyping the property name, it also reduces maintainability in the case that one of those properties get renamed (again, there are way too many of them).
To automatically resolve the member name, I created this helper method (for the sake of simplicity, let's assume I'm only dealing with reference-type properties, hence the P: class constraint):
public static P ValidateProperty<T, P>(T obj, Expression<Func<T, P>> member, List<ValidationResult> results, Func<P, P> onValidCallback = null)
    where T : class
    where P : class
{
    var expr = member.Compile();
    var memberName = ((MemberExpression)member.Body).Member.Name;
    var value = expr(obj);

    bool isValid = Validator.TryValidateProperty(value, new ValidationContext(obj) { MemberName = memberName }, results);
    return isValid ? (onValidCallback != null ? onValidCallback(value) : value) : null;
}

And I simply call it like this:
var value = ValidateProperty(myObject, x => x.PropertyFoo, errors, result => result.Trim());

Which works like a charm and doesn't involve any magic strings being passed around.
A sample request would look like this:
public class Request
{
    public class C1
    {
        Property1;
        Property2;
        ...
    }
    public class C2
    {
        Property1;
        Property2;
        ...
    }
    public class C3
    {
        Property1;
        Property2;
        ...
    }
    ...
}

My concern here however, is on performance implications for member.Compile(). Since there are many different possible permutations of T, P (C1, Property1, C1, Property2, C2, Property1 etc.) I won't be able to cache the compiled expression and execute it on the next call, unless both T and P are of the same type, which happens rarely.
I could optimize this by changing Expression<Func<T, P>> member to Expression<Func<T, object>> member so that now I would have to only cache the expression once per type of T (i.e. C1, C2, etc.)
I was wondering if anyone has any input on a better way to do it, or am I trying to "over engineer" the problem? Is there a common pattern for situations that involve passing around magic strings over and over again?

A: Another option: Rather than using C# 6 features or compiling, just use reflection. Now you're trading compile performance degradation for reflection performance degradation (which is probably less).
...
var property = (PropertyInfo) ((MemberExpression)member.Body).Member;
var propertyName = property.Name;
var value =  property.GetValue(obj, new object[0]);
...

A: Well, you are correct, Expression.Compile really has a significant performance overhead. If the performance is really a concern, and the reflection approach mentioned in another answer is still concerning you, here is how you can implement compiled delegate caching:
public static class ValidateUtils
{
    static readonly Dictionary<Type, Dictionary<string, Delegate>> typeMemberFuncCache = new Dictionary<Type, Dictionary<string, Delegate>>();

    public static P ValidateProperty<T, P>(this T obj, Expression<Func<T, P>> member, List<ValidationResult> results, Func<P, P> onValidCallback = null)
        where T : class
        where P : class
    {
        var memberInfo = ((MemberExpression)member.Body).Member;
        var memberName = memberInfo.Name;
        Func<T, P> memberFunc;
        lock (typeMemberFuncCache)
        {
            var type = typeof(T);
            Dictionary<string, Delegate> memberFuncCache;
            if (!typeMemberFuncCache.TryGetValue(type, out memberFuncCache))
                typeMemberFuncCache.Add(type, memberFuncCache = new Dictionary<string, Delegate>());
            Delegate entry;
            if (memberFuncCache.TryGetValue(memberName, out entry))
                memberFunc = (Func<T, P>)entry;
            else
                memberFuncCache.Add(memberName, memberFunc = member.Compile());
        }
        var value = memberFunc(obj);
        bool isValid = Validator.TryValidateProperty(value, new ValidationContext(obj) { MemberName = memberName }, results);
        return isValid ? (onValidCallback != null ? onValidCallback(value) : value) : null;
    }
}

Btw, I would remove P : class constraint, thus allowing validating also numeric, date etc. values, but anyway.

A: In C# 6 (VS2015), you can use nameof. This call to your ValidateProperty method involves an extra parameter (name of property vs. value of property) which introduces a bit of redundancy but resolves your potential performance issue of compiling a bunch of stuff dynamically.
var value = ValidateProperty(myObject, nameof(PropertyFoo), PropertyFoo, errors, result => result.Trim());


text:
Q: Ionic 5 dependencies update bug My Ionic 5 (Angular) Project packages/dependencies were too outdated, so I decided to update all of them at once, most important of which for me were Typescript, Angular and RxJS. I updated all of them to the latest versions. A lot of things seemed to break, not just in the code but also the ionic dependencies not being yet compatible, so I downgraded Angular to version 8. Then I had to fix some of the deprecated syntax in the code but not a big deal.
After fixing a couple of things like that, I get this scss file error:
node_modules/ionic-angular/fonts/ionicons.scss, line: 9
         File to import not found or unreadable: ionicons-icons.
    L9:  @import "ionicons-icons";
   L10:  @import "ionicons-variables";

I was looking for a lot of workarounds/fixes for this, but still no progress and my build fails because of this.


text:
Q: php header redirect not I have copied a php routine from my test file where it worked great when referencing it directly.  Now I have merged it to the saving to a database and making a post call from index.php
The part where it should take me to paypal.  Doesn't do anything, I am pretty stumped in where to look.
I can copy the url and paste it into a browser no problem.
I am sure the problem lies in the fact I am calling this through ajax
  $.ajax({
                    url: 'php/processorder.php',
                    data: {my_json_data: json}, // tableObject},
                    type: 'POST',
                    async: false,
                    dataType: 'json',
                    cache:false

                        });

<?PHP

//this is the layout of the json object
//Title:First Name:Surname:Group Name               this will need     amending as the json object builds
//checkout.php to be incorparated into this file

//namespaces here
//everything below here is from checkout.php
use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;

//requirements here
require("dbsettings.php");
require ("/../app/start.php");

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

//gets a new number
$sql = "SELECT max(`applicationNumber`) + 1 as newNum FROM   applicationheader;";
$result = mysqli_query($conn,$sql);

while($row = mysqli_fetch_assoc($result)) {

$NewOrder =  $row["newNum"];
}

$_Reference=  $_POST["my_json_data"] ;

// Loop through Array

$someArray = json_decode($_Reference, true);
$I = 1 ;
$lineNo =1 ;

foreach ($someArray as $key => $value) {
 //fist pass store header info as well
 if ($I == 1) {
     $sql = "INSERT into applicationheader    (applicationnumber,GroupName,applicationDate)
         Values (" . $NewOrder . ",'" . $value["Group Name"] .  "',curdate())";

     mysqli_query($conn,$sql);
  }

 //store detail
 //$mval holds the value of price
 $mVal = 5;
 if ($value["Age Bracket"] === 'A'){
     $mVal = 10;
 }

 $sql = "INSERT into applicationdetail (
 applicationnumber,lineNo,title,firstname,surname,address1,address2,city,county,postcode,paid,`size`,price,gender,agebracket,MobileNo)
 values(" . $NewOrder . " , " . $lineNo . "," . "'" . $value["Title"] . "','" . $value["First name"] . "','" . $value["Surname"] . "','" . $value["Address1"] . "','" . $value["Address2"] . "','" . $value["City"] . "','" . $value["County"] . "','" . $value["Postcode"] . "','" . "N" . "','"
 . $value["Size"] . "'," . $mVal . ",'" . $value["Gender"] . "','" . $value["Age Bracket"] . "','" . $value["Mobile"] . "')";

  mysqli_query($conn,$sql);

 $I ++;//control adding to the heder
 $lineNo ++;//control line no

 }
//close the database connection
mysqli_close($conn);

$pTotal = 20.00;
$shipping = 1.00;
$Total = $pTotal + $shipping ;

$payer = new Payer();
$payer->setPaymentMethod('paypal');

$item = new Item();
$item->setName("tieThisToSomething")
->setCurrency('GBP')
->setQuantity(1)
->setPrice($pTotal);

$itemList = new ItemList();
$itemList->setItems(array($item)); //I have removed square brackets  from   here []

$details = new Details();
$details->setShipping($shipping)
    ->setSubtotal($pTotal);

$amount = new Amount();
$amount->setCurrency('GBP')
    ->setTotal($Total)
    ->setDetails($details);

$transaction = new Transaction();
$transaction->setAmount($amount)
    ->setItemList($itemList)
    ->setDescription('Pay for all your santa fun')
    ->setInvoiceNumber(uniqid());//perhaps tie this to order number?

$redirectUrls = new RedirectUrls();

$redirectUrls->setCancelUrl(SITE_URL . '/php/pay.php?success=false')
         ->setReturnUrl(SITE_URL . '/php/php.php?success=true');

$payment = new Payment();
$payment->setIntent('sale')
    ->setPayer($payer)
    ->setRedirectUrls($redirectUrls)
    ->setTransactions(array($transaction)); //should [] be needed here?

//try {
//    $payment->create($paypal);
//} catch (Exception $e) {
//    die($e);
//}

try {
$payment->create($paypal);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
//    echo $ex->getCode(); // Prints the Error Code
//    echo $ex->getData(); // Prints the detailed error message
die($ex);
} catch (Exception $ex) {
die($ex);
}

$approvalUrl = $payment->getApprovalLink();
//echo $approvalUrl;

header("Location: {$approvalUrl}");

?>


text:
Q: Recursive listing of a particular file type in Windows PowerShell I was trying to recursively list using ls all the *.py files in a directory in Windows PowerShell. It didn't work. I checked up on the man page and then online page that -Recurse flag doesn't accept wildcards so *.py wouldn't work.
I want to know whether there is a simple in-built way to recursively list the files of a particular file extension in a directory using Windows PowerShell 2.0?
I am a newbie in PowerShell and don't want to indulge in Shell scripting at this stage. So please recommend in-built commands, flags, etc. only, if any.
By commands I means the in-built keywords of the PowerShell. I am not sure if that is proper vocabulary for PowerShell.

A: Use the Filter parameter:
ls $path -filter *.py -recurse

A: This will do the trick for you.
gci -Recurse | ? {$_.name -match ".py"}

or
gci -Recurse -Include *.py

A: ls is an alias for Get-ChildItem. (So is dir and gci). A simple Google will give you all kinds of examples but the thing to know is -include (or -exclude) are built in parameters that will show (or not show) file types you are looking for. An additional parameter, -filter, can also be used for partial file types. The switch parameter -recurse checks the contents of subfolders in the directory as well. Example01:
gci -path \$computername\$directory -Include *.py -recurse
Example02:
gci -path \$computername\$directory -Filter *.py -recurse
I like to suppress errors so a full example would look like this:
gci -path \Svr01\C$ -Include *.py -recurse -erroraction SilentlyContinue

A: I don't see how anybody would have got this working at any time.
gci -recurse works fine and lists all
gci -filter *.txt works fine, lists all .txt files but does not recurse
gci -filter *.txt -recurse returns either only .txt files from root or nothing.
It seems to apply the *.txt filter to the directory names therefor seeing no directories and thus does not recurse at all.


text:
Q: Are there ways to do if statements inside a cout line? I'm starting to learn C++, and something useful from my main language Lua, is the ability to say:
print(true/false and 1 or 0)

1 or 0 being anything but it seems in c++ it doesnt work the same way?
What I tried for C++ was
cout << (score == 0) and "Valid";

But only a true if check seems to work
if (score == 0) {
    cout << "Valid";
} else {
    cout << "A";
}

A: std::cout << ((score == 0) ? "Valid" : "A");

A: The << in your code isn't simply a syntax, it's an operator:
std::basic_ostream<CharT,Traits>::operator<<

Your attempt will not produce any compilation errors (assuming you have using namespace std;):
cout << (score == 0) and "Valid";
//        ^^ T/F ^^      ^^ T ^^

Apply some boolean algebra and that's equivalent to:
cout << true;  // if score is 0
cout << false; // if score is not 0

That's certainly not what you are trying to acheive.

Are there ways to do if statements inside a cout line?
if (score == 0)
    cout << "Valid";
else
    cout << "A";

You can do that using the conditional operator ?:
cout << (score == 0 ? "Valid" : "A");

But this approach is not guaranteed to work always. For example:
cout << (condition ? "String" : 1234);

Reason: Why in conditional operator (?:), second and third operands must have the same type?
Rearranging it like this will work:
condition ? cout << "String" : cout << 1234;

Now, talking about your Lua style:
print(true/false and 1 or 0)

I don't know Lua but that looks like a function. If you are looking for some template like that, try this:
template <typename T, typename U>
void conditionalPrint(const bool& condition, const T& arg1, const U& arg2)
{
    condition ? cout << arg1 : cout << arg2;
}

You can use it like this:
conditionalPrint(score == 0, "Valid", "A");
conditionalPrint(someCondition, "String", 1234);

Of course, I'm not going to explain how that works because you're new to C++. I would still recommend the if-else way of doing it. Readability of your code is very important:
if (condition)
{
    cout << "true block";
}
else
{
    cout << "false block";
}

"Lot can be learned by comparing two lanugages and try to see if what can be done in one can also be done in the other, but usually what is idiomatic in one can be crap in the other. Anyhow, I had my fun with exploring the issue, but imho the conclusion is as important as the rest of the answer" - idclev


text:
Q: AngularJS: Making multiple text fields editable I have multiple divs like this:

{{form.name}}

I can manually make them editable like so:

    {{form.name}}
    <button ng-click="editorEnabled=!editorEnabled">Edit</button>

      <input ng-model="form.name">
      <button ng-click="editorEnabled=!editorEnabled">Done</button>

Is it possible to automate this somehow, so that I don't have to copy/paste code?  I thought about using ng-repeat, but my model is not just an array--it is a json object, and not all field should have this applied to them.

A: Yes. You can add a class to the entire form. When class "edit-mode" is present, you can hide the divs with the text, and show the divs with the inputs. When it is removed, you could hide the divs with inputs and show the divs with texts. This would be the easiest, I think.
HERE IS AN EXAMPLE if you need one.
Add a special class to the bits that need this applied, and then use the CSS to hide/show their editable stuff.

A: This is a prime candidate for a custom directive. I found a few examples of a "click-to-edit" directive when I searched a while ago. You can also write your own for the experience (as I did).

A: This is a good fit for creating a directive. I created a similar directive that allowed in place edit. See here http://jsfiddle.net/cmyworld/6gMXL/
Here is the relevant code
app.directive('editable', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            model: '=model',
            defaultValue: '@defaultval',
            removeFn: '=onDelete'
        },
        templateUrl:'editable-template',
        controller: function($scope) {},
        // The linking function will add behavior to the template
        link: function(scope, element, attrs) {
            scope.editorEnabled = false;

            scope.unEdit = function($event) {
                scope.model = angular.copy(scope.editModel);
                scope.editorEnabled = false;
                if ($event != null) $event.preventDefault();
            };

            scope.enableEditor = function() {
                scope.editModel = angular.copy(scope.model);
                scope.editorEnabled = true;
                // The element enable needs focus and we wait for milliseconds before allowing focus on it.
                timer = setTimeout(function() {
                    element.find('input').focus().select();
                }, 100);
            };
        }
    }
});


text:
Q: How or why this is good for me I don't understand how this is good for me.
I don't understand why this is good for me.
Do they mean the same? If not what's the difference? Or maybe nuance? What context would one use them respectively and what would the answers be. Thanks.


text:
Q: Get stock data program with python I tried to get stock information from Yahoo with following code.
import pandas_datareader.data as web
import datetime
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2015, 12, 31)
f = web.DataReader('SNE', 'yahoo', start, end)
print(f)

But there is error like following ....
Please someone help me..
--------------------------------------------------------------------------- gaierror                                  Traceback (most recent call last) ~\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py in _new_conn(self)
    140             conn = connection.create_connection(
--> 141                 (self.host, self.port), self.timeout, **extra_kw)
    142

~\Anaconda3\lib\site-packages\requests\packages\urllib3\util\connection.py in create_connection(address, timeout, source_address, socket_options)
     59
---> 60     for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
     61         af, socktype, proto, canonname, sa = res

~\Anaconda3\lib\socket.py in getaddrinfo(host, port, family, type, proto, flags)
    742     addrlist = []
--> 743     for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
    744         af, socktype, proto, canonname, sa = res

gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

NewConnectionError                        Traceback (most recent call last) ~\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    599                                                   body=body, headers=headers,
--> 600                                                   chunked=chunked)
    601

~\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked,
**httplib_request_kw)
    355         else:
--> 356             conn.request(method, url, **httplib_request_kw)
    357

~\Anaconda3\lib\http\client.py in request(self, method, url, body, headers, encode_chunked)    1238         """Send a complete request to the server."""
-> 1239         self._send_request(method, url, body, headers, encode_chunked)    1240

~\Anaconda3\lib\http\client.py in _send_request(self, method, url, body, headers, encode_chunked)    1284             body =
_encode(body, 'body')
-> 1285         self.endheaders(body, encode_chunked=encode_chunked)    1286

~\Anaconda3\lib\http\client.py in endheaders(self, message_body, encode_chunked)    1233             raise CannotSendHeader()
-> 1234         self._send_output(message_body, encode_chunked=encode_chunked)    1235

~\Anaconda3\lib\http\client.py in _send_output(self, message_body, encode_chunked)    1025         del self._buffer[:]
-> 1026         self.send(msg)    1027

~\Anaconda3\lib\http\client.py in send(self, data)
    963             if self.auto_open:
--> 964                 self.connect()
    965             else:

~\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py in connect(self)
    165     def connect(self):
--> 166         conn = self._new_conn()
    167         self._prepare_conn(conn)

~\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py in _new_conn(self)
    149             raise NewConnectionError(
--> 150                 self, "Failed to establish a new connection: %s" % e)
    151

NewConnectionError: <requests.packages.urllib3.connection.HTTPConnection object at 0x0000001B3783DC18>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

MaxRetryError                             Traceback (most recent call last) ~\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    437                     retries=self.max_retries,
--> 438                     timeout=timeout
    439                 )

~\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    648             retries = retries.increment(method, url, error=e, _pool=self,
--> 649                                         _stacktrace=sys.exc_info()[2])
    650             retries.sleep()

~\Anaconda3\lib\site-packages\requests\packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
    387         if new_retry.is_exhausted():
--> 388             raise MaxRetryError(_pool, url, error or ResponseError(cause))
    389

MaxRetryError: HTTPConnectionPool(host='ichart.finance.yahoo.com', port=80): Max retries exceeded with url: /table.csv?s=SNE&a=0&b=1&c=2010&d=11&e=31&f=2015&g=d&ignore=.csv (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x0000001B3783DC18>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))

During handling of the above exception, another exception occurred:

ConnectionError                           Traceback (most recent call last) <ipython-input-1-7d307edbe1a3> in <module>()
      3 start = datetime.datetime(2010, 1, 1)
      4 end = datetime.datetime(2015, 12, 31)
----> 5 f = web.DataReader('SNE', 'yahoo', start, end)
      6 print(f)

~\Anaconda3\lib\site-packages\pandas_datareader\data.py in DataReader(name, data_source, start, end, retry_count, pause, session, access_key)
    115                                 adjust_price=False, chunksize=25,
    116                                 retry_count=retry_count, pause=pause,
--> 117                                 session=session).read()
    118
    119     elif data_source == "yahoo-actions":

~\Anaconda3\lib\site-packages\pandas_datareader\yahoo\daily.py in read(self)
     75     def read(self):
     76         """ read one data from specified URL """
---> 77         df = super(YahooDailyReader, self).read()
     78         if self.ret_index:
     79             df['Ret_Index'] = _calc_return_index(df['Adj Close'])

~\Anaconda3\lib\site-packages\pandas_datareader\base.py in read(self)
    155         if isinstance(self.symbols, (compat.string_types, int)):
    156             df = self._read_one_data(self.url,
--> 157                                      params=self._get_params(self.symbols))
    158         # Or multiple symbols, (e.g., ['GOOG', 'AAPL', 'MSFT'])
    159         elif isinstance(self.symbols, DataFrame):

~\Anaconda3\lib\site-packages\pandas_datareader\base.py in
_read_one_data(self, url, params)
     72         """ read one data from specified URL """
     73         if self._format == 'string':
---> 74             out = self._read_url_as_StringIO(url, params=params)
     75         elif self._format == 'json':
     76             out = self._get_response(url, params=params).json()

~\Anaconda3\lib\site-packages\pandas_datareader\base.py in
_read_url_as_StringIO(self, url, params)
     83         Open url (and retry)
     84         """
---> 85         response = self._get_response(url, params=params)
     86         text = self._sanitize_response(response)
     87         out = StringIO()

~\Anaconda3\lib\site-packages\pandas_datareader\base.py in
_get_response(self, url, params)
    112         # initial attempt + retry
    113         for i in range(self.retry_count + 1):
--> 114             response = self.session.get(url, params=params)
    115             if response.status_code == requests.codes.ok:
    116                 return response

~\Anaconda3\lib\site-packages\requests\sessions.py in get(self, url,
**kwargs)
    529
    530         kwargs.setdefault('allow_redirects', True)
--> 531         return self.request('GET', url, **kwargs)
    532
    533     def options(self, url, **kwargs):

~\Anaconda3\lib\site-packages\requests\sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    516         }
    517         send_kwargs.update(settings)
--> 518         resp = self.send(prep, **send_kwargs)
    519
    520         return resp

~\Anaconda3\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
    637
    638         # Send the request
--> 639         r = adapter.send(request, **kwargs)
    640
    641         # Total elapsed time of the request (approximately)

~\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    500                 raise ProxyError(e, request=request)
    501
--> 502             raise ConnectionError(e, request=request)
    503
    504         except ClosedPoolError as e:

ConnectionError: HTTPConnectionPool(host='ichart.finance.yahoo.com', port=80): Max retries exceeded with url: /table.csv?s=SNE&a=0&b=1&c=2010&d=11&e=31&f=2015&g=d&ignore=.csv (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x0000001B3783DC18>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))

A: If you want to utilize yahoo finance, use Yahoo_finance API.
from yahoo_finance import Share

and when you want to retrieve values for a specific share use:
Share('<Your Share Ticker Name>')

Then you can retrieve historical data and what not with something like
Share('Your Share Ticker Name>').get_historical(<start_date>, <end_date>)

Hope this helps


text:
Q: jquery .load() called then css not working I have created an image gallery of thumbnails using a carousel. Each gallery corresponds to a city, and the load function is used to replace the gallery with a different city.
For example:

 <

 >

The carousel and load functions are then implemented at the bottom to replace the gallery when necessary.

The simple carousel is implemented via "slick" as follows:

The CSS is as follows to keep the images a certain size:
#thumbs {
    display: inline-block;
    height: 90px;
    width: 670px;
    border: 1px solid red;
}

#thumbs div .pic {
    height: 80px;
    margin: 5px 0px 5px 0px;
    border: 1px solid green;
}

#thumbs div .pic img {
    height: 100%;
    width: auto;
    cursor: pointer;
}

The CSS code works correctly for the original city, such as NYC. But the strange thing that happens is when another city such as LA is loaded into the html file to replace the "replace" div, the CSS file doesn't seem to effect the new div.
The following code is found in Galleries.html

 <

A: try to change your CSS rules from div .pic to div.pic
#thumbs div.pic {
  /* .... */
}

and
#thumbs div.pic img {
  /* .... */
}


text:
Q: Make Gnome Hot Corner Delay Is there any way to make the top left gnome hot corner delay for 1s before triggering? It's a very useful feature, but I end up accidentally touching the corner (esp when reaching for the file button), so I was wondering if I could lessen the sensitivity.

A: There is also another extension called "Activities Configurator", which can be used to change the corner treshold, fully disable the hot corner, or switch it to the top right of the screen.
This extension can also do much more, like adding an icon next to the Activities button, changing the text of the Activities button, or fully removing it.

https://extensions.gnome.org/extension/358/activities-configurator/

A: No Top Left Hot Corner
This extension disables the top left hot corners. You can still click on Activities or press the dedicated key (generally Super key to reach the overview.
This doesn't do exactly what you want but it should prevent from accidental Hot Corner triggers

How do I install and manage GNOME Shell extensions?


text:
Q: How to add a keyboard shortcut for AMS multi-line environment in LyX I use the AMS multi-line environment a lot for homework, and I would like it to replace the regular math environment.
I use LyX, 3.2.2.
How can I do this?
Thank you very much!

A: You can use the LyX function math-mutate align to change any math environment into an AMS align one (see Help>Lyx Functions for the full list of functions).
To implement this by changing the action of the shortcut, go to Tools>Preferences>Editing>Shortcuts, find the shortcut that you currently use to open a math environment (the command will probably be math-display), double-click it and change the function to command-sequence math-display; math-mutate align;, OK and save. Note command-sequence just allows you to chain multiple functions together.
If this isn't exactly what you want, I'm sure you get the idea!


text:
Q: iOS5 Facebook API : Get Friends and show I'm developing a app that integrates with Facebook API (iOS 5). And I'm trying to get the user friends pictures to show on the initial screen.
I downloaded an example that have a class FriendPickerDelegate, and presents to user a list of his friends in a Table, and he select it.
But, I don't know how to get an array of his friends, just for presents on the screen the pictures of them.
How can I do this?
thanks a lot.

A: In this example, you can learn how to get information about the logged user (/me). To get your friends, you should do something like that, but instead of using [FBRequest requestForMe], you'd use [FBRequest requestForMyFriends] (https://developers.facebook.com/docs/reference/ios/3.0/class/FBRequest#requestForMyFriends).


text:
Q: How to use REST using Post Method to get XML information in android? For example,
URI: http://99.99.99.99:8080/services/api/products/getProduct

Method: POST

Content-Type: application/xml

Then, I use Advanced Rest Client can get these data
<Products>
  <Product>
    <category>Apple</category>
    <productCode>A1</productCode>
  </Product>
  <Product>
    <category>Orange</category>
    <productCode>A2</productCode>
  </Product>
  <Product>
    <category>Banana</category>
    <productCode>A3</productCode>
  </Product>
....
</Products>

How if I want to store all of the category and productCode.
What kinds of method should i use?
HttpPost? XML parser?
This is the sample code I try and I get nothing from the logcat.
public void getXml(){

            String result = "";

            HttpClient client = new DefaultHttpClient();

            try {

                HttpPost post = new HttpPost("http://99.99.99.99:8080/services/api/products/getProduct");

                HttpResponse responsePOST = client.execute(post);

                HttpEntity resEntity = responsePOST.getEntity();

                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                client.getConnectionManager().shutdown();
            }

             System.out.println(result);
        }

A: I think that the output of System.out.println is not visible in logcat.
You should use Log class instead:
Log.d("test", result);

Also you must make sure that your request is done in a separate thread.

A: I got your issue mainly you are calling the api in main thread,
But you have to call this api in background thread
Use AsynTask
    public class GetDetails extends AsyncTask<String, Void, String>{

    String response = null;
    @Override
    protected String doInBackground(String... strings) {
        try {

    HttpParams httpParameters = new BasicHttpParams();
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = null;

    httppost = new HttpPost("http://99.99.99.99:8080/services/api/products/getProduct");

    httppost.setHeader("Accept", "application/xml");
    httppost.setHeader("Content-type", "application/xml");

    HttpResponse httpResponse = httpClient.execute(httppost);

    InputStream inputStream = httpResponse.getEntity().getContent();
    if (inputStream != null)
         response = convertInputStreamToString(inputStream);
    else
        response = null;

    Log.v("data for list", response);

        } catch (Exception e) {
            Log.e("Cann", e.toString());
        }

        return strings[0];
    }

    @Override
    protected void onPostExecute(String result) {
    super.onPostExecute(result);
           if(response != null){
           XmlPullParserFactory factory =XmlPullParserFactory.newInstance();
             factory.setNamespaceAware(true);
             XmlPullParser xpp = factory.newPullParser();

             xpp.setInput(new StringReader (result));
             int eventType = xpp.getEventType();
             while (eventType != XmlPullParser.END_DOCUMENT) {
              if(eventType == XmlPullParser.START_DOCUMENT) {
                  System.out.println("Start document");
              } else if(eventType == XmlPullParser.END_DOCUMENT) {
                  System.out.println("End document");
              } else if(eventType == XmlPullParser.START_TAG) {
                  System.out.println("Start tag "+xpp.getName());
              } else if(eventType == XmlPullParser.END_TAG) {
                  System.out.println("End tag "+xpp.getName());
              } else if(eventType == XmlPullParser.TEXT) {
             System.out.println("End tag "+xpp.getName());
              }
              eventType = xpp.next();
             }
         }
      }

private String convertInputStreamToString(InputStream inputStream)
        throws IOException {
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while ((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}

}

And last where you calling the getXml() method change to new GetDetails().execute("")


text:
Q: Unable to see an array's content I have a database that contains things like "title, "color", and so on, and I want to display these informations in a webpage.
But, for some unknown reason, nothing won't appear, not even an error, which makes me totally lost.
I use this to put everything I need into an array :
<?php
try{
$req = $db ->prepare("SELECT titre, couleur, categorie, img_url, prix, type FROM articles WHERE id = 9");
$article = $req ->fetch(PDO::FETCH_ASSOC);

}
catch(PDOException $e){
echo $e;
exit();
}
?>

My connection to the database is successful, but I can't even see my array's content even if I use the
<pre> <?php print_r($array) ?> </pre>

technique. I'm basing my current code from a working one, and I can't notice what I did wrong...
Thank you in advance !

A: How about some executing between the preparation and the fetching? like this:
$req->execute();

Also i think you want to print the array where you fetched your data in like this:
<pre> <?php print_r($article) ?> </pre>

So all in all your code should look something like this:
<?php

    try{
        $req = $db->prepare("SELECT titre, couleur, categorie, img_url, prix, type FROM articles WHERE id = 9");
        $req->execute();
        $article = $req ->fetch(PDO::FETCH_ASSOC);

    } catch(PDOException $e) {
        $e->getMessage();

    }

    echo "<pre>";
    print_r($article);
    echo "</pre>";

?>


text:
Q: Why does replace() function return grammatically edited result when it was not requested with proper argument? This snippet in VS Code (Python 3):
print("This is it!".replace("is", "are"))

returns strange for me output:
'Thare are it!'

The request was to replace string "is" with string "are", but wasn't requested to replace string "This"?
Is it usual for python to make some kind of grammar corrections without requests?
Thank you in advance!

A: Since there is "is" in "This" , that too gets replaced. So instead of :
print("This is it!".replace("is", "are"))

use:
print("This is it!".replace(" is ", " are "))

Also if you have There it is!, you can use regex:
import regex
re.sub('(\W)(is)(\W)',r'\1are\3',"This it is!")

This is beautifully mentioned here

A: Replace don't know words nor grammar. It just searches for the characters given.
And "This" has "is" in it. So it gets replaced by "ar".

A: The .replace() function replaces a specified phrase with another specified phrase.
All occurrences of the specified phrase will be replaced, if nothing else is specified.

the actual syntax for .replace function is as follows-

string.replace(oldvalue, newvalue, count)

oldvalue - The string to search for
newvalue - The string to replace the old value with
count(Optional)- A number specifying how many occurrences of the old value you want to replace. By Default is all occurrences

It happens similarly to Java as well, its not about python only, JAVA Syntex is-
public String replace(char oldChar, char newChar)
and
public String replace(CharSequence target, CharSequence replacement)

check out this example-
public class ReplaceExample1{
public static void main(String args[]){
String s1="javatpoint is a very good language";
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'
System.out.println(replaceString);
}}

this will give result as follows in java
jevetpoint is e very good lenguege

if you want to replace "is" for your case you should use " is " it means you are using spacebar as an element for your string thus the required result will come-
print("This is it!".replace(" is ", " are "))
output- This are it!

A: The clean way to do it is to use a regular expression with word boundaries \b before and after your word:
import re

re.sub(r'\bis\b', 'are', "This is it. yes, it is!")
# 'This are it. yes, it are!'


text: Q: Encrypted data types in RAML Am trying to define an API spec, that is expecting the post body to be signed and encrypted. Is there any way we can define this in RAML? Security schemes etc allow you to define authN/authZ etc but not sure how to indicate that the data itself needs to be signed and encrypted a certain way.


text:
Q: How to find difference between two epoch time which is in milliseconds shell script I want to calculate the difference between expiry time of token which is in epoch ms and current time in epoch ms.
Example expiry time of token is 1640237992708 which is 12th December 2021 and current time suppose is 1634108098242 which is 13th October 2021.
Basically I want to calculate the difference in days between the two timestamps.
Like if the difference is less than 10 days and token will be expiring in 10 days, need to create a new token.
Any idea how to get difference in days and than compare it with 10 days?
Need to write in shell script.

A: A naive approach would be to:
a=1640237992708
b=1634108098242
diff="$((a-b))"
max_diff=$((1000 * 60 * 60 * 24 * 10))
if test "$diff" -gt "$max_diff"
then
  echo "Diff is higher than $max_diff"
fi


text:
Q: Do Neural Networks suffer from high bias or high variance For most ML models we say they suffer from high bias or high variance, then we correct for it. However, in DL do neural networks suffer from the same concept in the sense that they initially have high bias or high variance and then you correct through regularization and/or dropout? I would argue they initially suffer from high variance and they overfit the data. Then you correct through regularization, add dropout, image pre-processing in the case of CNNs, etc. Is this train of thought correct?

A: In general NNs are prone to overfitting the training set, which is case of a high variance. Your train of thought is generally correct in the sense that the proposed solutions (regularization, dropout layers, etc.) are tools that control the bias-variance trade-off.

A: Neural networks, including DNNs, don't by themselves suffer from high variance any more than other machine learning algorithms. It is just that we find it easier to start the training with more complex networks and control for variance by the techniques you mentioned, than to start with simpler (less expressive) networks and gradually increase their complexity. By observing the network behaviour during training you can already get hints regarding simplification. If you'd start with a simpler network, you'd be tapping in the dark how to augment it.


text:
Q: txt file to binary tree in python I have received a text file as part of a task that contains 2^n-1 characters (suitable for a perfect binary tree with height n) and I'm supposed to represent that text as a binary tree. Is there a proper way to do it? A certain order?
Thank you in advance and sorry for the weird question.


text:
Q: webBrowser won't open HTML string I want to have a webBrowser open a HTML string. This is what I got so far for opening the HTML string in a webBrowser:
public void show()
{
    routelistBrowser.ScriptErrorsSuppressed = true;
    reisOpties = fakeLijst(gekozenTijd);

    RouteListPanel rlp = new RouteListPanel();
    rlp.Session = new Dictionary<string, object>();
    rlp.Session["reisOpties"] = reisOpties;
    rlp.Initialize();
    Console.WriteLine(rlp.TransformText());
    DisplayHtml(rlp.TransformText());
}

private void DisplayHtml(string html)
    {
        routelistBrowser.Navigate("");
        HtmlDocument doc = routelistBrowser.Document.OpenNew(true);
        doc.Write(html);
        routelistBrowser.Refresh();
        Console.WriteLine(html);
    }

My problem is that my webBrowser won't load this HTML string. I am not sure what I am doing wrong. I have added the webBrowser in a User Control and added that User Control in the Main Form. The webBrowser will show, but will not load the HTML string.
Output Console (HTML string):
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=11" />
    <title></title>

17:54 --> 18:13

Totale tijd: 0:19
                Aantaloverstappen: 0x Perron: 1a

NS - Intercity

18:00 --> 18:19

Totale tijd: 0:19
                Aantaloverstappen: 0x Perron: 1a

NS - Intercity

18:06 --> 18:25

Totale tijd: 0:19
                Aantaloverstappen: 0x Perron: 1a

NS - Intercity

18:12 --> 18:31

Totale tijd: 0:19
                Aantaloverstappen: 0x Perron: 1a

NS - Intercity

18:18 --> 18:37

Totale tijd: 0:19
                Aantaloverstappen: 0x Perron: 1a

NS - Intercity

18:24 --> 18:43

Totale tijd: 0:19
                Aantaloverstappen: 0x Perron: 1a

NS - Intercity

18:30 --> 18:49

Totale tijd: 0:19
                Aantaloverstappen: 0x Perron: 1a

NS - Intercity


text:
Q: What is the MvvmCross version of DeviceNetworkInformation.IsNetworkAvailable I'm re-writing a Windows Phone app to make it cross platform using the excellent MvvmCross framework.
On Windows Phone I usually test DeviceNetworkInformation.IsNetworkAvailable to ensure I have a network connection before calling a REST service.
Is there a way of doing this in a cross-platform way using MvvmCross?

A: There is a cross-platform plugin Cirrious.MvvmCross.Plugins.Network specifically for Network functionality and this was originally built specifically to provide Reachability
However, sadly the WindowsPhone part of this isn't yet implemented! See https://github.com/MvvmCross/MvvmCross/blob/v3.1/Plugins/Cirrious/Network/Cirrious.MvvmCross.Plugins.Network.Phone/Plugin.cs
If you need Reachability within a cross-platform app including WindowsPhone, I'd probably opt for adding this Network plugin, and then also modifying your WindowsPhone Setup to register something like:
public class MyReachability : IMvxReachability
{
    public bool IsHostReachable(string host)
        return // something using DeviceNetworkInformation.IsNetworkAvailable
    }
}

// registered in Setup using:
protected override void InitializeLastChance() {
    base.InitializeLastChance();
    Mvx.RegisterType<IMvxReachability, MyReachability>();
}

Longer term, I'd be happy to see a decent implementation pushed back into the MvvmCross repository.
Also linking this question to: MvvmCross Reachability on Windows Phone and Network state with mvvmcross?


text:
Q: Comprehensive electronic academic state-of-the-art reference work? Is there any standard encyclopedia of mathematics available online, through a research library's offering of databases, which could help you hone in on exactly a mathematics topic or question you have?
For example, I am interested in two questions:

*

*The way of constructing numbers via "von Neumann ordinals"

*The question of some way to comprehensively characterize and also group types of mappings between all sets. Basically, I want to know if there are interesting sequences of mappings that are equivalent to some other mapping, and I want to try to discover every possible mapping in the space of all mappings that has the same outcome. Since this could be very large, I want to try to abstract the mappings into more distinct "types", to lump together mappings that are different only in a minor way. I think the category of sets is the closest topic to this, but that article doesn't seem to focus on that exact topic very directly, plus it's generally too hard for me, since I don't know much category theory.

Also, I don't just want to see information about the specific topics above - I want to see the connection between that topic and other topics - I want to see the enclosing topics, not just the internal sub-topics.
I can only imagine some kind of high quality academic encyclopedia which tries to have many articles on many specific topics, trying to cover a very wide range of recurrent concepts in math. There are some really good academic encyclopedias on linguistics that do exactly this.


text:
Q: Composer REST server custom auth I need to enable authentication on my REST server, but I have some troubles in understanding,I think.
So, if I use some custom strategy, I need to take some credentials and checked it on some data-base, and if it's right credentials, return some token which user will use later.
Am I right? If yes, how can I connect my database and how data must look like for rest-server understanding?

A: You need to learn how to create custom passport strategy. If you want to validate the credentials stored in some database then, I think you might find a passport strategy for that database. You just need to provide correct COMPOSER_PROVIDERS arguments (you can check with the documentation of the passport strategy) and that's it. And I dont think rest server has anything to do with the way data (credentials) are stored in your database. It's the passport strategy which checks for your credentials.


text:
Q: CTFd juice-shop : import failed Im currently running a ctf for a project in school. I use Juice Shop by OWASP and CTFd as framework.
Im generating my challenge by
juice-shop-ctf --config /vagrant/files/conf_ctfd.yml

with this conf
ctfFramework: CTFd
juiceShopUrl: http://192.168.56.10/
ctfKey: Mxx1
insertHints: free
insertHintUrls: free
insertHintSnippets: free

While importing in CTFd i got : Start date : Invalid Date
Can someone know how can i fix it ? I tried but nothing works....


text:
Q: Having multiple pip versions? In Ubuntu I have Python3 as default and pip and pip3. Now I need Python2 to install an app. I have Python2 installed but not pip2. If I try
sudo python2 -m pip install my_app

or
sudo python2 -m pip2 install my_app

I get:
No module named pip

If I install pip2 via easy_install or get-pip.py will it make me problems with pip wich is  for Python3? What is the right way?

A: You can safely install pip for both py2.x and py3.x simultaneously. You can explicitly specify which pip to use by using pip2 for py2.x or pip3 for py3.x.
sudo apt-get install python-pip installs pip2
while
sudo apt-get install python3-pip installs pip3
also to keep things simple, just using
sudo pip2 install my_app
will suffice.
EDIT:
I have noticed that in some cases even pip3 calls the python2.x interpreter. To be on a totally safe side I recommend using -
sudo python2 -m pip install my_app for python2.x and
sudo python3 -m pip install my_app for python3.x

A: sudo apt-get install python-pip
Is a right command to my knowledge. Bit I don't think the other methods will interrupt your python3 but no experience with those.


text:
Q: Listing the users who have actually submitted jobs in LSF I am use the following command to list all users and there pending jobs in LSF:
busers -w all

Example output:
USER/GROUP   JL/P   MAX  NJOBS   PEND    RUN  SSUSP  USUSP    RSV  MPEND
aaaaa          -     -      0      0      0      0      0      0   200
bbbbb          -     -     100     50     50     0      0      0   200
ccccc          -     -      1      0      1      0      0      0   200

I'm looking for a command that will only display the users whose NJOBS value is greater than 0, i.e. those who have actually submitted at least one job.
In the example, that would mean that only the lines for users 'bbbbb' and 'ccccc' should appear.

A: To check all users jobs the simpler method would be:
bjobs -u all

To check suspended ones just use:
bjobs -u all | grep SUSP


text:
Q: Javascript not operating on loaded elements I am trying to understand grid layouts so I wrote some js to recursively color each element on the page to expose each grid tile.
The problem
Every few refreshes some of the tiles don't get colored. I figured this was some kind of loading error so instead of running the code immediately I decided to run it in window.onload. That didn't change anything.
I even wrote a piece of code to print the uncolored elements to the console. I run that code in the same loop where individual elements are painted and expected nothing to be logged, to my surprise the color is generated,  the element is created, and still the element remains uncolored!
Plea
Can someone tell me what's going on here? It's not very important in this application but this goes against everything I know about how js operates, and it would be helpful to extend my understanding. Thanks!
P.S. Demo
I added this little demo and the problem happens here too. You will need to run the code a couple times to see the error, I wrote another piece of code that prints the uncolored element to the console so you can't miss it!

let colorize = (elements) => {
  for (let e of elements) {
    let color = '#' + Math.floor(Math.random() * 16777215).toString(16);
    e.style["background-color"] = color;
    checkcolor(e, color);
    colorize(e.children);
  }
}
let checkcolor = (e, color) => {
  if (!e.style['background-color']) {
    console.log(e, color);
  }
}
window.onload = () => colorize(document.querySelector("html").children);
body {
  height: calc(100vh - 3px);
  display: grid;
  grid-template-rows: repeat(5, minmax(10px, 100px));
  /* grid-template-columns: 1; */
  grid-auto-flow: row;
}

11

22

33

44

55

A: Here's an example of one of the console.log results:

55
 #43b0f

That should give you the idea - the string that was generated has only 5 characters (or fewer), not 6, so it's not a valid hex color. This will happen when the generated number has leading zeros.
One way to fix it would be to padStart the number with zeros:

const colorize = (elements) => {
  for (let e of elements) {
    let color = '#' +
      Math.floor(Math.random() * 16777215)
      .toString(16)
      .padStart(6, '0');
    e.style["background-color"] = color;
    colorize(e.children);
  }
}
colorize(document.querySelectorAll('div'));
body {
  height: calc(100vh - 3px);
  display: grid;
  grid-template-rows: repeat(5, minmax(10px, 100px));
  /* grid-template-columns: 1; */
  grid-auto-flow: row;
}

11

22

33

44

55


text:
Q: Copying data from one table to another using Insert Into I have two tables. They both have identical structures except table2 has an additional column. I currently copy data from table1 into table2 using a stored proc, as shown below.
However, due to the sheer number of records (20million+), and the structure of the stored proc, this currently takes a couple of hours to run.
Does anyone have any suggestions on how to optimize the code?
CREATE PROCEDURE dbo.insert_period @period INT AS

DECLARE @batchsize INT
DECLARE @start INT
DECLARE @numberofrows INT

SELECT @numberofrows = COUNT(*) from daily_table

SET @batchsize = 150000
SET @start = 1

WHILE @start < @numberofrows
BEGIN
    INSERT INTO dbo.main_table WITH (TABLOCK) (
    col1,
    col2,
    ....,
    col26,
    time_period
    )
    SELECT *, @period FROM dbo.daily_table
    ORDER BY id

    OFFSET @start ROWS
            FETCH NEXT @batchsize ROWS ONLY

    SET @start += @batchsize + 1
END

The id that I am using here is not unique. The table itself does not have any keys or unique id's.

A: First I would like to point out that the logic in your insert is flawed.
With @start starting at 1 your always skipping the first row of the source table. Then adding 1 to it at the end of your loop is causing it to skip another row on each subsequent run of the loop.
If your set on using batched inserts I suggest you read up on how it works over on MSSQLTips.
To help you with performance I would suggest taking a look at the following:
SELECT *
Remove the SELECT * and replace with the column names. This will help the optimizer get you a better query plan. Further reading on why SELECT * is bad can be found in this SO Question.
ORDER BY
That ORDER BY is probably slowing you down. Without seeing your query plan we cannot know for sure though. Each time your loop executes it queries the source table and has to sort all those records. Sorting 20+ milling records that many times is a lot of work. Take a look at my simplified example below.
CREATE TABLE #Test (Id INT);
INSERT INTO #Test VALUES (1), (2), (3), (4), (5);

DECLARE @batchsize INT;
DECLARE @start INT;
DECLARE @numberofrows INT;

SELECT  @numberofrows = COUNT(*) FROM   #Test;

SET @batchsize = 2;
SET @start = 0;

WHILE @start < @numberofrows
BEGIN
    SELECT
        *
        , 10
    FROM
        #Test
    ORDER BY
        Id OFFSET @start ROWS FETCH NEXT @batchsize ROWS ONLY;

    SET @start += @batchsize;
END;

Below is a portion of the query plan produced by the sample. Notice the Sort operation highlighted in yellow. Its cost accounts for 78% of that query plan.

If we add an index that is already sorted on the Id column of the source table we can eliminate the sort. Now when the loop runs it doesn't have to do any sorting.
CREATE INDEX ix_Test ON #Test (Id)

Other Options to Research

*

*Columnstore Indexes

*Batch Mode in RowStore

*Parallel Inserts

A: You copy the table row by row, that's why it takes so long. The simplest way to achieve what you want is an 'INSERT' combined with a 'SELECT' statement. This way, you would insert the data in one batch.
CREATE TABLE dbo.daily_table (id INT PRIMARY KEY IDENTITY,
                              value1 NVARCHAR(100) NULL,
                              value2 NVARCHAR(100) NULL);
GO

CREATE TABLE dbo.main_table (id INT PRIMARY KEY IDENTITY,
                             value1 NVARCHAR(100) NULL,
                             value2 NVARCHAR(100) NULL,
                             value3 NVARCHAR(100) NULL);
GO

INSERT INTO dbo.daily_table (value1, value2)
VALUES('1', '2');

-- Insert with Select
INSERT INTO dbo.main_table (value1, value2)
SELECT  value1,     value2
FROM    dbo.daily_table;

Also, it's better not to use an asterisk in your 'SELECT' statement since the result could be unpredictable.


text:
Q: GitLab port 2222 I cannot clone repository, which i have permissions to, using port 2222.
When i try to clone using git clone git@<address>:2222/<user>/<repo>.git,
i get this:
Cloning into '<repo_name>'...
remote:
remote: ========================================================================
remote:
remote: The project you were looking for could not be found or you don't have permission to view it.
remote:
remote: ========================================================================
remote:
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

A: Check first who GitLab think you are with:
ssh -Tv git@<address>:2222

You should receive a Welcome to GitLab, @username! message.
If @username is not a user added as collaborator to the project, that would explain the error message.
Or, if you do not see a welcome message, double-check "Use SSH keys to communicate with GitLab" and make sure your SSH public key is registered to the proper user SSH setting page.

A: Ok, it was problem on owner's side. He didnt give me full permissions needed. It's resolved. Sorry for bothering :)


text:
Q: Trying to use static class variable to create new ID for objects I am new to C++ and when I try to run this program it tells me: "error LNK2001: unresolved external symbol "private: static int Plate::plate_nID". I am right now just trying to create the plate class and print out the ID. Not sure where I went wrong.
#pragma once
#include <string>

using namespace std;

class Plate{
   private:
      int id;
      string plateName;
      static int plate_nID;

      int generateID(){
         plate_nID++;
         return plate_nID;
      }
   public:
      Plate(string name){
         plateName = name;
         id = generateID();
      }
      ~Plate(){}
      int getID(){
         return id;
      }
      string getName(){
         return plateName;
      }
};

Here is my main:
#include "Plate.cpp"
#include "PlateNode.cpp"
using namespace std;

int main(){
Plate s=Plate::Plate("p1");
cout << s.getID();}

I have looked at this question:
Undefined reference to static class member
which similar questions to mine were marked as dulpicates of, but I when I try to do that it tells me: cannot instantiate non-static member outside of class. Please Help!

A: You need to define the static variable outside your class, only then will your code work
int Plate::plate_nID = 0;

You must define it outside the class (preferably outside the main()  )
Probably better to define it right after your class.

A: You need to define the static member variable outside the class. Something along the lines of:
int Plate::plate_nID = 0;


text:
Q: Angular7 (was ok in Angular 6) ERROR TypeError: "e[n] is undefined" on firefox only in dev only due to "loading" variable in redux? So, I'm using a 'spinner' variable in my redux store to insert a class with ngClass on my progress bar and hide it/show it.
Now -- I know this is the culprit because if I remove all that logic everything is fine. This is an app that has been in production for a few months and everything worked up until upgradin to A7.

*

*I have tried using the @select() and | async pipe with ngIf. Removing the ngIf logic but leaving the spinner makes the error go away.

*I have tried filling a local variable based on the data from the store (if true hiddenSpinner="hiddenSpinner" else hiddenSpinner=""). Removing everything related in the markup does not make the error go away.

This makes me think it is purely something to do with the redux logic.
Everything works well if I run ng serve --prod.
All relevant redux store code:
//INTERFACE TYPES
export interface IAppState {
  spinner: boolean;
}

// DEFAULT STATE
export const INITIAL_STATE: IAppState = {
  spinner: false
};

//ROOT REDUCER
export function rootReducer(state: IAppState, action): IAppState {
  switch (action.type) {
      case START_LOADING: return startLoading(state, action);
      case STOP_LOADING: return stopLoading(state, action);
  }
  return state;
}

// FUNCTIONS FOR REDUCER TO CALL
function startLoading(state, action) {
  return tassign(state, { spinner: true});
}

function stopLoading(state, action) {
  return tassign(state, { spinner: false});
}

The error :
ERROR TypeError: "e[n] is undefined"
    unliftState http://localhost:4200/:2:30806
    getState http://localhost:4200/:2:30882
    storeToObservable http://localhost:4200/vendor.js:243:31
    _trySubscribe http://localhost:4200/vendor.js:154754:20
    subscribe http://localhost:4200/vendor.js:154740:17
    subscribeTo http://localhost:4200/vendor.js:166005:24
    subscribeToResult http://localhost:4200/vendor.js:166182:12
    _innerSub http://localhost:4200/vendor.js:163001:34
    _next http://localhost:4200/vendor.js:162991:9
    next http://localhost:4200/vendor.js:155373:13
    _next http://localhost:4200/vendor.js:160104:13
    next http://localhost:4200/vendor.js:155373:13
    _subscribe http://localhost:4200/vendor.js:154540:13
    _trySubscribe http://localhost:4200/vendor.js:154754:20
    _trySubscribe http://localhost:4200/vendor.js:155180:20
    subscribe http://localhost:4200/vendor.js:154740:17
    call http://localhost:4200/vendor.js:160081:16
    subscribe http://localhost:4200/vendor.js:154735:13
    call http://localhost:4200/vendor.js:162969:16
    subscribe http://localhost:4200/vendor.js:154735:13
    call http://localhost:4200/vendor.js:159541:16
    subscribe http://localhost:4200/vendor.js:154735:13
    call http://localhost:4200/vendor.js:160642:16
    subscribe http://localhost:4200/vendor.js:154735:13
    call http://localhost:4200/vendor.js:159541:16
    subscribe http://localhost:4200/vendor.js:154735:13
    ngOnInit http://localhost:4200/main.js:185:36
    checkAndUpdateDirectiveInline http://localhost:4200/vendor.js:77713:9
    checkAndUpdateNodeInline http://localhost:4200/vendor.js:78977:20
    checkAndUpdateNode http://localhost:4200/vendor.js:78939:16
    debugCheckAndUpdateNode http://localhost:4200/vendor.js:79573:19
    debugCheckDirectivesFn http://localhost:4200/vendor.js:79533:13
    View_AppComponent_Host_0 ng:///AppModule/AppComponent_Host.ngfactory.js:9:5
    debugUpdateDirectives http://localhost:4200/vendor.js:79525:12
    checkAndUpdateView http://localhost:4200/vendor.js:78921:5
    callWithDebugContext http://localhost:4200/vendor.js:79815:22
    debugCheckAndUpdateView http://localhost:4200/vendor.js:79493:12
    detectChanges http://localhost:4200/vendor.js:77302:13
    tick http://localhost:4200/vendor.js:73964:58
    tick http://localhost:4200/vendor.js:73964:13
    _loadComponent http://localhost:4200/vendor.js:73998:9
    bootstrap http://localhost:4200/vendor.js:73940:9
    _moduleDoBootstrap http://localhost:4200/vendor.js:73741:74
    _moduleDoBootstrap http://localhost:4200/vendor.js:73741:13
    bootstrapModuleFactory http://localhost:4200/vendor.js:73709:21
    invoke http://localhost:4200/polyfills.js:9654:17
    onInvoke http://localhost:4200/vendor.js:73236:24
    invoke http://localhost:4200/polyfills.js:9653:17
    run http://localhost:4200/polyfills.js:9404:24
    scheduleResolveOrReject http://localhost:4200/polyfills.js:10138:29
    invokeTask http://localhost:4200/polyfills.js:9687:17
    onInvokeTask http://localhost:4200/vendor.js:73227:24
    invokeTask http://localhost:4200/polyfills.js:9686:17
    runTask http://localhost:4200/polyfills.js:9454:28
    drainMicroTaskQueue http://localhost:4200/polyfills.js:9861:25
core.js:12584
defaultErrorLogger
core.js:12584
./node_modules/@angular/core/fesm5/core.js/ErrorHandler.prototype.handleError
core.js:12632
next
core.js:14611:109
./node_modules/@angular/core/fesm5/core.js/EventEmitter.prototype.subscribe/schedulerFn<
core.js:10238:34
./node_modules/rxjs/_esm5/internal/Subscriber.js/SafeSubscriber.prototype.__tryOrUnsub
Subscriber.js:196
./node_modules/rxjs/_esm5/internal/Subscriber.js/SafeSubscriber.prototype.next
Subscriber.js:134
./node_modules/rxjs/_esm5/internal/Subscriber.js/Subscriber.prototype._next
Subscriber.js:77
./node_modules/rxjs/_esm5/internal/Subscriber.js/Subscriber.prototype.next
Subscriber.js:54
./node_modules/rxjs/_esm5/internal/Subject.js/Subject.prototype.next
Subject.js:47
./node_modules/@angular/core/fesm5/core.js/EventEmitter.prototype.emit
core.js:10222:52
onHandleError/<
core.js:14165:48
./node_modules/zone.js/dist/zone.js/</ZoneDelegate.prototype.invoke
zone.js:388
./node_modules/zone.js/dist/zone.js/</Zone.prototype.run
zone.js:138
./node_modules/@angular/core/fesm5/core.js/NgZone.prototype.runOutsideAngular
core.js:14102
onHandleError
core.js:14165
./node_modules/zone.js/dist/zone.js/</ZoneDelegate.prototype.handleError
zone.js:392
./node_modules/zone.js/dist/zone.js/</Zone.prototype.runTask
zone.js:191
./node_modules/zone.js/dist/zone.js/</ZoneTask.invokeTask
zone.js:496
ZoneTask/this.invoke
zone.js:485
timer
zone.js:2054