text:
Q: Trying to remove a class and add a class with jquery I am having issues trying to resize my iframe. I want to be able to add and remove a class so that it can get wider then smaller. I can't even get adding a class to work for some reason. Any suggestions?

$(document).ready(
  $('#resize').onclick(function() {
    $('.frame_wrap').addclass('test');
  })
)

<button id="resize">Button</button>

http://jsfiddle.net/fesye0mu/3/

A: You need to pass a function to $(document).ready().
addclass should be addClass, uppercase C.
onclick is just click in jQuery:

$(document).ready(function() {
  $('#resize').click(function() {
    $('.frame_wrap').addClass('test');
  })
});
.test {
  border: 5px solid blue;
}

<button id="resize">Button</button>

A: There is not such function as onclick in jquery
It should be click(function(){}) or on('click', function(){}). Also addclass should be addClass
Change to
$(document).ready(
  $('#resize').click(function() {
    $('.frame_wrap').addClass('test');
  })
)

A: You should use addClass() instead of addclass because it is case sensitive.


text:
Q: Creating System Level Environmental Variables Manually How do one create System Level environmental variables manually. I just installed a GeoSupport Desktop Edition software and in the document it is mentioned that I need to
create system-level environmental
variables for PATH and GEOFILES manually
Add the location of the GDE executables to the system-level environmental variable PATH.
Normally this means adding C:\Program Files\Geosupport Desktop Edition\bin to the PATH.
How an I do that??

A: There's a few ways, all of them included in this post: http://blogs.msdn.com/brada/archive/2004/01/03/50984.aspx
They're for C#, but translating should be trivial.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS / JavaScript - Styling keywords in text? There is some text, and need to change color of some keywords, without using code in text. How can I do that with CSS / JS ?

Lorem ipsum RED dolor sit amet, RED consectetur adipiscing elit, RED sed do eiusmod
   tempor incididunt ut labore et dolore RED magna aliqua.

A: One way to achieve this is to replace the text "RED", with a span that has a style to color it: ""

var e = document.getElementById("text");
var txt = e.innerHTML;
e.innerHTML = txt.replace(new RegExp("RED", "g"),"RED");

Lorem ipsum RED dolor sit amet, RED consectetur adipiscing elit, RED sed do eiusmod
   tempor incididunt ut labore et dolore RED magna aliqua.


text:
Q: converting to pivot table Edit : Raymond Nijland has suggested and issue was at my end . i put extra group by in end
, right syntax is
SELECT
    bkg.status,
count( if( bkg.status = '1', bkg.bookingId, 0 ) ) AS 'confirmed',
count( if( bkg.status = '2', bkg.bookingId, 0 ) ) AS 'Tentative'
FROM
    tbl_booking bkg

thanks

I have table data for a table like this

i have a query
select bkg.status,
count(bkg.status) from tbl_booking bkg
GROUP BY
    bkg.status;

that is giving results like

I want to convert that into pivot format
like
1 | 2 | 3 | 4
21| 57| 7 | 14

I tried
SELECT
    bkg.status,
count( if( bkg.status = '1', bkg.bookingId, 0 ) ) AS 'confirmed',
count( if( bkg.status = '2', bkg.bookingId, 0 ) ) AS 'Tentative'
FROM
    tbl_booking bkg
GROUP BY
    bkg.status;

but that is giving me results like

If I tried to group by diffrent column like booking Id , result gone more different  . I am getting confused about which column to be placed in sum and which column to be placed in group by
please suggest


text:
Q: Move navigations into header part and do not disturb the responsive mobile screen My original theme screen is like this
But I want in this way
But due to these changes, my responsive view gets distorted like this.
I wrote this line of code in the default.xml file <move element="catalog.topnav" destination="header-wrapper" after="logo" />
Any help would be appreciated. Thanks

A: Kindly use this one:
<move element="navigation.sections" destination="header-wrapper" after="logo" />


text:
Q: Existence of a set with property that all subsets are members Within Zermelo Fraenkel Set theory (Edit: Without the axiom of regularity ), Does there exist a nonempty set $X$ with the property that if $Y \subseteq X$, then $Y \in X$?
My guess is no, but currently unable to prove it. Would the set $S = \{ x \in X : x \not\subseteq X \}$ derive a contradiction ? Or is this provable without the axiom of regularity?

A: If every subset of $X$ is an element of $X$, then $\mathcal P(X)\subset X$, which contradicts Cantor's theorem that $|X|<|\mathcal P(X)|$ (i.e., that there exists no injection from $\mathcal P(X)$ to $X$).
Cantor's theorem does not need regularity to be proven.

Some other objection, is that $X$ contains all ordinals: if $\alpha$ is an ordinal, and for each $\beta<\alpha$ we have $\beta\in X$, then $\alpha\subset X$, thus $\alpha\in X$. This shows that $0\in X$, that $\alpha\in X$ implies $\alpha+1\in X$, and that all limit ordinals are in $X$.


text:
Q: How to assign a value to a variable declared outside the scope I need to assign the value from the axios call to the variable outside it.Im using react.
 var starthaltname="sdsdsd";

 Axios.get('http://localhost:9090/route/getHalt?routeId=3').then(function (starthalt) {
      console.log(starthalt.data.name);
      return starthalt.data;
}.bind(this));

I can console log the output i want, but when assigned to the "starthaltname" variable, the variable is still has undefined as the value. Any Suggestions please?
here is the whole rendering part of the code. what i want is to populate the values inside the table.
render() {

        let table;
        let starthaltname;
        let endhaltname;
        let startdate;
        let starttime;
        let endtime;

        if (this.state.journeylist.length !== 0) {
            console.log("data available");
            console.log(this.state.journeylist.length);

            table = (

                        {this.state.journeylist.map((journey, j) => {
                            console.log(journey);

                            var starthaltname="sdsdsd";

                            Axios.get('http://localhost:9090/route/getHalt?routeId='+journey.busroute+'&haltIndex='+journey.jstartloc).then(function (starthalt) {
                                console.log(starthalt.data);
                                console.log(starthalt.data.name);
                                return starthalt.data;
                            }.bind(this)).then(function(starthaltresponse){
                                Axios.get('http://localhost:9090/route/getHalt?routeId='+journey.busroute+'&haltIndex='+journey.jendloc).then(function (endhalt) {
                                    console.log(endhalt.data);
                                    endhaltname=endhalt.data.name;
                                    return endhalt.data;
                                }.bind(this)).then(function(endhaltresponse){
                                    var  sdate =  new Date(journey.jstarttime);
                                    startdate = sdate.toDateString();
                                    starttime = sdate.toLocaleTimeString();
                                    var  edate =  new Date(journey.jendtime);
                                    endtime = edate.toLocaleTimeString();
                                    console.log(starttime);
                                }.bind(this));
                            }.bind(this));
                            console.log(starthaltname);
                            return (

                                    {

{startdate}

{starthaltname}

{starttime}

{endhaltname}

{endtime}

Rs. {journey.jfare}

                                    }

                            );
                        })}

            );
        }
        else {
            table = "No data available";
        }

        return (

                {table}

        );

    }

A: add another property in the state finalJournyList which will contain the request result and initialize with an empty array.
state = {
finalJournyList: []

}
componentDidMount() {
const { journeylist } = this.state;
const requestPromises = journeylist.map(async (journey, i) => {
    const { data: { name: starthaltname } } = await Axios.get('http://localhost:9090/route/getHalt?routeId=' + journey.busroute + '&haltIndex=' + journey.jstartloc);
    const { data: { name: endhaltname } } = await Axios.get('http://localhost:9090/route/getHalt?routeId=' + journey.busroute + '&haltIndex=' + journey.jendloc);
    const sdate = new Date(journey.jstarttime);
    const edate = new Date(journey.jendtime);
    return Promise.resolve({
        starthaltname,
        endhaltname,
        startdate: sdate.toDateString(),
        starttime: sdate.toLocaleTimeString(),
        endtime: edate.toLocaleTimeString(),
        jfare: journey.jfare,
        journeyId: journey.journeyId
    });
});

Promise.all(requestPromises)
    .then((result) => this.setSate({ finalJournyList: result }))
}

render() {
const { journeylist, finalJournyList } = this.state;
if (!finalJournyList.length) {
    return
No data available
;
}
return

        {this.state.finalJournyList.map((journey, j) => {
            return (

{journey.startdate}

{journey.starthaltname}

{journey.starttime}

{journey.endhaltname}

{journey.endtime}

Rs. {journey.jfare}

            );
        })}

}


text:
Q: xlsx file to list for dataset Here is a copy of my code when I run it the list output is in a weird format that I cant figure out how to change.
'''
import pandas as pd

inputdata = []
data = pd.read_excel('testfile.xlsx')
df = pd.DataFrame(data, columns=['black_toner_percentage'])
for i in df.values:
    inputdata.append(i)
print(inputdata)

'''
array([100], dtype=int64), array([100], dtype=int64)
This is the format my list is going into and Id like it to be [100,100,ext.]
What am I doing wrong here.


text:
Q: How can I String.Format a TimeSpan object with a custom format in .NET? What is the recommended way of formatting TimeSpan objects into  a string with a custom format?

A: For .NET 3.5 and lower you could use:
string.Format ("{0:00}:{1:00}:{2:00}",
               (int)myTimeSpan.TotalHours,
                    myTimeSpan.Minutes,
                    myTimeSpan.Seconds);

Code taken from a Jon Skeet answer on bytes
For .NET 4.0 and above, see DoctaJonez answer.

A: I would go with
myTimeSpan.ToString("hh\\:mm\\:ss");

A: Personally, I like this approach:
TimeSpan ts = ...;
string.Format("{0:%d}d {0:%h}h {0:%m}m {0:%s}s", ts);

You can make this as custom as you like with no problems:
string.Format("{0:%d}days {0:%h}hours {0:%m}min {0:%s}sec", ts);
string.Format("{0:%d}d {0:%h}h {0:%m}' {0:%s}''", ts);

A: Dim duration As New TimeSpan(1, 12, 23, 62)

DEBUG.WriteLine("Time of Travel: " + duration.ToString("dd\.hh\:mm\:ss"))

It works for Framework 4
http://msdn.microsoft.com/en-us/library/ee372287.aspx

A: This is awesome one:
string.Format("{0:00}:{1:00}:{2:00}",
               (int)myTimeSpan.TotalHours,
               myTimeSpan.Minutes,
               myTimeSpan.Seconds);

A: One way is to create a DateTime object and use it for formatting:
new DateTime(myTimeSpan.Ticks).ToString(myCustomFormat)

// or using String.Format:
String.Format("{0:HHmmss}", new DateTime(myTimeSpan.Ticks))

This is the way I know. I hope someone can suggest a better way.

A: You can also go with:
Dim ts As New TimeSpan(35, 21, 59, 59)  '(11, 22, 30, 30)    '
Dim TimeStr1 As String = String.Format("{0:c}", ts)
Dim TimeStr2 As String = New Date(ts.Ticks).ToString("dd.HH:mm:ss")

EDIT:
You can also look at Strings.Format.
    Dim ts As New TimeSpan(23, 30, 59)
    Dim str As String = Strings.Format(New DateTime(ts.Ticks), "H:mm:ss")

A: if (timeSpan.TotalDays < 1)
    return timeSpan.ToString(@"hh\:mm\:ss");

return timeSpan.TotalDays < 2
    ? timeSpan.ToString(@"d\ \d\a\y\ hh\:mm\:ss")
    : timeSpan.ToString(@"d\ \d\a\y\s\ hh\:mm\:ss");

All literal characters must be escaped.

A: This is the approach I used my self with conditional formatting. and I post it here because I think this is clean way.
$"{time.Days:#0:;;\\}{time.Hours:#0:;;\\}{time.Minutes:00:}{time.Seconds:00}"

example of outputs:

00:00 (minimum)
1:43:04 (when we have hours)
15:03:01 (when hours are more than 1 digit)
2:4:22:04 (when we have days.)

The formatting is easy. time.Days:#0:;;\\ the format before ;; is for when value is positive. negative values are ignored. and for zero values we have;;\\ in order to hide it in formatted string. note that the escaped backslash is necessary otherwise it will not format correctly.

A: Here is my extension method:
public static string ToFormattedString(this TimeSpan ts)
{
    const string separator = ", ";

    if (ts.TotalMilliseconds < 1) { return "No time"; }

    return string.Join(separator, new string[]
    {
        ts.Days > 0 ? ts.Days + (ts.Days > 1 ? " days" : " day") : null,
        ts.Hours > 0 ? ts.Hours + (ts.Hours > 1 ? " hours" : " hour") : null,
        ts.Minutes > 0 ? ts.Minutes + (ts.Minutes > 1 ? " minutes" : " minute") : null,
        ts.Seconds > 0 ? ts.Seconds + (ts.Seconds > 1 ? " seconds" : " second") : null,
        ts.Milliseconds > 0 ? ts.Milliseconds + (ts.Milliseconds > 1 ? " milliseconds" : " millisecond") : null,
    }.Where(t => t != null));
}

Example call:
string time = new TimeSpan(3, 14, 15, 0, 65).ToFormattedString();

Output:
3 days, 14 hours, 15 minutes, 65 milliseconds

A: Please note: this answer is for .Net 4.0 and above.  If you want to format a TimeSpan in .Net 3.5 or below please see JohannesH's answer.
Custom TimeSpan format strings were introduced in .Net 4.0.  You can find a full reference of available format specifiers at the MSDN Custom TimeSpan Format Strings page.
Here's an example timespan format string:
string.Format("{0:hh\\:mm\\:ss}", myTimeSpan); //example output 15:36:15

(UPDATE) and here is an example using C# 6 string interpolation:
$"{myTimeSpan:hh\\:mm\\:ss}"; //example output 15:36:15

You need to escape the ":" character with a "\" (which itself must be escaped unless you're using a verbatim string).
This excerpt from the MSDN Custom TimeSpan Format Strings page explains about escaping the ":" and "." characters in a format string:

The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.

A: Simple. Use TimeSpan.ToString with c, g or G. More information at MSDN

A: I used the code below. It is long, but still it is one expression, and produces very friendly output, as it does not outputs days, hours, minutes, or seconds if they have value of zero.
In the sample it produces output: "4 days 1 hour 3 seconds".
TimeSpan sp = new TimeSpan(4,1,0,3);
string.Format("{0}{1}{2}{3}",
        sp.Days > 0 ? ( sp.Days > 1 ? sp.ToString(@"d\ \d\a\y\s\ "): sp.ToString(@"d\ \d\a\y\ ")):string.Empty,
        sp.Hours > 0 ? (sp.Hours > 1 ? sp.ToString(@"h\ \h\o\u\r\s\ ") : sp.ToString(@"h\ \h\o\u\r\ ")):string.Empty,
        sp.Minutes > 0 ? (sp.Minutes > 1 ? sp.ToString(@"m\ \m\i\n\u\t\e\s\ ") :sp.ToString(@"m\ \m\i\n\u\t\e\ ")):string.Empty,
        sp.Seconds > 0 ? (sp.Seconds > 1 ? sp.ToString(@"s\ \s\e\c\o\n\d\s"): sp.ToString(@"s\ \s\e\c\o\n\d\s")):string.Empty);

A: I use this method.  I'm Belgian and speak dutch so plural of hours and minutes is not just adding 's' to the end but almost a different word than singular.
It may seem long but it is very readable I think:
 public static string SpanToReadableTime(TimeSpan span)
    {
        string[] values = new string[4];  //4 slots: days, hours, minutes, seconds
        StringBuilder readableTime = new StringBuilder();

        if (span.Days > 0)
        {
            if (span.Days == 1)
                values[0] = span.Days.ToString() + " dag"; //day
            else
                values[0] = span.Days.ToString() + " dagen";  //days

            readableTime.Append(values[0]);
            readableTime.Append(", ");
        }
        else
            values[0] = String.Empty;

        if (span.Hours > 0)
        {
            if (span.Hours == 1)
                values[1] = span.Hours.ToString() + " uur";  //hour
            else
                values[1] = span.Hours.ToString() + " uren";  //hours

            readableTime.Append(values[1]);
            readableTime.Append(", ");

        }
        else
            values[1] = string.Empty;

        if (span.Minutes > 0)
        {
            if (span.Minutes == 1)
                values[2] = span.Minutes.ToString() + " minuut";  //minute
            else
                values[2] = span.Minutes.ToString() + " minuten";  //minutes

            readableTime.Append(values[2]);
            readableTime.Append(", ");
        }
        else
            values[2] = string.Empty;

        if (span.Seconds > 0)
        {
            if (span.Seconds == 1)
                values[3] = span.Seconds.ToString() + " seconde";  //second
            else
                values[3] = span.Seconds.ToString() + " seconden";  //seconds

            readableTime.Append(values[3]);
        }
        else
            values[3] = string.Empty;

        return readableTime.ToString();
    }//end SpanToReadableTime

A: This is a pain in VS 2010, here's my workaround solution.
 public string DurationString
        {
            get
            {
                if (this.Duration.TotalHours < 24)
                    return new DateTime(this.Duration.Ticks).ToString("HH:mm");
                else //If duration is more than 24 hours
                {
                    double totalminutes = this.Duration.TotalMinutes;
                    double hours = totalminutes / 60;
                    double minutes = this.Duration.TotalMinutes - (Math.Floor(hours) * 60);
                    string result = string.Format("{0}:{1}", Math.Floor(hours).ToString("00"), Math.Floor(minutes).ToString("00"));
                    return result;
                }
            }
        }

A: The Substring method works perfectly when you only want the Hours:Minutes:Seconds. It's simple, clean code and easy to understand.
    var yourTimeSpan = DateTime.Now - DateTime.Now.AddMinutes(-2);

    var formatted = yourTimeSpan.ToString().Substring(0,8);// 00:00:00

    Console.WriteLine(formatted);

A: No one has shown approach with decimal format specifier which is my favorite one, especially when used with string interpolation - https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings?redirectedfrom=MSDN#decimal-format-specifier-d
For example:
$"{time.Hours:D2}:{time.Minutes:D2}:{time.Seconds:D2}.{time.Milliseconds:D3}"
// Sample output: 00:00:09.200

You can of course wrap it up in some helper method.

A: Here is my version.  It shows only as much as necessary, handles pluralization, negatives, and I tried to make it lightweight.
Output Examples
0 seconds
1.404 seconds
1 hour, 14.4 seconds
14 hours, 57 minutes, 22.473 seconds
1 day, 14 hours, 57 minutes, 22.475 seconds

Code
public static class TimeSpanExtensions
{
    public static string ToReadableString(this TimeSpan timeSpan)
    {
        int days = (int)(timeSpan.Ticks / TimeSpan.TicksPerDay);
        long subDayTicks = timeSpan.Ticks % TimeSpan.TicksPerDay;

        bool isNegative = false;
        if (timeSpan.Ticks < 0L)
        {
            isNegative = true;
            days = -days;
            subDayTicks = -subDayTicks;
        }

        int hours = (int)((subDayTicks / TimeSpan.TicksPerHour) % 24L);
        int minutes = (int)((subDayTicks / TimeSpan.TicksPerMinute) % 60L);
        int seconds = (int)((subDayTicks / TimeSpan.TicksPerSecond) % 60L);
        int subSecondTicks = (int)(subDayTicks % TimeSpan.TicksPerSecond);
        double fractionalSeconds = (double)subSecondTicks / TimeSpan.TicksPerSecond;

        var parts = new List<string>(4);

        if (days > 0)
            parts.Add(string.Format("{0} day{1}", days, days == 1 ? null : "s"));
        if (hours > 0)
            parts.Add(string.Format("{0} hour{1}", hours, hours == 1 ? null : "s"));
        if (minutes > 0)
            parts.Add(string.Format("{0} minute{1}", minutes, minutes == 1 ? null : "s"));
        if (fractionalSeconds.Equals(0D))
        {
            switch (seconds)
            {
                case 0:
                    // Only write "0 seconds" if we haven't written anything at all.
                    if (parts.Count == 0)
                        parts.Add("0 seconds");
                    break;

                case 1:
                    parts.Add("1 second");
                    break;

                default:
                    parts.Add(seconds + " seconds");
                    break;
            }
        }
        else
        {
            parts.Add(string.Format("{0}{1:.###} seconds", seconds, fractionalSeconds));
        }

        string resultString = string.Join(", ", parts);
        return isNegative ? "(negative) " + resultString : resultString;
    }
}

A: If you want the duration format similar to youtube, given the number of seconds
int[] duration = { 0, 4, 40, 59, 60, 61, 400, 4000, 40000, 400000 };
foreach (int d in duration)
{
    Console.WriteLine("{0, 6} -> {1, 10}", d, d > 59 ? TimeSpan.FromSeconds(d).ToString().TrimStart("00:".ToCharArray()) : string.Format("0:{0:00}", d));
}

Output:
     0 ->       0:00
     4 ->       0:04
    40 ->       0:40
    59 ->       0:59
    60 ->       1:00
    61 ->       1:01
   400 ->       6:40
  4000 ->    1:06:40
 40000 ->   11:06:40
400000 -> 4.15:06:40

A: I wanted to return a string such as "1 day 2 hours 3 minutes" and also take into account if for example days or minuttes are 0 and then not showing them. thanks to John Rasch for his answer which mine is barely an extension of
TimeSpan timeLeft = New Timespan(0, 70, 0);
String.Format("{0}{1}{2}{3}{4}{5}",
    Math.Floor(timeLeft.TotalDays) == 0 ? "" :
    Math.Floor(timeLeft.TotalDays).ToString() + " ",
    Math.Floor(timeLeft.TotalDays) == 0 ? "" : Math.Floor(timeLeft.TotalDays) == 1 ? "day " : "days ",
    timeLeft.Hours == 0 ? "" : timeLeft.Hours.ToString() + " ",
    timeLeft.Hours == 0 ? "" : timeLeft.Hours == 1 ? "hour " : "hours ",
    timeLeft.Minutes == 0 ? "" : timeLeft.Minutes.ToString() + " ",
    timeLeft.Minutes == 0 ? "" : timeLeft.Minutes == 1 ? "minute " : "minutes ");


text:
Q: Why are some PowerShell consoles resizable and some are not? I just noticed that on my main system, the PowerShell console is not resizable in that when you press maximise, the width does not change, and you cannot drag from the bottom corner to the right etc and you cannot hold CTRL + roll-mouse-wheel to resize, i.e. this console box is just like DOS. However, when I am on another system (with the exact same build of Windows 10), the PowerShell console is fully resizable (all of the above restrictions are gone). Does anyone know why these two quite different consoles exist, both called PowerShell, and how I can get access to the good (i.e. more modern / resizable) one (and get rid of the DOS-like one)?

A: The console window is not part of PowerShell – it's shown by Conhost.
Conhost is the common console window host for all "command-line" programs on Windows, i.e. the same kind of window is automatically displayed whenever powershell.exe or cmd.exe is started.
It doesn't involve DOS at all (cmd.exe hasn't been "DOS" since 1992), but it remained mostly the same ever since its original release as part of NT3.x and simply did not have resize or zoom functionality until very recently.
Conhost was somewhat improved through Windows 8.1 and Windows 10 to include various new features (zoom, dynamic resizing, Unix-style ANSI code support), but out of fear of breaking some existing programs it still allows the new "Conhost v2" additions to be disabled.
The "Use legacy console" toggle is at the bottom of in every console window's "Properties" dialog (which can be accessed through the window's AltSpace system menu):

However, after those updates, development of the original Conhost has been frozen once more – instead a new Windows Terminal app is being developed, which will become the new default console (and Unix-style terminal emulator) in Windows 11.


text:
Q: Sum of primes below 2 million What am i doing wrong here?
  #include<stdio.h>

    int main(){
        int i,count;
        long long int sum = 0, num;

        for(num = 1; num <= 1000; num++){
            count = 0;
            for(i = 2; i <= num / 2; i++){
                if(num % i == 0){
                    count++;
                    break;
                }
            }
            if(count == 0 && num != 1)
                sum = sum + num;
        }
        printf("Sum of prime numbers is: %d ", sum);
        return 0;
    }

I tried to make a program that outputs the sum of all primes below nth number, n being 2 million however when i try to run it, there is a slight delay and it outputs nothing... it works well enough  for small numbers like 1000 or 100 but big numbers it just does not output anything.There are no error or bugs that i know of either. (please help, i know nothing, so guide this young one)

A: The above program is fine, but it is possible to further reduce the time complexity and make it faster. The better approach is to use sieve of eratosthenes algorithm.You can read about it here http://www.geeksforgeeks.org/sieve-of-eratosthenes/
The program for your problem is
#include <bits/stdc++.h>
using namespace std;

void SieveOfEratosthenes(long long int n)
{

    bool prime[n+1];
    memset(prime, true, sizeof(prime));

    for (long long int p=2; p*p<=n; p++)
    {
        if (prime[p] == true)
        {
                 for (int i=p*2; i<=n; i += p)
                prime[i] = false;
        }
    }

 long long sum=0;
        for (int p=2; p<=n; p++)
       if (prime[p])
          sum+=p;
          cout << sum << " ";
}

int main()
{
    int n = 2000000;
    cout << "sum of prime numbers less then 2000000 is :" << endl;
    SieveOfEratosthenes(n);
    return 0;
}

Please let me know if you face difficulty in understanding the program.Note: You can also use Segmented seive to further reduce the time complexity

A: #include<stdio.h>
#include<math.h>
int main(){
int i,count;
long long int sum=0, num;
for(num = 1;num<=1000000;num++){
 count = 0;
for(i=2;i<=sqrt(num);i++){         //change here
if(num%i==0){
 count++;
 break;
  }
  }
     if(count==0 && num!= 1)
      sum = sum + num;
      }
  printf("Sum of prime numbers is: %lld ",sum);   //and here
     return 0;
    }

Some simple maths, while checking for prime, check up to square root of a number. And in printf() the format specifier for long long int is %lld not %d.


text:
Q: How do I make a custom "Read More Blogs" button for my blog page I'm actually working on my custom wordpress theme. And, when I tried to develop a "Read More Blogs" button, I was unable. Because, all the examples I saw on internet was for pagination.
I need a single button that take me to blog page 2 from the blog homepage. Like, a single button used to be on Twitter(load more tweets). Please can you help????
I don't need pagination but a single load more blog posts button.

A: This's the plugin you're looking for: https://wordpress.org/plugins/ajax-load-more/
Load more posts, pages and comments using AJAX.


text:
Q: Python: Is there any difference between "del a" and "del(a)"? As far as I can tell, both del a and del(a) seems to work with the same effect. If that's the case, why would Python allow del to exist both as a statement and a function?

A: del is always a statement. Using parenthesis doesn't mean you're making a function call, but you're grouping expressions. (1) is just the same as 1.

A: Thanks to @Juhana 's comment and @cdonts 's answer. Apparently parentheses here do not represent a function call. Here's another example:
In [40]: a=b=c=1
In [41]: del[a,(b,c)]
In [42]: b
Traceback (most recent call last):
  File "<ipython-input-42-60b725f10c9c>", line 1, in <module>
    b
NameError: name 'b' is not defined


text:
Q: How do I split a large file into multiple smaller ones based on the value in a text column? I have a large file that I need to split into workable pieces. (350 million records)
The key is the second column value cannot overflow into the next file.
Reading and writing take way to long, split command does not work. anything else I can do?
example file with 10 records to be split into 3 output files:
aa,22,xxx
aa,22,xxx
aa,22,xxx
aa,22,xxx
aa,22,xxx
aa,23,xxx
aa,23,xxx
aa,23,xxx
aa,23,xxx
aa,24,xxx

output1:
aa,22,xxx
aa,22,xxx
aa,22,xxx
aa,22,xxx
aa,22,xxx

output2:
aa,23,xxx
aa,23,xxx
aa,23,xxx
aa,23,xxx

output3:
aa,24,xxx

A: With awk:
awk -F, '$2 != ref { i++; ref = $2 } { print $0 >"output" i }' input

will split input according to the second column, into files output1, output2...
If you want to limit the number of lines per output file:
awk -F, '$2 != ref { i++; ref = $2; lines = 0 } lines >= 1000 { i++; lines = 0 } { print $0 >"output" i; lines++ }' input

will produce output files containing at most 1000 lines, respecting the constraint on the second column.
Here's another variant, which splits at the next change in the second column after a given limit has been reached (1000 lines in this example, you'd use 50000000 presumably):
awk -F, 'BEGIN { change = 1 } change && $2 != ref { i++; ref = $2; change = 0; lines = 0 } lines >= 1000 { change = 1 } { print $0 >"output" i; lines++; ref = $2 }' input

A: Using Miller:
$ mlr --nidx --fs comma put -q 'tee > $2 . ".dat", $*' ten.dat

$ cat 22.dat
aa,22,xxx
aa,22,xxx
aa,22,xxx
aa,22,xxx
aa,22,xxx

$ cat 23.dat
aa,23,xxx
aa,23,xxx
aa,23,xxx
aa,23,xxx

$ cat 24.dat
aa,24,xxx


text:
Q: Delay digital signal using flip-flop I'm trying to delay a digital signal using a D flip-flop.
This is what I expect:

I expect a delay between D and Q.
This is what I get:

There is no delay between.
Why does the delay not appear?
Is there an alternative circuit/flip-flop that I can use to delay the digital delay?
This is the link to the simulation to check.

A: Your clocks/signal are probably already synchronized. As such it's being clocked in on the first edge (The setup delay in the flip flop is likely zero in the simulation too). Try adjusting the phase of the signal to change how that appears in the simulation.
However, even then, the delay of this circuit will be almost zero to 1 clock period.
You may want to consider two stages instead of one with the data for the second state fed from Q of the first and the clocks common. Your delay will then be 1 to 2 clock cycles.

simulate this circuit – Schematic created using CircuitLab

A: You don't see a delay (in the second graph) because you are "inputting" the same signals you input on the original graph.
Your flip-flop will transfer D to Q on the rising edge of the CLK signal.
There are 2 changes you can make to get the desired efect: insert an inverter gate at the entry of the CLK signal; or change your flip-flop into one that as a negated clock, meanning that transfers D to Q on the falling edge of the CLK.
P.S: answering this question, with a delay of 5 years, just because it may help someone with the same problem.


text:
Q: How to get message by id discord.py I'm wondering how to get a message by its message id. I have tried discord.fetch_message(id) and discord.get_message(id), but both raise:
Command raised an exception: AttributeError: module 'discord' has no attribute 'fetch_message'/'get_message'

A: When getting a message, you're going to need an abc.Messageable object - essentially an object where you can send a message in, for example a text channel, a DM etc.
Example:
@bot.command()
async def getmsg(ctx, msgID: int): # yes, you can do msg: discord.Message
                                   # but for the purposes of this, i'm using an int

    msg = await ctx.fetch_message(msgID) # you now have the message object from the id
                                         # ctx.fetch_message gets it from the channel
                                         # the command was executed in

###################################################

@bot.command()
async def getmsg(ctx, channel: discord.TextChannel, member: discord.Member):
    msg = discord.utils.get(await channel.history(limit=100).flatten(), author=member)
    # this gets the most recent message from a specified member in the past 100 messages
    # in a certain text channel - just an idea of how to use its versatility

References:

*

*abc.Messageable

*TextChannel.history()

*TextChannel.fetch_message()

*Context.fetch_message()


text:
Q: What's a good, free source control system for eclipse android development? My app code is starting to get unmanageable and I want to start source control, primarily because I need to branch my code.
What are some good systems that you have used in the past and what would you recommend to me.
Requirements:
Must be free
Must integrate with eclipse
Must work well with android development plugin

A: I vote for Git

A: You can set up a project at code.google.com, and use a source code repository provided by them.  I think they offer Subversion and Mercurial as source control systems, and I use Subversion.
After you've got that set up, you can just use Subclipse to connect to the repository.

A: Git and SVN are both good choices, although I'd give SVN an edge since it's probably a bit easier to learn if you've never used a source control system before.  As far as Eclipse integration goes, you'd be hard pressed to find a popular source control system that doesn't have an Eclipse plugin.

A: SVN (Subversion) is very good and there is support for an Eclipse plug-in called Subclipse.

A: Besides all voting for git I'll vote for the following:

*

*If you are willing to use eclipse for android development use SVN or mercurial, because:

*

*Both have much better support from eclipse (I belive EGit is still in beta and no public releases are available yet)

*They are both supported by google code that is excellent source control for open source

*They both work on all major systems (no offence but git on windows even with MinGW is sometimes creepy)

*If you are not using eclipse:

*

*If you are not using windows for development choose Git because:

*

*android uses it

*it is awesome

*If you do use windows choose:

*

*Git if you are not afraid of console

*Mercurial otherwise

A: I would also vote for Git. I have little experience with Git and SVN, and I enjoyed Git more. It's fast, it's easy, i didn't have any problems with this. There's good Git repository service github.com, but setting up your own repository is very easy. But you can have some trouble with integrating it with Eclipse :(

A: If you are not working on a team and you just need version control for yourself, SourceGear Vault is free for a single user and they have a nice Eclipse plug-in.
I use it for Android development and it works like a charm.

A: If you're using a Mac, try out Versions. It's a tool for managing SVN repositories and working copies, and it's amazing (No... I don't work for them ;-) )They allow you to create repositories on your own computer, or setup a free one at BeanStalk.com

A: I'll put in another vote for subversion. It should be easier to learn than git, and will easily provide all you need.
As for the eclipse integration, you can choose between two different plugins: Subclipse or subversive. You can find lots of interesting debates on the net about which is the better one. I'm personally using subversive because it's a bit more intelligent about trunk/branches/tags handling in svn.

A: Find EGit Releases here : http://www.eclipse.org/egit/download/
Since Mar 2010 we did a release every 3 months, current release is 0.10.1
Next release is planned for end of Feb 2011 with Helios SR2.

A: Subversive plugin for eclipse.


text:
Q: Laravel MongoDB unset use?    {
    "_id": {
        "$oid": "60b609d6bd846108dc86433d"
    },
    "il": "Siirt",
    "ilce": "merkez",
    "ada": 466,
    "parsel": 1,
    "pafta": "M47-B-09-B-3-A",
    "tkgmkodu": "106478407",
    "tkgmeskikodu": [],
    "nitelik": "Tarla",
    "tapualani": "621,54",
    "cadde": "",
    "sokak": "",
    "mahalle": "",
    "kiracilar": [{
        "_id": {
            "$oid": "60b609d6bd846108dc86431d"
        },
        "durum": 1,
        "adi": "kiraci Adı",
        "soyadi": "kiraci soyadi",
        "tc": "456454654654",
        "tel": "5424210910",
        "blok": "b",
        "kat": "5",
        "d-no": 18,
        "kayitTarihi": {
            "$date": "2017-01-14T21:00:00.000Z"
        },
        "cikisTarihi": "",
        "kiraTutari": 1000,
        "notlar": "",
        "borcAlacak": [{
            "_id": {
                "$oid": "60b609d6bd846408dc86433d"
            },
            "tarih": {
                "$date": "2017-01-14T21:00:00.000Z"
            },
            "aciklama": "Ocak Ayı Borç Tahakkuku",
            "bankaKodu": "",
            "borc": 1000,
            "odeme": 0
        }, **{
            "_id": {
                "$oid": "632609d6bd846108dc86433d"
            },
            "tarih": {
                "$date": "2017-01-15T21:00:00.000Z"
            },
            "aciklama": "Ocak Ayı Borç Ödemesidir.",
            "bankaKodu": "ObjectId",
            "borc": 0,
            "odeme": 1000
        }**]
    }],
    "mahkemeler": [""]
}

How I delete unset from MongoDB with Laravel use

A: I don't know what actually you use in laravel, but if you already have connection with mongoDB, you can delete it like this (using JS):
//replace with your id
let id_needed = '60b609d6bd846108dc86433d'
let deleted = req.db.collection('brands').deleteOne( { "_id" : ObjectId(id_needed)});


text:
Q: Split string returning a record I have a single column table which looks like this:
Gaming | Austria | 47.9333, 15.1
Hebei | China | 39.8897, 115.275

This means that every row is a single string (VARCHAR) that contains some location, with the different fields separated by a pipe (|).
I would like to write a query that returns the following:
------- ---------- ---------------------------------
Gaming   Austria    Gaming | Austria | 47.9333, 15.1
Hebei    China      Hebei | China | 39.8897, 115.275

Which means I want 3 columns: for the city, for the country, and the original column.
While splitting the city is easy (combination of CHARINDEX and SUBSTRING), extracting the country seems to be more challenging. The tricky part is to know the length of the country field in the string, so it could be extracted using SUBSTRING.
I realize I might have to write a SPLIT function in T-SQL, but I'm not sure how to write one that returns the data as a record and not as a table.
Hints and/or solutions will be more than welcome.

A: Just a matter of specifying the appropriate starting position and dynamically calculating the length based on the positions of the delimiters within the string - as d. shows above with some additional tweaking:
select  substring(fieldName,0,charindex('|',fieldName,0)) as city,
        substring(fieldName,charindex('|',fieldName,0)+1,( charindex('|',fieldName,(charindex('|',fieldName,0)+1)) - charindex('|',fieldName,0) - 1)) as country,
        right(fieldName, charindex('|',reverse(fieldName),0)-1) as coordinates

Note that you may want to compare this with a CLR-based split function, as well as a variety of other possibilities which are outlined in this other serverfault thread.

A: You can pass a 3rd parameter, which specifies the first character to start looking from. That means you can extract country like this:
CHARINDEX(field, '|', CHARINDEX(field, '|')+1)


text:
Q: How to serve a GeoJSON file through WMS with MapServer? Could you please provide a working example of WMS mapfile with GeoJSON layer for the MapServer?
Mine is not working:
MAP
  EXTENT -120 34 -119 35 # Geographic
  SIZE 800 400

 LAYER
  TYPE polygon
  NAME "cells"
  METADATA
    OWS_TITLE "MetGeoJSON Polygon"
  END
  CONNECTIONTYPE OGR
  CONNECTION "shp/geoJson.json"
  DATA "OGRGeoJSON"
  STATUS default
  PROJECTION
    "init=epsg:4326"
  END
END
END

The error message is:
msDrawMap(): Image handling error. Failed to draw layer named 'cells'. msOGRFileOpen(): OGR error. GetLayer(OGRGeoJSON) failed for OGR connection. Check logs.

A: @david-osipyan I used your question as the excuse needed to create new documentation for GeoJSON access in MapServer, with a new page visible now at: https://mapserver.org/input/vector/geojson.html
I hope that helps the next person coming along, in the MapServer community :)
By the way, it was so nice to read here in an earlier comment from you that MS4W is working great for you for GeoJSON access.  Excellent! (it's nice to hear complements for once online, ha)  I spend a lot of effort (through my company, GatewayGeo) to create/distribute/pay for all the downloads of MS4W.  I'm glad to hear it helps your organization.
PS. as you notice at the bottom of that new page, it mentions that all MS4W installations include a default mapfile (in /ms4w/apps/local-demo/local.map) that includes GeoJSON output, out-of-the-box.
Have a nice weekend,
Jeff McKenna
@mapserving

A: Your mapfile is mostly OK. I used the states.shp shapefile from the GeoServer demo data in my test and converted it into GeoJSON with ogr2ogr
ogr2ogr -f geojson geoJson.json states.shp
I checked with ogrinfo that my geoJson.json file contains a layer named "states" and used that in my mapfile. Other edits that I did are

*

*edit EXTENT to be worldwide

*add CLASS and STYLE from the MapServer WMS manual https://www.mapserver.org/ogc/wms_server.html
Because you used the relative path I created also a subdirectory "shp" under the directory where the mapfile is located and plased the GeoJSON file there. Myself I prefer to use absolute paths but relative paths are OK as well.
MAP
  #EXTENT -120 34 -119 35 # Geographic
  EXTENT -180 -90 180 90 # Geographic
  SIZE 800 400

 LAYER
  TYPE polygon
  NAME "cells"
  METADATA
    OWS_TITLE "MetGeoJSON Polygon"
  END
  CONNECTIONTYPE OGR
  CONNECTION "shp/geoJson.json"
  #DATA "OGRGeoJSON"
  data "states"
  STATUS default
  CLASS
        NAME "Parks"
        STYLE
          COLOR 200 255 0
          OUTLINECOLOR 120 120 120
        END # Style
  END # Class
  PROJECTION
    "init=epsg:4326"
  END
END
END

I used this query on my browser for testing
http://localhost/cgi-bin/mapserv.exe?map=c:\test\json.map&mode=map
The result is this

I suppose that your GeoJSON file is not in the correct directory that is relational to the mapfile location, of the layer of the GeoJSON is not "OGRGeoJSON".
Your mapfile is very minimal but it does work even without CLASS and STYLE. You just won't see anything on the map because nothing is rendered. For next tests I suggest to use the mapfile from the WMS Server manual page as a template. It is still short but contains useful examples about how to configure projections and basic styles and all that is needed for setting up a WMS service.


text:
Q: AMQP connection closed when nova cells are enabled on Devstack I have set up Devstack on 3 servers having IPs 10.10.1.51,10.10.1.53 and 10.10.1.54. I configured the devstack on server 53(IP 10.10.1.53) as the parent/api cell and configured the openstack on 51 and 54 as child cells. I enabled cells by specifying enable_service n-cell in the respective localrc files.
The nova.conf in the parent is as follows:
[DEFAULT]
    # Swap out the compute_api class so actions are proxied to nova-cells service.
    compute_api_class=nova.compute.cells_api.ComputeCellsAPI

    [cells]
    name=api
    enable=true
    cell_type=api

nova.conf in the child cell1 is as follows:
[GLOBAL]
# Disable quota checking in child cells.  Let API cell do it exclusively.
quota_driver=nova.quota.NoopQuotaDriver

[cells]
enable=true
name=cell1  # something unique per child cell
cell_type=compute

nova.conf in child cell2 is as follows:
[GLOBAL]
# Disable quota checking in child cells.  Let API cell do it exclusively.
quota_driver=nova.quota.NoopQuotaDriver

    [cells]
    enable=true
    name=cell1  # something unique per child cell
    cell_type=compute

We have the following rabbit server info on the parent cell:
rabbit_host=10.10.1.53 rabbit_port=5672 rabbit_username=admin rabbit_password=password rabbit_virtual_host=api_vhost
And in the child cell named 'cell1' we have the following rabbit server info:
rabbit_host=10.10.1.54 rabbit_port=5673 rabbit_username=admin rabbit_password=password rabbit_virtual_host=cell1_vhost
And in the child cell named 'cell2' we have the following rabbit server info:
rabbit_host=10.10.1.51 rabbit_port=5673 rabbit_username=admin rabbit_password=password rabbit_virtual_host=cell2_vhost
After which I ran the following commands in the API cell to tell about its children:
>nova-manage cell create --name=cell1 --cell_type=child --username=admin --password=password --hostname=10.10.1.51 --port=5673 --virtual_host=cell1_vhost --woffset=1.0 --wscale=1.0

>nova-manage cell create --name=cell2 --cell_type=child --username=admin --password=password --hostname=10.10.1.54 --port=5673 --virtual_host=cell1_vhost --woffset=1.0 --wscale=1.0

The following command was run in both the child cells to tell them about their parent:
>nova-manage cell create --name=api --cell_type=parent --username=admin --password=password --hostname=10.10.1.53 --port=5672 --virtual_host=api_vhost --woffset=1.0 --wscale=1.0

n-cell-child and n-cell-region were restarted in all the 3 stack sessions.
n-cell-region of all 3 stack sessions gave an error saying:
 2014-07-24 12:54:01.633 ERROR oslo.messaging._drivers.impl_rabbit [req-5154ff13-4f6f-4582-8a44-d42941e9a4bc None None] AMQP server 10.10.1.53:5672 closed the connection. Check login credentials: Socket closed

n-cell-child screens in both the child cells gave the following error:
2014-07-24 12:57:11.579 ERROR oslo.messaging._drivers.impl_rabbit [req-ba63e502-f099-4e55-a8e9-297390f5598f None None] AMQP server on 10.10.1.54:5672 is unreachable: [Errno 111] ECONNREFUSED. Trying again in 30 seconds.

However there is no error in n-cell-child screen of the parent cell. AMQP broker running is rabbitmq-server on all 3 servers. I have checked the users listing in rabbitmq and the credentials seem to be fine.
Any help in debugging the error would be appreciated. Thanks in advance!


text:
Q: Deleting PriceBookEntry results in errors I'm trying to use the Data Loader to delete PriceBookEntry records. However, I end up getting an error for all of them. The weird thing is that the Error message is the same as the contents of the Name field of the records.
I know Salesforce says that PriceBookEntry cannot be deleted (see the isActive field description), but the option is certainly there in Data Loader. Moreover, the error message is very odd and I was wondering how I should proceed. Any advice on this would be appreciated.

A: Pricebookentries (PBE) can definitely be deleted by DataLoader or Excel Connector - I do it all the time.
If you try and delete the pricebookEntry on the standard pricebook when there are custom pricebooks using that same product (and hence custom PBE), you will get the error 'Delete Failed' with a reference to the product name. If you first delete PBE from the custom pricebook, then no error.
I can't speak for the documentation and would say it is wrong (or needs more elaboration). You can see at the bottom of the page, the following sentence:

If you delete a PricebookEntry while a line item references it, the line item is unaffected, but the PricebookEntry will be archived and unavailable from the API.

In addition, the object supports the delete() API operation.

A: According to your own reference you cited for the IsActive field:

Indicates whether this object is active (true) or not (false). Although you can never delete PricebookEntry records, your client application can set this flag to false. Inactive PricebookEntry objects are hidden in many areas in the user interface. You can change this flag on a PricebookEntry record as often as necessary.

Although the object reference does include an IsDeleted field, from the above, I'd conclude that once a field has been used in the PriceBook, it likely can't be deleted and would need to have it's IsActive flag set to "false". I strongly suspect that's because of Opportunity history but would have to check with an associate who would know more about it than I to be able to say with certainty.


text:
Q: javascript 'curry', need some explanations on this code I am reading the book "JavaScript-The Good Parts", in chapter 4.14 Curry, the book gives the following example:
Function.method('curry', function(){
    var slice = Array.prototype.slice,
        args = slice.apply(arguments), //1st-arguments
        that=this;

    return function(){
       return that.apply(null, args.concat(slice.apply(arguments))); //2nd-arguments
    }
})

var add1=add.curry(1);
document.writeln(add1(6)); // 7

I have two questions on this code:

*

*There are two places using 'arguments'. In the method invoking in the last two lines code, is it so that '1' goes to the 1st-arguments and '6' goes to the 2nd-arguments?

*There is a line of code apply(null, args.concat(slice.apply(arguments))), why does it apply(null,...) here?, what is the sense to apply a argument to a null object?

A:
There are two places using 'arguments'. In the method invoking in the last two lines code, is it so that '1' goes to the 1st-arguments and '6' goes to the 2nd-arguments?

Yes, 1 is part of arguments of the outer function, while 6 goes the arguments in the inner function. The inner function can capture all other variables in a closure except for arguments and this, which have a special meaning inside a function, hence are not part of that closure. So that, and args are captured, but not arguments.

There is a line of code apply(null, args.concat(slice.apply(arguments))), why does it apply(null,...) here?, what is the sense to apply a argument to a null object?

Invoking a method with a null context will simply set the this value to the global object. In the case it seems the author does not care what that context is.

A: That example was kind of tricky for me too, because I'm not experienced in JavaScript, so I will try to explain it as I would have wished to be explained to me. Due to that reason it might be too explicit!
Also, before you start, I would recommend you to review the 'closure' part (for me to understand closure, was very helpful this quote):
"A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created." (from Mozilla developer network) - Closures: Line by Line explanation of "Javascript: Good Parts" example?
And now about the curry example:
apply(this, arguments) - this method can be applied to a function to  call it and sends the 'this' variable and the parameters variables as an array (arguments).
For example:
// JSON objects
var ob1 = { // first object
    a : 0,
    b : 0
};

var ob2 = { // the second one
    a : 0,
    b : 0
};

// a function that updates 'a' and 'b'
function update(newA, newB) {
    this.a = newA;
    this.b = newB;
}

// 'this' is equal with ob1 and arguments array is [10, 20]
update.apply(ob1, [10, 20]);

// the same as above, but 'this' is here ob2
update.apply(ob2, [30, 40]);

/* after update:
ob1 {
      a: 10,
      b: 20
    }
ob2 {
      a: 30,
      b: 40
    }
*/

Now, that you have understood apply, you might ask why is in this example is called only with a single parameter.
  args = slice.apply(arguments);

The function 'slice' takes an array and some parameters that represent indexes and forms a new array only with those.For example:
var anArray = ['red', 'green', 'black'];
var otherArray = anArray.slice(0); // after this line 'otherArray' will be ['red']
otherArray = anArray.slice(1,2); // 'otherArray' will be ['green','black']
// but what happens id you don't specify any indexes?
otherArray = anArray.slice();
// otherArray will be equal with ['red', 'green', 'black'], the same as 'anArray'
// it just makes a copy of it

So, when it does:
args = slice.apply(arguments)

is the same as:
args = slice.apply(/*this*/ arguments, /*arguments*/ undefined);

which is it 'almost' like saying:
args = arguments.slice(); // args will have all the elements the same as arguments

The reason why it does that is because args will be an array with all the methods of an array, but 'arguments' doesn't have any methods.
"Because of a design error, arguments is not really an array. It is an array-like object. Arguments has a length property, but it lacks all of the array methods." (from the book)
Let's recap, we need it these two lines:
   var slice = Array.prototype.slice;
   args = slice.apply(arguments);

just to make 'arguments' to have all the methods that are specific to the an array.
In our case we will need the 'concat' method that takes two array and joins them.
Function.method('curry', function(){
       var slice = Array.prototype.slice;
       args = slice.apply(arguments);
       that=this; // saves this (which will be a function)

       return function(){
    // 'that' will be the same as this from above
    // and is a function that we call it with the apply
          return that.apply(/*this*/null, /*arguments*/ args.concat(slice.apply(arguments)));
   // 'this' was null, an arguments was a join between 'args' and 'arguments'
}
});

Finally, you just have to understand how will be used:
function add(a, b) {
    return a + b;
}

var add1 = add.curry(1); // add is function, and 'add.curry(1)' returns a function
    // that will have 'a' set as 1(one) and 'b' as undefined(not being set)

var sum = add1(6); // 7
// when you call add1(6), you actually call that function that was returned by
// the line add.curry(1), with 'b' equal with 6


text:
Q: How do I access the oauth2 authenticated user in a Lumen controller? I have followed this excellent tutorial Building a Web App with Lumen and  OAuth2 for setting up OAuth2 and Lumen.  Everything is working fine apart from now I want to access the currently authenticated user information/model.
My route correctly posts the supplied information after I have logged in and I can break with Netbeans inside the controller but I am not clear how to get the user from the underlying Auth framework.  I have tried the three methods indicated here Authentication - Laravel but to no avail.  The lumen logs shows:
==== routes.php ====

$app->group(['namespace' => 'App\Http\Controllers','prefix' => 'api', 'middleware' => 'oauth'], function($app)
{
    $app->post('info', 'InfoController@send');
}

==== InfoController.php ====
namespace App\Http\Controllers;

// the controllers
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Illuminate\Contracts\Auth\Authenticatable;

class InfoController extends Controller{

    /* /api/info methods */

    public function send(Request $request){

        // can iterate over the entire users table but I just
        // want the current user (must be some method through
        // the authentication stack)
        $users = \App\Auth\User::all();

        foreach ($users as $user) {
           $name = $user->name;
           $key = $user->getAuthIdentifier();
           $pwd = $user->getAuthPassword();
        }

        // CODE GETS HERE BUT how to get the current user?
        // Authenticated OK (request supplies "Access-Token: Bearer ...")
    }
}

A: This is probably not the cleanest solution and may not match your requirements exactly but it does retrieve the user.
I decided to make another DB query in the proxy to get the user with the same key (in my case, email address) that was requested by the client.
In my case I was sending the user id along with the standard oauth token.
You could use the same technique to set some value in the session.
// ../app/Auth/Proxy.php
namespace App\Auth;

use App\User;   //     -----    added this line
use GuzzleHttp\Client;

class Proxy {

...

   private function proxy($grantType, array $data = [])
   {
      ...

      $response = json_decode($guzzleResponse->getBody());

      if (property_exists($response, "access_token")) {
         ...
        // added the following line to get the user
        $user = User::where('email',$data['username'])->get()->first();
        // untested, but you could add the user to your session here
        $request = app()->make('request');
        $request->session()->put('current_user', $user);

        $response = [
                'accessToken'            => $response->access_token,
                'accessTokenExpiration'  => $response->expires_in,
                'userId'                 => $user->id,
        ];
    }
 ...


text:
Q: Querying for a key in DynamoDB with a fallback to a default value There is a table in DynamoDB books, no indices, just a partition key book_id. There is also a "default" book that has an id default. Is it possible to query for a specific book OR for a default one? Kind of having a fallback. I am want to use it in combination with API Gateway.
{
    "TableName": "books",
    "KeyConditionExpression": "book_id = :v1 or book_id = :v2",
    "ExpressionAttributeValues": {
        ":v1": {
            "S": "12345"
        },
        ":v2": {
            "S": "default"
        }
    }
}

I get "Invalid operator used in KeyConditionExpression: OR". Thank you!

A: You can't do that in KeyConditionExpression which supports only direct partition key comparison and optional second condition for sort key where both of these condition (if the second is provided) must be true. In other words, you can only use and operator and the second condition must be based on a sort key, not on the partition key.
What you can do is to run the query to look for a book with a given book_id, if there is no such book, query will return empty result. Then you can either run another query to look for the default book and return it instead, or ,more preferably, you can precache that default book and return it without performing another query. Of course, this depends on how often you want to change the default book, if ever.
So in pseudo-code it might look like
result = query(book_id)

if (result is empty) {
  result = cached_result || query(default_book_id)
}

return result


text:
Q: Changing xml node value in SQL with xquery [SQL Server] I have example XML in one of the table column:
<Root>

      <C>c</C>
      <D>d</D>

   b
</Root>

How can I replace value of A node into something like that:
<Root>

      <E>e</E>
      <F>f</F>

   b
</Root>

I tried the following solution
DECLARE @var varchar(100);
SET @var = '<E>e</E><F>f</F>'
SET @xml.modify('replace value of (/Root/A/text())[1] with sql:variable("@var")');

but it did not work...
regards

A: I do not think it is possible to use replace to replace nodes, only values.
You can use delete and then insert instead.
declare @xml as xml = '
<Root>

    <C>c</C>
    <D>d</D>

  b
</Root>'

declare @var xml
set @var = '<E>e</E><F>f</F>'

set @xml.modify('delete /Root/A/*')
set @xml.modify('insert sql:variable("@var") into (/Root/A)[1]')

select @xml


text:
Q: Conditional formatting an entire row + sub-rows I'm trying to format the rows within my google sheets in a very specific way.
I have multiple rows with a date on the left. I run conditional formatting and have the entire row colored.
I use the following custom formula: =$B4=today()
Now I'd like to include the sub-rows where the farthest left column is empty.
Let's say today's the 3.1.19. The number of sub-rows can vary (from none to up to 10). I have an example of how it should look like below:
+---------+----------+---------+---------+
| 1.1.19  | cell 1   | cell 2  | cell 3  |
|         | cell 1   | cell 2  | cell 3  |
| 2.1.19  | cell 1   | cell 2  | cell 3  |
| 3.1.19  | cell 1   | cell 2  | cell 3  | <- colored right now
|         | cell 1   | cell 2  | cell 3  | <- should be colored too
|         | cell 1   | cell 2  | cell 3  | <- should be colored too
|         | cell 1   | cell 2  | cell 3  | <- should be colored too
| 4.1.19  | cell 1   | cell 2  | cell 3  |
+---------+----------+---------+---------+

A: =IF(TODAY()=TO_DATE(IF(LEN(B1),
 VLOOKUP(ROW(A1), FILTER({ROW(A:A), A:A}, LEN(A:A)), 2), )), 1)

A: Suppose you have dates in B column, starting from B1.
Then in conditional formatting you can apply the formula:
=INDEX(FILTER($B$1:$B1; NOT(ISBLANK($B$1:$B1)));ROWS(FILTER($B$1:$B1; NOT(ISBLANK($B$1:$B1)))))=TODAY()

You can apply it to entire rows.


text:
Q: Wordpress, Genesis theme, streamline pro, How to add an extra .PHP file? I would like to create a new formhandler.php file where I can collect the info from a form on a page in the streamline pro theme on the genesis framework. I am looking at appearance-> editor -> streamline pro theme. I see a list of php files:
Templates

*

*front-page.php

*Theme functions (function.php)

*theme-defaults.php (lib/theme-defaults.php)

*Landing page templates (page_landing.php)

Now my question is: How do I add another .php file under this? (or anywhere else) to gather the form info using the PHP POST Method. Other suggestions are welcome. Should I do this by building a custom plugin?

A: You put files in your Child theme, how to add new template, take a look here https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/#Custom_Page_Template, and here also
http://www.carriedils.com/custom-page-template-genesis/


text:
Q: creating map report in SSRS. In which on click of particular area it should go to that area map in same report I want to create map report of us state. When I click on perticular state  it should display only that state in same report.
Can somebody help me.
Thanks


text:
Q: Why do rubber duck antennas have this metal part, while other antennas do not? If you open up a rubber duck antenna, it usually has a wire inside, plus a crimped on piece of metal, like this:

Other antennas, like those on an RC receiver do not have this second metal part:

Both of these antennas are 2.4ghz, why does one require this metal part where the other does not?
Also, if the metal tube forms part of a dipole, then how is it electrically different than the shield it's covering? I think they're connected. Wouldn't it do nothing that the shield isn't already doing?

A: The cutaway picture looks like a coaxial sleeve antenna.  Section 3 in the linked reference discusses this type of antenna.
edit: also see figure a on page 11 (assymetrically-fed sleeve dipole)

A: I found a source, that seems to answer my question.
https://www.rchelicopterfun.com/rc-antenna.html
The "whisker" type antenna is a linear monopole.
The sleeved antenna is an "assymetrically-fed sleeve dipole" (as AlmostDone pointed out).
According to the link:

Since the transmitter is transmitting the RF as a sinusoidal wave, it needs both poles as it alternates between positive and negative voltage for improved efficiency. If the transmitter only had a monopole, roughly half the power would be transmitted. Lost efficiency...

This is the "practical" answer that I was looking for (if it's correct).


text:
Q: Splitting a column with float numbers and add both int and decimal parts in a new column I have a column (version number) with more than 200k occurences as float for instance 1.2, 0.2 ...
I need to sum both sides of the floating number into a new column (total version), so that it gives me in the example 3, 2. Just integer numbers
Any advice?

A: Here is a solution that should be very easy to understand. I can make a oneline also you want to have that.
mylist = [1.3, 2.6, 3.1]

number = 0
fractions = 0

for a in mylist:
    (a,b)=str(a).split('.')
    number = number + int(a)
    fractions = fractions + int(b)

print ("Number: " + str(number))
print ("Fractions: " + str(fractions))

This gives:
Number: 6
Fractions: 10

A: Do not use str(x).split('.') !
The one comment and the two other answers are currently suggesting to get the integer and fractional parts of a number x using
i,f = (int(s) for s in str(x).split('.'))

While this does give a result, I believe it is a bad idea.
The problem is, if you expect a meaningful result, you need to specify the precision of the fractional part explicitly. "1.20" and "1.2" are two string representations of the same number, but 20 and 2 are two very different integers. In addition, floating-point numbers are subject to precision errors, and you could easily find yourself with a number like "1.19999999999999999999999", which is only a small rounding error away from "1.2", but results in a completely different result with this str(x).split('.') approach.
One way to avoid this chaotic behaviour is to set a precision, ie, a number of decimal places, and stick to it. For instance, when dealing with monetary values, we're used to talk about cents; although 1.5€ and 1.50€ are technically both valid, you'll always hear people say "one euro fifty" and never "one euro five". If you hear someone say "one euro oh five", it actually means 1.05€. We always add exactly two decimal places.
With this approach, there is no chaotic behaviour of 1.2 becoming (1,2) or (1,20) or (1,1999999999). If you fixed the number of decimal places to 2, then 1.2 will always map to (1,20) and that's that.
A more standard way
Here are two standard ways of getting the integer and fractional parts of a number in python:
x = 1.20

# method 1
i = int(x)
f = x - i
# i = 1 and f = 0.2; i is an int and f a float

# method 2
import math
f, i = math.modf(x)
# i = 1.0 and f = 0.2; i and f are both floats

(EDIT: There is also a third method, pandas' divmod function. See user2314737's answer.)
Once you've done that, you can turn the fractional part f into an integer by multiplying it with the chosen power of 10 and converting it to an integer:
f = int(f * 100)
# f = 20

Finally you can apply this method to a whole list:
data = [13.0, 14.20, 12.299, 4.414]

def intfrac_pair(x, decimal_places):
  i = int(x)
  f = int((10**decimal_places) * (x - i))
  return (i, f)

data_as_pairs = [intfrac_pair(x, 2) for x in data]
# = [(13, 0), (14, 20), (12, 30), (4, 41)]

sum_of_integer_parts    = sum(i for i,f in data_as_pairs)  # = 43
sum_of_fractional_parts = sum(f for i,f in data_as_pairs)  # = 91

A: The following should work:
df['total_number']=[sum([int(i) for i in str(k).split('.')]) for k in df.version_number]

A: You can use divmod on the column
df = pd.DataFrame([1.2, 2.3, 3.4, 4.5, 0.1])

df
#      0
# 0  1.2
# 1  2.3
# 2  3.4
# 3  4.5
# 4  0.1

df['i'], df['d'] = df[0].divmod(1)

df
# Out:
#      0    i    d
# 0  1.2  1.0  0.2
# 1  2.3  2.0  0.3
# 2  3.4  3.0  0.4
# 3  4.5  4.0  0.5
# 4  0.1  0.0  0.1

To sum row-wise as integers (a precision is needed, here I use p=1 assuming the original floats contain only one decimal digit) :
p = 1
df['s'] = (df['i']+10**p*df['d'].round(decimals=p)).astype(np.int)

df
# Out:
#      0    i    d  s
# 0  1.2  1.0  0.2  3
# 1  2.3  2.0  0.3  5
# 2  3.4  3.0  0.4  7
# 3  4.5  4.0  0.5  9
# 4  0.1  0.0  0.1  1

Sum by columns:
df.sum()
# Out:
# 0    11.5
# i    10.0
# d     1.5

Note: this will only work for positive integers as for instance divmod(-3.4, 1) returns (-4.0, 0.6).

A: Thank you all guys. I finally managed in a quite stupid, but effictive way. Before splitting, I transformed it to a string:
Allfiles['Version'] = Allfiles['Version'].round(3).astype(str)

Note that I rounded to 3 digits because a number like 2.111 was transformed to 2.11099999999999999999
Then I just did the split, creating a new column for minor versions (and having the major in the original colum
Allfiles[['Version', 'minor']] = Allfiles['Version'].str.split('.', expand=True)

Then I converted again both files into integers and sum both in the first column.
Allfiles['Version'] = Allfiles['Version']+Allfiles['minor']

(My dataframe name is Allfiles and the column version, as you can imagine.


text:
Q: AttributeError: type object 'DatasetV2' has no attribute 'from_tensor' I am learning Tensorflow 2.0 and I am getting an error as I run the following code:
data = np.random.randint(0,10, (3,4))
dataset1 = tf.data.Dataset.from_tensor(data)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-38-9873d7e2b8bc> in <module>()
----> 1 dataset1 = tf.data.Dataset.from_tensor(data)
AttributeError: type object 'DatasetV2' has no attribute 'from_tensor'

The same here:
e= tf.data.Dataset.from_element(10)
AttributeError: type object 'DatasetV2' has no attribute 'from_element'

But I can run the code:
dataset = tf.data.Dataset.range(10)

without a problem.

A: for your case tf.Data can be created in two possible ways which are tf.data.Dataset.from_tensors and tf.data.Dataset.from_tensor_slices.
tf.data.Dataset.from_tensors will Create a Dataset with a single element, comprising the given tensors. Below is the example by taking your sample input.
data = np.random.randint(0,10, (3,4))
dataset = tf.data.Dataset.from_tensors(data)
for i in dataset.take(-1):
  print(i)

#Print output
tf.Tensor(
[[1 4 0 2]
 [6 3 5 6]
 [4 2 9 6]], shape=(3, 4), dtype=int64)

You can see it has created a single tensor of the given shape.
tf.data.Dataset.from_tensor_slices as the name says it creates a slices of tensors.
The given tensors are sliced along their first dimension. This operation
preserves the structure of the input tensors, removing the first dimension
of each tensor and using it as the dataset dimension. All input tensors
must have the same size in their first dimensions.
dataset2 = tf.data.Dataset.from_tensor_slices(data)
for i in dataset2.take(-1):
  print(i)

#Print Output

tf.Tensor([1 4 0 2], shape=(4,), dtype=int64)
tf.Tensor([6 3 5 6], shape=(4,), dtype=int64)
tf.Tensor([4 2 9 6], shape=(4,), dtype=int64)

You can see it has created 3 tensors by slicing along first dimension of data of shape (3,4).


text:
Q: Get the coordinates of detected words using pytesseract Am making a digital assistant as final year project and I want to automate the browser tab by getting title of tab including the location of the detected words and use the coordinates to click the tab. I tried this answers I found here but not what I needed.
from pytesseract import *
from PIL import ImageGrab

pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'

while True:
   cap = ImageGrab.grab(bbox=(0, 0, 1182, 34))  # bounding box of the browser tab bar

   text = pytesseract.image_to_data(cap, output_type=Output.DICT)
   print(text)
    data = {}
    for i in range(len(text['line_num'])):
        txt = text['text'][i]
        block_num = text['block_num'][i]
        line_num = text['line_num'][i]
        top, left = text['top'][i], text['left'][i]
        width, height = text['width'][i], text['height'][i]
        if not txt == '' or txt.isspace():
            tup = (txt, left, top, width, height)
            if block_num in data:
                if line_num in data[block_num]:
                    data[block_num][line_num].append(tup)
                else:
                    data[block_num][line_num] = [tup]
            else:
                data[block_num] = {}
                data[block_num][line_num] = [tup]
    linedata = {}
    idx = 0
    for _, b in data.items():
        for _, i in b.items():
            linedata[idx] = i
            idx += 1
line_idx = 1
for _, line in linedata.items():
    xmin, ymin = line[0][1], line[0][2]
    xmax, ymax = (line[-1][1] + line[-1][3]), (line[-1][2] + line[-1][4])
    print(f'line{line_idx}, {xmin}, {ymin}, {xmax}, {ymax}, {txt}')
    line_idx += 1

I need the title of each tab and their coordinates. Am pretty confident that pytesseract.image_to_data() is what I need but don't know how to extract the information that need


text:
Q: How to find all edges from Root node in recursive way? There is a list which contains the following data about tree edges,
alist=[[Root, A],[Root, B],[Root,C],[A,D],[A,E],[D,F]...[]]

I want to find out all paths from 'Root' node to leaf node. Also, some edges in alist can never be traveled from 'Root' node.
I prefer to use recursion. Could someone give me a tip for that?
[Edit]
I expect the output just like alist, but all orphan edges are deleted.


text:
Q: Vue.js FullCalendar v5 component - events not displaying Recently we have upgraded our FullCalendar component in our Vue.js project from version 4.4.2 to version 5.9.0. However, we have issues with events not displaying. Since I couldn't find why that is in our original file, I have decided to start building calendar in an entirely new file, build the calendar step-by-step in order to hopefully find the error. However, even in this new file, I can't get events to display, and at this point I am completely lost on what am I doing wrong. In the console, I can see the array of events, but I can't get them to be displayed on the calendar.
Here is the code:
<template>
    <b-container fluid @click="logEvents">
        <VueFullCalendar :options="calendarOptions" style="width: 100%; height: 100%;" />
    </b-container>
</template>

<script>
import VueFullCalendar from '@fullcalendar/vue'
import resourceTimeGrid from '@fullcalendar/resource-timegrid'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import listPlugin from '@fullcalendar/list'

export default {
  components: {
    VueFullCalendar
  },
  name: 'Calendar',
  data: function () {
    return {
      calendarOptions: {
        plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin, resourceTimeGrid, listPlugin],
        headerToolbar: {
          left: 'prev,next today',
          center: 'title',
          right: 'dayGridMonth,resourceTimeGridWeek,resourceTimeGridDay'
        },
        initialView: 'resourceTimeGridWeek',
        slotMinTime: '09:00:00',
        slotMaxTime: '21:30:00',
        allDaySlot: false,
        events: [
          {
            title: 'Event 2',
            start: '2021-09-28T09:00',
            end: '2021-09-28T10:30'
          },
          {
            title: 'Event 1',
            start: '2021-09-28T11:00',
            end: '2021-09-28T13:00'
          }
        ]
      }
    }
  },
  methods: {
    logEvents () {
      console.log(this.calendarOptions.events)
    }
  }
}
</script>

<style>

@import '~@fullcalendar/list/main.min.css';
</style>

And ideas on what I am doing wrong?
Thank you so much in advance.
Kind regards.

A: It is all because of date and time format. So, once you manage it, it will be displayed.
events:
[
    { id: 10, title: "All day event", date: new Date('2022-02-25')}
    { id: 20, title: "Timed event", start: new Date(),allDay:true },
    { id: 30, title: "Timed event", start: new Date(),allDay:true },
],


text:
Q: Extracting the graph of Keys in nested Associations Related to this q: Extract all Values from nested Association
How to extract the direct graph of all Keys in nested Associations?
Mapping Keys doesn't seem to get at the deeper branches:
as = <|"a" -> <|"c" -> <|"e" -> 2|>, "d" -> 4|>, <|"b" -> 5|>|>

Then
as // Map[Keys, #, Infinity] &  /* Quiet
<|"a" -> {"c", "d"}, "b" -> Keys[5]|>

To limit application of keys to only Associations, can define the handler:

keys[as_Association] := Keys[as]; keys[expr_] := expr

But even so:
as // Map[keys, #, Infinity] &

<|"a" -> {"c", "d"}, "b" -> 5|>

Why isn't "e" included?
While the Replace based answer in the Q linked above works for Values, it does not work for Keys:
as //. a_Association :> Keys[a] // Flatten

{"a", "b"}

A: Associations are very different from mere lists of rules. For instance, they are atomic, so Replace cannot dive into them.
The replacement
as //. a_Association :> Keys[a] // Flatten

with  does work because one uses //. (a.k.a. ReplaceRepeated): After the first replacement, the outer association was removed and so the next round of replacement can attack the next level. Try ReplaceAll instead and you will see that it stops after the first level:
as /. a_Association :> Keys[a]

The following however works:
ToGraph[a_Association] := Graph[Flatten[{
     Map[x \[Function] DirectedEdge["root", x], Keys[a]],
     toGraph[a]
     }],
   VertexLabels -> "Name",
   GraphLayout -> "LayeredEmbedding"];

toGraph[a_Association] := {
   MapThread[
    {key, value} \[Function] If[AssociationQ[value],
      {Map[x \[Function] DirectedEdge[key, x], Keys[value]], toGraph[value]},
      {DirectedEdge[key, value]}
      ],
    {Keys[a], Values[a]}
    ]
   };

as2 = <|"a" -> <|"c" -> <|"e" -> 2, "f" -> 3|>, "d" -> 4|>, <|"b" -> 5|>|>
ToGraph[as2]

This is a slightly modified version of the code.
SetAttributes[AssociationToGraph, HoldAll];
AssociationToGraph[a_] := Module[{toGraph, data},
   toGraph[b_] := {
     KeyValueMap[{key, value} \[Function] If[AssociationQ[value],
        {
         Map[x \[Function] DirectedEdge[key, x], Keys[value]],
         toGraph[value]},
        {}
        ],
      b]
     };
   data = Flatten[{Map[
    x \[Function] DirectedEdge[ToString[Unevaluated[a]], x], Keys[a]],
    toGraph[a]
    }];
   Graph[data, VertexLabels -> "Name", GraphLayout -> "LayeredEmbedding"]
   ] /; AssociationQ[a]

as2 = <|"a" -> <|"c" -> <|"e" -> 2, "f" -> 3|>, "d" -> 4|>, <|"b" -> 5|>|>
AssociationToGraph[as2]


text:
Q: keeping 2 tables with 2 identical columns in sync Okay So I am relatively new to excel but have worked with mysql databases alot over the years I'm looking for a way to have a master table which is basically a master schedule sort of like so

    |  LOT  | task1 | task2 | task3 | task4 | task 5 |
    |   3   |mar-10 | mar-12| mar-15| mar-19|  mar-20|
    |   7   |mar-16 | mar-18| mar-22| mar-25|  mar-28|

and i basically want on a seperate tables to be automatically generated based on above table:

    |  LOT   |other info| task1 |
    |    3   |    bla   |mar-10 |
    |    7   |    bffd  |mar-16 |

    |  LO T  |  other   | task2 |
    |    3   |  this    | mar-12|
    |    7   |  that    | mar-18|

This seems like It should be really easy to do but from what Ive deemed its not possible with a pivot table It should some how be possible with data relationships im guessing but can't figure out exactly how
any help or insight would be greatly appreciated

A: Let's pretend this is a query table.

*

*The Master Sheet, should be the first tab.

*Set up a new sheet (or tab) for each task and name the tab, to
correspond to the task name.

*The Master, will directly link to each Task's task.

Note: Excel is smart. If you copy formula, in Master tab cell C2, and paste it to C3, or paste it to C3:C50, Excel will also link it to the matching offset in the sheet its linked to.
Or visa versa:

*

*The Master Sheet, should be the first tab.

*Set up a new sheet (or tab) for each task and name the tab, to
correspond to the task name.

*The Tasks, will directly link to the Master tab.


text:
Q: Restricting user access on sorcery i have a rails app with sorcery
everything work .
the problem is when edit a user like :
http://localhost:3000/users/1/edit
its work fine , but when i change the user id to 2 or 3 ..
i can update all users data
how can i restrict the edit page only if the current user is the one that logged in
here is my controller :
skip_before_action :require_login, only: [:new, :create, :show]

def new
 @user = User.new
end

def create
@user = User.new(user_params)
if @user.save
  auto_login(@user)
  flash[:info] = "Welcome."
  redirect_to root_url
else
  render 'new'
end
end

def edit
  @user = User.find(params[:id])
end

def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
  flash[:success] = "Profile updated"
  redirect_to @user
else
  render 'edit'
end
end

def show
 @user = User.find(params[:id])
end

private

def user_params
 params.require(:user).permit(:email, :password, :password_confirmation)
end

A: you can also do something like this
before_action :edit_rights?, only: [:update, :edit]

private
def edit_rights?
  @user = User.find(params[:id])
  redirect_to(root_path) unless current_user == @user
end

you won't need @user = User.find(params[:id]) in both update and edit actions then

A: There are (at least) two ways to do that. First and straightforward is detailed in another answer, fine-tune your controller.
A less obvious way is to create a singular resource and its own controller. In routes that could look like:
resource :profile, only: [:show, :edit, :update]
# generates:
# /profile (GET, PATCH, PUT)
# /profile/edit (GET)

Then create a controller that is responible solely for user's own profile and operates only on current_user.
Yes, it's okay for one model to have multiple controllers, if your model should behave really differently in different parts of your app.
Why would you do that?

*

*User's own profile could show much more information than is available publicly, you can lay it out in a separate view

*No "access denied" errors, as the resource is auto-selected via current_user, all you need is ensure the user is logged in in the entire controller.


text:
Q: material-ui TextField not clearing Currently using this version of material-ui: "@material-ui/core": "^4.2.1".
This is the piece of code that is not consistent with the examples provided on the website:
<div>
    <TextField id="outlined-search" label="Search field" type="search" variant="outlined" size="small"/>
</div>

On my application it looks like this: no x icon in TextField
On the example code-sandbox it looks like this: x icon present in TextField
Not quite sure what the problem is, as it seems quite straightforward. Any help would be much appreciated.

A: With regards to the actual component API, its working perfectly.
Try to update your dependencies since the latest version of material-ui is 4.8.2.
you can update them by using npm update or yarn upgrade.
If that does not fix the issue there seems to be some style that is not loading in your application causing the clear button to disappear. going to need your code to diagnose further.


text:
Q: secure a API request form? Ok I have the following php:
    <?php

 //function to return nice url's for our pdf's
 function seoUrl($string) {
    //Lower case everything
    $string = strtolower($string);
    //Make alphanumeric (removes all other characters)
    $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
    //Clean up multiple dashes or whitespaces
    $string = preg_replace("/[\s-]+/", " ", $string);
    //Convert whitespaces and underscore to dash
    $string = preg_replace("/[\s_]/", "-", $string);
    return $string;
}
//Set up our POST variables
$name = $_POST['name'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$zipcode = str_replace(' ', '',$_POST['zipcode']);
//Store your XML Request in a variable
    $input_xml = urlencode('<ExternalReturnLabelRequest>
                            <CustomerName>'.$name .'</CustomerName>
                            <CustomerAddress1>'.$address1.'</CustomerAddress1>
                            <CustomerAddress2>'.$address2.'</CustomerAddress2>
                            <CustomerCity>Washington</CustomerCity>
                            <CustomerState>DC</CustomerState>
                            <CustomerZipCode>'.$zipcode.'</CustomerZipCode>
                            <LabelFormat>NOI</LabelFormat>
                            <LabelDefinition>Zebra-4X6</LabelDefinition>
                            <ServiceTypeCode>020</ServiceTypeCode>
                            <AddressOverrideNotification>false</AddressOverrideNotification>
                            <CallCenterOrSelfService>Customer</CallCenterOrSelfService>
                            <AddressValidation>false</AddressValidation>
                            </ExternalReturnLabelRequest>');

//start Curl tried file_get_contents but to no avail..
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,"https://returns.usps.com/Services/ExternalCreateReturnLabel.svc/ExternalCreateReturnLabel?externalReturnLabelRequest=".$input_xml);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$query = curl_exec($curl_handle);
curl_close($curl_handle);

//decode the response this will fail if nothing returned
$pdfdecode = base64_decode($query);

if($pdfdecode != false){

    $urlfriendlyname = seoUrl($name);
    $myFile = "labels/labelfor".$urlfriendlyname.$zipcode.".pdf";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh, $pdfdecode);
    fclose($fh);

    header("Location: http://thedarkroom.com/wp-content/themes/thedarkroom2012/".$myFile);
    exit();

    /*
    MID 201198
    */
}else{
    header("Location: http://thedarkroom.com/label/?labelerror=".$query);
    exit();
}
echo "
";

var_dump($pdfdecode);
var_dump($query);

echo "
";

and this html:
            <form method="POST" action="<?php echo get_template_directory_uri(); ?>/get_labels.php" >
                <fieldset id="labelfields">
                    Name

                    <input name="name" type="text" placeholder="Name"/>

                    Address Line one
                    <input name="address1" type="text" placeholder="Address line one"/>

                    Address Line two
                    <input name="address2" type="text" placeholder="Address line two"/>

                    Zip code
                    <input name="zipcode" type="text"  placeholder="Zip Code"/>

                    State
                    <input name="CustomerState" type="text"  placeholder="State"/>

                    City
                    <input name="CustomerCity" type="text"  placeholder="City"/>

                    <input type="submit" value="Create Label" />
                </fieldset>
            </form>

what are the best practises for securing this?
I've gone for strip tags...

A: All data that comes to your server must be checked and sanitized. Always. No exception.
Escape potentially dangerous characters. The specific characters you should be cautious with vary depending on the context in which the data is used and the server platform you employ, but all server-side languages have functions for this.
Limit the incoming amount of data to allow only what's necessary.
Sandbox uploaded files (store them on a different server and allow access to the file only through a different subdomain or even better through a fully different domain name).
For preventing cross-site forgeries please refer this article
http://shiflett.org/articles/cross-site-request-forgeries


text:
Q: How to fix the error: TypeError: logger.logSuccess is not a function I am developing a back-end service using Spring mvc and the front-end client is in angularjs. I am trying to send a message to the user on the front-end upon successful upload of a file but the error above keeps popping up in my console. Where do I need to correct in my code:?
Java:
    @Override
    public CompasResponse UploadClaim(String filePath) {
        try
        {
            ArrayList<Claim>list = getClaimsExcel(filePath);
             if (uploadClaims(list))
             {

                return new CompasResponse(200, "Uploaded Successfully");
            } else {
                return new CompasResponse(201, "Oops! No Records to upload");
            }
        }
        catch(IOException e) { e.printStackTrace(); return new CompasResponse(201, "Error. Could not process uploaded document."); }

    }

Javascript:
uploadclaimApp.controller('uploadclaimCtrl', //['$scope', '$filter',
'uploadclaimSvc','organizationSvc', '$rootScope',
//'blockUI', 'logger', '$location','$http',
//function ($scope, $filter, uploadclaimSvc,organizationSvc, $rootScope,
blockUI, logger, $location,$http)
    ["$scope", "$filter", "uploadclaimSvc", "localStorageService",
"$rootScope", "blockUI", "logger", "$location", function ($scope, $filter,
uploadclaimSvc, $rootScope, blockUI, logger, $location, localStorageService)
        $scope.uploadClaim = function()
    {
        console.log('uploading: ', $scope.myFile);
        uploadclaimSvc.saveFile($scope.myFile, $scope.orgId).success(function(response){
            if (response.respCode == 200) {
                logger.logSuccess("Great! The service information was saved successfully.")
                } else  {
                    logger.logWarning(response.respMessage);
                }
        });
    }
}]);

uploadclaimApp.service('uploadclaimSvc', function($http){
    this.saveFile = function (file,orgId) {
            console.log("uploading file...");
            var fd = new FormData();
            fd.append('file', file);
            fd.append('orgId',orgId);
            return $http({
                url: '/compas/rest/transaction/uploadclaim',
                method: 'POST',
                transformRequest: angular.identity,
                headers: { 'Content-Type': undefined },
                data: fd
            });
        };
});

I expect a message to be displayed to the user on successful/unsuccessful upload of a file

A: Just like Error say.logger.logSuccess is not defined. Maybe you can use the ng-serviece $log to instead.


text:
Q: Pointer to base class and private inheritance The following simple example will produce a compiler error, since I accidently use private inheritance:
main.cpp:21: error: 'A' is an inaccessible base of 'B'
class A
{

};

class B : /*ups forgot that -> public*/ A
{

};

int main(int , char *[])
{
    A* test = new B;

    return 0;
}

Could you help me and explain what exactly is inaccessible in the base class and why it is needed in the conversion from B* to A*?

A:
Could you help me and explain what exactly is inaccessible in the base class and why it is needed in the conversion from B* to A*?

Ouside of B and the friends of B, the simple fact that B is an A is not visible. This is not hiding a member variable or member function, but hiding the relationship itself. That is why from main you cannot bind the result of new B with a pointer to A, because as far as main is concerned, B is not an A (in the same way that you could not do A * p = new unrelated;)
As to why it is needed, the answer it exactly the same: because without access to the relationship, the compiler does not know (well, it knows, but will not tell you) how to obtain a pointer to the A subject inside B, because as far as it can see within that context there is no relationship between A and B at all.

A: The conversion from B* to A* is inaccessible, because the base-class subobject is private. When you convert B* to A*, you return the pointer to the base-class subobject. The latter must be accessible for the conversion to be accessible. In any function that is friend to B the conversion becomes accessible. By the way, you can always access the conversion by an explicit cast.
A* p = (A*)(new B);

Note that in some cases just accessible conversion is required, but in some cases it is required that A be a public (stronger than accessible) base of B. For example, when you try to catch an exception of type B with catch(A&) - it is required that A be a public base class of B.

A: Private inheritance means that for everyone except B (and B's friends), B is not derived from A.

A: Since the reference or pointer of Base class can not point to object of inherited class, does it mean that protected and private inheritance is nothing to do with polymorphism?

A: Since B is inherited from A, the default constructor of A would be called before the constructor of B. But because it is private and not inherited to B, you get a compiler error.

A: Public/private inheritance is equivalent to public/private member variable.
The result of the conversion is a reference to the base class subobject of the derived class object.
I think the accessibility means the accessibility of the base class subobject of the derived class object.For client,only if we ues public inheritance,the base class subobject is accessible.For the member function of derived class,no matter we use public/protected/privaye inheritance, the base class subobject is accessible.
class A{

};

class B: private  A{
private:
    int* m_pb;
public:
    B(){m_pb=new int(10)};
    void func()
    {
        A* pa= new B;      //OK
        int *pmb = m_pb;   //OK
    }

};
int main()
{
    B* pb = new B;
    A* pa= pb;             // inaccessible
    int *pmb = pb->m_pb;   // inaccessible
}

OK.I means that public/private inheritance is equivalent to public/private member variable.
reference:
http://pic.dhe.ibm.com/infocenter/ratdevz/v8r5/index.jsp?topic=%2Fcom.ibm.tpf.toolkit.compilers.doc%2Fref%2Flangref_os390%2Fcbclr21011.htm


text:
Q: Can not import matplotlib with pyenv ipython notebook I am a ruby developer and I've started learning python for a project. I installed pyenv, pyenv virutualenv, ipython, notebook, matplotlib. Everything worked fine except the part I called
import matplotlib.pyplot as plot

Then I 've got this error from notebook:
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-1-08ad587cbf6a> in <module>()
----> 1 import matplotlib.pyplot as plot

/Users/ilab/.pyenv/versions/2.7.11/envs/mlcoursera/lib/python2.7/site-packages/matplotlib/pyplot.py in <module>()
112
113 from matplotlib.backends import pylab_setup
--> 114 _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
115
116 _IP_REGISTERED = None

/Users/ilab/.pyenv/versions/2.7.11/envs/mlcoursera/lib/python2.7/site-packages/matplotlib/backends/__init__.pyc in pylab_setup()
 30     # imports. 0 means only perform absolute imports.
 31     backend_mod = __import__(backend_name,
---> 32                              globals(),locals(),[backend_name],0)
 33
 34     # Things we pull in from all backends

/Users/ilab/.pyenv/versions/2.7.11/envs/mlcoursera/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py in <module>()
 22
 23 import matplotlib
---> 24 from matplotlib.backends import _macosx
 25
 26

RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are Working with Matplotlib in a virtual enviroment see 'Working with Matplotlib in Virtual environments' in the Matplotlib FAQ.

Can anyone help me to get this to work?
ps: I am on python 2.7.1 with pyenv.

A: Matplotlib expects a Framework install on OS X in order to manipulate GUI elements.
You can install Framework versions with a command like this knowing your python version and your environment name :
env PYTHON_CONFIGURE_OPTS="--enable-framework CC=clang" pyenv virtualenv <python_version> <env_name>


text:
Q: PHP - regex to allow letters and numbers only I have tried:
preg_match("/^[a-zA-Z0-9]", $value)

but im doing something wrong i guess.

A: As the OP said that he wants letters and numbers ONLY (no underscore!), one more way to have this in php regex is to use posix expressions:
/^[[:alnum:]]+$/

Note: This will not work in Java, JavaScript, Python, Ruby, .NET

A: You left off the / (pattern delimiter) and $ (match end string).
preg_match("/^[a-zA-Z0-9]+$/", $value)

A: *

*Missing end anchor $

*Missing multiplier

*Missing end delimiter

So it should fail anyway, but if it may work, it matches against just one digit at the beginning of the string.
/^[a-z0-9]+$/i

A: 1. Use PHP's inbuilt ctype_alnum
You dont need to use a regex for this, PHP has an inbuilt function ctype_alnum which will do this for you, and execute faster:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo "The string $testcase consists of all letters or digits.\n";
    } else {
        echo "The string $testcase does not consist of all letters or digits.\n";
    }
}
?>

2. Alternatively, use a regex
If you desperately want to use a regex, you have a few options.
Firstly:
preg_match('/^[\w]+$/', $string);

\w includes more than alphanumeric (it includes underscore), but includes all
of \d.
Alternatively:
/^[a-zA-Z\d]+$/

Or even just:
/^[^\W_]+$/

A: try this way .eregi("[^A-Za-z0-9.]", $value)


text:
Q: The contraction of an ideal in a ring homomorphism Let $f:R\rightarrow{S}$ be a ring homomorphism. Let $I$ be an ideal in $R$. The extension $I^e=f(I)S$. Let $A$ be an ideal in $S$. The contraction $A^c=f^{-1}(A)$ is always an ideal in $R$.
But I have read that if $D$ is a subring of a ring $E$ and $J$ is an ideal in $E$ then the contaction of $J$ is $J^c=J\cap{D}$. I am looking whether there is any connection between these two definitions. Can we say that for the ideal $A$ in $S$, the contraction $A^c=f^{-1}(A)=A\cap{R}$?
Would you help me, please? Thank you in advance.

A: In the case $D$ is a subring of $E$, then the homomorphism under consideration is the inclusion map $i\colon D\to E$, $i(x)=x$.
If $J$ is an ideal of $E$, then
$$
J^c=\{x\in D:i(x)\in J\}=D\cap J
$$
by definition of intersection.