text:
Q: What is the significance of using a statement like : int a = 12L; Statement like this compiles as well. Please let me know, what can be the intention behind using such statements ?

A: The L postfix is only useful when you need to define a long constant which you cannot really define otherwise, e.g.:
long l = 10000000000; // will not compile as the number does not fin into long type
long l = 10000000000L; // compiles and you have to explicitly define the L

In your case it does not matter whether you use L or not.

A: With a line like this, there's no point at all. 12L is a long integer, and so the constant has a long type, but it can always be represented by an int. C guarantees that an int must be equal or less than the length of a long.
By default the constant 12 is an int -- any constant that requires a long will automatically be long. In this case the constant is automatically narrowed to an int in the assignment. Remember that the assignment operator is not a bit-for-bit copy, it often involves implicit type conversions.
The usual case for a suffix like this is to force arithmetic with a wider type than is necessary in each part of the expression, e.g.
long x = (1000L * a * b);

If a and b are ints and the L is not used, the expression could overflow before it reaches x.

A: int a = 12L;

Initialize a long and assign it to a

A:
int a = 12L;

returns :
 java.lang.Error: Unresolved compilation problem:
        Type mismatch: cannot convert from long to int

long a = 10000000000;

returns :
java.lang.Error: Unresolved compilation problem:
    The literal 10000000000 of type int is out of range

So you can use it as long a = 10000000000L;

A: It will be implicitly casted:
int a = 12L;   is equivalent to   int a = (int)12L;

Btw: In my IDE (Eclipse Kepler) it won't compile with int a = 12L;.


text:
Q: Auto-detect new controllers to add actions to menu I am developing a Rails 3 application that will have an admin area with a side menu (similar to the Wordpress admin menu.)
I was wondering what the best method would be to have rails automatically detect when a new controller is added to the admin and add the appropriate actions to the menu.

A: Anything about 'Admin' needs to be done? It's best that you use Active Admin
It will take care of your problem too. I would highly recommend that you check it out.

A: You can get a list of controllers with this code:
Rails.application.routes.routes.map do |route| route.defaults[:controller] end

Inspect the output, as it will give you duplicate results, filter them and you can use it.
As a side note: are you sure you want all controllers in your admin interface? It makes no sense, maybe you should try Active Admin, has suggested earlier.

redpajama_set_name: RedPajamaStackExchange


text:
Q: This filter is not returning expected result function get20(arr){
 let result = arr.filter((theArtist) => {
   let birth = Number(theArtist.years.splice(0,3))
   let death = Number(theArtist.years.splice(7,10))
   return birth >= 1900 && death <= 2000;
  })
 return result;
}

This keeps giving me the error "theArtist.years.splice is not a function" I do not understand why it isn't taking the first four and last four letters of the "years" string and turning them into numbers. the years string looks like "1971 - 1984"

A: Splice is a method for arrays, not strings. Try this:
years = theArtist.years.split('')
let birth = Number(years.splice(0,4))
let death = Number(years.splice(7,4))

Alternatively, use substring.
let birth = Number(theArtist.years.substring(0,4))
let death = Number(theArtist.years.substring(7,11))

A: You should use substring on strings (splice is a similar function for arrays). Also note your indexes were off by 1 !

var years = "1971 - 1984";
let birth = Number(years.substring(0,4))
let death = Number(years.substring(7,11))
console.log(birth,death)

A: Use slice instead splice:
'1971 - 1984'.slice(0,4) // '1971'
'1971 - 1984'.slice(7,11) // '1984'


text:
Q: OpenCV: subtract same BGR values from all pixels I have some BGR image:
cv::Mat image;

I want to subtract from all the pixels in the image the vector:
[10, 103, 196]

Meaning that the blue channel for all the pixels will be reduced by 10, the green by 103 and the red by 196.
Is there a standard way to do that, or should I run for loops over all the channels and all the pixels?

A: suppose we have image that all channels filled with zero and for instance it's dimension is 2x3
cv::Mat image = cv::Mat::zeros(2,3,CV_32SC3)

output will be:
 [0, 0, 0, 0, 0, 0, 0, 0, 0;
  0, 0, 0, 0, 0, 0, 0, 0, 0]

then if we want to add or subtract a singleton variable, then we can use cv::Scalar
1- suppose we want to add 3 in blue channel:
image = image + Scalar(3,0,0);  // the result will be same as image=image+3;

with above code our matrix is now:
[3, 0, 0, 3, 0, 0, 3, 0, 0;
 3, 0, 0, 3, 0, 0, 3, 0, 0]

2- if you want to add to another channel you can use second or third argument(or forth) of cv::Scalar like below
image = image +Scalar(3,2,-3);

output will be
[3, 2, -3, 3, 2, -3, 3, 2, -3;
 3, 2, -3, 3, 2, -3, 3, 2, -3]

Using cv::subtract
cv::Mat image = cv::Mat::zeros(2,3,CV_32SC3);
subtract(image,Scalar(2,3,1),image);

output
[-2, -3, -1, -2, -3, -1, -2, -3, -1;
 -2, -3, -1, -2, -3, -1, -2, -3, -1]


text:
Q: How can I use Conditional Formatting to colour cells on one sheet using information from another sheet? I need to make Google sheets calendar respond to a conditional formatting formula that takes data from each month's sheet into the yearly sheet. Basically, I want to enter information into the monthly sheets and have that week/day change colour on the yearly sheet. In the image examples, we booked a job in June from June 21-25. I have the Monthly sheets set up to highlight when something is booked. I would like the Yearly calendar sheet to reflect the same week highlighted. In the example, I have highlighted it manually as I haven't found a way to automate the process.
Can anyone help me, please?
https://docs.google.com/spreadsheets/d/1wc42B4REgbwtfTD1FDJGuxWllsG0Ptbm6sgc1HhFiWc/edit?usp=sharing


text:
Q: Java Spring Servlet cannot find Bean in another ApplicationContext I am new to Java Spring, so I may have some difficulties explaining my configurations.
I have a Java Spring Web Application that contains a Servlet that needs to access a Bean. However, the issue is the Bean is located in another common project xml file that gets loaded whenever the application get's loaded.
Project C
common-context.xml
<bean id="common-bean" ...>

CommonLoader.class
protected AbstractApplicationContext mContext;

public void start(String[] pArgs) {
   mContext = new ClassPathXmlApplicationContext("common-context.xml");
}

In another Project A, I have a servlet that needs to access common-bean, however, it is unable to find the bean.
Project A
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  ApplicationContext mAppContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

  for (String name : mAppContext.getBeanDefinitionNames()) {
    System.out.println(name);
  }
}

However, nothing gets found even though I know for a fact that common-bean is running due to the logs. My guess is because they are running in separate ApplicationContexts, they cannot talk to each other even though they are in the same Java application.
Is there any way for them to communicate or pass the bean directly to the servlet?


text:
Q: secure access to external web API .NET CORE I have two web APIs applications developed in .Net core. I need to import Json data from the second application to the first. However,I have a security issue. I need to secure the access to the external API. How should I securely  manage the connection between these two APIs.
For example, I need to secure the access to the URL in the code bellow => securely access to the covid API without another authentication.
PS: I'm using JWT token authentication in both applications
Best regards.

    using (var client = new HttpClient())
    {
      string url = string.Format("https://covid19.mathdro.id/api");
      var response = client.GetAsync(url).Result;

      string responseAsString = await response.Content.ReadAsStringAsync();
      result = JsonConvert.DeserializeObject<CovidResult>(responseAsString);
    }

A: If both APIs are protected by the same accessToken, then you can read the authorization header from the first request and pass it to the second request.
Something like this to read the header:
var authHeader = context.Request.Headers.Get("Authorization");

You should end up with authHeader equal to "Bearer ey...(a bunch of base64)"
Then add the auth header to the client:
var request = new HttpRequestMessage() {
RequestUri = new Uri("http://https://covid19.mathdro.id/api"),
    Method = HttpMethod.Get,
};

...

request.Headers.Authorization.Add(new AuthenticationHeaderValue(authHeader));
var task = client.SendAsync(request)


text:
Q: Python: Exporting Output to Google Sheets I wrote this web scraping program that extracts retail trading sentiment data for 26 forex pairs from IG markets.
The output in the console looks like:
AUD-CAD: 64% of client accounts are short.
AUD-CHF: 54% of client accounts are long.
AUD-JPY: 60% of client accounts are short.
AUD-NZD: 60% of client accounts are long.
AUD-USD: 53% of client accounts are short.
CAD-CHF: 56% of client accounts are long.
CAD-JPY: 56% of client accounts are long.
CHF-JPY: 68% of client accounts are short.
EUR-AUD: 68% of client accounts are long.
EUR-CAD: 65% of client accounts are short.
EUR-CHF: 66% of client accounts are long.
EUR-GBP: 53% of client accounts are short.
EUR-JPY: 57% of client accounts are short.
EUR-NZD: 55% of client accounts are long.
EUR-USD: 54% of client accounts are short.
GBP-AUD: 73% of client accounts are long.
GBP-CAD: 66% of client accounts are long.
GBP-CHF: 63% of client accounts are long.
GBP-JPY: 52% of client accounts are short.
GBP-NZD: 57% of client accounts are long.
GBP-USD: 59% of client accounts are short.
SPOT-FX-NZDCAD: 68% of client accounts are short.
NZD-CHF: 59% of client accounts are short.
NZD-JPY: 57% of client accounts are short.
NZD-USD: 72% of client accounts are short.
USD-CAD: 69% of client accounts are long.
USD-CHF: 79% of client accounts are long.
USD-JPY: 58% of client accounts are long.

I would like to export this data to a Google Sheet named "GsheetTest", but I'm stuck and
I have no idea how to do it.
Google API is enabled. I've created the credentials, got the service account json key.
I'm able to write simple text to this google sheet file "GsheetTest" using pygsheets and panda dataframe.
Here's the code:
import bs4, requests

def getIGsentiment(pairUrl):
    res = requests.get(pairUrl)
    res.raise_for_status()'

soup = bs4.BeautifulSoup(res.text, 'html.parser')
elems = soup.select('.price-ticket__sentiment')
return elems[0].get_text(" ", strip = True)

pair_list = ['aud-cad', 'aud-chf', 'aud-jpy', 'aud-nzd', 'aud-usd', 'cad-chf', 'cad-jpy',
             'chf-jpy', 'eur-aud', 'eur-cad', 'eur-chf', 'eur-gbp', 'eur-jpy', 'eur-nzd',
             'eur-usd', 'gbp-aud', 'gbp-cad', 'gbp-chf', 'gbp-jpy', 'gbp-nzd', 'gbp-usd',
             'spot-fx-nzdcad', 'nzd-chf', 'nzd-jpy','nzd-usd', 'usd-cad', 'usd-chf',
             'usd-jpy']
for i in range(len(pair_list)):
    retail_positions = getIGsentiment('https://www.ig.com/us/forex/markets-forex/ +(pair_list[i]))
    pair = pair_list[i]
    print(pair.upper() +': ' + retail_positions[0:32].rstrip() + '.')

A: If you have a list of strings and you want to write each string into single cell. which i think is how you want it.
import pygsheets
import numpy as np

pair_data = []  # data fro your code

gc = pygsheets.authorize()

# Open spreadsheet and then worksheet
sh = gc.open('GsheetTest')
wks = sh.sheet1
wks.wks.update_values('A1', pair_data)

A: First open json file in browser and find email address, now share spreadsheet with that email along with editing right, after that use following code..
#Import these libraries or pip install if not installed already
from oauth2client.service_account import ServiceAccountCredentials
import gspread
import bs4, requests
def getIGsentiment(pairUrl):
    res = requests.get(pairUrl)
    res.raise_for_status()'

soup = bs4.BeautifulSoup(res.text, 'html.parser')
elems = soup.select('.price-ticket__sentiment')
return elems[0].get_text(" ", strip = True)

pair_list = ['aud-cad', 'aud-chf', 'aud-jpy', 'aud-nzd', 'aud-usd', 'cad-chf', 'cad-jpy',
             'chf-jpy', 'eur-aud', 'eur-cad', 'eur-chf', 'eur-gbp', 'eur-jpy', 'eur-nzd',
             'eur-usd', 'gbp-aud', 'gbp-cad', 'gbp-chf', 'gbp-jpy', 'gbp-nzd', 'gbp-usd',
             'spot-fx-nzdcad', 'nzd-chf', 'nzd-jpy','nzd-usd', 'usd-cad', 'usd-chf',
             'usd-jpy']

#now you need auth and set scope

scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('path-to-your-json.json', scope)
#Auth
gc = gspread.authorize(creds)
sh = gc.open('Spread Sheet name You want to open')
worksheet = sh.add_worksheet('sheet to be added name', int(rows), int(columns))

for i in range(len(pair_list)):
    retail_positions = getIGsentiment('https://www.ig.com/us/forex/markets-forex/ +(pair_list[i]))
    pair = pair_list[i]
    foo = pair.upper() +': ' + retail_positions[0:32].rstrip() + '.'
    worksheet.insert_row(foo, 1)


text:
Q: Record speakers output with PyAudio I'm trying to record the output from my computer speakers with PyAudio.
I tried to modify the code example given in the PyAudio documentation, but it doesn't work.
Technically, there's no error. I obtain the file output.wav and I can open it, but there's no sound. On Audacity, I can only see a straight line.
What's going wrong?
import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

SPEAKERS = p.get_default_output_device_info()["hostApi"] #The part I have modified

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK,
                input_host_api_specific_stream_info=SPEAKERS) #The part I have modified

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

A: In case someone is still stumbling over this like me, I found a PyAudio fork to record the output on windows.
Explanation:
The official PyAudio build isn't able to record the output. BUT with Windows Vista and above, a new API, WASAPI was introduced, which includes the ability to open a stream to an output device in loopback mode. In this mode the stream will behave like an input stream, with the ability to record the outgoing audio stream.
To set the mode, one has to set a special flag (AUDCLNT_STREAMFLAGS_LOOPBACK). Since this flag is not supported in the official build one needs to edit PortAudio as well as PyAudio, to add loopback support.
New option:

"as_loopback":(true|false)

A: You can't record from an output stream as though it were input.  To record, you need to connect PyAudio to an input device, like a microphone.  At least that's the normal way to do things.
Try connecting to a microphone first, and see if you get anything.  If this works, then try doing something unusual.
As a small speedup to your iterations, rather than recording and looking at the file, it's often easier just to print out the max for a few chunks to make sure you're bringing in data.  Usually just watching the numbers scroll by and comparing them to the sound gives a quick estimate of whether things are correctly connected.
import audioop
mx = audioop.max(data, 2)
print mx

A: If you create an application on windows platform, you can use default stereo mixer virtual device to record your PC's output.
1) Enable stereo mixer.
2) Connect PyAudio to your stereo mixer, this way:
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
                channels = CHANNELS,
                rate = RATE,
                input = True,
                input_device_index = dev_index,
                frames_per_buffer = CHUNK)

where dev_index is an index of your stereo mixer.
3) List your devices to get required index:
for i in range(p.get_device_count()):
    print(p.get_device_info_by_index(i))

Alternatively, you can automatically get index by device name:
for i in range(p.get_device_count()):
    dev = p.get_device_info_by_index(i)
    if (dev['name'] == 'Stereo Mix (Realtek(R) Audio)' and dev['hostApi'] == 0):
        dev_index = dev['index'];
        print('dev_index', dev_index)

4) Continue to work with pyAudio as in the case of recording from a microphone:
data = stream.read(CHUNK)

A: I got to record my speaker output with pyaudio with some configuration and code from pyaudio's documentation.
Code
"""PyAudio example: Record a few seconds of audio and save to a WAVE file."""

import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

Configuration
First, with pulseaudio running, create a loopback device:
pacmd load-module module-loopback latency_msec=5

Then set the default (fallback) to this loopback device in pavucontrol:

Then you can start the script, wait 5 seconds, and you should have an output.wav.

A: The speaker is an output stream even if you open it as an input. The hostApi value of the speaker is probably 0.
You can check the 'maxInputChannels' and 'maxOutputChannels' of every connected devices and the maxInputChannels for the speaker shall be 0.
You can't write to an input stream and you can't read from an output stream.
You can detect the available devices with the following code:
import pyaudio

# detect devices:
p = pyaudio.PyAudio()
host_info = p.get_host_api_info_by_index(0)
device_count = host_info.get('deviceCount')
devices = []

# iterate between devices:
for i in range(0, device_count):
    device = p.get_device_info_by_host_api_device_index(0, i)
    devices.append(device['name'])

print devices

After you get all the connected devices you can check the 'hostApi' of each devices.
For instance if the speaker index is 5 than:
p.get_device_info_by_host_api_device_index(0, 5)['hostApi']


text:
Q: Is $(\mathbb{Z},+)$ a solvable group? Ok, so abelian groups are solvable.
And Thm II.8.5 of Hungerford says
A group is solvable iff it has a solvable series. (The group may be finite or infinite.)
However, I can't seem to find a solvable series for $\mathbb{Z}$, for example $\mathbb{Z},2\mathbb{Z},6\mathbb{Z},\ldots$ will not terminate in the identity group.
Someone said that $\mathbb{Z},\left\{0\right\}$ is a solvable series for $\mathbb{Z}$. Is this a definition set by Hungerford since $\mathbb{Z},\left\{0\right\}$ is not even a composition series : $\mathbb{Z}/\left\{0\right\}$ is not a simple group.

A: We don't need the quotients to be simple. If the quotients are simple then you have obtained a composition series of the group. A solvable group has a composition series iff it is finite. Therefore in your case it won't happen.
Don't confuse solvable series with composition series.

A: While I'm not familiar with Hungerford's book, I imagine that he defines a solvable series to be a (finite) sequence of subgroups of $G$ such that $$1=G_0\unlhd G_1\unlhd\cdots\unlhd G_n=G$$ where each $G_i/G_{i-1}$ is abelian: there's no requirement that these quotients should be simple. In other words a solvable series is not necessarily a composition series.
So the series you allude to in your last paragraph ($G_0={0}$ and $G_n=G_1=\mathbb{Z}$) will do the trick.

A: Z is solvable as it has a normal series where the factors are abelian as Z being abelian ( which is the definition of solvable series) but as Z is not finite so it can't have a composition series ( which follows from the result - an abelian group has a composition series if and only if it is finite ) .


text:
Q: Can't add files for staging I've got some files i'd like to commit to my github repo, and I created the branch I'd like to used to track my changes.  I create it from the terminal using
git checkout -b my_branch

I've created the branch in the directory where the files are located.  When I run ls to view the files in the directory, I have the following:
folder_where_files_are
other_random_file

But when I run git status the directory where the files I'd like to track are located do not show as untracked, but the other_random_file does show as untracked.  Further, when I do git add, it doesn't throw an error, but when I go to commit it says.
nothing added to commit but untracked files present (use "git add" to
track)

*

*Why isn't it showing the files in the directory i'm in?

*Why can't I add files for staging?

Thank you in advance for you help.

A: thanks to @caramba I figured out the issue.  I need to move the directory I wanted to track into the local version of the repo that I set up.  I was able to solve my problem by with the following:
mv folder_where_files_are/ local_git_repo

This moved my files to the proper place.  Now when I git status the directory shows as untracked.  I was able to add, commit and push from there.


text:
Q: Simplification algebraic of a cube root. I am trying to simplify this:
$$\frac{1000}{\pi \cdot (\frac{500}{\pi})^{\frac{2}{3}}}$$
and I think it becomes:
$$2 \cdot \sqrt[3]{\frac{500}{\pi}}$$
I basically thought we cube root the $\frac{500}{\pi}$ and then multiply the denominator by $\frac{500}{\pi}$ which could cancel out some stuff. This is how I thought about it:
$$\frac{1000}{\pi \cdot \sqrt[3]{\frac{500}{\pi}} \cdot \frac{500}{\pi}}$$
$$ = \frac{1000 \cdot \pi}{\pi \cdot \sqrt[3]{\frac{500}{\pi}} \cdot 500}$$
Is there a better way to do this cancellation?

A: I would do it like this:
$$\dfrac{1000}{\pi\cdot\frac{\sqrt[3]{500^2}}{\sqrt[3]{\pi^2}}}=\dfrac{1000}{\pi\cdot\frac{\sqrt[3]{500^2}}{\sqrt[3]{\pi^2}}\cdot\dfrac{\sqrt[3]\pi}{\sqrt[3]{\pi}}}=\dfrac{1000}{\pi\cdot\frac{\sqrt[3]{250000\pi}}{\pi}}=\dfrac{1000}{\sqrt[3]{250000\pi}}=\dfrac{1000}{50\sqrt[3]{2\pi}}=\dfrac{20}{\sqrt[3]{2\pi}}\cdot\dfrac{\sqrt[3]{4\pi^2}}{\sqrt[3]{4\pi^2}}$$
$$=\dfrac{20\sqrt[3]{4\pi^2}}{2\pi}=\dfrac{10\sqrt[3]{4\pi^2}}{\pi}$$
The part where you are going wrong is where you are disregarding the square inside the cube root of $\frac {500}{\pi}$, and you are just "taking it out" of the cube root to the denominator.
This is the step where you have gone wrong:$$\dfrac{1000}{\pi\cdot \sqrt[3]{\frac{500}{\pi}}\cdot \frac {500}{\pi}}$$

A: $$\frac{1000}{\pi \cdot (\frac{500}{\pi})^{\frac{2}{3}}}=$$
$$ 2 \frac {\frac {500}{\pi}}{(\frac {500}{\pi})^\frac {2}{3}}=$$
$$ 2(\frac {500}{\pi})^\frac {1}{3}=$$
$$10(\frac {4}{\pi})^\frac {1}{3}$$

A: $$\frac{1000}{ \pi \cdot (\frac{500}{\pi})^{\frac{2}{3}} }
=\frac{1000}{\pi^{\frac{1}{3}}\cdot 2^{-\frac{2}{3}}\cdot 2^{\frac{2}{3}}\cdot 500^{\frac{2}{3}}}
=\frac{1000}{\pi^{\frac{1}{3}}\cdot 2^{-\frac{2}{3}}\cdot 1000^{\frac{2}{3}}}
=\frac{2\cdot 1000^{\frac{1}{3}}}{(2\pi)^{\frac{1}{3}}}
=\frac{20}{\sqrt[3] {2\pi} }=\frac{10\sqrt[3] {4\pi^2} }{\pi}=10\sqrt[3]{\frac{4}{\pi}}$$


text:
Q: LWC URL reading parameters I am trying to authorize another sandbox/production to create connection. When I first time authorize the connected app, it is returning the Auhorization Code in the URL, however when it gets redirected to LWC app, code is disappeared because the parameter is 'code' not like 'c__code'. So, pagereference state is unable to read the param value. It was working till the previous release, with Spring release it started behaving differently.
Original URL: not working
https://xxxx.lightning.force.com/lightning/n/Deployment_Tool?code=aPrxmksMoIsrem319S_JL_ssM0may9ttdjsdP6MjyuRrJYxtMz9MphqoRf7eQj8tbm5Lgw.Tg%3D%3D
I tested with adding 'c__' to the param manually and it worked fine.
Modified URL: Working
https://xxxxx.lightning.force.com/lightning/n/Deployment_Tool?c__code=aPrxmksMoIsrem319S_ssM0may9ttdjsdP6MjyuRrJYxtMz9MphqoRf7eQj8tbm5Lgw.Tg%3D%3D
is there a way we can rename the redirected URL params dynamically?
'code' to 'c__code'

A: The State parameter of the URL addressable component using pagereference always needs a namespace. For normal orgs c is the namespace and hence you will need to make sure within the URL parameter you pass the namespace.
A workaround for this is to first redirect it to a visualforce page which upon load can read parameter and redirect to a lightning URL with correct namespace i.e c__parametername and for an ISV app it will be namespace__parametername
The other approach would be to use VF page itself to do an OAuth dance and then post the message back to the lwc component (window.postmessage or use LMS) and close the vf page.


text:
Q: Total cpu utilization of running app engine flexible instances I need to make decisions in an external system based on the current CPU utilization of my App Engine Flexible service. I can see the exact values / metrics I need to use in the dashboard charting in my Google Cloud Console, but I don't see a direct, easy way to get this information from something like a gcloud command.
I also need to know the count of running instances, but I think I can use gcloud app instances list -s default to get a list of my running instances in the default service, and then I can use a count of lines approach to get this info easily. I intend to make a python function which returns a tuple like (instance_count, cpu_utilization).
I'd appreciate if anyone can direct me to an easy way to get this. I am currently exploring the StackDriver Monitoring service to get this same information, but as of now it is looking super-complicated to me.

A: You  can use the gcloud app instances list -s default command to get the running instances list, as you said. To retrieve CPU utilization, have a look on this Python Client for Stackdriver Monitoring. To list available metric types:
from google.cloud import monitoring
client = monitoring.Client()
for descriptor in client.list_metric_descriptors():
   print(descriptor.type)

Metric descriptors are described here. To display utilization across your GCE instances during the last five minutes:
metric = 'compute.googleapis.com/instance/cpu/utilization'
query = client.query(metric, minutes=5)
print(query.as_dataframe())

Do not forget to add google-cloud-monitoring==0.28.1 to "requirements.txt" before installing it.
Check this code that locally runs for me:
import logging

from flask import Flask
from google.cloud import monitoring as mon

app = Flask(__name__)

@app.route('/')
def list_metric_descriptors():
    """Return all metric descriptors"""
    # Instantiate client
    client = mon.Client()

    for descriptor in client.list_metric_descriptors():
        print(descriptor.type)
    return descriptor.type

@app.route('/CPU')
def cpuUtilization():
    """Return CPU utilization"""
    client = mon.Client()
    metric = 'compute.googleapis.com/instance/cpu/utilization'
    query = client.query(metric, minutes=5)
    print(type(query.as_dataframe()))
    print(query.as_dataframe())
    data=str(query.as_dataframe())
    return data

@app.errorhandler(500)
def server_error(e):
    logging.exception('An error occurred during a request.')
    return """
    An internal error occurred: <pre>{}</pre>
    See logs for full stacktrace.
    """.format(e), 500

if __name__ == '__main__':
    # This is used when running locally. Gunicorn is used to run the
    # application on Google App Engine. See entrypoint in app.yaml.
    app.run(host='127.0.0.1', port=8080, debug=True)


text:
Q: How to respond to a friend suggestion One of my colleague has sent me a message.

Hi xyz, this is my friend abc and you might become friends... Her parents are from qwe place

How should I respond to this message in a way saying that I am interested in meeting the person.


text:
Q: I can't get my Button widget to do anything I'm new at this android stuff and trying to teach myself the language and I'm running into a brick wall here.
I'm trying to program a really simple widge that is just a button. When the button is pressed the phone goes to silent mode. Unfortunately, the onlky thing that I am able to program the button do is pop a toast message.
Can someone please advise me on my errors. Thanks a bunch in advance. Here is my code:
package com.DoNotDisturb.widget;

import com.DoNotDisturb.widget.R;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class DoNotDisturbWidget extends AppWidgetProvider {

    public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";
    public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);

        Intent active = new Intent(context, DoNotDisturbWidget.class);
        active.setAction(ACTION_WIDGET_RECEIVER);

        active.putExtra("msg", "Phone is silent");

        PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);

        remoteViews.setOnClickPendingIntent(R.id.button_one, actionPendingIntent);

        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        // v1.5 fix that doesn't call onDelete Action
        final String action = intent.getAction();
        if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
            final int appWidgetId = intent.getExtras().getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);

            if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
                this.onDeleted(context, new int[] { appWidgetId });
            }
        } else {
            // check, if our Action was called
            if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
                String msg = "null";
                try {
                    msg = intent.getStringExtra("msg");
                } catch (NullPointerException e) {
                    Log.e("Error", "msg = null");
                }
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();

                PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);

                NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
                Notification noty = new Notification(R.drawable.icon, "Do Not Disturb Feature Activated", System.currentTimeMillis());

                noty.setLatestEventInfo(context, "Notice", msg, contentIntent);
                notificationManager.notify(1, noty);

            } else {
                // do nothing
            }

            super.onReceive(context, intent);
        }
    }

    private AudioManager getSystemService(String audioService) {
        // TODO Auto-generated method stub
        return null;
    }
}


text:
Q: 3rd Party API call in MEAN I am learning MEAN stack and doing a POC to connect Firebase Cloud Messaging (FCM) with MEAN. To connect FCM (or any other 3rd party API) to MEAN, can we connect to Angular directly or do we have to connect through Express. Which is the best practice to follow.
Thanks in Advance.


text:
Q: Making closed curves with random shapes filled with a solid color in matplotlib or OpenCV-python To create a dataset for deep learning, I need to produce gray-scale images like this:

To give you a context, it is droplet passing light. There I four features I need to produce which have been specified by a number:

*

*Backround - usually a shade of gray

*A light halo around the droplet

*A dark shadow

*A focused light

#3&4 could get thinner or wider or lighter and darker.
The shape of the droplet is a small deviation from the sphere.
My idea was to make randomly-deviated curve from a circle like this:
H = 10
rho = np.random.rand(H)*np.logspace(-0.5,-2.5,H)
phi = np.random.rand(H)* 2*np.pi

t = np.linspace(0,2*np.pi,101)
r = np.ones(len(t))
for h in range(H):
    r = r + rho[h]*np.sin(h*t+phi[h])
x = r * np.cos(t)
y = r * np.sin(t)

I need to create three closed curves and fill them with solid color and add a blur effect.
Is it possible to do this in matplotlib?
Can I use an equation to specify a contour in OpenCV and then do those operations?


text:
Q: Using boost::lambda with an STL container The complete code is on https://gist.github.com/1341623
I'd like to sort an index array (or vector) for another vector, such that the array is ordered by the index of the other vector. However, the type of vector::at cannot be resolved.
I did a try as follows:
This is OK
sort(v.begin(), v.end());

I'd like to sort the indexes according to the array, but placeholders do not overload operator[]
sort(index,index+10, a[_1] < a[_2]);

However, they overload operator+ and operator*
sort(index,index+10, *(a+_1) < *(a+_2));

I'd like to sort the indexes according to the vector, but compiler cannot resolve the type of `vector::at'.
sort(index,index+10,
  bind(&(vector<int>::at), &v, _1) < bind(&(vector<int>::at), &v, _2));
// error: no matching function for call
// to 'bind(<unresolved overloaded function type>, ...

After searching on the web, I found I have to specify the overloaded method type, but compiler still says it cannot resolve the type.
sort(index,index+10,
   bind(&static_cast<const int (*)(size_t)>(vector<int>::at), &v, _1)
 < bind(&static_cast<const int (*)(size_t)>(vector<int>::at), &v, _2));
// error: invalid static_cast from type '<unresolved overloaded function type>'
// to type 'const int (*)(size_t)' ...

I tried to get the version of vector::at I want, but the conversion seems to be failed.
vector<int>::const_reference (*vector_int_at)(vector<int>::size_type)(vector<int>::at);
sort(index,index+10,
  bind(&vector_int_at, &v, _1) < bind(&vector_int_at, &v, _2));
// error: no matches converting function 'at' to type 'const int& (*)(size_t)' ...

What can I do for this problem? Or I misunderstand something?

A: Remember that pointers to member functions and pointers to free functions have different types.  Try:
vector<int>::const_reference (vector<int>::*vector_int_at)(vector<int>::size_type) const = &vector<int>::at;

A: I usually just declare a forwarding function to avoid the various cans of worm associated with this sort of thing:
int vector_at(vector<int> const * v, size_t index) { return v->at(index); }

...

sort(index, index+10, bind(vector_at, &v, _1) < bind(vector_at, &v, _2));

A: Any reason why you do not use a lambda?
sort(index, index+10, [&a](int i, int j) { return a[i] < a[j]; });


text:
Q: How to reconnect to slime/swank-clojure session? It seems that whenever I disconnect from clojure slime session, I cannot reconnect again. I am using leiningen to start the swank session (with lein-swank plugin). So, every time I quit emacs (I know I shouldn't) or reboot/logout I have to restart both slime and swank. Is there a way to re-connect to a slime/clojure-swank session?

A: Yes, but you have to tell swank not to close the connection:
lein swank 4005 "localhost" :dont-close true

Note that you have to supply the port and host name if you want to pass the :dont-close true portion; 4005 and "localhost" are the default values.
In fact, this makes it possible to connect multiple REPLs to the same swank instance at the same time! Then you can type in (def foo :foo) in one Emacs and see foo evaluate to :foo in the other. :-)


text:
Q: Jquery get length of json array I've an issue with a json array row length...
I want to extract the correct length of data-row json (in this case "2")...
If I try to count the length I get the value "1". Why ? How can I get the correct length ?
{
    "data-row": {
        "data1": [{
            "firstName": "John",
            "lastName": "Doe"
        }, {
            "firstName": "Anna",
            "lastName": "Smith"
        }, {
            "firstName": "Peter",
            "lastName": "Jones"
        }],
        "data2": [{
            "firstName": "John",
            "lastName": "Doe"
        }, {
            "firstName": "Anna",
            "lastName": "Smith"
        }]
    }
}

A: You have a Object and to find length of Object

var json = {
  "data-row": {
    "data1": [],
    "data2": []
  }
}

alert(Object.keys(json["data-row"]).length);

As you are having - in key use json["data-row"] to access object

A: This is the another way to find length. but not right way.

var json = {
  "data-row": {
    "data1": [],
    "data2": []
  }
}
length=0;
$.each(json["data-row"],function(i){
  length++;
});
alert(length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>


text:
Q: Pull a file from android emulator/device programmatically I am familiar with adb pull command. Is it possible to pull a file from android device/emulator and saving it in specified location in PC programmatically?

A: In C, on linux use system() to execute adb (perhaps by its full path) with the appropriate arguments.  OSX is probably something quite similar.
On windows... CreateProcess() but that returns before the child is finished, so you may have to spend some time wandering around MSDN to figure out the equivelent of system()


text:
Q: How do i get my data from mysql to behave So I want to fill and display a HTML table, that is 2 columns wide. But, no matter what I try, my data always sticks together.
The thing is, that I actually want to put the entire data into a table, where it's sorted by the starting letter.
This is my code:
<?php include_once 'Database/dbh.php'; ?>

<!DOCTYPE html>

        <?php
        $fetch = "SELECT DISTINCT Kategori, LEFT(Kategori, 1) AS Letter FROM kategorier ORDER BY Kategori;";
        $result = mysqli_query($conn, $fetch);
        $resultCheck = mysqli_num_rows($result);

        if ($resultCheck > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                if (!isset($lastLetter) || $lastLetter != $row['Letter']) {
                    $lastLetter = $row['Letter'];
                    echo "
", $row['Letter'], "
";
                }
                echo "

" . $row['Kategori'] . "

";
            }
        }
        ?>

Here is a picture of how it is right now:

Here is how I want it to look like:

A: I am sorry to disappoint you, but the solution is a bit more complex than you maybe thought. As I see, @aynber already suggested it. So, if he writes an answer, it would be fair to take his answer into consideration first.
Suggestions
About Separation of Concerns:
Let me now begin by saying, that, for the future, you should familiarize yourself with the Separation of Concerns principle. In simple words, taking your code as example: always separate the code involving access to database (for fetching data, updating, etc) from the one displaying the data (e.g. the HTML part of the page).
This means that, if you need to fetch data from the database, then do it at the top of the web page, and save it in arrays. Then just use these arrays inside the HTML part of the web page, instead of some db-related functions like mysqli_query, or mysqli_fetch_assoc, or etc. For clarity, see the HTML part of the code I provided ("index.php").
A big advantage of this approach is, that you can move the whole php code from the top of the page into php functions, or class methods. The arrays will then just contain data resulting from calling these functions/methods.
The main point for all of the above statements? Juggle as you wish with the php code and the data on top of the web page, and save the results in php arrays. The arrays should, in the end, have such a structure, that the job of the HTML part of the web page will be totally simple: to just read and display the array elements.
So don't mix HTML code with db-related code. If you do it, then the code is too hard to maintain.
About printing client-side code from PHP:
Another important convention you should remember for the future is, to not print any client-side code by using php code. E.g. to not use such statements like echo "

".... In this echo case, just save the content that you want to present into variables, and display them in the HTML part of the web page as desired.
About prepared statements:
If you need to execute sql statements with parameters, then use prepared statements (instead of mysqli::query in this case). They will protect your code against eventual sql injections. For completion, at the end of this answer I posted an example of index.php using prepared statements instead of mysqli::query.
Solution to question:
Steps:
Regarding the solution I prepared, it involves four steps:

*

*Fetch the data from the database and save it into an array ($data).

*First, create a second array ($formattedData). Then iterate through $data and save its items into $formattedData in such a way, that they can be very easily displayed in chosen HTML structures (div for letter, table for categories).

*Iterate through $formattedData and append an item with null as category name for each missing category in the last category row of each letter. Sorry, I wrote here one sentence, but, if you'll read the comments in my code, you'll certainly understand better what I mean.

*Display the data in HTML part of the page by iterating through $formattedData and reading its values.

Of course, you can optimize the php code as you wish and/or distribute it into two-three functions. Then you can just call them and assign their returned values to the $data and $formattedData variables.
Note:
If you use my connection code, don't forget to replace my db credentials with yours.

index.php
<?php
require 'Database/dbh.php';

$sql = 'SELECT
            DISTINCT Kategori,
            LEFT(Kategori, 1) AS Letter
        FROM kategorier
        ORDER BY Kategori';

$result = mysqli_query($conn, $sql);

/*
 * Fetch all data at once, into an array like this:
 *
 *  Array
 *  (
 *      [0] => Array
 *          (
 *              [Kategori] => Artiskok
 *              [Letter] => A
 *          )
 *
 *      [1] => Array
 *          (
 *              [Kategori] => Asiatisk
 *              [Letter] => A
 *          )
 *
 *      [2] => Array
 *          (
 *              [Kategori] => Burger
 *              [Letter] => B
 *          )
 *
 *      [...] => [...]
 *
 *  )
 */
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);

/*
 * Free the memory associated with the result. You should
 * always free your result when it is not needed anymore.
 *
 * @link http://php.net/manual/en/mysqli-result.free.php
 */
mysqli_free_result($result);

/*
 * Close the previously opened database connection. Not really needed because
 * the PHP engine closes the connection anyway when the PHP script is finished.
 *
 * @link http://php.net/manual/en/mysqli.close.php
 */
mysqli_close($conn);

/*
 * Iterate through the fetched data and save it into a new array, with a structure suited for the
 * required HTML display. To each letter, a list of category rows is assigned. The new array will
 * look like this, when the maximal number of categories per category row is 2:
 *
 *  Array
 *  (
 *      [A] => Array
 *          (
 *              [0] => Array
 *                  (
 *                      [0] => Aoiuoiiiu
 *                      [1] => Aqewroiuoiiu
 *                  )
 *
 *              [1] => Array
 *                  (
 *                      [0] => Artiskok
 *                      [1] => Asiatisk
 *                  )
 *
 *              [2] => Array
 *                  (
 *                      [0] => Azkajhsdfjkh
 *                  )
 *
 *          )
 *
 *      [B] => Array
 *          (
 *              [0] => Array
 *                  (
 *                      [0] => Bhaskdfhjkh
 *                      [1] => Biuzutt
 *                  )
 *
 *              [1] => Array
 *                  (
 *                      [0] => Burger
 *                  )
 *
 *          )
 *
 *      [...] => [...]
 *
 *  )
 */
$formattedData = [];

// The maximal number of categories per each category row.
$maximalNumberOfCategoriesPerCategoryRow = 2;

// The number of categories per current category row.
$numberOfCategoriesPerCurrentCategoryRow = 0;

// The index of a category row in the list of all category rows assigned to a letter.
$indexOfCurrentCategoryRow = 0;

foreach ($data as $item) {
    $letter = $item['Letter'];
    $category = $item['Kategori'];

    if (!array_key_exists($letter, $formattedData)) {
        /*
         * Assign an item with the current letter as key and an array as value.
         * The array holds all category rows for the current letter.
         */
        $formattedData[$letter] = [];

        // Reset.
        $indexOfCurrentCategoryRow = 0;

        // Reset.
        $numberOfCategoriesPerCurrentCategoryRow = 0;
    }

    // Append the current category to the current category row for the current letter.
    $formattedData[$letter][$indexOfCurrentCategoryRow][] = $category;

    // Increment.
    $numberOfCategoriesPerCurrentCategoryRow++;

    /*
     * If the maximal number of categories per category row is reached...
     *
     * @see "Modulo" operator at https://secure.php.net/manual/en/language.operators.arithmetic.php
     */
    if (
            $numberOfCategoriesPerCurrentCategoryRow %
            $maximalNumberOfCategoriesPerCategoryRow === 0
    ) {
        // Reset.
        $numberOfCategoriesPerCurrentCategoryRow = 0;

        // Increment.
        $indexOfCurrentCategoryRow++;
    }
}

/*
 * Append an item with "null" as category for each missing category in the last
 * category row of each letter. The array holding the formatted data will look
 * like this, when the maximal number of categories per category row is 2:
 *
 *  Array
 *  (
 *      [A] => Array
 *          (
 *              [...] => [...]
 *
 *              [2] => Array
 *                  (
 *                      [0] => Azkajhsdfjkh
 *                      [1] => null
 *                  )
 *
 *          )
 *
 *      [B] => Array
 *          (
 *              [...] => [...]
 *
 *              [1] => Array
 *                  (
 *                      [0] => Burger
 *                      [1] => null
 *                  )
 *
 *          )
 *
 *      [...] => [...]
 *
 *  )
 */
foreach ($formattedData as $letter => $categoryRows) {
    $lastCategoryRow = end($categoryRows);
    $lastCategoryRowKey = key($categoryRows);

    $numberOfCategoriesPerLastCategoryRow = count($lastCategoryRow);

    $numberOfMissingCategoriesInLastCategoryRow = $maximalNumberOfCategoriesPerCategoryRow -
            $numberOfCategoriesPerLastCategoryRow;

    for ($i = 0; $i < $numberOfMissingCategoriesInLastCategoryRow; $i++) {
        // Append an item with "null" as category.
        $formattedData[$letter][$lastCategoryRowKey][] = null;
    }
}

//=====================================================================================
//@todo Just for testing: uncomment the next two lines to display the arrays on screen.
//=====================================================================================
//echo '
' . print_r($data, TRUE) . '
';
//echo '
' . print_r($formattedData, TRUE) . '
';
//=====================================================================================
?>
<!DOCTYPE html>

        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />

        <title>Demo</title>

        <link href="custom.css" type="text/css" rel="stylesheet">

            Demo: Print a list of categories per category letter, on multiple columns.

        <?php
        if ($formattedData) { /* Data exists */
            foreach ($formattedData as $letter => $categoryRows) {
                ?>

                        <?php echo $letter; ?>

                        <?php
                        foreach ($categoryRows as $categoryRow) {
                            ?>

                                <?php
                                foreach ($categoryRow as $category) {
                                    ?>

                                        <?php echo $category; ?>

                                    <?php
                                }
                                ?>

                            <?php
                        }
                        ?>

                <?php
            }
        } else { /* No data */
            ?>

                No data found

            <?php
        }
        ?>

custom.css
body {
    margin: 0;
    padding: 20px;
    color: #333;
}

a {
    text-decoration: none;
}

.categories-container {
    margin-bottom: 10px;
}

.letter {
    padding: 10px;
    text-align: left;
    font-weight: 700;
    background-color: #a0c3e5;
}

.categories {
    width: 100%;
    border-spacing: 1px;
    border-collapse: separate;
}

.categories td {
    width: 50%;
    padding: 10px;
    background-color: #f4f4f4;
}

.no-data {
    padding: 10px;
    background-color: #f4f4f4;
}

Database/dbh.php
<?php

/*
 * This page contains the code for creating a mysqli connection instance.
 */

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'root');
define('PASSWORD', 'root');

// Error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 1); /* SET IT TO 0 ON A LIVE SERVER! */

/*
 * Enable internal report functions. This enables the exception handling,
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions
 * (mysqli_sql_exception).
 *
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings.
 *
 * @link http://php.net/manual/en/class.mysqli-driver.php
 * @link http://php.net/manual/en/mysqli-driver.report-mode.php
 * @link http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Create a new db connection.
$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE, PORT);

Used data for testing
CREATE TABLE `kategorier` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `Kategori` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `kategorier` (`id`, `Kategori`)
VALUES
    (1,'Artiskok'),
    (2,'Asiatisk'),
    (3,'Burger'),
    (4,'Pizza'),
    (5,'Asiatisk'),
    (6,'Artiskok'),
    (7,'Artiskok'),
    (8,'Durum'),
    (9,'Durum'),
    (10,'Pizza'),
    (11,'Chinaboks'),
    (12,'Azkajhsdfjkh'),
    (13,'Aoiuoiiiu'),
    (14,'Aqewroiuoiiu'),
    (15,'Bhaskdfhjkh'),
    (16,'Biuzutt');

Result

Additional content:
This is an example of how to fetch the data using prepared statements instead of mysqli::query. Note that I only put the data fetching code here. The rest of the code is identical with the omolog part of the above index.php page, which uses mysqli::query.
index.php
<?php

require 'Database/dbh.php';

/*
 * Save the values, with which the database data will be filtered, into variables.
 * These values will replace the parameter markers in the sql statement.
 * They can come, for example, from a POST request of a submitted form.
 */
$letterParam1 = 'A';
$letterParam2 = 'C';
$letterParam3 = 'P';

/*
 * The SQL statement to be prepared. Notice the so-called markers, e.g. the "?" signs. They
 * will be replaced later with the corresponding values when using mysqli_stmt::bind_param.
 *
 * @link http://php.net/manual/en/mysqli.prepare.php
 */
$sql = 'SELECT
            DISTINCT Kategori,
            LEFT(Kategori, 1) AS Letter
        FROM kategorier
        WHERE
            LEFT(Kategori, 1) = ?
            OR LEFT(Kategori, 1) = ?
            OR LEFT(Kategori, 1) = ?
        ORDER BY Kategori';

/*
 * Prepare the SQL statement for execution - ONLY ONCE.
 *
 * @link http://php.net/manual/en/mysqli.prepare.php
 */
$statement = mysqli_prepare($conn, $sql);

/*
 * Bind variables for the parameter markers (?) in the SQL statement that was passed to prepare().
 * The first argument of bind_param() is a string that contains one or more characters which
 * specify the types for the corresponding bind variables.
 *
 * @link http://php.net/manual/en/mysqli-stmt.bind-param.php
 */
mysqli_stmt_bind_param($statement, 'sss'
        , $letterParam1
        , $letterParam2
        , $letterParam3
);

/*
 * Execute the prepared SQL statement. When executed any parameter markers
 * which exist will automatically be replaced with the appropriate data.
 *
 * @link http://php.net/manual/en/mysqli-stmt.execute.php
 */
mysqli_stmt_execute($statement);

/*
 * Get the result set from the prepared statement.
 *
 * NOTA BENE:
 *
 * Available only with mysqlnd ("MySQL Native Driver")! If this is not installed, then
 * uncomment "extension=php_mysqli_mysqlnd.dll" in PHP config file (php.ini) and restart
 * web server (I assume Apache) and mysql service. Or use the following functions instead:
 * mysqli_stmt::store_result + mysqli_stmt::bind_result + mysqli_stmt::fetch.
 *
 * @link http://php.net/manual/en/mysqli-stmt.get-result.php
 * @link https://stackoverflow.com/questions/8321096/call-to-undefined-method-mysqli-stmtget-result
 */
$result = mysqli_stmt_get_result($statement);

/*
 * Fetch all data at once, into an array like this:
 *
 *  Array
 *  (
 *      [0] => Array
 *          (
 *              [Kategori] => Artiskok
 *              [Letter] => A
 *          )
 *
 *      [1] => Array
 *          (
 *              [Kategori] => Asiatisk
 *              [Letter] => A
 *          )
 *
 *      [2] => Array
 *          (
 *              [Kategori] => Burger
 *              [Letter] => B
 *          )
 *
 *      [...] => [...]
 *
 *  )
 */
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);

/*
 * Free the memory associated with the result. You should
 * always free your result when it is not needed anymore.
 *
 * @link http://php.net/manual/en/mysqli-result.free.php
 */
mysqli_free_result($result);

/*
 * Close the prepared statement. It also deallocates the statement handle.
 * If the statement has pending or unread results, it cancels them
 * so that the next query can be executed.
 *
 * @link http://php.net/manual/en/mysqli-stmt.close.php
 */
mysqli_stmt_close($statement);

/*
 * Close the previously opened database connection. Not really needed because
 * the PHP engine closes the connection anyway when the PHP script is finished.
 *
 * @link http://php.net/manual/en/mysqli.close.php
 */
mysqli_close($conn);

/*
 * ---------------------------------------------------------------------------------------------
 * The rest of the page is identical with the omolog part of index.php, which uses mysqli::query
 * ---------------------------------------------------------------------------------------------
 */

// ...

A: Instead of a Table element, I suggest using a Definition List element dl, since its purpose is your desired display result.
To resolve your issue though, I suggest a few modifications.
First, keep in mind that DISTINCT applies to the entire list of columns, not just the column it is next to. Second, ORDER BY from MySQL is typically slower than sorting alphabetically in PHP, and MySQL does not order by alphanumeric values naturally. Lastly, since the data needs to be iterated over alphabetically to determine the first letter to display before moving to the next group, using LEFT() in your MySQL query is not really needed.
Definition List Example: https://3v4l.org/hETha
 $sql = 'SELECT DISTINCT Kategori FROM kategorier;';
 $result = mysqli_query($conn, $sql);
 if ($kategorier = mysqli_fetch_all($result, MYSQLI_ASSOC)) {
    //convert array of arrays to single array - PDO supports PDO::FETCH_GROUP|PDO::FETCH_COLUMN
    $kategorier = array_column($kategorier, 'Kategori');
    //sort the resulting array as a human would
    natsort($kategorier);
 }
 $previousLetter = null;
 ?>

 <?php
 foreach ($kategorier as $kategori) {
     $currentLetter = strtoupper($kategori[0]);
     if ($previousLetter !== $currentLetter) { ?>

<?php echo $currentLetter; ?>

     <?php  } ?>

<?php echo $kategori; ?>

     <?php $previousLetter = $currentLetter;
     } ?>

Table Data:
Kategori
---------
Burger
Pizza
Pizza2
Pizza3
Chinaboks
Artiskok
Durum
Asiatisk
Asiatisk2
Asiatisk20
Asiatisk3

Database Results: (MySQL will order by 1, 10, 2, 20, not 1, 2, 10, 20)
[
    ['Kategori' => 'Burger'],
    ['Kategori' => 'Pizza'],
    ['Kategori' => 'Pizza2'],
    ['Kategori' => 'Pizza3'],
    ['Kategori' => 'Chinaboks'],
    ['Kategori' => 'Artiskok'],
    ['Kategori' => 'Durum'],
    ['Kategori' => 'Asiatisk'],
    ['Kategori' => 'Asiatisk2'],
    ['Kategori' => 'Asiatisk20'],
    ['Kategori' => 'Asiatisk3'],
];

Sorted PHP Array Result:
[
    'Artiskok',
    'Artiskok2',
    'Artiskok3',
    'Artiskok20',
    'Asiatisk',
    'Burger',
    'Chinaboks',
    'Durum',
    'Pizza',
    'Pizza2',
    'Pizza3',
];

Resulting HTML Output:
Note: using float will sort from left to right i.e.
1 | 2
3 | 4
5

/* Suggested CSS */
* {
  box-sizing: border-box;
}
dd {
  margin-left: 0;
  float: left;
  width: 50%;
}
dt {
  padding: 12px 0;
  clear: both;
}

A

Artiskok

Asiatisk

Asiatisk2

Asiatisk3

Asiatisk20

B

Burger

C

Chinaboks

D

Durum

P

Pizza

Pizza2

Pizza3

If you would like to do more complex CSS styling, such as columns sorting. You can use a nested list instead. However it is best to organize the data before iterating over it in the display view.
Nested List Example: https://3v4l.org/bAVGW
//...

$letters = [];
if (!empty($kategorier)) {
    $kategorier = array_column($kategorier, 'Kategori');
    //sort the resulting array as a human would
    natsort($kategorier);

    foreach ($kategorier as $kategori) {
        $k = strtoupper($kategori[0]);
        if (!isset($letters[$k])) {
             $letters[$k] = [];
        }
        $letters[$k][] = $kategori;
    }
}
?>

<?php foreach ($letters as $k => $kategorier) { ?>

<?php echo $k; ?>

        <?php foreach ($kategorier as $kategori) { ?>

<?php echo $kategori; ?>

        <?php } ?>

<?php } ?>

Resulting HTML Output:
Note: Using the columns CSS definition, will sort from left-top to bottom-right i.e.
1 | 4
2 | 5
3

/* Suggested CSS */

* {
  box-sizing: border-box;
}

ul.category-index ul,
ul.category-index {
  list-style: none;
  margin: 0;
  padding: 0;
}

ul.category-index li {
  padding: 0;
  margin: 0;
}

ul.category {
  columns: 2;
}

A

Artiskok

Asiatisk

Asiatisk2

Asiatisk3

Asiatisk20

B

Burger

C

Chinaboks

D

Durum

P

Pizza

Pizza2

Pizza3

As for your desired table element usage. You can use the nested list example PHP code, with the inclusion of the below html. However to ensure the entire table is uniform, you will need to use a single table. colspan="2" can be used for the category index rows, to expand them across the two columns. To determine when a new row is needed, % 2 is used, which will occur on each even iteration of the categories. As well as using count to determine if an empty table cell needs to be added to the current category list and avoid creating an extra empty table row.
Table Example: https://3v4l.org/ZuN20
//...

$letters = [];
if (!empty($kategorier)) {
    $kategorier = array_column($kategorier, 'Kategori');
    //sort the resulting array as a human would
    natsort($kategorier);

    foreach ($kategorier as $kategori) {
        $k = strtoupper($kategori[0]);
        if (!isset($letters[$k])) {
             $letters[$k] = [];
        }
        $letters[$k][] = $kategori;
    }
}
?>

    <?php foreach($letters as $k => $kategorier) { ?>

<?php echo $k; ?>

        <?php
        $l = count($kategorier);
        if ($l & 1) {
           $kategorier[] = '';
           $l++;
        }
        $y = $l - 1;
        foreach ($kategorier as $i => $kategori) { ?>
            <?php echo $kategori; ?>
            <?php if ($i % 2 && $i !== $y) { ?>

<?php } ?>
        <?php } ?>

    <?php } ?>

Resulting HTML:
Note: using table will sort from left to right. i.e.
1 | 2
3 | 4
5 |

/* Example CSS */

* {
  box-sizing: border-box;
}

table {
  width: 100%;
}

A

    Artiskok
    Asiatisk

    Asiatisk2
    Asiatisk3

    Asiatisk20

B

    Burger

C

    Chinaboks

D

    Durum

P

    Pizza
    Pizza2

    Pizza3

A: Change to (untested):
while ($row = mysqli_fetch_assoc($result)) {
      if (!isset($lastLetter) || $lastLetter != $row['Letter']) {
            echo "

";
            $lastLetter = $row['Letter'];
            echo "
", $row['Letter'], "
";
            echo "

";
      }
      echo "" . $row['Kategori'] . "	";

}
Hope this helps you out ;)
Cheers
Nicolas

A: I suggest that you may use Bootstrap Template, and use code as below for the result, the result will separate on two column as you needed.
echo "

" . $row['Kategori'] . "

";


text:
Q: Base64-decode a string using NetEncoding in Delphi XE7? In Delphi XE7 Update 1, when trying to execute this code in a VCL program:
uses System.NetEncoding;
...
tempstring := TNetEncoding.Base64.Decode(tempstring);

I get this error message:

So how can I base64-decode a string using NetEncoding?

A: You are calling the Decode overload that accepts base64 encoded text and returns a string. The way that Decode method is implemented is as follows:

*

*Decode the base64 to binary.

*Treat the binary as UTF-8 encoded text.

*Decode the UTF-8 bytes to text.

Your error message indicates that the binary that results from step 1 is not valid UTF-8. In order to work out why this is so requires knowledge of where the base64 encoded text originated.
Your current code assumes that the following process took place to create the base64 encoded value:

*

*Encode some text to UTF-8 bytes.

*Base 64 encode those bytes.

The problem is not necessarily in your code to decode. The problem is that your decoding does not match the process that originally encoded. The fault could lie either in the original encoding, or the decoding. You need to check how the base64 value was encoded. Was it encoded using the steps described above?
If I had to guess, I would suspect that the original data was not in fact textual. My guess is that the original data is binary, that is a stream of bytes. I suspect that you started from some code which held a binary data in an AnsiString variable. It is very common to see Delphi code that abuses strings in this way. For historical reasons it seems to have been written in to the lore that AnsiString can be used to hold binary data. I guess this all started when Delphi 2 introduced AnsiString and at that time there were no dynamic arrays.
Anyway, if you have previously been using AnsiString to hold binary data then you should take this opportunity to stop doing so. Use TBytes, for instance, for that purpose. In which case you would use:
var
  bytes: TBytes;
....
bytes := TNetEncoding.Base64.DecodeStringToBytes(...);

to decode your base64 value to binary.
So, suppose that the base64 that you have is actually ANSI encoded text. Then you would decode it like this:
var
  bytes: TBytes;
  text: string;
....
bytes := TNetEncoding.Base64.DecodeStringToBytes(...);
text := TEncoding.ANSI.GetString(bytes);

This assumes the prevailing ANSI code page on the machine on which you decode. If you need to specify an ANSI code page then you might write it like this:
var
  bytes: TBytes;
  text: string;
  Encoding: TEncoding;
....
bytes := TNetEncoding.Base64.DecodeStringToBytes(...);
Encoding := TEncoding.GetEncoding(CodePage);
try
  text := Encoding.GetString(bytes);
finally
  Encoding.Free;
end;

As you can see, I am now reduced to guessing. If you want to make progress you will find out how your data was encoded.


text:
Q: char pointer initialization I have come across a line that is given below
           char *ch=(char*)3000

I want to know the meaning of this line .....

A: It looks like the pointer, ch, is being assigned an absolute memory address 3000. Generally a very bad idea, unless you're working on an embedded system with no paging and you know exactly what's at memory location 3000.

A: Maybe seeing the rest of the code would be relevant...
That pointer could be relative to the segment in which it resides (on Intel processors). In this case the 3000 could be simply an index into that segment, defined earlier in the program, where we don't have the lines.
This depends upon the system architecture, the environment, the OS, the compiler, the rest of the code (and the programmer...).

A: Isn't it obvious?
The numerical value "3000" is cast to a char pointer, i.e. ch is initialized to memory address 3000 (decimal).

A: AFAIK, 3000 is no special address/value, and In most of the cases accessing it would result in segmentation fault or a garbage value.
If you see that in code, may be it is incorrectly used instead of a (void*), say in case of maps where you have key value pairs, the result may be cast into an integer in that case.


text:
Q: can i resign an ipa with the certificate and embedded.mobileprovision only without the private key? I have extracted an enterprise distribution certificate from the mobileprovision file from an  ipa but could not get the private key
So can i resign an another ipa with the certificate and embedded.mobileprovision only without the private key?
And if yes how to do this ?


text:
Q: Error while adding location plugin in flutter? i'm trying to add location plugin in my application but its throwing me an error.when i add some
other package its not giving the error.can someone help me in it.
Here's my pubspec.yaml code:
name: location
description: A new Flutter application.

version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  firebase_core: ^0.4.3+1
  location: ^2.3.5

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:

  uses-material-design: true

Error:
Error on line 27, column 3 of pubspec.yaml: A package may not list itself as a dependency.

   ╷

27 │   location: ^2.3.5

   │   ^^^^^^^^
   ╵
pub get failed (65;    ╵)

A: Is your project name by any chance by any chance the same name as your library name?
Rename your project to something else than location, and it might work.


text:
Q: Generate all possible arithmetic solutions and then determine which are essential the "same" I'm looking to code a variant of the card game 24 in Python, but would like the user to offer up, say, 4 "unique" solutions using all 4 given numbers using the operators: +-*/. As of now, the user does not have access to parenthesis and the equation evaluates from left to right.
So far, I have code that would give me all the possible solutions below. However, I'm struggling with the next step where I need to match up the ones that are the "same".
For example: A+B+C+D is the same as B+C+D+A, or A+B+C-D is the same as B-C+A+B, or A * B-C+D is the same as B*A+D-C. Does anyone have any ideas?
import pandas as pd
import numpy as np
from itertools import permutations, combinations_with_replacement, product

given_numbers_string = ['x1', 'x2', 'x3', 'x4']

operators = ["+","-","*","/"]

solution_space =  {}

seen = set()

for values in permutations(given_numbers_string,len(given_numbers_string)):
    for operCombo in combinations_with_replacement(operators,len(given_numbers_string)-1):
        for oper in permutations(operCombo,len(given_numbers_string)-1):
            formula = "".join(o+v for o,v in zip([""]+list(oper),values))
            if formula not in seen:
                solution_space[formula] = 0
print(solution_space, len(solution_space))

def function():
    global solution_space

    given_numbers = [1,2,3,4]

    given_numbers_string = list(map(str, given_numbers))

    target = 24
    operators = ["+","-","*","/"]

    solution_counter = 0
    for values in permutations(given_numbers_string,len(given_numbers_string)):
        for operCombo in combinations_with_replacement(operators,len(given_numbers_string)-1):
            for oper in permutations(operCombo,len(given_numbers_string)-1):
                formula = "".join(o+v for o,v in zip([""]+list(oper),values))
                if formula not in solution_space and isinstance(eval(formula),int):
                    solution_space[(formula)] = 1
                    if eval(formula)==target:
                        print(formula,"=",eval(formula))
                        solution_counter += 1

    solution_space = {}
    return(given_numbers, solution_counter)

function()


text:
Q: Install an R package in Dockerfile in Deepnote I've set up a custom environment with R kernel in Deepnote and I want to use the Dockerfile to install the mosaic package (otherwise I have to install it manually every day and it takes a while). When I add
RUN R -e 'install.packages("mosaic")'

after the IRkernel::installspec line in the Dockerfile, I get this output:
Step #1: > install.packages("mosaic")
Step #1: Installing package into '/usr/local/lib/R/site-library'
Step #1: (as 'lib' is unspecified)
Step #1: Warning in install.packages("mosaic") :
Step #1:   'lib = "/usr/local/lib/R/site-library"' is not writable
Step #1: Error in install.packages("mosaic") : unable to install packages
Step #1: Execution halted
Step #1: The command '/bin/sh -c R -e 'install.packages("mosaic")'' returned a non-zero code: 1
Finished Step #1
ERROR
ERROR: build step 1 "gcr.io/cloud-builders/docker" failed: step exited with non-zero status: 1
Step #1:

What am I doing wrong?

A: The example you link to has a sudo:
RUN sudo apt-get update && \
    sudo apt-get install -y r-base

RUN sudo R -e "install.packages('IRkernel', repos='http://cran.rstudio.com/')"
    ^^^^

You likely need that as well since you get a is not writable message.


text:
Q: Breakout game: Trouble with ball/paddle collisions and movements I'm having trouble with my method, my balls movement in breakout game and collisions between ball and paddle.
I have a bug too, when the ball hits left or right side on paddle. The bug does so the ball goes threw paddle and speed becomes alot faster after that.
So i'm asking you for another solution on ball movement so it's more flexible and alot like the real breakout game :)
    void BallPaddleCollisions()
    {
        //IF BALL HITS LEFT/RIGHT SIDE
        if (ball_rect.X > Window.ClientBounds.Width - ball_texture.Width || ball_rect.X < 0)
            ball_speed.X *= -1;

        //IF BALL HITS THE ROOF
        if (ball_rect.Y > Window.ClientBounds.Height - ball_texture.Height || ball_rect.Y < 0)
            ball_speed.Y *= -1;

        //IF BALL HITS THE BOTTOM
        if (ball_rect.Y > Window.ClientBounds.Height - ball_texture.Height)
        {
            //NEW VALUES TO BALL AND PADDLE
            ball_rect.X = (Window.ClientBounds.Width - ball_texture.Width) / 2;
            ball_rect.Y = 556;
            paddle_rect.X = (Window.ClientBounds.Width - paddle_texture.Width) / 2;
            paddle_rect.Y = 580;
        }

        //IF PADDLE HITS RIGHT SIDE, STOPS
        if (paddle_rect.X > Window.ClientBounds.Width - paddle_rect.Width)
            paddle_rect.X = (Window.ClientBounds.Width - paddle_rect.Width);

        //IF PADDLE HITS LEFT SIDE, STOPS
        if (paddle_rect.X < 0)
            paddle_rect.X = 0;

        //IF BALL HIT PADDLE
        if (paddle_rect.Intersects(ball_rect))
        {
            ball_speed.Y *= -1;

            //WHEN YOU HOLD LEFT KEY
            if (holdingleft == true)
            {
                ball_speed.X -= 3;
            }
            //WHEN YOU HOLD RIGHT KEY
            else if (holdingright == true)
            {
                ball_speed.X += 3;
            }
            //IF YOU ARE NOT HOLDING ANY KEY AND STANDING STILL WITH PADDLE
            else if (resetballspeed == true)
            {
                ball_speed.X = 1;
            }
        }
    }

        else if (ks.IsKeyDown(Keys.Space))
        {
            Start = true;
        }

        //IF YOU HIT SPACEBAR THIS WILL START
        if (Start == true)
        {
            ball_rect.X += (int)ball_speed.X;
            ball_rect.Y += (int)ball_speed.Y;
        }


text:
Q: Proper way to keep a single data in sql server? I have a table (myData) with lots of columns and rows,
and have another table (myFileNo) single value which means single row, single column, single cell (FileNo),
I wrote an sql query which updates myData by checking  myFileNo, and after process ends it changes the value of FileNo.
It does not make much sense to me to keep the single value data in a table, is this the proper way to do it ?
Edit: purpose of FileNo
It acts as an identification number, but not created like a primary key. An example (before, and after):
Before
myData, FileNo
A, NULL
A, NULL
B, NULL
C, NULL
A, NULL
D, NULL
D, NULL

FileNo: 15
After
myData, FileNo
A, 16
A, 16
B, 17
C, 18
A, 16
D, 19
D, 19

FileNo: 19

A: In the case that the fileNo is being referenced by multiple tables and processes then storing it in a table is fine, you could investigate extended properties, but I would keep it in a table.
If you only need it for this table and you only need to be able to identify the maximum value + 1 for the next load, I suggest you just check Max(FileNo) before inserting, providing this does not cause performance issues, based on the size of the table.


text:
Q: delete directories step by step without calculate the whole amount before I have a lan hard disk, on which are millions of files i will delete. But everytime I call the delete function (Windows-Explorer or rmdir) the system calculates to death before any file will be deleted. So i'm searching for an automated way to delete files and directories iterativley ad hoc.

A: I've created me a batch file that handles me the above features. So I can start the script an it will erase files ad hoc. Even if I have to pause I can abort the script and continue at a later time with the processing at the point I cancelled the script before:
@echo off
set OFFSETDIR="%1"
if "%OFFSETDIR%"=="" goto HELP
pushd %OFFSETDIR%
cd /d %OFFSETDIR%
set OFFSETDIR="%cd%"

:PSUBDIR
for /f "tokens=*" %%D in ('DIR /A:D /b') do (
pushd "%%~fD"
goto PSUBDIR
)
echo [INFO] erase /F /Q "%cd%\*"
erase /F /Q "%cd%\*"
if errorlevel 1 goto ANYERROR
if "%cd%"==%OFFSETDIR% goto PEND
set LASTSUBDIR="%cd%"
popd
echo [INFO] rmdir /q %LASTSUBDIR%
rmdir /q %LASTSUBDIR%||rem
if errorlevel 1 goto ERASEHIDDEN
goto PSUBDIR

:ERASEHIDDEN
echo [WARNING] there was an error when trying to rmdir %LASTSUBDIR%
echo [WARNING] this may be in cause of existing hidden files in the directory. so...
echo [INFO] erase /F /Q /A:H %LASTSUBDIR%\*
erase /F /Q /A:H %LASTSUBDIR%\*
if errorlevel 1 goto ANYERROR
echo [INFO] hidden files erased successfully. second try for rmdir %LASTSUBDIR%
rmdir /q %LASTSUBDIR%||rem
if errorlevel 1 goto ANYERROR
goto PSUBDIR

:ANYERROR
echo [ERROR] the script has cancelled due to an unhandled error
popd
goto SEND

:PEND
echo [INFO] the script has successfull ended
popd
goto SEND

:HELP
echo [INFO] A little script to erase iterative recursivley files and directories.
echo [INFO] Usage: %0 PATH_TO_DELETE
echo [INFO] the script will delete all files an directories below the given path.
echo [INFO]
echo [INFO] directories will be erased with rmdir /q
echo [INFO] /q supresses the user-confirmation
echo [INFO] files will be erased with erase /f /q
echo [INFO] /f means to delete also readonly-files
echo [INFO] /q supresses the user-confirmation
echo [INFO] when the rmdir will fail, there's a second try to erase also hidden files
echo [INFO] with option /a:h

:SEND
echo.


text:
Q: Codenameone list scrollbar quetions I have a list and its scroll bar on the right along with two custom buttons representing upscroll and downscroll. These two buttons simulate scrolling by using list.setSelectedIndex(index, true) and are placed above and below my scrollbar via my custom layout.
I have two questions regarding this:
1). Since the upscroll and downscroll buttons are overlayed on top of the list, they disappear when i click elsewhere..and they kind of flash into appearance when i click the area it's supposed to be in. How can I remedy this behavior?
2). I have a scrollbar image that I have used in the "Scroll" theme in the GUI builder. It's alignment is IMAGE_ALIGNED_CENTER. However the scroll thumb doesn't reach the end of the bar when i scroll to the end of the list via my upscroll and downscroll buttons. The upscroll and downscroll buttons essentially scroll the list by one index with each press (using setSelectedIndex(index, true)).
Thanks

A: How do you overlay the buttons. I'm assuming you just set them into a specific location which disallowed as we can't possibly adapt them to the various resolutions. I suggest reading the developer guide section on layouts very carefully.
To place something on top of the list in a portable way you need to use the LayeredLayout or the LayeredPane and a Container + correct layout to position this within (e.g. BorderLayout EAST).
In this blog post there is a sample for making a scrollbar but it isn't "on top". It can be used as a starting point.


text:
Q: TypeScript `not assignable` to seemingly identical type In the following code, TypeScript gives an error saying Type '(...params: P) => O' is not assignable to type 'T[K]' on the obj[key] assignment although it seems to me like it should be fine.
type Function <P extends any[], O> = (...params: P) => O

type Z <K extends string | number | symbol, P extends any[], O> = {
  [key in K]: Function<P, O>
}

/**
 * Wraps an existing function to call the given function with the result.
 * The original function is functionally identical.
 */
export function consumer <
  T extends Z<K, P, O>,
  K extends keyof T,
  P extends any[],
  O
> (
  obj: T,
  key: K,
  consume: Function<[O], void>
) {
  obj[key] = (...params: P) => {
    const value = obj[key](...params)
    consume(value)
    return value
  }
}


text:
Q: mongoose, getting object's id after using collection.insert I'm trying to get the object id after adding it to the db (using collection.insert)
mongoose.model('Persons').collection.insert(person, function(err, newPerson) {
 console.log('lets see you', newPerson);
});

and from the console I'm getting only result: { ok: 1, n: 1 } in stand of the new obj, any ideas how can I rich to the new object ?
thanks!

A: You can use save() here
var Persons = mongoose.model('Persons');
var personJSON = {
  ..... // persons schema values you want to insert
};
var person = new Persons(personJSON);
var result = yield person.save();

result variable will contain all the fields you inserted along with _id


text:
Q: How to Babel Transpile Object.entries/values in Aurelia CLI app? When using IE11, I get errors like below anywhere my code uses Object.entries or Object.values:

Unhandled rejection TypeError: Object doesn't support property or method 'entries'...

My problem I figure stems from the code not being transpiled to ES5, but wasn't sure how to check or change my project settings for transpiling/Babel when using the Aurelia CLI.
Looking into it further, I believe the Babel/settings packaged with Aurelia don't support Object.entries/values (or other proposed ES2017 options) so I installed babel-preset-es2017 and babel-plugin-transform-runtime per another thread - Babel support for Object.entries
However, I wasn't able to figure out how to update the project to include these for transpiling. Adding in transform-runtime in the aurelia.json or .babelrc file breaks the au run and simply adding es2017 to the .babelrc file didn't seem to do anything. I was also looking at the jsconfig.json and transpile.js files, but couldn't figure out a solution.
aurelia.json file:
...
"transpiler": {
    "id": "babel",
    "displayName": "Babel",
    "fileExtension": ".js",
    "options": {
        "plugins": [
            "transform-es2015-modules-amd",
            "transform-runtime" <---tried
        ]
    },
    "source": "src/**/*.js"
},
...

.babelrc file:
{
    "sourceMap": true,
    "moduleIds": false,
    "comments": false,
    "compact": false,
    "code": true,
    "presets": ["es2015-loose", "stage-1", "es2017"], <---tried
    "plugins": [
        "syntax-flow",
        "transform-decorators-legacy",
        "transform-flow-strip-types",
        "transform-runtime" <---tried
    ]
}

Adding the transform-runtime in either results in the following error:

Error: ENOENT: no such file or directory, open 'C:\Users...\src\babel-runtime\helpers\classCallCheck.js'

Not sure why I'm getting this error or if fixing it would help, but my guess could be because of the "source": src/**/*.js in aurelia.json
Any help would be greatly appreciated. Thanks!

A: My solution was installing the following plugin by doing npm install babel-plugin-transform-es2017-object-entries --save-dev, which transpiles object.entries and object.values.
The .babelrc file then looked like this:
{
    "sourceMap": true,
    "moduleIds": false,
    "comments": false,
    "compact": false,
    "code": true,
    "presets": ["es2015-loose", "stage-1"],
    "plugins": [
        "syntax-flow",
        "transform-decorators-legacy",
        "transform-flow-strip-types",
        "transform-es2017-object-entries"
    ]
}

Additionally, according to the Babeljs.io (https://babeljs.io/docs/plugins/preset-es2017/), it appears babel-preset-es2017 does not included a plugin/support for object.entries/values. Also, the purpose of babel-tranform-runtime appears to be for something different from what I needed and is not part of my solution.


text:
Q: Is it correct to use the word "come" followed by a date or time at the beginning of a sentence? Is it formally or grammatically correct or appropriate to use the word "come" - followed by a date or time - in the beginning of a sentence?
For example : "Come June and things started falling apart".
If not then what should be the appropriate or acceptable version?

A: Harold Wentworth, American Dialect Dictionary (1944) has this relevant coverage of come followed by a time-related noun:

come ... 3. Used with a term expressing future time, = 'when (that time) comes'; — now oldfashioned.

And Dictionary of American Regional English (1985) has this:

come v ... Intr[ansitive] senses. ... 5 Of a specified time or seasonal event: to arrive, come to pass—used in inverted constr[uction]s. {Survival of arch[aic] subjunc[tive] constr[uction] ...} esp[ecially] S[outh] Midl[and]

"South Midland" refers to a geographical band of the United States that runs approximately east to west from Maryland to northeastern Oklahoma and north to south from the Ohio River Valley to the northern quarter of Louisiana, Mississippi, and Alabama.
Although Wentworth is certainly correct that "come [time frame]" most often occurs in connection with discussions of future events, DARE points out instances in which speakers apply it to past events, such as this one recorded in Georgia/Alabama in 1908:

Come Friday a week ago, I went to see him about it.

meaning that the speaker had gone to see the person on the preceding Friday, which wasn't yet a full week before.
Much more common, however, are instances such as this one (also mentioned by DARE) recorded in Tennessee in 1954:

I'll do that come spring.

meaning that the speaker will do the thing in question when the next spring season arrives. The sentence would be equally valid if the "come spring" component came first:

Come spring, I'll do that.

The particular sentence that the poster asks about is

Come June and things started falling apart.

In colloquial U.S. English, I think, a speaker would most likely not include the "and" in that construction, but otherwise it sounds fine to me, albeit somewhat regional or old-fashioned (as Wentworth puts it) as a way of saying either "When June came, things started falling apart" or "And then June came, and things started falling apart." In writing it without the and, I would add a comma after June:

Come June, things started falling apart.

A: The relevant definition is

2 c 2 : to come to pass : take place —used in the subjunctive with inverted subject and verb to express the particular time or occasion

There is a rather formal discussion of the grammar in the book Contrastive Studies in Morphology and Syntax.
Any time reference can be used - a day, an hour, a season, etc.  Yes, it is normal and acceptable to begin sentences this way, although as a native US English speaker I think it is somewhat informal.  Here are some examples from real usage:

Come Friday, they were forgiven.

But come spring, I'm quitting the mill.

Come five o'clock, the atmosphere was just unbelievable


text:
Q: Save Image From URL in a Specific Location in Android I'm creating an app that downloads images off the internet! Images are downloaded without a problem! But the problem is that they get downloaded in an unknown folder,and those downloaded images are not seen in the gallery app!
How can I download images in a specific gallery folder that they are visible in the gallery as well?
 Thanks in advance!
Download Method:
    DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    Uri uri = Uri.parse(url);
    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setDescription("Downloading Wallpaper").setTitle("Downloading");
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    myDownloadReference = dm.enqueue(request);

    Toast.makeText(Wallpaper.this, "Downloading..", Toast.LENGTH_SHORT).show();
}

A: image url to bitmap
 try {
        URL url = new URL("http://....");
        Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    } catch(IOException e) {
        System.out.println(e);
    }

 public void saveImageToExternal(String imgName, Bitmap bm) throws IOException {
    //Create Path to save Image
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+appFolder); //Creates app specific folder
    path.mkdirs();
    File imageFile = new File(path, imgName+".png"); // Imagename.png
    FileOutputStream out = new FileOutputStream(imageFile);
    try{
        bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
        out.flush();
        out.close();

        // Tell the media scanner about the new file so that it is
        // immediately available to the user.
        MediaScannerConnection.scanFile(context,new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                Log.i("ExternalStorage", "Scanned " + path + ":");
                Log.i("ExternalStorage", "-> uri=" + uri);
            }
        });
    } catch(Exception e) {
        throw new IOException();
    }
    }

A: Try this after downloading file :
 // refresh gallery
            try {
                MediaScannerConnection.scanFile(getActivity(), new String[]{savedImagePath}, null, new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(String path, Uri uri) {
             //   ApplicationUtil.showToast(getActivity(), "onScanCompleted!");
                   }
               });
            } catch (Exception e) {
            }

This will refresh your gallery.

A: Please check out the following links:
To set the location for the downloaded file:
https://developer.android.com/reference/android/app/DownloadManager.Request.html#setDestinationUri(android.net.Uri)
http://www.programcreek.com/java-api-examples/index.php?class=android.app.DownloadManager.Request&method=setDestinationUri
To make the downloaded file scannable by MediaScanner:
https://developer.android.com/reference/android/app/DownloadManager.Request.html#allowScanningByMediaScanner()
https://www.codota.com/android/methods/android.app.DownloadManager.Request/allowScanningByMediaScanner

A: you need to convert image uri to file and save it in internal or external storage, Convert uri to file like this
File myFile = new File(uri.getPath());

For saving file in local refer this link
saving files in storage android
I hope it helps.


text:
Q: Multithreading with shared_ptr I gos tuck in my simple multithreading application which I am using as a simple test bench. What I want to achieve is to modify value of one variable passed to multiple threads and after all are done read the result.
#include <iostream>
#include <memory>
#include <thread>
#include <mutex>

void updateValue(const std::shared_ptr<int>& value);

int main()
{
    auto sp = std::make_shared<int>(0);
    std::thread incrementThread_1(updateValue,sp);
    std::thread incrementThread_2(updateValue,sp);
    incrementThread_1.join();
    incrementThread_2.join();
    std::cout << *sp << std::endl;
}

void updateValue(const std::shared_ptr<int>& value)
{
    std::mutex g_i_mutex;
    for(int i = 0; i<100;i++)
    {
        std::unique_lock<std::mutex> lk(g_i_mutex);
        (*value)++;
        lk.unlock();
    }
}

Currently it just crashes. I don't have any meaningful info in debug window, so it's also not helping. Can someone please tell me what I might did wrong?
One thing to point out - I don't want to use global variables, because the functions originally are in different files.

A: Data that is shared between threads needs to ship its own mutex (which is shared with the exact same set of threads) and require all accessors to agree to use that mutex to serialize access.
A typical solution is to provide a custom type to encapsulate this responsibility. With this approach, your code would look roughly as follows:
struct SyncInt
{
    int n = 0;
    std::mutex mx;
};

void updateValue(SyncInt & value)
{
    for (int i = 0; i != 100; ++i)
    {
        std::lock_guard<std::mutex> lock(value.mx);
        ++value.n;
    }
}

int main()
{
    SyncInt v;
    std::thread t1(updateValue, std::ref(v)), t2(updateValue, std::ref(v));
    t1.join();
    t2.join();
    std::cout << v.n << "\n";
}

(Note that the shared pointer in your example was not material to the question regarding concurrency, since all your code only ever used the pointee, never the pointer itself.)

A:
Currently it just crashes. Can someone please tell me what I might did
  wrong?

You are updating shared variable value from 2 different thread actually without any synchronization. This is data race condition which is Undefined Behavior. The simplest way to fix it is to make g_i_mutex global:
#include <iostream>
#include <memory>
#include <thread>
#include <mutex>

std::mutex g_i_mutex;

void updateValue(const std::shared_ptr<int>& value);

int main()
{
    auto sp = std::make_shared<int>(0);
    std::thread incrementThread_1(updateValue,sp);
    std::thread incrementThread_2(updateValue,sp);
    incrementThread_1.join();
    incrementThread_2.join();
    std::cout << *sp << std::endl;
}

void updateValue(const std::shared_ptr<int>& value)
{
    for(int i = 0; i<100;i++)
    {
        std::unique_lock<std::mutex> lk(g_i_mutex);
        (*value)++;
        lk.unlock();
    }
}

Another solution without global variable:
#include <iostream>
#include <memory>
#include <thread>
#include <mutex>

void updateValue(const std::shared_ptr<int>& value, std::mutex& g_i_mutex)
{
    for(int i = 0; i<100;i++)
    {
        std::unique_lock<std::mutex> lk(g_i_mutex);
        (*value)++;
        lk.unlock();
    }
}

int main()
{
    auto sp = std::make_shared<int>(0);
    std::mutex g_i_mutex;
    std::thread incrementThread_1(updateValue, sp, std::ref(g_i_mutex));
    std::thread incrementThread_2(updateValue, sp, std::ref(g_i_mutex));
    incrementThread_1.join();
    incrementThread_2.join();
    std::cout << *sp << std::endl;
}

A: On the merits of the question, there is no need to use shared_ptr in this scenario at all. All you need is an atomic<int>.

A: You want to use a data structure something like this, which strongly ties your mutex to the piece of data it's protecting access to:
class somethingShared
{
    int        m_value;
    std::mutex m_mtx;

    public:
    somethingShared( int initialVal ) : m_value( initialVal ) { }

    void increment()
    {
        std::unique_lock<std::mutex> lk(m_mtx);
        ++m_value;
    }

    int value() const { return m_value; }

};

void updateValue( somethingShared & value)
{
    for ( int i = 0; i < 100; ++i )
    {
        value.increment();
    }
}

N.B. I haven't compiled or run this, it's just to show the general idea.


text:
Q: GPM annual precipitation using Google earth engine I'm trying to calculate GPM v6 annual precipitation using the google earth engine.
but show this error:
Line 11: ee.ImageCollection(...).select(...).filterDate(...).filterBounds(...).clip is not a function

I'm using this code:
Map.addLayer(geometry);
Map.centerObject(geometry);

var ano_inicial = 2000
var ano_final = 2020
var mes = ee.List.sequence(1,12)
var intervalo = ee.List.sequence(ano_inicial,ano_final)
var inicio =  ee.Date.fromYMD(ano_inicial,1,1);
var fim = ee.Date.fromYMD(ano_final,12,31);

var GPM = ee.ImageCollection('NASA/GPM_L3/IMERG_V06')
    .select('IRprecipitation')
    .filterDate(inicio,fim)
    .filterBounds(geometry)
    .clip(geometry);

var GPM_Anual = ee.ImageCollection.fromImages(
  intervalo.map(function (ano) {
    var annual = GPM.filter(ee.Filter.calendarRange(ano,ano,'year'))
    .sum()
    .multiply(24*30*12)
    .clip(table)
    return annual
    .set('year',ano)
    .set('system:time_start',ee.Date.fromYMD(ano,1,1))
    }))

Export.image.toDrive({
  image : GPM_Anual,
  description : 'GPM_annual_2000_2020',
  scale : 1000,
  region : geometry,
  maxPixels : 1e9
});

what is wrong?

A: clip is a function you can apply to images only, you are now trying to apply to the entire imageCollection. Instead you need to map over the entire collection (=select individual images) and clip it.
.map(function(img){
      return img.clip(geometry)
    })

https://code.earthengine.google.com/9ad4f0384def03fafe12fc94a3ab5f5d


text:
Q: Recursive linked list in C I've just tried to implement a recursive linked list append in C, and for some reason l keeps being NULL no matter what I do, even though I malloc when encountering a NULL value.
The following code prints nothing. Any ideas?
#include <stdlib.h>
#include <stdio.h>

typedef struct node {
  unsigned v;
  struct node* next;
} node;

void insert(unsigned x, node* l) {
  if (l == NULL){
    node* new_node = (node*)malloc(sizeof(node));
    new_node->v = x;
    new_node->next = NULL;
    l = new_node;
  }
  else {
    insert(x, l->next);
  }
}

void print(node *l) {
  if (l == NULL) return;
  printf("%d\n", l->v);
  print(l->next);
}

int main(){

  node* l = NULL;
  insert(1, l);
  insert(2, l);

  print(l);

  return 0;
}

Help much appreciated.
EDIT: Even if I initialize it, it's still the same.

A: First off, you're passing l to your function by value so you won't see any changes made to it. Currently, when you set l to new_node, you only change the local value of l in the method insert. You may want to modify your function to return l and set l in your main to the return value of this function.
node *insert(int x, node *l){
  //.... your method
  return l;
}

In main:
node *l = NULL;
l = insert(1, l);
l = insert(2, l);

Second, your recursive call will not append nodes to your LL for the same reason. Change that call to this:
 l->next = insert(x, l);

A: #include <stdlib.h>
#include <stdio.h>

typedef struct node {
unsigned v;
struct node* next;
} node;

node* insert(unsigned x, node** ll) {
  if (*ll == NULL){
*ll = (node*)malloc(sizeof(node));
(*ll)->v = x;
(*ll)->next = NULL;

  }
  else {
    insert(x, &(*ll)->next);
}
}

void print(node *l) {if (l == NULL) return;
printf("%d\n", l->v);
print(l->next);
}

int main(){

node* l = NULL;
insert(1, &l);
insert(2, &l);
print(l);

return 0;
}

compiled with no gcc no switches
output:
1
2