text:
Q: Resample pandas times series that contains elapsed time values I have time series data in the format shown on the bottom of this post.
I want to re-sample the data to 30 minute intervals but i need the Time in State values to be split accordingly to the correct interval (these values are expressed in whole seconds).
Now imagine for a certain row the Time in State is 2342 seconds (more than 30 minutes) and say the start time is at 08:22:00.
User    Start Date  Start Time  State   Time in State (secs)
J.Doe   03-02-2014  08:22:00    A       2342

When the re-sample is done I need for the Time in State to be split accordingly into the  periods it overflows into, like this:
User    Start Date  Time Period State   Time in State (secs)
J.Doe   03-02-2014  08:00:00    A       480
J.Doe   03-02-2014  08:30:00    A       1800
J.Doe   03-02-2014  09:00:00    A       62

480+1800+62 = 2342
I'm completely lost on how to achieve this in pandas...I would appreciate any help :-)
Source data format:
User    Start Date  Start Time  State   Time in State (secs)
J.Doe   03-02-2014  07:58:00    A       36
J.Doe   03-02-2014  07:59:00    A       43
J.Doe   03-02-2014  08:00:00    A       59
J.Doe   03-02-2014  08:01:00    A       32
J.Doe   03-02-2014  08:21:00    A       15
J.Doe   03-02-2014  08:22:00    B       3
J.Doe   03-02-2014  08:22:00    A       2342
J.Doe   03-02-2014  09:01:00    B       1
J.Doe   03-02-2014  09:01:00    A       375
J.Doe   03-02-2014  09:07:00    B       3
J.Doe   03-02-2014  09:07:00    A       6408
J.Doe   03-02-2014  10:54:00    B       2
J.Doe   03-02-2014  10:54:00    A       116
J.Doe   03-02-2014  10:58:00    B       2
J.Doe   03-02-2014  10:58:00    A       122
J.Doe   03-02-2014  10:58:00    A       12
J.Doe   03-02-2014  11:00:00    B       2
J.Doe   03-02-2014  11:00:00    A       3417
J.Doe   03-02-2014  11:57:00    B       3
J.Doe   03-02-2014  11:57:00    A       120
J.Doe   03-02-2014  11:59:00    C       165
J.Doe   03-02-2014  12:02:00    B       3
J.Doe   03-02-2014  12:02:00    A       7254

A: I would first create Start and End columns (as datetime64 objects):
In [11]: df['Start'] = pd.to_datetime(df['Start Date'] + ' ' + df['Start Time'])

In [12]: df['End'] = df['Start'] + df['Time in State (secs)'].apply(pd.offsets.Second)

In [13]: row = df.iloc[6, :]

In [14]: row
Out[14]:
User                                  J.Doe
Start Date                       03-02-2014
Start Time                         08:22:00
State                                     A
Time in State (secs)                   2342
Start                   2014-03-02 08:22:00
End                     2014-03-02 09:01:02
Name: 6, dtype: object

One way to get the split times is to resample from Start and End, merge, and use diff:
def split_times(row):
    y = pd.Series(0, [row['Start'], row['End']])
    splits = y.resample('30min').index + y.index  # this fills in middle and sorts too
    res = -splits.to_series().diff(-1)
    if len(res) > 2: res = res[1:-1]
    elif len(res) == 2: res = res[1:]
    return res.astype(int).resample('30min').astype(np.timedelta64)  # hack to resample again

In [16]: split_times(row)
Out[16]:
2014-03-02 08:22:00   00:08:00
2014-03-02 08:30:00   00:30:00
2014-03-02 09:00:00   00:01:02
dtype: timedelta64[ns]

In [17]: df.apply(split_times, 1)
Out[17]:
    2014-03-02 07:30:00  2014-03-02 08:00:00  2014-03-02 08:30:00  2014-03-02 09:00:00  2014-03-02 09:30:00  2014-03-02 10:00:00  2014-03-02 10:30:00  2014-03-02 11:00:00  2014-03-02 11:30:00  2014-03-02 12:00:00  2014-03-02 12:30:00  2014-03-02 13:00:00  2014-03-02 13:30:00  2014-03-02 14:00:00
0              00:00:36                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
1              00:00:43                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
2                   NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
3                   NaT             00:00:32                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
4                   NaT             00:00:15                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
5                   NaT             00:00:03                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
6                   NaT             00:08:00             00:30:00             00:01:02                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
7                   NaT                  NaT                  NaT             00:00:01                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
8                   NaT                  NaT                  NaT             00:06:15                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
9                   NaT                  NaT                  NaT             00:00:03                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
10                  NaT                  NaT                  NaT             00:23:00             00:30:00             00:30:00             00:23:48                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
11                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT             00:00:02                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
12                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT             00:01:56                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
13                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT             00:00:02                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
14                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT             00:02:00             00:00:02                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
15                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT             00:00:12                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
16                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT
17                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT             00:26:57                  NaT                  NaT                  NaT                  NaT                  NaT
18                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT             00:00:03                  NaT                  NaT                  NaT                  NaT                  NaT
19                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT             00:02:00                  NaT                  NaT                  NaT                  NaT                  NaT
20                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT             00:01:00             00:01:45                  NaT                  NaT                  NaT                  NaT
21                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT             00:00:03                  NaT                  NaT                  NaT                  NaT
22                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT                  NaT             00:28:00             00:30:00             00:30:00             00:30:00             00:02:54

To replace the NaTs with 0 it looks like you have to do some fiddling in 0.13.1 (this may already be fixed up in master, otherwise is a bug):
res2 = df.apply(split_times, 1).astype(int)
# hack to replace NaTs with 0
res2.where(res2 != -9223372036854775808, 0).astype(np.timedelta64)
# to just get the seconds
seconds = res2.where(res2 != -9223372036854775808, 0) / 10 ** 9


text:
Q: How to reduce duplicate outputs in Ruby? Currently, I was writing a code with Ruby to find out all the possible combination of numbers which equal to a sum. However, I meet the TLE problem and not all combination come out. The output came out with many duplicate combination such as:
sum([39,39,119,79,89,79,79,38,19,127.5,77,29,39,39,40,39,39])= 1009.5
sum([39,39,119,79,89,79,79,38,19,127.5,29,39,77,39,39,40,39])= 1009.5

Hope someone can teach me to modify my code in order to reduce the duplicate output and maybe this can help to solve TLE problem.Thanks.
My code:
def subset_sum(numbers,target,partial=[])
  s = partial.inject 0, :+
  puts "sum(#{partial})=#{target}" if s == target

  return if s >= target

  (0..(numbers.length - 1)).each do |i|
    n = numbers[i]
    remaining = numbers.drop(i+1)
    subset_sum(remaining ,target ,partial +[n])
  end
end

 > subset_sum([19,19,19,39,29,40,38,39,39,39,39,39,79,59,119,119,79,129,129,78,139,69.5,89,77,79,128,98,109,109,138,127.5,119,108,148,118],1009.5)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Definition of "a microservice"? I've seen many, many references to "microservice architecture". In those discussions, they almost never refer to "a microservice", but instead call it "a service".
In interest of my company getting terminology correct, would I be correct in saying that "a microservice" is not a real thing?

A: I think most refer to a microservice as a runnable instance, an endpoint, and directly correlate it to a Service in SOA (an autonomous technical authority of a business capability)...
But it should just be called an endpoint and we should try and define the business boundaries or Service Boundaries in our systems or else we will end up with a distributed monolith...
Therefore I suggest that a microservice as you said, does not mean anything...
This post might be a good read for you?

A: I would claim that a microservice should offer some characteristics:

*

*solves a single business problem in a minimal way (only solves one problem and that well)

*the operation's execution is idempotent (given the same input data the operation can be called multiple times without adverse effects to the data consistency)

*the operation is stateless (all State is provided as an input parameter). This would make the operation pure functional in developer speak

*the operation has minimal dependencies upon other operations

A: In the context of a microservices architected system, a service to a microservice is just like a config is to a configuration - a common shortening for everyday use.
The Microservices approach is about breaking your system ("pile of code") into many small services, each typically has its own:

*

*Clear business-related responsibility

*Running process

*Database

*Code version control (e.g. git) repository

*API (the protocol how other services / clients will contact the Microservice)

*UI

The services themselves are kept small so as your system grow, there are more services - rather than larger services.
It worth to mention that these days (2018) the "microservices approach" is still a buzz. Hence, people tend to describe a system's architecture as "microservices" even if only a single aspect of it actually match the approach.

A: The term micro-service is coined to have a clear domain defined for each of the service developed and its way beyond than a service.
A micro-service ideally works on a single responsibility and should avoid to take an extremely small responsibilities(anti nano pattern). Micro-service architecture referred as software system as a collection of independent(programming language selection, developed, deployed and scaled independently) loosely coupled services. It gives you the capability to scale horizontally on demand and can use many ways of communication among them and not have restriction over ways of communication like SOA architecture.
The responsibility of each service is to focus only on business value it creates and the other responsibilities can also be carved out using patterns like side car patterns.

A: Most concise definition I have ever came across is from Sam Newman
"Microservices are small, autonomous services that work together"


text:
Q: How to update and insert multiple row in Mysql I have an array $feedArraysomething like this
Array ( [0] => array('id'=>'3','val=>'Renta Comerciales'),
        [1] => array('id'=>'4','val=>'Renta de Casas'),
        [2] => array('id'=>'6','val=>'Venta de Casas '),
        [3] => array('id'=>'7','val=>'Venta de Departamentos'),
        [4] => array('id'=>'1','val=>'Venta de Terrenos') )

I have to make two query in a table called categoriasPlantilla
Then table has three columns
plantilla ,categoriaFeed, id

I have to check if the val of the array exist  in the categoriafeed  column of table then I have to update that id with the array id
if not then I have to insert a new row to the table
The value for plantilla is 11
I know how to do multiple insert in one query but how I can build such a query for update ?
To begin I was thinking of doing something like this
$sql = "INSERT INTO categoriaplantilla (plantilla,categoriafeed,id) values ";
    $sqlUpdate = "UPDATE  categoriaplantilla ";
    foreach($feedArray as $key =>$val)
    {
        $sqlUpdate . =;
        $sql . = ;
    }

Please help me out
Thanks & Regards

A: You can't update rows set in one query. One row - one query. Also, you can use something like this
UPDATE table SET field1='aaa', field2='bbb' where id IN (1, 2,4).

But this query will set equal data to each row.
Sometimes I use this one
INSERT INTO table(field1, field2) VALUES ('aaa', 'bbb')
ON DUPLICATE KEY
UPDATE SET field1='aaa', field2='bbb' where id IN (1, 2,4)

ps if you are use PK in your query, you may forgot about preformance almost in any case.

A: Most solutions used are based on checking primary keys, like INSERT INTO... ON DUPLICATE KEY, or REPLACE INTO....
But, if you are checking non-primary keys which is column categoriaFeed as you mentioned, I suggest you can create a mysql procedure to do that using mysql functions.
The basic code should be like this:
DROP PROCEDURE IF EXISTS func;

DELIMITER //
CREATE PROCEDURE func()
BEGIN
    IF '123' in ('Renta Comerciales', 'Renta de Casas', 'Venta de Casas') THEN
        UPDATE `may` SET `fone` = 'aaaaa' WHERE `id` = 1;
    ELSE
        INSERT INTO `may` VALUES ('1','2','3');
    END IF;
END//
DELIMITER ;

CALL func();

The 123 equals to your val, you can check if it's in your given array. Then you can just update or insert data by the if-statement.
This is probably an useful way to solve your problem. I'm in GMT+8 time zone and I'm gonna sleep now, it's 23:00PM. I'll check your replies tomorrow to see what I can help then.


text:
Q: ASP Dropdown list with options set to false I have a dropdownlist of the form:
 <asp:DropDownList runat="server" CssClass="holdTypeDDL" ID="holdTypeDDL"></asp:DropDownList>

and is filled onload in c# codebehind of an aspx page when !Page.isPostback via :
 holdTypeDDL.Items.Add(new ListItem(string.Empty, false.ToString()));
            holdTypeDDL.Items.Add(new ListItem(HoldTypeType.Now.Description(), false.ToString()));
            holdTypeDDL.Items.Add(new ListItem(HoldTypeType.AAHoldType.Description(), true.ToString()));
            holdTypeDDL.Items.Add(new ListItem(HoldTypeType.AAAHoldType.Description(), true.ToString()));
            holdTypeDDL.Items.Add(new ListItem(HoldTypeType.AAAAHoldType.Description(), false.ToString()));

I have noticed if one of the options of the select are selected that have a string value of False, it does not consider it selected. I.e. the selected index is 0 after postback. If an item with true is selected and value grabbed on postback, it works fine.
I cannot find any documentation as to why this is. Why does having a "False" string in the value of an option element make it not post back properly?
EDIT:
Renders in HTML as such:
<select class="holdTypeDDL" id="BodyContent_holdTypeDDL" name="ctl00$BodyContent$holdTypeDDL">
    <option value="False"></option>
    <option value="False">Now</option>
    <option value="True">AA Hold Type</option>
    <option value="True">AAA Hold Type</option>
    <option value="False">AAAA Hold Type</option>

</select>

A: I believe values should be unique. Because you have multiple True, False values, when it marks it as selected, it takes the first one with that value as selected. Why are you using these values? You could use the same as the Text, or change the values like this:
holdTypeDDL.Items.Add(new ListItem(string.Empty, false.ToString() + "0"));
holdTypeDDL.Items.Add(new ListItem(HoldTypeType.Now.Description(), false.ToString() + "1"));
holdTypeDDL.Items.Add(new ListItem(HoldTypeType.AAHoldType.Description(), true.ToString() + "2"));
holdTypeDDL.Items.Add(new ListItem(HoldTypeType.AAAHoldType.Description(), true.ToString() + "3"));
holdTypeDDL.Items.Add(new ListItem(HoldTypeType.AAAAHoldType.Description(), false.ToString() + "4"));

That should work.


text:
Q: Biztalk CSV file - Calling Stored procedure I have a requirement in that I receive CSV files from various sources with different formats. All the mappings are done in a SQL stored procedure. I would like to use the BizTalk to transfer the CSV files from SFTP locations to a local folder and inform SQL server that a file a received. Thus, from BizTalk I need to call a stored procedure only once per file. Not once for each line in the file. How can I achieve this?

A: You can achieve your goal by using ths sql adapter.
-create a receive location when you receive files
-a stored procedure with an xml parameter to put within all the file content
-an orchestration where receive the message containing your csv file content
-from biztalk generate a schema to call your stored procedure with the content of your
Have a look on this sample : https://msdn.microsoft.com/en-us/library/ms935658(v=bts.10).aspx

A: I do not think you should use BizTalk here. all you need to do is load the csv file, pass its content to a sql sp.


text:
Q: ubuntu dual boot 14.04 dell inspiron - wifi does not work My computer is the following: Dell - Inspiron 15 - 7000 Series - Model: 7559
Display:
15.6" Full HD display with webcam Performance:
Intel Core i5-6300HQ Processor 8GB RAM 256GB Solid State Drive (SSD) NVIDIA GeForce GTX, 960M 4GB Graphics
I have installed ubuntu 14.04 wifi isnt working because I cant find wifi driver.
infy@infy:~$ lspci -knn | grep Net -A2
05:00.0 Network controller [0280]: Intel Corporation Device [8086:3165] (rev 79)
    Subsystem: Intel Corporation Device [8086:4410]

A: You need to upgrade the kernel.
Connect to internet by wire or some other way and run in terminal:
sudo apt-get install linux-generic-lts-wily
wget http://mirrors.kernel.org/ubuntu/pool/main/l/linux-firmware/linux-firmware_1.156_all.deb
sudo dpkg -i linux-firmware_1.156_all.deb
sudo cp /lib/firmware/iwlwifi-7265D-13.ucode  /lib/firmware/iwlwifi-3165-13.ucode

and reboot.


text:
Q: Get value out JSON Object containing JSON arrays How can I get the value of "distance" out of the following JSON object with java?
{
  "destination_addresses" : [ "New York City, New York, Verenigde Staten" ],
  "origin_addresses" : [ "Washington D.C., District of Columbia, Verenigde Staten" ],
  "rows" : [
    {
       "elements" : [
          {
             "distance" : {
                "text" : "225 mijl",
                "value" : 361714
             },
             "duration" : {
                "text" : "3 uur 51 min.",
                "value" : 13877
             },
             "status" : "OK"
          }
       ]
    }
 ],
 "status" : "OK"
}

I tried:
json.getJSONArray("rows").getJSONObject(0).getJSONObject("distance").toString();
But I always get org.json.JSONException: JSONObject["distance"] not found.

A: I think you are missing the second array "elements", you find array "row" so get object 0, in object 0 you need to find the "elements" array then take the object 0 again, so you can get the "distance" object.
Try this:
json.getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getJSONObject("distance").toString();

Again, I think. I hope this helped you.

A: Use java-json.jar
Convert JSON String to object and fetch the element.
You can refer this.
Try this:
package Sample;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class TestMain
{

    public static void main(String[] args) throws JSONException
    {
        String s="{  \"destination_addresses\" : [ \"New York City, New York, Verenigde Staten\" ],  \"origin_addresses\" : [ \"Washington D.C., District of Columbia, Verenigde Staten\" ],  \"rows\" : [    {       \"elements\" : [          {             \"distance\" : {                \"text\" : \"225 mijl\",                \"value\" : 361714             },             \"duration\" : {                \"text\" : \"3 uur 51 min.\",                \"value\" : 13877             },             \"status\" : \"OK\"          }       ]    } ], \"status\" : \"OK\"} ";

        JSONObject jsonObj = new JSONObject(s);

        JSONArray array= (JSONArray) jsonObj.get("rows");

        JSONObject jsonObj2 =(JSONObject) array.get(0);

        JSONArray array2= (JSONArray)jsonObj2.get("elements");

        JSONObject jsonObj3 =(JSONObject) array2.get(0);

        System.out.println(jsonObj3.get("distance"));

    }
}

OUTPUT:

{"text":"225 mijl","value":361714}


text:
Q: How do I get rows numbers from a DataFrame based on some equations? how do i get rows list where condition equals in rows at python?
i'm trying to drop outliers and show to user which rows numbers are dropped in list like:
0,5,21,58 dropped.
y= (df[x].loc[df[x] <= low_lim])
        print(y)
        print(type(y))

i tried that and get only one value
0
<class 'numpy.int64'>

A: If you create the binary mask and apply it on different rows, you can then check from the mask what rows were dropped. Also, the mask works such that you specify which value you want to keep, not drop, so you have to use > instead if you want to drop value below your lower limit:
import pandas as pd
import random

# Randomize data
df = pd.DataFrame({"x": [random.randint(0, 10) for _ in range(10)], "y": [random.randint(10, 20) for _ in range(10)]})
low_lim = 5
# Create binary mask
mask = (df["x"] > low_lim)
# Drop rows according to binary mask
df_masked = df[mask]
# Make list from mask row indexes that are False i.e. dropped
dropped = list(mask[mask == False].index)
print(df_masked)
print(dropped)


text:
Q: Split String At Every Non-Letter/Non-Number Character Imagine a string that contains special characters like $§%%,., numbers and letters.
I want to receive the letter and number junks of an arbitrary string as an array of strings.
A good solution seems to be the use of regex, but I don't know how to express [numbers and letters]
// example
"abc" = {"abc"};
"ab .c" = {"ab", "c"}
"ab123,cd2,  ,,%&$§56" = {"ab123", "cd2", "56"}

// try
string input = "jdahs32455$§&%$§df233§$fd";
string[] output = input.Split(Regex("makejunksfromstring"));

A: To extract chunks of 1 or more letters/digits you may use
[A-Za-z0-9]+   # ASCII only letters/digits
[\p{L}0-9]+    # Any Unicode letters and ASCII only digits
[\p{L}\p{N}]+  # Any Unicode letters/digits

See a regex demo.
C# usage:
string[] output = Regex.Matches(input, @"[\p{L}\p{N}]+").Cast<Match>().Select(x => x.Value).ToArray();

A: Yes, regex is indeed a good solution for this.
And in fact, to just match all standard words in the input sequence, this is all you need:
(\w+)

Let me quickly explain
\w matches any word character and is equivalent to [a-zA-Z0-9_] - matching a through z or A through Z or 0-9 or _, you might wanna go with [a-zA-Z0-9] instead to avoid that underscore.
Wrapping an expression in () means that you want to capture that part as a group.
The + means that you want sequences of 1 or more of the preceding characters.
Refer to a regular expression cheat sheet to see all the possibilities, such as
https://cheatography.com/davechild/cheat-sheets/regular-expressions/
Or any that you find online.
Also there are tools available to quickly test out your regular expressions, such as
https://regex101.com/ (quite well visualised matching)
or http://regexstorm.net/tester specifically for .NET


text:
Q: Audio URL cannot be played even though the file exists and is reachable I have written a download function in my app which downloads a .mp3 file from a url and saves it into Application Support directory locally.
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
     if let url = downloadTask.originalRequest?.url {
            let destinationURL = moveFileToSupportDirectory(source: location, fileName: url.lastPathComponent , subDir: "MyApp")
            onDownloadComplete?(destinationURL, nil)
     }
}

func moveFileToSupportDirectory(source: URL, fileName: String, subDir: String) -> URL? {
    do {
        let manager = FileManager.default
        let directoryURL = try manager.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent(subDir)
        let destination = directoryURL.appendingPathComponent(fileName)
        do {
            try FileManager.default.createDirectory (at: directoryURL, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print("Error creating directory: \(error)")
            return nil
        }
        if FileManager().fileExists(atPath: destination.path) {
            print("File already exists [\(destination.path)]")
            return destination
        }
        else {
            print("Move from \(source.path) to destination \(destination.path)...")
            try manager.moveItem(at: source, to: destination)
            return destination
        }
    } catch {
        printTrace("\(error)")
        return nil
    }
}

After that when user presses "Play" button, the app will retrieve the saved URL using fileName and play it locally.
The function of retrieving URL:
func getSavedURL(of name: String) -> URL? {
    do {
        let manager = FileManager.default
        let directoryURL = try manager.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("MyApp")
        let destination = directoryURL.appendingPathComponent(name)
        if FileManager().fileExists(atPath: destination.path) {
            print("File exists [\(destination.path)]")
            let isReachable = try destination.checkResourceIsReachable()
            if isReachable {
                print("File is reachable \(destination.absoluteString)")
                return destination
            } else {
                print("File is unreachable")
                return nil
            }
        }
        else {
            print("File \(name) doesn't exist")
            return nil
        }
    } catch {
        print("\(error)")
        return nil
    }
}

The question is that when I download and play it in the same build, all works perfectly. However if I start another build and play the file saved previously, the audio player will throw following error:
ExtAudioFile.cpp:193:Open: about to throw 'wht?': open audio file
[avae]            AVAEInternal.h:109   [AVAudioFile.mm:134:AVAudioFileImpl: (ExtAudioFileOpenURL((CFURLRef)fileURL, &_extAudioFile)): error 2003334207

From this thread the error seems to be related to nil of audio file:
OSStatus error 2003334207 when using AVAudioPlayer
But when retrieving the URL it has already passed all the checks (i.e. exists and is reachable) and return a non-nil URL. How come the audio file cannot be played properly even though it does exist and is reachable?
Is it related to this sandbox issue?
Document directory path change when rebuild application.
But I retrieve the URL using the relative method, I think this should not happen in my case.
p.s. I use SwiftAudioPlayer to play my audio file locally. It seems to use AudioEngine inside.


text:
Q: Accessing a node.js global module The npm documentation says this:

*

*If you're installing something that you want to use in your program, using
  require('whatever'), then install it locally, at the root of your project.

*If you're installing something that you want to use in your shell, on the command line or
  something, install it globally, so that its binaries end up in your PATH environment variable.

I am currently writing --- or, at least, trying to write --- a genuine command line program in node that's intended to be used from the shell. Therefore, according to the above, my dependencies should be installed as global modules.
How do I actually use a global module installed with npm in node? Calling require() doesn't work, of course, because the npm global module directory (/usr/local/lib/node_modules) isn't on the path by default. I can make it working by explicitly adding it to the path at the top of my program, but that's a really lousy solution because it's not portable --- it requires knowledge of where the npm's global module directory is on any given system.
Just to make life even more aggravating, I have some global modules installed via dpkg. These have been put in /usr/lib/nodejs, and they just work. This confuses me, because if global modules aren't supposed to be used for ordinary applications I would expect neither to be on the path; or else I would expect them both to be on the path and requiring global modules to just work everywhere. Having one but not the other seems very odd. What's going on here?
Update: I should point out that this program is just a script, with #!/usr/bin/env nodejs at the top; it's not a formal node module, which is way overkill for something quite this trivial. As the Debian modules are all requireable from such a script, it seems sensible to me that npm's global modules should be requireable too, but I have a feeling that this is a Debianism...

A:
Therefore, according to the above, my dependencies should be installed as global modules.

Not quite.
It meant that your module could be installed as a global so its binaries would be available from the shell:
npm install -g your-module
your-module-binary --option etc.

Its dependencies, on the other hand, should be installed following the 1st point, residing in a node_modules directory within your project (generally specified in a package.json so npm can manage them).
But, global modules aren't (normally) available for require. They don't follow Loading from node_modules folders, which npm follows for local modules, and their path isn't typically listed in the NODE_PATH variable for Loading from global folders.

A: So the instructions you have pertain to npm modules, but you are doing local development. Here are some guidelines.
In terms of your source code, you only need 2 types of require statements
var dep = require('somedep')

Use this for any core modules (like fs) and third party modules your library needs that you are including via npm (listing them in your package.json as dependencies). Here you specify an unqualified package name and node finds the module according to its search algorithm.
var mymod = require('./lib/mymod')

Use this for requiring the other modules in your project itself by path relative to the current javascript file.
That's all you have to do to handle your javascript dependencies.
OK, now how do you install your dependencies?
For local development (within your project's source tree), just cd into the project directory and run npm install, which will read your package.json file and install the modules you need in the node_modules subdirectory and all will be well for local development.
If you were to actually publish this as an npm module, other users (and you can be both the developer and one of the "other users"), could install it with npm -g if they wanted to access your project's binary utilities on their PATH which would need to include /usr/lib/nodejs/lib/node_modules, but in that case, the npm -g will handle installing both your code and your project's dependencies all at once.
Here's where you are getting confused.

Therefore, according to the above, my dependencies should be installed as global modules.

You don't need to explicitly install dependencies as globals, only the top-level module you are interested in, which in this case is your project itself. npm will handle the dependencies automatically, which is its primary purpose in life. Your project's dependencies won't be installed globally per say, but rather in the node_modules subdirectory of your project, which WILL be installed globally.
Here's the directories and what lives there:

*

*~/yourproject: local development for your source code

*~/yourproject/node_modules: npm modules used by your project during development. Created/populated by running npm install in ~/yourproject

*/usr/lib/nodejs/lib/node_modules: npm modules (which could eventually include yourproject if you publish it to the npm registry) that are installed globally

*/usr/lib/nodejs/lib/node_modules/yourproject/node_modules: your project's dependencies will get installed here when you do npm install -g yourproject
You may also find my blog post on managing interpreters and the PATH relevant.

A: Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:
1: $HOME/.node_modules
2: $HOME/.node_libraries
3: $PREFIX/lib/node


text:
Q: How to solve multiple unwanted array when output using foreach When I look at the output of my foreach loop, I get multiple copies of the array itself. The problem is from the output of exper3.php below. Here's my code:
file exper.php
<!DOCTYPE html>

<title>Multiple form with output</title>

<form action="exper1.php" method="POST">
    Banyaknya nilai yang anda masukkan
    <input type="text" name="nilai">
    <input type="submit" name="kirim" value="kirim">
</form>

file exper1.php
<!DOCTYPE html>

<title>Multiple form with output</title>

<form action="exper1.php" method="POST">
    Banyaknya nilai yang anda masukkan
    <input type="text" name="nilai">
    <input type="submit" name="kirim" value="kirim">
</form>

<form action="exper3.php" method="POST">
<?php
$nilai = $_POST['nilai'];
    $wtf = $nilai/$nilai;
    $i = $nilai + 1;
    $counter = 1;
do {
        echo "Nilai ke-";
        echo $counter;
        echo " : ";
        echo "<input type='text' name='hasil[]'>";
        echo "
";
        $counter++;
        $wtf++;
    } while ($wtf<$i);
?>
<input type="submit" name="simpan" value="simpan">
</form>

file exper3.php
<!DOCTYPE html>

<title>Multiple form with output</title>

<form action="exper1.php" method="POST">
    Banyaknya nilai yang anda masukkan
    <input type="text" name="nilai">
    <input type="submit" name="kirim" value="kirim">
</form>

<?php
$hasil = $_POST['hasil'];
$i=1;
    foreach ($hasil as $value) {
        echo "Nilai ke ".$i++." adalah ".join('
Nilai ke ' .$i++. ' adalah ', $hasil)."
";;
}
?>

the output
Output of file expert.php: First
Output of file exper1.php: Second
Output of file exper3.php: Third, the problem
The intended output of exper3.php should be like this:
Nilai ke 1 adalah 343
Nilai ke 2 adalah 732
Nilai ke 3 adalah 958

not like this:
Nilai ke 1 adalah 343
Nilai ke 2 adalah 732
Nilai ke 2 adalah 958
Nilai ke 3 adalah 343
Nilai ke 4 adalah 732
Nilai ke 4 adalah 958
Nilai ke 5 adalah 343
Nilai ke 6 adalah 732
Nilai ke 6 adalah 958

What is wrong with my code ? Thanks

A: The join and foreach duplicate each other in this case - join already operates on multiple values.
foreach ($hasil as $value) {
    echo "Nilai ke ".$i++." adalah ".$value."
";
}

would give you the result you want


text:
Q: Syntax Error in Controller#Index in Ruby on Rails Im going to build an Ruby on Rails based Application with a little data base. But when I created the db with the scaffold tool I got an Syntax Error when I try to call the page via localhost:3000/informations.
On the top of the page:
SyntaxError in InformationsController#index

c:/anwendung/app/views/layouts/application.html.erb:24: syntax error, unexpected keyword_ensure, expecting keyword_end
c:/anwendung/app/views/layouts/application.html.erb:26: syntax error, unexpected $end, expecting keyword_end

this is the code of application.html.erb
<!DOCTYPE html>
<html>
<head>
  <title>Anwendung</title>
  <% if mobile_device? %>
    <%= stylesheet_link_tag 'sencha-touch' %>
    <%= javascript_include_tag 'touch/sencha-touch' %>
    </head>
    <body>
    </body>
    </html>
  <% else %>
      <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
      <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
      <%= csrf_meta_tags %>
</head>
<body>

<%= yield %>
</end>
</body>
</html>

It would be really nice if someone could help me with this.

A: You have missing <% end %> for your if-else condition. Also, HTML tags are not well paired.
Try this one:
<!DOCTYPE html>
<html>
<head>
  <title>Anwendung</title>
  <% if mobile_device? %>
    <%= stylesheet_link_tag 'sencha-touch' %>
    <%= javascript_include_tag 'touch/sencha-touch' %>
  <% else %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
    <%= csrf_meta_tags %>
  <% end %>
</head>
<body>

<%= yield %>
</body>
</html>


text:
Q: failed to send join request to master I am using elasticsearch version 1.3.0. After restarting data node its unable to detect master node. I am getting error failed to send join request to master
In Error log :-
[[app101][dGRBqTFTQfae76IFCjsMmQ][app101][inet[/127.0.0.2:9300]]{master=true, river=_none_}],
reason [org.elasticsearch.transport.RemoteTransportException:
[app101][inet[/127.0.0.2:9300]][discovery/zen/join];
org.elasticsearch.transport.RemoteTransportException:
[app102][inet[/127.0.0.1:9300]][discovery/zen/join/validate];
org.elasticsearch.ElasticsearchIllegalArgumentException:
No custom index metadata factory registered for type [rivers]]

Edit:
after reinstalling jdbc river fix the problem. But still I am looking the way if remove jdbc river and restart the ES cluster. Then it should detect master node.


text:
Q: CancellationTokenSource proper replace with new one The Window hides automatically after 5 seconds after it appears (ShowWindow method). It can be also hide manually (HideWindow method). Here is my current implementation.
The issue: When I open and then close window manually some times in row, it then hides immediately to 1 sec after opening. It shouldn't by design. The reason is I replace CTS with new one, and cancellation is never requested. I have poor skill with CTS and can't get in mind how to implement this properly.
public class Window
    {
        public bool Visible { get; set; }
        public CancellationTokenSource HideErrorWindowCTS { get; set; }

        public async void ShowWindow()
        {
            Visible = true;
            await Task.Delay(TimeSpan.FromSeconds(5));
            if (!HideErrorWindowCTS.IsCancellationRequested)
            {
                Visible = false;
            }
        }

        public void HideWindow()
        {
            HideErrorWindowCTS.Cancel();
            HideErrorWindowCTS = new CancellationTokenSource();
            Visible = false;
        }
    }

A: Because ShowWindow looks at HideErrorWindowCTS, it's looking at the newly updated cancellation token source, not the token corresponding to the CTS at the time you showed the window.  Just grab ahold of that token and store it in a local variable before you wait, so that even if HideErrorWindowCTS changes, you still have the same token to check after the delay has finished.


text:
Q: Disk Throughput Terminology Imagine running a test where you have a network-attached storage device, and there are two running processes (on different machines), reading and writing the same file on the NAS. Process 'W' does dedicated writes, and process 'R' does dedicated reads.
What is the correct terminology for the total time it takes a single byte written by 'W' to be made available for reading by 'R'? Is this throughput, latency or something else? This would factor in all protocol and network related latency.
Edit: Actual problem is discussed below:
We have a NAS device on our network, and a requirement that we read a growing file being written by one device (the 'W' process described above), on a second device (the 'R' process). We need to read very close to the tail of the file, and periodically we receive I/O errors ("Broken pipe"). We are trying to determine what is causing the broken pipe and tune the NAS accordingly.

A: Depending on where in the two-way chain of events you place this term, it could be "commit rate" or "commit time".

A: I'm not sure you understand the question, is this homework, if so please read our FAQ, we're not here for that kind of thing.
Anyway the answer is 'who knows' - because it depends on how long after the write it's committed on the filer and when the file is unlocked and its metadata is updated to reflect the change, only then will the reading app realise its cached copy has been updated so will read the updated data.
There's no set-time that's universal.


text:
Q: how to enable prometheus custom metrics for Django backend process (realtime kafka consumer) and access web endpoint I have django app for kafka consumer which consumed realtime events and I have added custom prometheus metrics to track consumed events but when my app is running i don't see custom metrics at the web endpoint /metrics. I am getting 504 gateway timeout error because my consumer is running in the background and no response gets send out. I tried with Django health check but its the same issue.
I tried running my consumer using Django custom management command, but then web endpoint didn't work.
So is there a way to run consumer app in background and exposed prometheus metrics and access web endpoint


text:
Q: CS8766: Nullability of reference types in return type doesn't match implicitly implemented member I've enabled Nullable References in my C# 8.0 project.  I've also set all warnings as errors to force myself to address all such warnings.  But one of them is confusing me.  It is a dependency property that returns an interface pointer that might validly be null.  Here is the property (inside a control called "LayerView")
private static readonly DependencyProperty ShapeBeingDrawnProperty = DependencyProperty.Register(
    nameof(ShapeBeingDrawn),
    typeof(IShape),
    typeof(LayerView),
    new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));

public IShape ShapeBeingDrawn
{
    get => GetValue(ShapeBeingDrawnProperty) as IShape;  // RIGHT SIDE OF "=>" UNDERLINED IN RED
    set => SetValue(ShapeBeingDrawnProperty, value);
}

With nullable references enabled, this understandably causes a warning on the getter.  The entire right side of the get is underlined in red and I get this build error
1>C:\Users\jmole\Documents\Dev\Mobile\Core\Views\LayerView.xaml.cs(429,13,429,16): error CS8766:
Nullability of reference types in return type of 'IShape? LayerView.ShapeBeingDrawn.get' doesn't
match implicitly implemented member 'IShape ILayerView.ShapeBeingDrawn.get' (possibly because of
nullability attributes).

First of all,  what "implicitly" implemented member are they talking about?  This is an explicitly implemented member.  I am literally implementing it right here.  But that aside, I tried to fix this as I've fixed many other such validly nullable properties:  Make the property return a nullable reference
public IShape? ShapeBeingDrawn     // ONLY CHANGE IS HERE
{
    get => GetValue(ShapeBeingDrawnProperty) as IShape; // NOW, JUST "get" IS UNDERLINED IN RED
    set => SetValue(ShapeBeingDrawnProperty, value);
}

Unfortunately, this does not help.  I still get the same error but this time the only part underlined in red is just the left side of the getter (the word "get").
Finally I was able to eliminate this error by changing the property back to a normal reference and using a hard cast in the getter
public IShape ShapeBeingDrawn
{
    get => (IShape)GetValue(ShapeBeingDrawnProperty);
    set => SetValue(ShapeBeingDrawnProperty, value);
}

But now, any code that tries to set this property to null (which is valid) gets a compiler error and I have to address that.
private void LayerView_OnKeyDown(object sender, KeyEventArgs e)
{
    // Don't do anything if we've disabled shape mouse/touch input.

    if (e.Key != Key.Escape)
        return;

    UnselectAll();
    ShapeBeingDrawn = null;  // COMPILER NO LIKEY
}

So what is the proper way to integrate nullable references and dependency properties?  Should I just #pragma warning disable around such problems?  I'd like to avoid that if I can.

A: TL;DR
The problem occurs because property ShapeBeingDrawn is declared as non-nullable reference type IShape in the interface ILayerView, but in the class LayerView it is implemented as nullable reference type IShape?. Therefore compiler complains that return type of the property in the class does not match the return type in the interface.
To fix the problem we should ensure that both the interface and the class declare the property as nullable or non-nullable. If in one of them the declaration differs then we will again get compiler error.

Explanation
Why does the problem occur?

error CS8766: Nullability of reference types in return type of
'IShape? LayerView.ShapeBeingDrawn.get' doesn't match implicitly
implemented member 'IShape ILayerView.ShapeBeingDrawn.get' (possibly
because of nullability attributes).

From the error message we can see that there is an interface ILayerView with a non-nullable property ShapeBeignDrawn:
interface ILayerView
{
    IShape ShapeBeingDrawn { get; set; }
}

and a class LayerView that implements this interface but declares property ShapeBeignDrawn as nullable:
public class LayerView
{
    public IShape? ShapeBeingDrawn
    {
        get => GetValue(ShapeBeingDrawnProperty) as IShape;
        set => SetValue(ShapeBeingDrawnProperty, value);
    }
}

So the interface declares property as non-nullable but the class implements it as nullable. Therefore compiler complains that return type of the getter of the property in the class does not match the return type in the interface.
Question:

First of all, what "implicitly" implemented member are they talking
about?

Answer:
When we declare a property compiler implicitly generates for it two methods: get_PropertyName and set_PropertyName. Therefore compiler complains for the return type of the implicitly implemented getter method.

How should we fix the problem?
To fix the problem we should ensure that both an interface and a class declare a property as nullable or non-nullable. If in one of them the declaration differs then we will again get compiler error CS8766.
Here is a code sample that reproduces the problem and gives a hint how to fix it.


text:
Q: Migrate Schema.org questions to webmasters.se? The tag schema.org, being about a way of marking up HTML documents so search engines can add rich data to their results, seems like it's a better fit over at webmasters.se. Should the schema.org questions be migrated over there?

A: Out of the 20 questions tagged schema.org there are only 5 unanswered, yet only 5 questions score 1 or more vote. So if your reasoning for migration is to get greater attention, then yes flag for migration (on a case by case basis).
On the other hand WebMasters does not have a schema.org tag but for whichever questions do contain "schema.org" (16 questions) there are a relatively high number of votes and views.
What you risk by asking for a migration is the OP of the questions and answers losing ownership until they associate their accounts on WebMasters
The better approach would be to migrate a good quality question that was recently posted. Migrating in bulk just puts monotonous overhead for moderators on both sides and in addition floods the WebMasters home page.


text:
Q: Eliminating duplicates in a database table For those who read the original question, I am sorry it was so confusing.  I am redoing the question to make it a litte more clear (to the best of my ability)
I have a table in DB2 that is being populated from a source database and data using conditions out of my control.  My goal is to create an expected query to make sure the data going into this target table matches what is expected.  The first 5 columns will have primary key constraints.
The source data may sometimes have duplicates in the columns that are meant to be primary keys.  So I need to let my query account for that.  Here are some examples of what the records might look like.  (Due to the privacy restrictions of the real data, I have to use generic data to illustrate)
Apple Banana Carrot Dog Elephant A+
Apple Banana Carrot Dog Elephant B
Apple Bowl Carrot Dog Elephant 231
Apple Bowl Carrot Dog Elephant A-
AppleJack Bowl Carrot Dog Elephant 142
AppleJack Bowl Carrot Dog Elephant 204

So if we consider the first 5 records as the criteria for the primary key, then we would have 3 duplicates here. The first two records would be a duplicate of each other, the next two, and the final two.  Here is the criteria I have in choosing which records to keep.
1.) If duplicates occur, eliminate records that have 6th column value = 'NR'
(There are no examples of this in my question, but it does occur in my actual data.
2.) After removing NR, if duplicates still occur, remove records where the 6th column value = numeric.  If both records are numeric, keep
3.) After checking numeric, if duplicates still occur, sort 6th column in alphabetical order and take first record.
I need my query to check these criteria while deleting at the same time.  So after my query executes, the only records that should be still there (by my understanding are as follows):
Apple Banana Carrot Dog Elephant A+
Apple Bowl Carrot Dog Elephant A-
AppleJack Bowl Carrot Dog Elephant 142
AppleJack Bowl Carrot Dog Elephant 204

I hope this is a bit more clear of what I need.  Any help would be greatly appreciated!  I am forever grateful for those who have provided input!  It really does mean a lot! I'm still quite new to SQL but understand most of the basic concepts.  Thanks again for taking the time to read.

A: Example (the filter for numeric only is rather clumsy):
DELETE
-- SELECT * -- for testing
FROM rubbish d
WHERE EXISTS (
    SELECT *
    FROM rubbish x
    WHERE x.a=d.a
    AND x.b=d.b
    AND x.c=d.c
    AND x.d=d.d
    AND x.e=d.e
    AND (   0=1
            -- delete NR record only if a non-NR record exists
        OR  (d.val = 'NR' AND x.val <> 'NR')
            -- d=numeric, x= non numeric
        OR  (length(translate(d.val, '0123456789' , '' )) = 0
            AND length(translate(x.val, '0123456789' , '')) > 0
            )
            -- both numeric
       --  OR  (length(translate(d.val, '0123456789' , '' )) = 0
       --     AND length(translate(x.val, '0123456789' , '' )) = 0
       --     AND d.val::integer < x.val::integer
       --     )
            -- both non-numeric
        OR  (length(translate(d.val, '0123456789' , '' )) > 0
            AND length(translate(x.val, '0123456789' , '' )) > 0
            AND d.val > x.val AND x.val <> 'NR'
            )
        )
    )
    ;

A: Essentially what you need is order records within groups determined by the first five columns according to your criteria: non-numeric first, then numeric, then 'NR', then order those alphabetically, and delete all except the first record in each group. So for a simplified example:
create table t (f1 varchar(10), f2 varchar(10), f3 varchar(10))

insert into t values ('foo', 'bar', 'A+'), ('foo', 'bar', 'B'),
                     ('jack','jill','231'), ('jack','jill','A-'),
                     ('apple', 'banana', '142'), ('apple', 'banana', '204'),
                     ('yum','sum','NR'), ('yum','sum','42')

Try selecting first:
select * from (
  select
  f1, f2, f3,
  row_number()
  over (partition by f1, f2
  order by
    case
        when f3 = 'NR' then 3 -- check for 'NR' first otherwise it will match the non-numeric check
        when length(trim(translate(f3,'','0123456789') )) > 0 then 1 -- non-numeric
        when length(trim(translate(f3,'','0123456789') )) = 0 then 2 -- numeric
        else 4 -- shouldn't happen anyway
    end,
    f3
    ) rn
    from t
) where rn = 1
order by f1, f2, f3

And delete:
delete from (
  select
  row_number() -- don't need any other columns
  over (partition by f1, f2
  order by
    case
        when f3 = 'NR' then 3
        when length(trim(translate(f3,'','0123456789')  )) > 0 then 1
        when length(trim(translate(f3,'','0123456789') )) = 0 then 2
        else 4
    end,
    f3
    ) rn
    from t
) where rn > 1

Obviously in your case you would partition by five columns, not two.


text:
Q: Error in opening Python executable file, created using cx_freeze Before asking this question have checked other queries (cx_freeze ImportError when executing file) was related to my issue, error was "DLL load failed" but my case is "No module named".
My question is - I have created a Python executables using cx_freeze but when I open the Main.exe file, the application opens with Traceback errors on it..
    import sys
    from cx_Freeze import setup, Executable

    # Dependencies are automatically detected, but it might need fine tuning.
    build_exe_options = {
        "optimize": 2,
        "includes": [],
        "compressed": True,
        "copy_dependent_files": True,
        "create_shared_zip": False,
        "append_script_to_exe": True,
        "include_in_shared_zip": False,

        "include_files":[('vPlot.ui'),
                         ('vPlot.py'),
                         ('company.jpg')],
        "include_msvcr": True,
        "packages": [],
    }

    # GUI applications require a different base on Windows (the default is for a
    # console application).
    base = None
    if sys.platform == "win32":
       base = "Win32GUI"

    setup(  name = "plcTest",
            description = "plcTest!",
            options = {"build_exe": build_exe_options},
            executables = [Executable("Main.py",
                                      base=base,
                                      copyDependentFiles=True,
                                      appendScriptToExe=True)])

my error is (http://i.imgur.com/TSVg6Ft.png), I can't find the file "'matplotlib.backends.backend_tkagg'", please give your advise, thanks in advance

A: cx-freeze have good module analysis but sometimes it is fails. Especially back and modules.
Matplotlib uses tkagg (i am not sure it is package name)as backend gui module. To solve this, you have two options;
1- import missing package somewhere in your code
2- pass package name to cx-freeze as parameter.
Example: i used cx-freeze from command-line
cxfreeze FooMain.py --include-module=simplejson, lxml  # FooMain.py my main script

edit: using python build_exe_options
"packages": ["simplejson", "lxml"],


text:
Q: Assigning Complex (Mutable) Variables in python by Value Variables in python are effectively pointers in practical use. The assignment operator "=" automatically creates an effective pointer - unless it is a basic type (called an immutable).  Examples of basic data types include:  int, float, str and bool. Assignment of these data types do not use pointers .
On the other hand, pointers are used when assigning: lists, dicts, class objects etc.
This is frustrating when I need to assign variables of the latter type (list for example) by value.
For example:
background = [1, 1, 0, 2, 2]
screen = background

background[2] = 8

print(background)  # [1, 1, 8, 2, 2]
print(screen)      # [1, 1, 8, 2, 2]

# However, I did NOT want screen to change

Can this be done?

A: Sure, you just need to make a copy. The copy module provides both shallow and deep copies.
import copy

...

screen = copy.copy(background)

A shallow copy (as above) only copies the outermost data structure. In your case, that suffices, since all of the elements of the list are immutable values. If you had nested lists or a more complex data structure, you could use copy.deepcopy to copy the entire structure. Use the latter with caution, as any loops in the structure will cause infinite recursion.
Also, in the case of lists specifically, we can use Python's slice syntax to do a shallow copy even more easily.
screen = background[:]

The a:b slice syntax selects a sublist of a list and always copies. Omitting the beginning index defaults to 0, and omitting the end index defaults to the end of the list, so omitting both copies the whole list.

A: There are other ways to assign by value. For example, you can use a list comprehension:
screen = [i for i in background]

This creates a new variable that contains values of background.
There are multiple ways to do this kind of assignment. Another one is using list unpacking:
screen = [*background]

This will unpack variables from the original object and put them into a new list.
Another way is to use copy as suggested in other answer.


text:
Q: Problems installing Ubuntu stdin: Invalid argument If I try to install ubuntu on my desktop pc, i get the following error during the boot process. The problem occours with Ubuntu 20.04 and Ubuntu 21.10. The boot medium is a DVD. The downloaded images were ok:
First error
After the first error, it shows the ubuntu boot screen, but fails a little bit later with the following error:

stdin: Invalid argument
/init: line 49: can't open /dev/sda: no medium found

Second error
I use the following Hardware:

*

*Mainboard: gigabyte x299 Designare EX (latest BIOS)

*CPU: Intel Core i7-7800X

*Graphic: NVIDIA GeForce GT 710

A: It was possible to install Ubuntu 20.04. without error using an USB device instead of a DVD.


text:
Q: Unexpectedly blocky output to console from threaded functions In the following program, I was expecting an (approximately) alternating pattern of red and green dots generated by the two threads to print as, or while the program was running. However, I fail to understand why the sequence of dots are printed in blocks only after 10s of seconds are up on my M1 Mac mini. I can't see why the console can't keep up with dots printing at 1Hz.
main.cpp
#include <thread>
#include <fmt/core.h>
#include <fmt/color.h>

void work(const fmt::color &c) {
    int seconds = 600;
    for (int i = 0; i < seconds; ++i) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        fmt::print(fmt::fg(c), ".");
    }
}

int main() {
    auto thread0 = std::thread([&]() {
        work(fmt::color::red);
    });
    auto thread1 = std::thread([&]() {
        work(fmt::color::green);
    });
    thread0.join();
    thread1.join();
    return 0;
}

Expected output after just beyond 3 seconds:
......

Actual output after 3 seconds

Why don't the dots print in real-time as it were?


text:
Q: Android Realm and on a null object reference in fragment I'm looking the answer of my problem. It's my first contact with Realm database and I have a problem with null object reference in fragment during saving data. Does anyone know what I'm doing wrong?
Helper method:
public void saveTask(final String text, final String date, final String time ) {
    realm.executeTransactionAsync(new Realm.Transaction() {
        @Override
        public void execute(Realm bgRealm) {
            Task task = bgRealm.createObject(Task.class);
            task.setText(text);
            task.setDate(date);
            task.setTime(time);
        }
    }, new Realm.Transaction.OnSuccess() {
        @Override
        public void onSuccess() {
            // Transaction was a success.
            Log.d(TAG, "ON_SUCCESS: Data Written Successfully");
        }
    }, new Realm.Transaction.OnError() {
        @Override
        public void onError(Throwable error) {
            // Transaction failed and was automatically canceled.
            Log.d(TAG, "ON_ERROR: Error");
        }
    });

}

OnClick method in fragment:
@OnClick(R.id.save_button)
public void onClickSave() {

    realmHelper.saveTask(title_text.getText().toString().trim(), date_text.getText().toString().trim(), time_text.getText().toString().trim());
}

Code inside onCreateView:
    ButterKnife.bind(this, view);

    ((MainActivity) getActivity()).hideFloatingActionButton();

    Realm.init(getActivity());
    RealmConfiguration configuration = new RealmConfiguration
            .Builder()
            .deleteRealmIfMigrationNeeded()
            .build();
    realm = Realm.getInstance(configuration);

I tried solution with textview fields inside onClick method, but still same.

A: From your OnClick method in fragment, I observe that you have a realm helper class which you created an instance of called realmHelper. Since you are using realm asynchronously I suggest you pass the instantiated realm object to the helper method or instantiate realm afresh in the helper method or class.
Passing the realm instance to the helper method
public void saveTask(Realm realm, final String text, final String date, final String time ) {
    realm.executeTransactionAsync(new Realm.Transaction() {
        @Override
        public void execute(Realm bgRealm) {
            Task task = bgRealm.createObject(Task.class);
            task.setText(text);
            task.setDate(date);
            task.setTime(time);
        }
    }, new Realm.Transaction.OnSuccess() {
        @Override
        public void onSuccess() {
            // Transaction was a success.
            Log.d(TAG, "ON_SUCCESS: Data Written Successfully");
        }
    }, new Realm.Transaction.OnError() {
        @Override
        public void onError(Throwable error) {
            // Transaction failed and was automatically canceled.
            Log.d(TAG, "ON_ERROR: Error");
        }
    });

}

Instantiating realm in the helper method
public void saveTask(Context context, final String text, final String date, final String time ) {
    Realm.init(context);
    RealmConfiguration configuration = new RealmConfiguration
        .Builder()
        .deleteRealmIfMigrationNeeded()
        .build();
    Realm realm = Realm.getInstance(configuration);
    realm.executeTransactionAsync(new Realm.Transaction() {
        @Override
        public void execute(Realm bgRealm) {
            Task task = bgRealm.createObject(Task.class);
            task.setText(text);
            task.setDate(date);
            task.setTime(time);
        }
    }, new Realm.Transaction.OnSuccess() {
        @Override
        public void onSuccess() {
            // Transaction was a success.
            Log.d(TAG, "ON_SUCCESS: Data Written Successfully");
        }
    }, new Realm.Transaction.OnError() {
        @Override
        public void onError(Throwable error) {
            // Transaction failed and was automatically canceled.
            Log.d(TAG, "ON_ERROR: Error");
        }
    });

}


text:
Q: Get Json Value with extra quotes using php Get all value from json using json_decode. Given name is Juliet"es this json. If using json_decode this array will be change null value. how do i get this json to array
$jsonobj = '{"Name":"Juliet"es","Maths":37,"English":43}';

if anyone having any idea please post answer.

A: Try $convertedJson = json_decode(addslashes($jsonobj));.
But has suggested by @Barmar and @CBroe , always generated JSON strings from array or object with json_encode().


text:
Q: Есть ли готовые решения для загрузки и обработки видеофайлов на Codeigniter? Есть ли готовые решения для загрузки и обработки видеофайлов на Codeigniter?
Нигде не смог найти оптимального решения, желательно обработка видеофайлов в ffmpeg
A: Юзаю ffmpeg на codeignter, не нужно там не какою библиотеку... там же и так все делаешь через класс и методы.... если есть вопросы задавайте..


text:
Q: SpringREST API with resttemplate Whitelabel Error Page on the GET customers request Hello guys am currently working with An api from swagger but am getting a whitelable error page
This is my Customers APIservice
          package services;
    import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import domains.Customers;

@Service
public class CustomersApiService {

//  define a RestTemplate object
private final RestTemplate restTemplate;

//  web service resources endpoints
private final String GET_ALL_USER =
"https://api.predic8.de/shop/customers/";

 //  define an argument constructor, then pass in the RestTemplate object
   and
Autowire it
@Autowired
public CustomersApiService (RestTemplate restTemplate){
    this.restTemplate = restTemplate;
}

//  Get All Users
//  @returns a list
@SuppressWarnings("unchecked")
public List<Customers> findAllCustomers(){

   return Arrays.stream(restTemplate.getForObject
(GET_ALL_USER,Customers[].class)).collect(Collectors.toList());
}

}
This is my Customers Controller
    package controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import services.CustomersApiService;

@Controller
public class CustomersController {

private final CustomersApiService service;

@Autowired
public CustomersController(CustomersApiService service) {
    this.service = service;
}

@GetMapping("/customers")
public String getAll(Model model){
    model.addAttribute("customers", service.findAllCustomers());
    return "customers";
}

}
This is my Customers POJO
      package domains;
import java.util.HashMap;
import java.util.Map;

public class Customers {

private String firstname;
private String lastname;
private String customerUrl;
private Map<String, Object> additionalProperties = new HashMap<String,
Object>();

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public String getCustomerUrl() {
return customerUrl;
}

public void setCustomerUrl(String customerUrl) {
this.customerUrl = customerUrl;
}

public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}

This is the customers file
<!DOCTYPE html>

<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Users</title>

<link href="..static/css/bootstrap.min.css"
th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<link href="..static/css/bootstrap-theme.min"
th:href="@{/css/bootstrap.min.css}" rel="stylesheet">

<link href="..static/css/carousel.css" th:href="@{/css/carousel.css}"
rel="stylesheet">

Java SringREST API

Users List

              FirstName
              LastName
              CustomerUrl

Back to top

© 2017-2018 Company, Inc. · Privacy
  · Terms


text:
Q: Check if an array item is set in JS I've got an array
    var assoc_pagine = new Array();
    assoc_pagine["home"]=0;
    assoc_pagine["about"]=1;
    assoc_pagine["work"]=2;

I tried
    if (assoc_pagine[var] != "undefined") {

but it doesn't seem to work
I'm using jquery, I don't know if it can help
Thanks

A: var is a statement... so it's a reserved word... So just call it another way.
And that's a better way of doing it (=== is better than ==)
if(typeof array[name] !== 'undefined') {
    alert("Has var");
} else {
    alert("Doesn't have var");
}

A: Use the in keyword to test if a attribute is defined in a object
if (assoc_var in assoc_pagine)

OR
if ("home" in assoc_pagine)

There are quite a few issues here.
Firstly, is var supposed to a variable has the value "home", "work" or "about"? Or did you mean to inspect actual property called "var"?
If var is supposed to be a variable that has a string value, please note that var is a reserved word in JavaScript and you will need to use another name, such as assoc_var.
var assoc_var = "home";
assoc_pagine[assoc_var] // equals 0 in your example

If you meant to inspect the property called "var", then you simple need to put it inside of quotes.
assoc_pagine["var"]

Then, undefined is not the same as "undefined". You will need typeof to get the string representation of the objects type.
This is a breakdown of all the steps.
var assoc_var = "home";
var value = assoc_pagine[assoc_var]; // 0
var typeofValue = typeof value; // "number"

So to fix your problem
if (typeof assoc_pagine[assoc_var] != "undefined")

update: As other answers have indicated, using a array is not the best sollution for this problem. Consider using a Object instead.
var assoc_pagine = new Object();
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;

A: This is not an Array.
Better declare it like this:
var assoc_pagine = {};
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;

or
var assoc_pagine = {
                 home:0,
                 about:1,
                 work:2
               };

To check if an object contains some label you simply do something like this:
if('work' in assoc_pagine){
   // do your thing
};

A: This worked for me
if (assoc_pagine[var] != undefined) {

instead this
if (assoc_pagine[var] != "undefined") {

A: var assoc_pagine = new Array();
assoc_pagine["home"]=0;

Don't use an Array for this. Arrays are for numerically-indexed lists. Just use a plain Object ({}).
What you are thinking of with the 'undefined' string is probably this:
if (typeof assoc_pagine[key]!=='undefined')

This is (more or less) the same as saying
if (assoc_pagine[key]!==undefined)

However, either way this is a bit ugly. You're dereferencing a key that may not exist (which would be an error in any more sensible language), and relying on JavaScript's weird hack of giving you the special undefined value for non-existent properties.
This also doesn't quite tell you if the property really wasn't there, or if it was there but explicitly set to the undefined value.
This is a more explicit, readable and IMO all-round better approach:
if (key in assoc_pagine)

A: TLDR; The best I can come up with is this: (Depending on your use case, there are a number of ways to optimize this function.)
function arrayIndexExists(array, index){
    if ( typeof index !== 'number' && index === parseInt(index).toString()) {
        index = parseInt(index);
    } else {
        return false;//to avoid checking typeof again
    }
    return typeof index === 'number' && index % 1===0 && index >= 0 && array.hasOwnKey(index);
}

The other answer's examples get close and will work for some (probably most) purposes, but are technically quite incorrect for reasons I explain below.
Javascript arrays only use 'numerical' keys. When you set an "associative key" on an array, you are actually setting a property on that array object, not an element of that array. For example, this means that the "associative key" will not be iterated over when using Array.forEach() and will not be included when calculating Array.length. (The exception for this is strings like '0' will resolve to an element of the array, but strings like ' 0' won't.)
Additionally, checking array element or object property that doesn't exist does evaluate as undefined, but that doesn't actually tell you that the array element or object property hasn't been set yet. For example, undefined is also the result you get by calling a function that doesn't terminate with a return statement. This could lead to some strange errors and difficulty debugging code.
This can be confusing, but can be explored very easily using your browser's javascript console. (I used chrome, each comment indicates the evaluated value of the line before it.);
var foo = new Array();
foo;
//[]
foo.length;
//0
foo['bar'] = 'bar';
//"bar"
foo;
//[]
foo.length;
//0
foo.bar;
//"bar"

This shows that associative keys are not used to access elements in the array, but for properties of the object.
foo[0] = 0;
//0
foo;
//[0]
foo.length;
//1
foo[2] = undefined
//undefined
typeof foo[2]
//"undefined"
foo.length
//3

This shows that checking typeof doesn't allow you to see if an element has been set.
var foo = new Array();
//undefined
foo;
//[]
foo[0] = 0;
//0
foo['0']
//0
foo[' 0']
//undefined

This shows the exception I mentioned above and why you can't just use parseInt();
If you want to use associative arrays, you are better off using simple objects as other answers have recommended.

A: if (assoc_pagine.indexOf('home') > -1) {
   // we have home element in the assoc_pagine array
}

Mozilla indexOf

A: function isset(key){
ret = false;
array_example.forEach(function(entry) {
  if( entry == key ){
    ret = true;
  }
});
return ret;
}

alert( isset("key_search") );

A: The most effective way:
if (array.indexOf(element) > -1) {
   alert('Bingooo')
}

W3Schools


text:
Q: Exchange mailbox migration to office365 stuck at Syncing/inprogress Hello guys, so i am currently migrating our exchange server 2012 to office 365 exchange online using the hybrid connectivity approach (remote move). All pilot users were successfully migrated except this one user who has been stuck at syncing for a very long period of time without any significant activity going on (Data migrated still at 0). I have tried to stop/delete the user using Stop-migrationUser cmdlet and tried to start the migration again using new-MoveRequest and still the same. From powershell moveRequestStatistics of that user, the Status is stuck at In progress while the StatusItem is stuck at WorkItemPickup. This particular users mailbox seems to be larger than every other user in the initial pilot batch created @13.31Gb worth of mailbox size. Please what can i do to re-mediate this? see below migration stats of current problem user/mailbox..

RunspaceId                               : 4b9964c2-cc29-4cdc-9ce5-499bdb0545f1
MailboxIdentity                          : Wonuola Oyeledun
DistinguishedName                        : CN=Wonuola Oyeledun,OU=egbinpower.onmicrosoft.com,OU=Microsoft Exchange
                                           Hosted Organizations,DC=EURPR10A003,DC=PROD,DC=OUTLOOK,DC=COM
DisplayName                              : Wonuola Oyeledun
Alias                                    : wonuola.oyeledun
ExchangeGuid                             : d90a27ed-4017-486e-a843-09af3214612b
ArchiveGuid                              :
Status                                   : InProgress
StatusDetail                             : WorkItemPickup
SyncStage                                : None
Flags                                    : CrossOrg, Pull
RequestStyle                             : CrossOrg
Direction                                : Pull
IsOffline                                : False
Protect                                  : False
DoNotPreserveMailboxSignature            : True
Priority                                 : Normal
WorkloadType                             : Onboarding
Suspend                                  : False
SuspendWhenReadyToComplete               : False
IgnoreRuleLimitErrors                    : False
RecipientTypeDetails                     : MailUser
SourceVersion                            : Version 15.0 (Build 1367.0)
SourceDatabase                           :
SourceServer                             : EGB032.egbin-power.local
TargetVersion                            : Version 15.20 (Build 2856.0)
TargetDatabase                           : EURPR10DG070-db073
TargetServer                             : HE1PR1001MB1113.EURPRD10.PROD.OUTLOOK.COM
SourceArchiveDatabase                    :
SourceArchiveVersion                     :
SourceArchiveServer                      :
TargetArchiveDatabase                    :
TargetArchiveVersion                     :
TargetArchiveServer                      :
RemoteHostName                           : owa.egbin-power.com
RemoteTenant                             :
RemoteGlobalCatalog                      :
BatchName                                : Wonuola_oyeledun
StartAfter                               :
CompleteAfter                            : 12/31/9999 1:00:00 AM
EffectiveIncrementalSyncInterval         : 1.00:00:00
ConfiguredIncrementalSyncInterval        :
RemoteCredentialUsername                 : egbin-power\o365.admin
RemoteDatabase                           : 9c976c93-8f25-4712-a6f2-23bb74aab4bd
RemoteDatabaseName                       : EG_Dbase1B
RemoteArchiveDatabase                    :
RemoteArchiveDatabaseName                :
TargetDeliveryDomain                     : egbinpower.mail.onmicrosoft.com
ArchiveDomain                            : egbinpower.mail.onmicrosoft.com
BadItemLimit                             : 500
RetryCleanup                             : False
BadItemsEncountered                      : 0
LargeItemLimit                           : 100
LargeItemsEncountered                    : 0
AllowLargeItems                          : False
DataConsistencyScore                     :
QueuedTimestamp                          : 3/29/2020 10:54:10 PM
StartTimestamp                           :
LastUpdateTimestamp                      : 3/30/2020 4:42:49 AM
LastSuccessfulSyncTimestamp              :
InitialSeedingCompletedTimestamp         :
FinalSyncTimestamp                       :
CompletionTimestamp                      :
SuspendedTimestamp                       :
OverallDuration                          : 08:35:55.8622131
TotalSuspendedDuration                   : 00:00:00
TotalFailedDuration                      : 00:00:00
TotalQueuedDuration                      : 00:00:14.3613461
TotalInProgressDuration                  : 08:35:04.9331586
TotalStalledDueToContentIndexingDuration : 00:00:00
TotalStalledDueToMdbReplicationDuration  : 00:00:00
TotalStalledDueToMailboxLockedDuration   : 00:00:00
TotalStalledDueToReadThrottle            : 00:00:00
TotalStalledDueToWriteThrottle           : 00:00:00
TotalStalledDueToReadCpu                 : 00:00:00
TotalStalledDueToWriteCpu                : 00:00:00
TotalStalledDueToReadUnknown             : 00:00:00
TotalStalledDueToWriteUnknown            : 00:00:00
TotalTransientFailureDuration            : 00:00:36.5677084
MRSServerName                            : HE1PR1001MB1113.EURPRD10.PROD.OUTLOOK.COM
TotalMailboxSize                         : 13.31 GB (14,286,756,692 bytes)
TotalMailboxItemCount                    : 92203
TotalArchiveSize                         :
TotalArchiveItemCount                    :
TotalPrimarySize                         : 13.31 GB (14,286,756,692 bytes)
TotalPrimaryItemCount                    : 92203
BytesTransferred                         : 0 B (0 bytes)
BytesTransferredPerMinute                : 0 B (0 bytes)
ItemsTransferred                         : 0
ShardBytesTransferred                    : 0 B (0 bytes)
ShardItemsTransferred                    : 0
ArchiveBytesTransferred                  : 0 B (0 bytes)
ArchiveItemsTransferred                  : 0
PercentComplete                          : 0
CompletedRequestAgeLimit                 : 3650.00:00:00
InternalFlags                            : SkipKnownCorruptions
JobFeatures                              : BinaryJobFeatures, UseRequestGuidForMoveReport, ShardMergeOnboarding
FailureCode                              :
FailureType                              :
FailureSide                              :
Message                                  :
FailureTimestamp                         :
IsValid                                  : True
ValidationMessage                        :
RequestGuid                              : e5b70882-0bc2-4b46-8148-455f8117596e
RequestQueue                             : EURPR10DG070-db073
MigrationMailboxGuid                     :
SourceEndpointGuid                       :
Identity                                 : Wonuola Oyeledun
Report                                   :
OutOfSlaConditions                       : {}
LastFailure                              :
RequestExpiryTimestamp                   : 3/29/2022 9:54:10 PM
CanSetRetryingStatus                     : False
RemoveRequestWhenCorrupt                 : False
IsContinousJob                           : False
IsSyncAggregation                        : False
IsShadowSync                             : False
CloudCacheAccountType                    : None
Diagnostics                              :
DiagnosticInfo                           :
ObjectState


text:
Q: How to get extras form intent when Intent.ACTION_MEDIA_EJECT? I put in my broadcast receiver for action ACTION_MEDIA_EJECT
if(action.equals(Intent.ACTION_MEDIA_EJECT)){
       for(String k : intent.getExtras().keySet()){
        Log.d("arek","klucz = "+k);
        Log.v("arek","wartość= "+intent.getExtras().get(k).toString());
 }

and get in logs:
05-10 15:13:33.871: D/arek(10322): klucz = storage_volume
05-10 15:13:33.871: V/arek(10322): wartość= StorageVolume [mStorageId=131073 mPath=/storage/extSdCard mDescriptionId=17041195 mPrimary=false mRemovable=true mEmulated=false mMtpReserveSpace=0 mAllowMassStorage=false mMaxFileSize=0 mOwner=null mSubSystem=sd mActivitySecureContainer=false]
05-10 15:13:33.881: I/arek(10322): mStorageManager.getVolume(filePath).getStorageId() = 131073

but where is defined string for key: storage_volume
because I want to do:
StorageVolume sv = (StorageVolume) intent.getExtras().get("storage_volume");

So where is defined constant value with string "storage_volume"?

A: It's android.os.storage.StorageVolume.EXTRA_STORAGE_VOLUME. But this class itself is hidden.
See StorageVolume.java.


text:
Q: android mapview doesn't display markers after back press I have a mapview in a fragment and after I go to another fragment and press back button it navigates me to the same screen but the map doesn't have markers and camera does not update
IN ON VIEW CREATED
mapView = (MapView) rootView.findViewById(R.id.store_map) ;
        mapView.onCreate(savedInstanceState) ;
    map = mapView.getMap() ;
    map.setOnMarkerClickListener(this);
    map.setMyLocationEnabled(true);
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(-28.362402,24.587402) , 5.0f)  ;
    map.animateCamera(cameraUpdate) ;
    map.getUiSettings().setZoomControlsEnabled(false) ;

    Marker tmpStore;
    LatLng pos;

    BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.ic_map_pin);

            for(int b=0;b<5;b++)
            {

                try
                {
                    pos = new LatLng(Float.parseFloat(storesForMap.get(b).getLatitude()), Float.parseFloat(storesForMap.get(b).getLongitude()));
                    tmpStore = map.addMarker(new MarkerOptions()
                            .position(pos)
                            .title(storesForMap.get(b).getRetailer().getName())
                            .icon(bitmapDescriptor)
                            .snippet(storesForMap.get(b).getAddress()));
                    stores.add(tmpStore);

                }
                catch(Exception e)
                {
                    Log.v("STORE_SIZE", "add stores exception: " + e.getMessage());
                    e.printStackTrace();
                }
            }
            Log.v("STORE_SIZE", "stores " + stores.size());
            new getTime().execute();

            map.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(-33.9652825, 18.8397661) , 12.0f) );

    }

IN MY XML I HAVE
    <com.google.android.gms.maps.MapView
    android:layout_below="@+id/llTextView"
    android:id="@+id/store_map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.MapFragment"
    android:gravity="center|top"
    />

A: I think this has to do with your lifecycle and where you are actually adding the markers.
You are adding them in OnCreate, move that logic to OnResume.
When you go to another fragment and come back from it, OnCreate isn't called again but onResume.

A: it needs to only to press zoom buttons [+]/[-], the markers are loaded, but not shown


text:
Q: How well will a C++ app communicating through Apache handle traffic?  I'm writing an online game that has to run in a web browser and I'm worried about whether my server-side architecture will be able to handle the load.
I'm designing for 1000-2000 simultaneous clients.  Each client will need to query the server once every 2 seconds - so 500-1000 transactions per second is my design goal.
My game server communicates with Apache via FastCGI.  I'm actually running Apache on Windows for the moment.  All this will run on a dedicated "dual-core" server. The game server application itself is written in C++ and the transactions are pretty simple and fairly low bandwidth (maybe 2k data per) so I'm not too worried about the game server piece.
My client is written in Javascript and uses XMLHTTP to communicate with the server.
So am I smoking something to think I can get 500 to 1000 transactions per second?  If so, what number might I expect?

A: I've seen benchmarks using ab for PHP run at around 500 requests per second and upwards of 1200 per second for Python. Note, however, that these are basic requests that don't really do anything spectacular.
So really, your bottleneck will be your server code: It's definitely possible to reach 1k requests per second using Apache/FastCGI/C++, it all depends on your server hardware and complexity of your server code though (and server-side I/O, etc).

On a side note, is there a reason that you're using this particular tech stack? C++ usually isn't a very nice language to write server code in (as opposed to Java, etc). I might also look at a language like Erlang for server-side code to get around the FastCGI requirement to give your server even more of a boost.

In response to the OP's comments (a little too long winded for a comment):
@Joe Rice: TBH, I'd find it perfectly acceptable that gaming users would be forced to use the most up to date browsers - you can't use old PC-based gaming clients in most environments and you definitely can't in the console world, so why should browser-based gaming be any different? You might be signing yourself up for a world of hurt otherwise, especially given your budget constraints.
If your concerns are around budgeting, why not take a look at node.js as your server tech with socket.io libs both client and server side? There are a few bonuses here:

*

*No context switching (well, limited). Same language used both client and server side, so you don't have to be continuously switching mindsets.

*Graceful degredation handled for you: socket.io has a bunch of built-in fallback mechanisms to handle support on most browsers.

*node.js supports TCP and (AFAIK) UDP, so you don't have to worry about the overhead of HTTP (although you'd obviously have to deal with UDP synchronizing issues yourself if you chose to go that route)

*As you're familiar with C++, if you find a bottleneck server-side, you can dive into the library code and update as required.

Of course, there are potential downsides as well. I'm not familiar with any high-usage gaming servers being written entirely using node.js. You can also check out hacknews for node.js flame wars for further potential gotchas with using node as well.


text:
Q: Get ip address and set as variable bash shell script I am trying to write a bash script to configure an app (unattended install). All I need to do is this. I need to get the IP address for the server and set it as a variable. I am writing this script to simplify that. What I have noticed is that when I test this in a vps though eth0 is listed its not the default, its something along the lines of venet0:0. Is there any way of getting this ip set as a vaiable (I know how to if I know the interface name, i am trying to do this without knowing as its hard to plan for every possible device naming). if not then i will just add a prompt for the ip address for the user right as they run the script.
This is not a duplicate question as I am asking for the server's IP not just the public IP of the server. Even though this is aimed at building a public mail server I am building it to work on an internal one as well.

A: 'The' IP address... servers have so many, default management, application, DB listener?
Does this do it for you?
IP_ADDR=$(getent hosts `hostname` | awk '{print $1}')

A: If you have one interface:
ip addr show | grep "inet " | grep -v "127.0.0.1/8" | awk '{print $2}'
10.10.1.254/16


text:
Q: tcl script not able to read a element from array? I am taking an array and printing its values using tcl scripts but when I run the script is says
 can't read "ipname(0)": no such element in array
Here is the code I am using
array set ipname {UART TEST SPI I2C}
set asize 4
for {set i 0} {$i < $asize} {incr i}  {
      puts "$ipname($i) "
}

A: Your array set command doesn't do what you think. Essentially, it is as if you defined it as follows:
ipname("UART") = "TEST"
ipname("SPI") = "I2C"

What you want is
set ipname(0) "UART"
set ipname(1) "TEST"
set ipname(2) "SPI"
set ipname(3) "I2C"

or
array set ipname {0 UART 1 TEST 2 SPI 3 I2C}

See the documentation for Tcl arrays: http://tcl.tk/man/tcl8.5/TclCmd/array.htm


text:
Q: git push a sub branch I was in branch feature_swap there I did some change but I am not confident enough to push those changes in feature_swap branch. So I tried to create another sub branch feature_swap_experiment with
git branch feature_swap_experiment
git checkout feature_swap_experiment

Now I want to push to feature_swap_experiment I've tried git push origin feature_swap_experiment which is not working
error: src refspec feature_swap_experiment does not match any.
error: failed to push some refs to 'https://uname@bitbucket.org/uname/project.git'

A: git push origin feature_swap_experiment

should be the right command. Is there any chance that your remote is not set up correctly?

*

*if you check master back out, can you push to the remote?

*Do the contents of your .git/config file look correct?  Especially check the [remote "origin"] section of the file.

Also, git branch -a should give you a list of all branches, local and remote, so you should be able to quickly see if things are set up correctly.
This may help:
How do you create a remote Git branch?
Edit:  After looking at the error message you added to the question, it seems like you might have the same problem as described here:  Error when "git push" to github
So in your case, you would run:
git push https://uname@bitbucket.org/uname/project.git  HEAD:feature_swap_experiment


text:
Q: Logging only top-most ThreadContext stack item We're using Log4net's ThreadContext.Stacks and it is mostly working well.  My problem comes if there have been multiple ThreadContext.Stacks["key"].Push(...).
With a simple ConversionPattern:
<param name="ConversionPattern value="... topProp=%properties{key} ..."/>

I see log entries like:
... topProp=first second third ...

I'd really like to see only the most recently pushed value rather than all the values.  I had hoped I could put something like the following in my appender/layout/ConversionPattern:
<param name="ConversionPattern value="... topProp=%properties{key}{1} ..."/>

but that doesn't work.  I can kludge it by assuming/requiring all values to be the same length (say 5) and doing:
<param name="ConversionPattern value="... topProp=%5.5properties{key} ..."/>

But that isn't real attractive.  Any ideas?
Thanks!
[Edit to add very simple example]
using System;
using System.IO;
using log4net;
using log4net.Config;

namespace ThreadLocalExample {
class Program {
    private const string PropJobId = "Example:JobId";

    static void Main() {
        XmlConfigurator.Configure(new FileInfo("log4net.cfg"));
        var log = LogManager.GetLogger(typeof(Program));

        ThreadContext.Stacks[PropJobId].Push("Old");

        log.Debug("Enter using");
        using (ThreadContext.Stacks[PropJobId].Push("New")) {
            log.Debug("stuff");
        }
        log.Debug("Out of using");

        log.Debug("done.");
        Console.ReadKey();
    }
  }
}

With the log4net configuration:
<appender name="Console" type="log4net.Appender.ConsoleAppender">
    <threshold value="ALL" />
    <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="[jobId=%P{Example:JobId}]: %m%n" />
    </layout>
</appender>

Produces:
[jobId=Old]: Enter using
[jobId=Old New]: stuff
[jobId=Old]: Out of using
[jobId=Old]: done.

But I'd like:
[jobId=Old]: Enter using
[jobId=New]: stuff
[jobId=Old]: Out of using
[jobId=Old]: done.

A: I had the same problem, and it was not only about 'bad formatting', because I used database appender (AdoNetAppender) which expects integers. So after joining all stacked values together the result is not an integer any more. Consider an appender like this:
<appender name="DbAppender" type="log4net.Appender.AdoNetAppender">
...
<commandText value="INSERT INTO Log ([Id]) VALUES (@Id)" />
<parameter>
    <parameterName value="@Id" />
    <dbType value="Int32" />
    <layout type="log4net.Layout.PatternLayout" value="%P{someId}" />
</parameter>

This appender will not accept any log message, where 'someId' is stacked twice or more - no logs in database ...
So, to solve this problem I gave up with stacks and turned back to flat properties.
I've coded some short extension:
    public static class Log4NetExt {
        public static IDisposable ThreadContextPush(string key, object value) {
            object oldVal = ThreadContext.Properties[key];
            ThreadContext.Properties[key] = value;
            var topMostCleaner = new DispCleaner();
            topMostCleaner.EvDispose += () => {
                // Pop = restore old value
                ThreadContext.Properties[key] = oldVal;
            };
            return topMostCleaner;
        }

        private class DispCleaner : IDisposable {
            public event Action EvDispose;

            public void Dispose() {
                if (EvDispose != null) EvDispose();
            }
        }
    }

And now, instead of:
using (ThreadContext.Stacks[PropJobId].Push("New")) {

write:
using (Log4NetExt.ThreadContextPush(PropJobId, "New")) {

and it works ok ;)
(This short code does not follow all best practises of building disposable objects, deleting event handlers and all this stuff, but it is short and I think it is safe in this simple case).

A: I have Done it via Filip solution modified as
 public static class Log4NetExt
    {
        public static IDisposable ThreadContextSet(string key, object value)
        {
            //object oldVal = ThreadContext.Properties[key];
            ThreadContext.Properties[key] = value;
            var topMostCleaner = new DispCleaner();
            topMostCleaner.EvDispose += () => {
                // Pop = restore old value
                //ThreadContext.Properties[key] = oldVal;
                ThreadContext.Properties[key] = null;
            };
            return topMostCleaner;
        }

        private class DispCleaner : IDisposable
        {
            public event Action EvDispose;

            public void Dispose()
            {
                if (EvDispose != null)
                {
                    EvDispose();
                }
            }
        }
    }

And used it like
using (Log4NetExt.ThreadContextSet("ContextId", "Feed"))
            using (Log4NetExt.ThreadContextPush("ContextValue", objFeed.FeedId))
            {
}