text:
Q: Entanglement in double slit experiment Suppose we send 2 entangled photons through the 2 slit, does measuring the position of one of the photons affect the other particle's wave function or does the other particle still behave as a wave ?

A: Here are single photons at a time arriving at the slits:

Single-photon camera recording of photons from a double slit illuminated by very weak laser light. Left to right: single frame, superposition of 200, 1'000, ... frames

The "measurement" of each photon is a dot.

Suppose we send 2 entangled photons through the 2 slit, does measuring the position of one of the photons affect the other particle's wave function or does the other particle still behave as a wave ?

As your two entangled photons move with velocity c, they will have to be parallel to each other and close in space, in order to both  reach the double slits and go through, and both will materialize as a point on the screen. If there were a polarimeter at the location of the dot , the spin correlation could be registered, but the probability waves are reduced to points after the slits, and appears in the accumulation of points in the interference.

A: There are some interesting research about using entangled twin photons, slits and different detection position to achieve a specific quantum state of the complete Hilbert space. The schematic diagram is shown as the figure below.
According to the results, like your prediction, different detection positions of one double-slits system will affect the measuring results of the other system, so that we can control the state of the two-particle system. One of the relevant reference's DOI is 10.1103/PhysRevA.78.012307. Hope it is helpful for you.


text:
Q: Implementing PaymentResultWithDataListener in RazorPay Android SDK Excuse the trivial question. I am doing RazorPay integration for the first time.
In my app I want to carry forward a couple of strings about the user's order. This is NOT the order as defined by RazorPay.
I see that the interface PaymentResultWithDataListener provides PaymentData in the callback. How to I send extra data to Checkout ?

A: PaymentData contains following fields

*

*Contact number of the user

*Email address of the user

*Razorpay payment id

*Razorpay order id(It will be present in case you are using Razorpay orders API and sending order id to Checkout)

*Signature, which can be used to capture payment on backend(not compulsory to make use of it)

*Data, A JSON object which will contain data like payment id, signature etc.

If you want to send any custom data from your side. You can send it in from of JSON object in checkout option with key as notes
Example:
//notesData is json object which contain your custom data
options.put("notes", notesData);

This notes will be available in DashBoard and you will get it in payment details also when you fetch payment detail via API.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling Nested function I am trying to redraw image after every 10 seconds. by using

 $(document).ready(function() {
setInterval("marker()",10000);
});

but  marker() function inside initialize() function how can i access only marker to work it for above setInterval

 function initialize(x,y) {
  var myLatlng = new google.maps.LatLng(x,y);
  var mapOptions = {
  zoom: 4,
  center: myLatlng,
  mapTypeId: google.maps.MapTypeId.ROADMAP
 }
 var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
 marker(x,y);
 function marker(){
   var image = 'myimage.png';
   var myLatLng = new google.maps.LatLng(x, y);
   var beachMarker = new google.maps.Marker({
   position: myLatLng,
   map: map,
   icon: image
   });
 }
}

A: Just change it to
setInterval(marker, 10000);

and move that into a scope where the marker function is available, i.e. into initialize.


text:
Q: SwipeGesture in Iphone Cocos2d I am using UISwipeGestureRecognizer to get swipe gesture in iPhone. i want to get 2 location points on Began of swipe touch and on end of swipe touch. i have implemented swipe touch method as below
- (void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {

    CGPoint touchLocation = [recognizer locationInView:recognizer.view];
    touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
    touchLocation = [self convertToNodeSpace:touchLocation];

    CCLOG(@"Hello %@ - %d",NSStringFromCGPoint(touchLocation),recognizer.state);

    if (recognizer.state == UIGestureRecognizerStateBegan) {

        CGPoint touchLocation = [recognizer locationInView:recognizer.view];
        touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
        touchLocation = [self convertToNodeSpace:touchLocation];

        CCLOG(@"UIGestureRecognizerStateBegan %@",NSStringFromCGPoint(touchLocation));

    } else if (recognizer.state == UIGestureRecognizerStateChanged) {

        CCLOG(@"UIGestureRecognizerStateChanged");

    } else if (recognizer.state == UIGestureRecognizerStateEnded) {
        CGPoint touchLocationEnd = [recognizer locationInView:recognizer.view];
        touchLocationEnd = [[CCDirector sharedDirector] convertToGL:touchLocationEnd];
        touchLocationEnd = [self convertToNodeSpace:touchLocationEnd];
        CCLOG(@"UIGestureRecognizerStateEnded %@",NSStringFromCGPoint(touchLocationEnd));
        }

    //}
}

My swipe touch is working. but it only shows UIGestureRecognizerStateEnded. even when i swipe on screen and my touch is not ended yet but the StateEnded is called. how can i call StateBegin and get location and then StateEnd. right now just StateEnded is working other two Begin and Changing are not working.

A: Update:
I find the reason:

A swipe is a discrete gesture, and thus the associated action message
  is sent only once per gesture.

And this image:

So there are only three states for UISwipeGestureRecognizer:possible, recognized and ended. But I still don't know why possible is not called.

I tried your code and get the same result. I also don't know why this happen. If you can't find solution for this problem I suggest you use the for touch methods to analysis the touch yourself. This can surely handle the event but a little complicated than use gesture recognizer.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;


text:
Q: Does the solenoid force formula apply to electromagnets? Related questions:

*

*How to calculate the repulsion force between two electromagnets

*With what force can a solenoid pull?

*What assumptions does the solenoid force equation make?
I am trying to design a simple electromagnet, and I'd like a formula to let me calculate the holding force I can expect from a particular design.
I have seen the usual formula:
\$\LARGE F=(N\cdot I)^2 \cdot \frac{u_0 \cdot A}{2g^2}\$
Where 'g' is reportedly "Length of the gap between the solenoid and a piece of metal". What exactly this means, I don't know. Does this assume we're dealing with an air cored solenoid, or an electromagnet with a mild steel bar inside? From which bit of the solenoid are we measuring the distance? From the end of the metal bar, or from the centre of the coil?

Problem: If we're assuming 'g' is measured from the end of the bar, and the electromagnet is actually holding the object, I.E. touching it, then 'g' is zero, and the resulting force is undefined.
What is going on here? Is it just that this formula doesn't work for electromagnets that are actually holding something?  Does a formula exist for the situation where the object is touching the rod?
(My suspicion is that the formula is for a solenoid with a moving plunger, and 'g' is not the distance marked in that diagram, but something else.)


text:
Q: Decrease Regex steps At the moment I'm trying to build a (C#-)Regex to rename variables in a C#-Sourcefile. It should avoid DllImports, and avoid renaming string contents, and avoid renaming variables containing the name to replace (e.g. not replacing "anotherTest" when "Test" is to replace).
Well the Regex works, but It is really slow. RegexBuddy told me it takes 411 steps to debug this input (Yes I know it's totally dumb code, but it's for testing purposes):

[DllImport("user32.dll")]   [return:...] public extern int test();
"test "
""test
testProcess.StartInfo.Arguments = (start + \"\" \"" + test + "\")");

As I'm new to Regex, I don't know where to improve it... I hope someone can help me...
Here's the (C#-)Regex itself:
(?<!\[DllImport\(.*\)\]\s*\r\n(|\[return\:.*\]\s*\r\n).*)(?((?<![\"\'][^+=]*))|(?![^+=]*[\"\']))(?<![\w_]+?)test(?![\w_]+?)


text:
Q: Followers network with tweepy I'm trying to do a network of my followers in twitter with Python and tweepy. My problem is that I'm not obtaining all the followers for each user oly a few. This is the code:
import tweepy

# Copy the api key, the api secret, the access token and the access token secret from the relevant page on your Twitter app

api_key = 'xxxx'
api_secret = 'xxxx'
access_token = 'x-x'
access_token_secret = 'xxxx'
# You don't need to make any changes below here # This bit authorises you to ask for information from Twitter
auth = tweepy.OAuthHandler(api_key, api_secret)
auth.set_access_token(access_token, access_token_secret)
# The api object gives you access to all of the http calls that Twitter accepts
api = tweepy.API(auth)

#User we want to use as initial node
user='xxxx'

import csv
import time
#This creates a csv file and defines that each new entry will be in a new line
csvfile=open(user+'network.csv', 'w')
spamwriter = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
#This is the function that takes a node (user) and looks for all its followers #and print them into a CSV file... and look for the followers of each follower...

def fib(n,user,spamwriter):
    if n>0:
        #There is a limit to the traffic you can have with the API, so you need to wait
        #a few seconds per call or after a few calls it will restrict your traffic
        #for 15 minutes. This parameter can be tweeked
        time.sleep(40)
        try:
            users=api.followers(user)
            for follower in users:
                print(follower.screen_name)
                spamwriter.writerow([user+';'+follower.screen_name])
                fib(n-1,follower.screen_name,spamwriter)
                #n defines the level of autorecurrence

        except tweepy.TweepError:
            print("Failed to run the command on that user, Skipping...")

n=2
fib(n,user,spamwriter)

A: API.followers([id/screen_name]) only returns followers 100 at a time.
Try:
API.followers_ids(id/screen_name/user_id)

It will return a list of  ID's for all the people following the specified user. Just put your ID in the parameters.


text:
Q: Set up View Column to be last Value I have a View in my database set up to display data for parts that my company uses for projects.
One of the columns in the View shows what our recorded price for the part is.  However, as time goes on, and prices change, there will be many such entries for part prices.
Is there a way within a View setup, to set it so that the value retrieved for a column is that last value in that table?
Or is this a situation where I'd need to include the date of the price log as part of the view data, and then do a TOP 1 ... ORDER BY DESC type query against my view?
EDIT:
For example right now if I query my View for specifically the part with Part_Number = '0010.05.20.20' I will get the following Table result:
Part_Number    Supplier     Manufacturer  Price  Discount  Currency
0010.05.20.20  A2A Systems  Vario         55.97  1.000     CAD
0010.05.20.20  A2A Systems  Vario         50.25  1.000     USD

I know that the 50.25 price value is the most recent one, because it is the one I just inserted into the database for testing purposes.  However, there is no way to know just from doing a SELECT * FROM PartsView query which price is the most current one.
This is the code for creating my View, to clarify, I am wondering if there is a way to modify this so that the Price column only shows the most recent entry for any criteria it is looking up.  If that is not possible, is my only discourse to add a 'Log Date' Column for when the price was logged?
CREATE VIEW PartsView AS
SELECT
    p.part_number          AS [Part_Number],
    s.supplier_name        AS [Supplier],
    m.manufacturer_name    AS [Manufacturer],
    pl.cost_per_unit       AS [Price],
    pl.discount_percentage AS [Discount],
    cu.currency_type       AS [Currency]
FROM
    dbo.parts      AS p     INNER JOIN
    dbo.suppliers  AS s  ON p.supplier_id = s.supplier_id INNER JOIN
    dbo.price_logs AS pl ON p.part_id = pl.part_id INNER JOIN
    dbo.currencies AS cu ON pl.currency_id = cu.currency_id
GO

A: Here is an example of how you can pick the latest price for a part.
declare @Parts table (PartID int, PartName varchar(50))
declare @PartsLog table (PartID int, TransactionDate Datetime, Price decimal(11,2))

insert into @Parts(PartID, PartName) values
    (1,'Hammer'),
    (2,'Drill')
insert into @PartsLog(PartID,TransactionDate,Price) values
    (1,'2018-01-01',100.00),
    (1,'2018-07-01',200.00),
    (2,'2018-01-01',50.00),
    (2,'2018-03-01',75.00)

SELECT p.PartID
    ,p.PartName
    ,pl.price
FROM @Parts p
JOIN @PartsLog pl
    ON pl.PartID = p.PartID
        AND pl.TransactionDate = (
            SELECT max(TransactionDate)
            FROM @PartsLog
            WHERE PartID = pl.PartID
            )

| PartID | PartName | price  |
|--------|----------|--------|
| 1      | Hammer   | 200.00 |
| 2      | Drill    | 75.00  |


text:
Q: Space in PHP xpath query (new SimpleXMLElement) I receive a XML output and I convert it with new SimpleXMLElement.
The output is an array. So the XML element is $xml.
print_r($xml->xpath('categories[categories_name="Toners"]/childs/categories[categories_name="Color LaserJet"]'));

In the second [categories_name], the value has a space in the string. There goes something wrong because of the space. I don't get any information returned, if I delete the value with another existing value without a space, I get the information I want.
What can I do?

A: Breaking down the question to a small reproducible example:
$xml = <<<'XML'
<books>
  <book><title>A Title</title></book>
  <book><title>  A Title  </title></book>
</books>
XML;
$books = new SimpleXMLElement($xml);

echo  "String compare:\n";
foreach ($books->xpath('//book[title="A Title"]') as $book) {
  var_dump((string)$book->title);
}

Output:
String compare:
string(7) "A Title"

The second book title contains preceding and following whitespaces, so a simple string compare will not match it. One way to solve that is to use normalize-space(). This Xpath function will replace any sequence of whitespaces with a single space and remove preceding/following whitespaces. It does a little to much but for the most cases it should not matter.
echo  "\nwith normalize-space():\n";
foreach ($books->xpath('//book[normalize-space(title)="A Title"]') as $book) {
  var_dump((string)$book->title);
}

Output:
with normalize-space():
string(7) "A Title"
string(11) " A Title "

Now it matches both titles, but it will match something like A      Title as well.
Another solution allows you more control, but requires DOM. In DOM you can register PHP functions to be callable from XPath expressions. This can be existing functions or your own. You can make trim() available:
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);
$xpath->registerNamespace("php", "http://php.net/xpath");
$xpath->registerPhpFunctions(['trim']);

echo  "\nCall back into PHP:\n";
$expression = '//book[php:functionString("trim", string(title)) = "A Title"]';
foreach($xpath->evaluate($expression) as $node) {
  var_dump($xpath->evaluate('string(title)', $node));
}

With you own callback function you could do anything like RegEx matches or unicode string transliterations.


text:
Q: Flutter Bluetooth package can not build I had an error with my codes from https://github.com/pauldemarco/flutter_blue/tree/master/example
when I try to build apk with shrink or no shrink that gives me the same error.
My friend tried to build his own computer and he did it for the first time.
But I can not do that, it warns me about null safety or old buttons I changed but it still gives the same errors.
so anyone has an idea to fix that? I downloaded again this package but there is no difference.
decreased null safety changed codes for null safety
deleted, download again
removed text styles and raised buttons from the example because this code is old.
tried running' flutter build apk --no-shrink'
I added
    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
            // FIXME: Work-around for https://github.com/pauldemarco/flutter_blue/issues/772
            shrinkResources false
            minifyEnabled false
        }
    }

to android / app / build.gradle
Errors in : https://github.com/pauldemarco/flutter_blue/issues/1106


text:
Q: How to convert selenium.webdriver.get_cookies() to cookie text file for use with pycurl selenium.webdriver.get_cookies() gives me two dictionaries of value/pairs. I assume each of these dictionaries is a cookie. How do I write these cookies to a text file that will work with the following code to load the cookies from the cookie.txt file to a curl session?
p = pycurl.Curl()
cookiefile = open('cookie.txt', 'r')
p.setopt(pycurl.URL, my_url)
p.setopt(pycurl.COOKIEFILE, cookiefile)
p.perform()

Is there a better way to transfer the cookies from a selenium session to a curl session for a file download? I saw the post about using pickle, but using the file produced by pickle.dump() as cookiefile in the above code results in the following error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: invalid arguments to setopt

I think this is because the file is just a binary dump of the python dictionary and not a properly formatted text file. How can I write these two dictionaries to a text file that can be read and used by pycurl? I found some information in RFC6265:

Each cookie begins with a name-value-pair, followed by zero or more
  attribute-value pairs.

Each dictionary from selenium.webdriver.get_cookies() has a name and value attribute along with other attributes. How do I format these into a properly formatted cookie.txt file? I am not sure about the syntax description in RFC6265:
set-cookie-header = "Set-Cookie:" SP set-cookie-string
set-cookie-string = cookie-pair *( ";" SP cookie-av )
cookie-pair       = cookie-name "=" cookie-value
...
path-av           = "Path=" path-value

So would it start like
Set Cookie: ASP.NET_SessionId=4jqhjdiq9k12ry45ahqtux3e (path=/; secure=False; httpOnly=True; domain=www.domain.com)

and then another line starting with Set Cookie: and the second dictionary's name and value followed with its additional attributes in parentheses?

A: Everything I have found since asking this question points to the answer to this question: https://unix.stackexchange.com/questions/36531/format-of-cookies-when-using-wget, being the answer to my question as well (https://curl.haxx.se/docs/http-cookies.html says curl uses the netscape cookie format).

A: Use this code
I used requests, not pycurl, but I think this will help you a little.
cookies_list = driver.get_cookies()
cookies_dict = []
for cookie in cookies_list:
    cookies_dict.append([cookie['name'],cookie['value']])
cookies_dict = dict(cookies_dict)

and
requests.get(URL, cookies=cookies_dict)

this will work.


text:
Q: When spring boot service starts, insert data into mongodb I'm currently new to the Spring Boot Java framework and I'm building a simple application. When my service starts, I want to be able to read a raw file from a URL, parse that data, and upload it into my mongodb database of atlas. So far this is what I have:
@Service
public class CoronaVirusDataService {
  private List<LocationStats> allConfirmedStats = new ArrayList<>();
  MongoOperations mongoOperations;

  @PostConstruct // run this method as soon as the application runs
  @Scheduled(cron = "* * 1 * * *") // execute this method every day
  public void fetchVirusData() {
    List<LocationStats> newStats = new ArrayList<>(); // to hold the stats of each state
    HttpClient client = HttpClient.newHttpClient();
    // creating a new http request
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(ConstantsUtil.VIRUS_CONFIRMED_DATA_URL))
        .build();

    // get a response by having the client send the request
    try {
      HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
      // parse the body of the request from csv format to readable format
      StringReader csvBodyReader = new StringReader(httpResponse.body());
      Iterable<CSVRecord> records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(csvBodyReader);
      for (CSVRecord record: records) {
        // create a model with the parsed data
        LocationStats stats = new LocationStats();
        stats.setState(record.get("Province/State"));
        stats.setCountry(record.get("Country/Region"));
        // the latest day
        int latestCases = Integer.parseInt(record.get(record.size() - 1));
        int prevDayCases = Integer.parseInt(record.get(record.size() - 2));
        stats.setLatestTotalCases(latestCases);
        stats.setDiffFromPreviousDay(prevDayCases);

        mongoOperations.save(LocationStats);

        // add to new stats
        newStats.add(stats);
      }
      // assign to class array -> we use this array to display the data
      this.allConfirmedStats = newStats;

    } catch (IOException | InterruptedException e) {
      e.printStackTrace();
    }
  }

}

So the main issue with this is the data is not saving to the mongoDB once I call mongoOperations.save(). Also, I've learned that it is bad practice to maintain some type of state in a Service. What is the best practice for this? Will inserting the data into MongoDB take care of that since we are not managing state.
Here is my model class that I want to save to mongodb
@Document(collection = "LocationStats")
public class LocationStats {
  /** Location model to show corona virus statistics in each state*/
  @Id
  private String state;
  private String country;
  private int latestTotalCases;
  private int diffFromPreviousDay;

  public String getState() {
    return state;
  }

  public void setState(String state) {
    this.state = state;
  }

  public String getCountry() {
    return country;
  }

  public void setCountry(String country) {
    this.country = country;
  }

  public int getLatestTotalCases() {
    return latestTotalCases;
  }

  public void setLatestTotalCases(int latestTotalCases) {
    this.latestTotalCases = latestTotalCases;
  }

  public int getDiffFromPreviousDay() {
    return diffFromPreviousDay;
  }

  public void setDiffFromPreviousDay(int diffFromPreviousDay) {
    this.diffFromPreviousDay = diffFromPreviousDay;
  }

  @Override
  public String toString() {
    return "LocationStats{" +
        "state='" + state + '\'' +
        ", country='" + country + '\'' +
        ", latestTotalCases=" + latestTotalCases +
        '}';
  }
}

once I have my models saved into mongoDB, I want to read from the database and get all the data from each collection and display it on the webpage. I'm thinking I'd fetch that data within the controller class and pass it to the frontend, is this good practice? here is my controller class.
@Controller
public class HomeController {
  /** Controller class to generate/render the html UI */
  @Autowired
  CoronaVirusDataService coronaVirusDataService;

  @Autowired
  MongoOperations mongoOperations;

  @GetMapping("/") // map this to the root template
  public String home(Model model) {
    List<LocationStats> allStats = coronaVirusDataService.getAllConfirmedStats();

    // instead of above getter method, have a method call that fetches all data from mongoDB and return it as a List<LocationStats>

    // get the total confirmed cases
    int totalConfirmedCases = allStats.stream().mapToInt(LocationStats::getLatestTotalCases).sum();
    int totalNewCases = allStats.stream().mapToInt(LocationStats::getDiffFromPreviousDay).sum();

    // send the models to the view
    model.addAttribute("locationStats", allStats);
    model.addAttribute("totalReportedCases", totalConfirmedCases);
    model.addAttribute("totalNewCases", totalNewCases);

    return "home";
  }
}


text:
Q: Nginx proxy, linked to other docker containers I've created two containers running two different web applications. I'm trying to create a third container to have a nginx proxy redirecting the request to the correct container depending on the hostname. My Nginx configuration looks correct when I'm running the nginx official image, and modifying manually inside the container the default configuration file with the proxy setup.
My two web applications containers are already running, and I start the proxy container as follow :
docker run -i -t --link webapp1 --link webapp2 -p 80:80 nginx /bin/bash

To do the cleanest way as I think, I'd create a Dockerfile to create the container, and passing the local default.conf file to the container when building it.
This is my nginx proxy configuration file :
server {
    listen       80;
    server_name  www.webapp1.ch;

    location / {
        proxy_pass   http://webapp1/;
    }
}

server {
    listen       80;
    server_name  www.webapp2.ch;

    location / {
        proxy_pass   http://webapp2/;
    }
}

And the proxy Docker file :
# Set the base image to use to Ubuntu
FROM nginx:latest

# Set the file maintainer (your name - the file's author)
MAINTAINER Me

# Update the default application repository sources list
RUN apt-get update && apt-get install -y \
        wget \
        vim

RUN rm /etc/nginx/conf.d/default.conf
COPY default /etc/nginx/conf.d/default.conf
CMD /etc/init.d/nginx restart

But unfortunately, when I'm trying to build it, the container doesn't know yet the webapp1 and webapp2 container address / ip as they aren't linked yet. I receive this error :
Step 7 : RUN /etc/init.d/nginx restart
 ---> Running in aef974e80e74
Restarting nginx: nginx2016/12/29 17:07:17 [emerg] 11#11: host not found in upstream "webapp1" in /etc/nginx/conf.d/default.conf:6
nginx: [emerg] host not found in upstream "webapp1" in /etc/nginx/conf.d/default.conf:6
nginx: configuration file /etc/nginx/nginx.conf test failed

What am I doing wrong and would be the best approach to fix it?

A: Using links is a legacy feature, you should use User defined networks.
sudo docker network create mynetwork
docker run -d --network mynetwork -p 80:80 -v /path/to/nginx/config/default.conf:/etc/nginx/conf.d/default.conf nginx

Then I used my recently created user defined network in docker run command.
Another thing that I did there, I mounted my nginx config instead of building a new image for it.
One of the advantages would be automatic dns based on container names in the same userdefined networks.
Now back to your nginx problem:
proxy_pass   http://webapp2:port/;

I'm guessing you are running all 3 containers on the same docker host, they all cant be running on port 80 so you should provide ports in your nginx reverse proxy config.


text:
Q: How to match/replace a string in PHP? I need to delete a part of a string of characters, the problem is that I do not know either the position or the character of beginning, even for the end.
Example 1:

The source string : image_807x400.jpg
Expected Result : image.jpg

Example 2:

The source string : image-7x2.jpg
Expected Result : image.jpg

At that moment I found a solution but it takes a lot of time:
function replace($output)
{
    $final = array();
    foreach ($output as $table => $files) {
        foreach ($files as $file => $ids) {
            for ($i = 0; $i <= 9999; $i++) {
                for ($j = 0; $j <= 9999; $j++) {
                    $param = '_' . $i . 'x' . $j . '.';

                    $exist = strpos($file, $param);

                    if (!$exist) {
                        $param = '-' . $i . 'x' . $j . '.';
                        $exist = strpos($file, $param);
                    }

                    if ($exist) {
                        $newFileName = str_replace($param, '.', $file);
                        $final[$table][$file] = $newFileName;
                    }
                }
            }
        }
    }
    return $final;
}

A: For your example data, you can use preg_replace and make use of \K to forget what was matched:
\w+\K[_-]\d+(?:x\d+)?

Regex demo | Php demo
For example:
$strings = [
    "image_807x400.jpg",
    "image-7x2.jpg",
    "actuality_1x30.jpg",
    "team_1200x800.jpg ",
    "help_504x300.jpg",
    "image2_807x400",
    "2Dimage_01",
    "2D-image_01"
];

foreach ($strings as $string) {
    echo preg_replace('/\w+\K[_-]\d+(?:x\d+)?/', '', $string) . PHP_EOL;
}

Result:
image.jpg
image.jpg
actuality.jpg
team.jpg
help.jpg
image2
2Dimage
2D-image

A: I can't make sense of all the looping and variable names so just adapt this:
$info = pathinfo($file);
preg_match('/^[a-z]+/i', $info['basename'], $match);
$final = $match[0].$info['extension'];

*

*Get the basename

*Match only letters [a-z] at the beginning ^, where i means case-insensitive

*Add the extension

A: This regex might cover your instances by creating two groups, your first partial word and everything else including the extension(s). You may only need to add any other characters except for [a-z] that you might have in your initial first word in your output array.
It may not be the best idea to bound your regex from the right, since you may have JPG, JPEG, jpg and other extensions similar to:
$output = array(
    'table1' => array(
        '1' => 'image_807x400.jpg',
        '2' => 'image-7x2.jpg',
        '3' => 'image-7x2.JPEG',
        '4' => 'image-7x2.JPG',
        '5' => 'image-7x2.PNG',
        '6' => 'image_807x400.png',
        '7' => 'image_807x400.gif',
        '8' => 'image_807x400.GIF',
    ),
    'table2' => array(
        '1' => 'image_807x400.jpg',
        '2' => 'image-7x2.jpg',
        '3' => 'image-7x2.JPEG',
        '4' => 'image-7x2.JPG',
        '5' => 'image-7x2.PNG',
        '6' => 'image_807x400.png',
        '7' => 'image_807x400.gif',
        '8' => 'image_807x400.GIF',
    ),
    'table3' => array(
        '1' => 'actuality_1x30.jpg',
        '2' => 'help_504x300.jpg',
        '3' => 'team_1200x800.jpg',
    ),
);

replace($output);

function replace($output)
{
    $final = array();
    foreach ($output as $table => $files) {
        foreach ($files as $file => $ids) {
            $final[$table][$file] = preg_replace('/(?:^|(?:\.\s))([a-z]+)(.*)/s', '$1.jpg', $output[$table][$file]);
        }
    }
    var_dump($final);
    return $final;
}

Output
array(3) {
  ["table1"]=>
  array(8) {
    [1]=>
    string(9) "image.jpg"
    [2]=>
    string(9) "image.jpg"
    [3]=>
    string(9) "image.jpg"
    [4]=>
    string(9) "image.jpg"
    [5]=>
    string(9) "image.jpg"
    [6]=>
    string(9) "image.jpg"
    [7]=>
    string(9) "image.jpg"
    [8]=>
    string(9) "image.jpg"
  }
  ["table2"]=>
  array(8) {
    [1]=>
    string(9) "image.jpg"
    [2]=>
    string(9) "image.jpg"
    [3]=>
    string(9) "image.jpg"
    [4]=>
    string(9) "image.jpg"
    [5]=>
    string(9) "image.jpg"
    [6]=>
    string(9) "image.jpg"
    [7]=>
    string(9) "image.jpg"
    [8]=>
    string(9) "image.jpg"
  }
  ["table3"]=>
  array(3) {
    [1]=>
    string(13) "actuality.jpg"
    [2]=>
    string(8) "help.jpg"
    [3]=>
    string(8) "team.jpg"
  }
}

A: Finally I found the solution:
$newFileName = preg_replace('/\K[_-]\d+x\d+/', '', $file);


text:
Q: Why is my code for a single fql query not working anymore? I have the following code:
     <?php

      require '../src/facebook.php';

     // Create our Application instance (replace this with your appId and secret).

   $facebook = new Facebook(array(
    'appId'  => 'app_id',
    'secret' => 'app_secret'
    ));
    $access_token = $facebook->getAccessToken();

    $fql = "select user_id, object_id, object_type from like where user_id=me()";
    $result = $facebook->api(array(
         'method'       => 'fql.query',
         'access_token' => $access_token, //tried either with/without this
         'query'        => $fql,
      ));
    print_r($result);
?>

It used to work perfectly but now it is just returning an empty array() Can this be solved? or is there any other code that could work better?
note: I have all the access tokens necessary, I tried small changes in the code like quotations, spaces...
please help
Thank a lot!

A: It should work !! There was an issue in the like table back in 2013 which is resolved.
One of the issue not getting data is that your application does not ask for read_stream
So in the login part you may need to pass the scope read_stream
You can check here.
https://developers.facebook.com/tools/explorer/
Generate a new access token by adding extended permission read_stream
And then run your FQL.
I just tested your FQL in my app which ask for read_stream and it works pretty well I get the data.


text:
Q: How can I improve this React component with correct lifecycle usage? I am trying to make a list item toggle on and off. So I capture the click event, send a request to my endpoint with PATCH method, get the new value returned from the backend and update the state of the component based on that value. And it works perfectly. But I have the feeling that I might have to use useEffect here in some way. But I can't figure out how to do it. Any suggestions would be much appreciated.
import { useState } from 'react';
import { useSelector } from 'react-redux';

export function ListItem({ id, content, checked }) {
    const token = useSelector(state => state.auth.token);

    const [isChecked, setIsChecked] = useState(checked);

    const makeRequest = async () => {
        const uri = `http://127.0.0.1:8000/listitems/${id}/`;

        const h = new Headers();
        h.append('Authorization', `Token ${token}`);
        h.append('Content-Type', 'application/json');

        const req = new Request(uri, {
            method: 'PATCH',
            headers: h,
            body: JSON.stringify({
                checked: !isChecked
            }),
            mode: 'cors'
        })

        const response = await fetch(req);
        const json = await response.json();

        const result = json.checked;

        return result;
    }

    const handleClick = async (e) => {
        // request the endpoint to check/uncheck the item
        const result = await makeRequest();

        // add/remove the strikethrough class to/from the content
        setIsChecked(result);
    }

    return (
        <>
        <label>
            <input onChange={handleClick} type="checkbox" name="list-items" checked={isChecked}/>
            {isChecked ? <s children={content} /> : content}
        </label> <br/>
        </>
    );
}


text:
Q: XPATH query, HtmlAgilityPack and Extracting Text I had been trying to extract links from a class called "tim_new" . I have been given a solution as well.
Both the solution, snippet and necessary information is given here
The said XPATH query was "//a[@class='tim_new'], my question is, how did this query differentiate between the first line of the snippet (given in the link above and the second line of the snippet).
More specifically, what is the literal translation (in English) of this XPATH query.

Furthermore, I want to write a few lines of code to extract the text written against NSE:

BSE: 523395   |   NSE: 3MINDIA   |   ISIN: INE470A01017

Would appreciate help in forming the necessary selection query.
My code is written as:
IEnumerable<string> NSECODE = doc.DocumentNode.SelectSingleNode("//div[@NSE:]");

But this doesnt look right. Would appreciate some help.

A: The XPath in the first selection reads "select all document elements that have an attribute named class with a value of tim_new".  The stuff in brackets is not what you're returning, it's the criteria you're applying to the search.
I don't have the HTML Agility pack, but if you are trying to query the divs that have "NSE:" as its text, your XPath for the second query should just be "//div"  then you'll want to filter using LINQ.
Something like
var nodes =
    doc.DocumentNode.SelectNodes("//div[text()]").Where(a => a.InnerText.IndexOf("NSE:") > -1);

So in English, "Return all the div elements that immediately contain text to LINQ, then check that the inner text value contains NSE:".
Again, I'm not sure the syntax is perfect, but that's the idea.
The XPath  "//div[@NSE:]"  would return all divs that have and attribute named, NSE:, which would be illegal anyway because ":" isn't allowed in an attribute name.  Youre looking for the text of the element, not one of its attributes.
Hope that helps.'
Note:  If you have nested divs that both contain text as in
NSE:  some text
NSE:  more text

  you're going to get duplicate results.


text:
Q: How to resolve PHP Laravel Sql Insert error? When I press the buy button I get this error
QueryException in Connection.php line 729:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'qty' cannot be null (SQL: insert into orders (user_id, product_id, qty, updated_at, created_at) values (3, 1,    , 2018-10-06 20:44:27, 2018-10-06 20:44:27))

first of all, I'm a beginner so I'm still learning and I do not know if some of this is correct, all I want is when I press the buy button it will display the form and I will type the quantity then submit and my quantity will increase and the products inventory will decrease and if I deleted my order, The products will increase again (I did this and I think it will work) and the user can update his quantity and if someone ordered something the seller cannot delete it, only update his inventory as same as the buy button way and  the form, and if the users ordered all products it will display (out of stock) with a dead link button, I am training, It is not homework and I do not know how to write all functions..
this is the Buy button

Buy

which should pop up the next form when I press it,
this is my form code for the buy button
<form method="POST" action="/add_order/{{ $product['id'] }}" class="klaviyo_subscription_form" enctype="multipart/form-data">

    {{ csrf_field() }}

    <input type="hidden" name="g" value="LIST_ID">

Please define quantity you need, then order it.

has('qty') ? ' has-error' : '' }}">
            Quantity
            <input type="number" id="k_id_modal_$email" name="qty" style="display: block; margin:auto">

            @if ($errors->has('qty'))

                    {{ $errors->first('qty') }}

            @endif

        <button type="submit" class="klaviyo_submit_button">
            Order Now
        </button>

</form>

OrderController
public function store(Request $request, $id)
{
    $product = Product::find($id);
    $order = new Order();
    $order->user_id = Auth::user()->id;
    $order->product_id = $id;
    $order->qty = $request->get('qty');
    $product->inv = $product->inv - $order->qty;
    $order->save();
    $product->save();

    return redirect('/');
}

thanks for reading :D

A: Request is object and not array! You need to use method to get request value. Check updated code
  public function store(Request $request, $id)
  {
    $product = Product::find($id);
    $order = new Order();
    $order->user_id = Auth::user()->id;
    $order->product_id = $id;
    $order->qty = $request->get('qty');
    $product->inv = $product->inv - $order->qty;
    $order->save();
    $product->save();
    return redirect('/');
  }

This will work if logic for passing "qty" to request is correct. You can do dump of request and die inside store function, to make sure about this fact.

A: Your Problem is you sending the data with the POST method.
But you access the data from the GET method.
OrderController
$order->qty = $request->get('qty');   // this is where you are wrong.

Change this either,
$order->qty = $request->post('qty');

or,
$order->qty = $request->qty // this is the preferred approach.

A: In your database table filed "qty" set default value null or as default 0.
and write
$order->qty = $request->qty;

it will work fine


text:
Q: Change Range Of Displayed Pixel Values from Command Line? I'm working with some MRI data in Matlab 2014b, but the data is formed of intensity values not RGB. To get around this I use the code below to form a movie out of the MRI frames (I'm working on dynamic data here)
My problem is that the images need to have altered display values for the pixels, as the default only displays between -Inf and Inf, and I need between 0 and 0.25 to get a sensible image out of my data.
Are there any ways to pass that change from the script in to the movie, and then to write to file? I can only seem to do this per image in implay, and I'd like an automated way to edit each image and then store as a frame for a movie..?
%Code for producing movie.

graymap = gray(256);

for i = 1:32
    a(:,:,i) = cmunique(Reformed_Data_Colourmap(:,:,i));
end

for i = 1:32
    b = im2frame(a(:,:,i),graymap);

    a(:,:,1) = ((b.cdata));

    image(a(:,:,1))

    colormap 'gray'

%The change needs to be here, to display pixel values from 0 to 0.25, to allow for a sensible image from the MR data.

    frames(1,i) = getframe;

end

movie(frames)

A: The solution is provided:
for i = 1:32

b = im2frame(a(:,:,i),graymap);
a(:,:,1) = ((b.cdata));

clims = [0 250];

%image(a(:,:,1),clims)
colormap 'gray'

imagesc(a(:,:,1),clims);

%set('window', [0 400])
frames(1,i) = getframe;
end

clims solves the issue.


text:
Q: From the perspective of an observer inside a black hole's horizon, where does the energy for Hawking radiation come from? Would energy be seen to "flow" to the outside of the black hole? Through what mechanism?

A: The observer inside the event horizon does not observe Hawking radiation--- this is a pure external effect.

A: This is an incomplete answer, but I would bring two important points here:
1) When observer moves freely in GR, he/she observes locally flat spacetime up to quadratic corrections in 3-distance from his/her worldline. Hence, if you are falling into a black hole, you shall see the same as what you would see, if you were in Minkowski spacetime throughout all your infall, unless you start measuring the tidal forces. Hence, you shall see no Hawking radiation generated around you at all, until you come so close to the singularity, that the tidal forces shall become very strong and you shall eventually observe local generation of particle-antiparticle pairs around.
However, this doesn't exclude the possibility of observing some flux falling with you from the infinity into the black hole.
2) The notion of particles in GR depends on your reference frame. If you imagine an observer located above the event horizon, accelerated in such a way that he/she has stationary spatial coordinates, he/she will not be moving freely due to acceleration and shall see particles/antiparticles generated around, some of them falling under the horizon, and some of them flying away from the black hole. If you consider some static asymptotically flat coordinate system, you shall see that some particles in this system shall escape to infinity and shall be visible to the remote observers, moving freely with respect to that system.
To conclude, you shall not observe Hawking radiation generated around you, though you might possibly see already existing particle-antiparticle background (possibly, exactly Hawking radiation).

A: An observer inside a black hole is impossible because a black hole has no internal structure (otherwise it would be possible to transfer information from inside by moving massive bodies.
Also no information can be under the horizon because this would mean information loss which is impossible thermodynamically.
So any black hole is an uniform body without internal structure.


text:
Q: Optimal control of leaky integrator I'm having trouble with the following problem:

Control the following 1st order system $$\dot x =  -x + u$$ from $x(0)=2$ to $x(4)=5$ such that the following cost function is minimized $$J= x(4) + \int_{0}^{4} u^2 (t) \, \mathrm{d}t$$ Find the optimal control $u^*$ and the optimal trajectory $x^*$.

I used the Pontryagin's maximum principle by writing the Hamiltonian
$$H = u^2 + \lambda ( - x + u)$$
Unfortunately, I did not find a stable solution ($u$ does not converge)
$$\frac{\partial H }{\partial u} =0 $$
implies $u^* = -\lambda/2$ and $\lambda$ is given by solving
$$\dot \lambda = - \frac{\partial H }{\partial x}$$
I found $\dot \lambda = \lambda$ which is first-order. The solution is an increasing exponential and, therefore, the control $u^*$ is an increasing exponential as well. Any help would be appreciated. Thanks!

A: Since you minimize your cost functional, the Pontryagin maximum principle says that the Hamiltonian is to be chosen as $H(x,\lambda,u,t)=\lambda_0 u^2(t) + \lambda(-x+u)$, where $\lambda_0$ can be set to $-1$ (we assume that the optimal control problem is regular). So, we have
$$H(x,\lambda,u,t)= -u^2 + \lambda(-x+u).$$
As @Rodrigo-de-Azevedo rightfully noticed, $x(4)$ does not play any role in the cost functional as the right end-point is fixed.
Now we use the first order optimality condition to determine $u^*=\lambda/2$. One can check that $u^*$ does indeed maximizes $H(x,\lambda,u)$ as $\frac{\partial^2 H}{\partial^2 u}=-2<0$, which implies that $H$ is concave w.r.t. $u$. As for now, we assume that $u^*\in [u_{min}, m_{max}]$, i.e., $u^*$ is within the admissible control set.
Now we can write the DE for $\lambda$, $\dot{\lambda}=\lambda$, which is not very informative as we do not know both the initial and the final values of $\lambda(t)$. So, we choose $\lambda(0)=\Lambda$ and try to find $\Lambda$ s.t. the end-point conditions on $x(t)$ are fulfilled.
Solving $\dot{\lambda}=\lambda$ with $\lambda(0)=\Lambda$ we get $\lambda(t)=\Lambda e^{t}$. Using $u^*=\lambda/2$ and substituting it into the DE for $x$ we get
$$\dot{x}=-x+\Lambda e^t/2,\quad x(0)=2$$
which solves to yield $x(t)=\frac{1}{4}\left[\Lambda e^t - e^{- t}(\Lambda - 8)\right]$. Finally, from $x(4)=5$ we get $\Lambda=\dfrac{20 e^4 - 8}{e^8 - 1}$ and the optimal control is $u^*=\dfrac{10 e^4 - 4}{e^8 - 1}e^t$.
Below is the optimal control plot and the corresponding optimal trajectory.

A: Integrating the differential equation $\dot x = -x + u$, we obtain
$$x(4) = e^{-4} \left( x(0) + \int_0^4 e^t \,u (t) \, \mathrm d t\right)$$
Since the fixed endpoints are $x(0) = 2$ and $x(4) = 5$, we obtain the following equality constraint
$$\int_0^4 e^t \,u (t) \, \mathrm d t = 5 e^4 - 2$$
Since the cost function is the energy of the input function $u$, we obtain the following constrained optimization problem in function $u : [0,4] \to \mathbb R$
$$\begin{array}{ll} \text{minimize} & \qquad\displaystyle\int_0^4 u^2 (t) \, \mathrm d t\\ \text{subject to} & \displaystyle\int_0^4 e^t \,u (t) \, \mathrm d t = 5 e^4 - 2\end{array}$$
Let the Lagrangian be
$$\mathcal L (t, u) := u^2 + \lambda e^t u$$
The Euler-Lagrange equation produces
$$u (t) = -\frac{\lambda}2 e^t$$
Using the equality constraint, we eventually obtain the Lagrange multiplier
$$\lambda = -4 \left(\frac{5 e^4 - 2}{e^8 - 1}\right)$$
and, thus, the optimal input function is
$$\bar u (t) := \color{blue}{2 \left(\frac{5 e^4 - 2}{e^8 - 1}\right) e^t}$$


text:
Q: How to get broweser name when each thread in parallel test execution with multiple browsers in TestNG, Cucumber and Selenide Is there a way to get the current browser name of each thread running using Selenide?
I integrated TestNG Cucumber with multiple browsers.
So I need to know at @After hook, which browser is running the test.
And based on browser do some stuff.
    <?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="TestSuite" thread-count="8" parallel="tests" >
    <test name="ChromeTest">
        <parameter name="browser" value="chrome" />
        <classes>
            <class name="com.site.runner.TestRunner">
            </class>
        </classes>
    </test>
    <test name="FirefoxTest">
        <parameter name="browser" value="firefox" />
        <classes>
            <class name="com.site.runner.TestRunner">
            </class>
        </classes>
    </test>
    <test name="SafariTest">
        <parameter name="browser" value="safari" />
        <classes>
            <class name="com.site.runner.TestRunner">
            </class>
        </classes>
    </test>
</suite>

Selenide set driver
public static synchronized void setDriver(String browser) {
        setBrowser(browser);
    }

public String setBrowser(String browser){

        switch(browser){
            case "chrome":
                return setCapabilities(browser);
            case "firefox":
                return Configuration.browser = "firefox";
            case "edge":
                return Configuration.browser = "edge";
            default:
                return "No Browser found";
        }

public static void directToBrowserUrl(String browserUrl) {
        open(browserUrl);
    }

A: Get the capabilities and current thread of the driver in @After method.
Code:
 Capabilities capabilities = ((RemoteWebDriver) driver).getCapabilities();
    String browserName = capabilities.getBrowserName();
    String threadName = Thread.currentThread().getName();
    long threadId = Thread.currentThread().getId();

    System.out.println("Thread name & browser name: "+threadName +" --> "+browserName);
    System.out.println("Thread id & browser name: "+threadId +" --> "+browserName);

    if(browserName.equalsIngnoreCase("Chrome"){
     //do your stuff
    }

Output:
Thread name & browser name: com.CallerScript.Caller.main() --> chrome
Thread id & browser name: 16 --> chrome


text:
Q: How do I expand my express API across multiple files/folders? I am practicing with APIs and have one working, but all of the endpoints are in the default app.js file. My question is, how can I move endpoints to different files/folders to organize my code?
HERE IS AN EXAMPLE:
App.js
app.get('/contact', (req, res)=>{
    res.status(200).send('CONTACT')
})

app.get('/about', (req, res)=>{
    res.status(200).send('ABOUT')
})

How can I move my '/about' endpoint to another file called 'about.js' and have it still be accessible as an endpoint? All express tutorials that I look up only use the app.js file and never create multiple files.

A: You can use the below code for your reference.
app.js
const express = require('express')
const about = require('./about');
const contact = require('./contact');
const app = express()
const port = 3000

app.use('/contact', contact);
app.use('/about', about);

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})

about.js
const express = require('express')
const app = express()

module.exports = app.get('/', (req, res)=>{
    res.status(200).send('ABOUT From about.js file')
});

contact.js
const express = require('express')
const app = express()

module.exports = app.get('/', (req, res)=>{
    res.status(200).send('CONTACT From contact.js file')
});

A: You can use this below file structure
app.js
  var admin = require('./routes/admin.js');
  app.use('/admin',admin)

admin.js
  var adminController = require('../Controllers/admin/index.js');
  admin.post('/register', function (req, res, next) {
adminController.insertAdmin(req.headers, req.body).then(function (insertAdmin) {
    res.status(200).send(insertAdmin);
}, function (err) {
    res.status(400).send(err);
}).catch(function (e) {
    console.log('500 error', err);
    res.status(500).send(e);
})
});


text:
Q: How to fire a trigger after data has been inserted in a table in mysql I want to fire a trigger after my table has been filled with records ,I don't want to fire a row-wise trigger.
Please tell how can we do that in mysql?

A: CREATE TRIGGER trigger_name AFTER INSERT ON table_name

Updated:
The FOR EACH ROW option determines whether the trigger is a row trigger or a statement trigger. If you specify FOR EACH ROW, then the trigger fires once for each row of the table that is affected by the triggering statement. The absence of the FOR EACH ROW option indicates that the trigger fires only once for each applicable statement, but not separately for each row affected by the statement.


text:
Q: How to check if a macro can be followed by a newline I'm trying to create a class that allows you to define a name using
\name{Whatever}

This is defined as
\newcommand{\name}[1]{\def\gsy@name{#1}}

Whatever is passed to this is used in the header, and is followed by \\
and more content:
\rhead{\gsy@name\\More stuff on the next line}

Unfortunately, the whole thing breaks when someone passes nothing or a space
to \name:
\name{   }

This results in the \\ trying to end a blank line, and the whole thing
refusing to compile.
Is there any way I can detect if something that can't be followed by \\ is
passed to my macro?

A: Using \notblank{\gsy@name}{stuff with \\}{empty or other stuff} with an \expandafter of \gsy@name should work. It tests whether the first argument is empty (blank/space/white space) or not.
Please not that fancyhdr might complain about the \headheight value
\documentclass{article}
\usepackage{fancyhdr}
\usepackage{etoolbox}
\makeatletter
\newcommand{\name}[1]{\def\gsy@name{#1}}
\rhead{\expandafter\notblank\expandafter{\gsy@name}{\gsy@name\\More stuff on the next line}{}}

\makeatother
%\name{Stuff }
\name{}

\pagestyle{fancy}
\begin{document}
Foo

\end{document}


text:
Q: InvalidArgumentError: assertion failed: [Unable to decode bytes as JPEG, PNG, GIF, or BMP] I have a folder structure where every subfolder represents a class, for every class there is exactly one example picture. I want to load the data in a Keras dataset as described here: https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image_dataset_from_directory
I expect to get the tuple "(images, labels)" returned, but when I assign the functions output to a tuple, I get an error.
Here is my code:
import pathlib
data_path = "./patterns"
data_dir = pathlib.Path(data_path)

batch_size = 32
img_height = 120
img_width = 30

train_ds, train_labels = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  labels='inferred',
  label_mode='categorical', #int
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

And this is the error I receive:
Found 2160 files belonging to 2160 classes.
Using 1728 files for training.
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
/usr/local/lib/python3.7/site-packages/tensorflow/python/eager/context.py in execution_mode(mode)
   2101       ctx.executor = executor_new
-> 2102       yield
   2103     finally:

/usr/local/lib/python3.7/site-packages/tensorflow/python/data/ops/iterator_ops.py in _next_internal(self)
    757             output_types=self._flat_output_types,
--> 758             output_shapes=self._flat_output_shapes)
    759

/usr/local/lib/python3.7/site-packages/tensorflow/python/ops/gen_dataset_ops.py in iterator_get_next(iterator, output_types, output_shapes, name)
   2609     except _core._NotOkStatusException as e:
-> 2610       _ops.raise_from_not_ok_status(e, name)
   2611     except _core._FallbackException:

/usr/local/lib/python3.7/site-packages/tensorflow/python/framework/ops.py in raise_from_not_ok_status(e, name)
   6842   # pylint: disable=protected-access
-> 6843   six.raise_from(core._status_to_exception(e.code, message), None)
   6844   # pylint: enable=protected-access

/usr/local/lib/python3.7/site-packages/six.py in raise_from(value, from_value)

InvalidArgumentError: assertion failed: [Unable to decode bytes as JPEG, PNG, GIF, or BMP]
     [[{{node decode_image/cond_jpeg/else/_1/decode_image/cond_jpeg/cond_png/else/_20/decode_image/cond_jpeg/cond_png/cond_gif/else/_39/decode_image/cond_jpeg/cond_png/cond_gif/Assert/Assert}}]] [Op:IteratorGetNext]

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-74-f878a6f234dd> in <module>
      7   seed=123,
      8   image_size=(img_height, img_width),
----> 9   batch_size=batch_size)

/usr/local/lib/python3.7/site-packages/tensorflow/python/data/ops/iterator_ops.py in __next__(self)
    734
    735   def __next__(self):  # For Python 3 compatibility
--> 736     return self.next()
    737
    738   def _next_internal(self):

/usr/local/lib/python3.7/site-packages/tensorflow/python/data/ops/iterator_ops.py in next(self)
    770   def next(self):
    771     try:
--> 772       return self._next_internal()
    773     except errors.OutOfRangeError:
    774       raise StopIteration

/usr/local/lib/python3.7/site-packages/tensorflow/python/data/ops/iterator_ops.py in _next_internal(self)
    762         return self._element_spec._from_compatible_tensor_list(ret)  # pylint: disable=protected-access
    763       except AttributeError:
--> 764         return structure.from_compatible_tensor_list(self._element_spec, ret)
    765
    766   @property

/usr/local/lib/python3.7/contextlib.py in __exit__(self, type, value, traceback)
    128                 value = type()
    129             try:
--> 130                 self.gen.throw(type, value, traceback)
    131             except StopIteration as exc:
    132                 # Suppress StopIteration *unless* it's the same exception that

/usr/local/lib/python3.7/site-packages/tensorflow/python/eager/context.py in execution_mode(mode)
   2103     finally:
   2104       ctx.executor = executor_old
-> 2105       executor_new.wait()
   2106
   2107

/usr/local/lib/python3.7/site-packages/tensorflow/python/eager/executor.py in wait(self)
     65   def wait(self):
     66     """Waits for ops dispatched in this executor to finish."""
---> 67     pywrap_tfe.TFE_ExecutorWaitForAllPendingNodes(self._handle)
     68
     69   def clear_error(self):

InvalidArgumentError: assertion failed: [Unable to decode bytes as JPEG, PNG, GIF, or BMP]
     [[{{node decode_image/cond_jpeg/else/_1/decode_image/cond_jpeg/cond_png/else/_20/decode_image/cond_jpeg/cond_png/cond_gif/else/_39/decode_image/cond_jpeg/cond_png/cond_gif/Assert/Assert}}]]

Anyway it is interesting that I still get the output:
Found 2160 files belonging to 2160 classes.
Using 1728 files for training.

When I assign the function output just to a single variable (train_ds), I do not receive an error.

A: I think one of your images is corrupted. Use this function and see if it crashes. It will print the filename before reading it, so you'll see which picture is corrupted.
Modify the os.listdir() part so it includes all your images in the different folders.
import tensorflow as tf
import os

def validate_image(file_name):
    tf.py_function(tf.print, inp=[file_name], Tout=[])
    image = tf.io.read_file(file_name)
    image = tf.io.decode_image(image, channels=3)
    return image

os.chdir(r'path\to\images')

accepted_extensions = ('jpg', 'png', 'bmp', 'gif')

files = list(filter(lambda x: x.lower().endswith(accepted_extensions), os.listdir()))

ds = tf.data.Dataset.from_tensor_slices(files).map(validate_image)

for i in ds:
    pass


text:
Q: Android Studio: I can not run/debug my project after cloning it from my repository My HD died two days ago, luckily my android app is versioned on Bitbucket. So I got an SSD, reinstalled Windows 10 and the latest Android Studio. With Android Studio installed, I've cloned the project of my app through the 'Checkout project from Version Control' option in the welcome window of Android Studio. The project seems to have been cloned correctly, bringing all my source codes.
However, Android Studio was not able to create a Run / Debug configuration automatically. So, I tried to create a configuration by my own by clicking Edit Configurations> Add New Configuration (green cross) and choosing the option Android App. When choosing this option, the error 'Error: Module not specified' is showing below in the window, like Shows the image I attached.

This is the first time I have to clone my Android project from my repository and unfortunately I am not sure how to handle it. Can anybody help me?

A: Looks like you are missing the settings.gradle file. Create a new one in the project root folder with the following content:
include ':app'
include ':BaseGameUtils'
include ':squarecamera'
include ':volley'

I just guessed your modules, fix them in case they are not correct.


text:
Q: "Not all code paths return a value" C# Hello i am currently in the infant stages of writing a petshop app on Windows phone/C#. I have made the class below to set up my generic lists and to be able to add the pets to the shop using the given fields ( Name, age, breed and type ). The problem i believe lies in the fact that i am making a display method to be called (in another page which is below called Mainpage.xaml.cs) below called DisplayShop() and i am reading in 3 strings and an int, i believe it has something to do with the fact that my DisplayShop() method is a string, although i tried to rectify the problem by converting the age field to a string in the Display() method, although this has not fixed the problem.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Assignment_1
{
    public class Shop
    {
        private string name;
        private int age;
        private string breed;
        private string type;

        public Shop(string Name, int Age, string breed, string Type)
        {
            this.Name = name;
            this.Age = age;
            this.breed = breed;
            this.Type = type;
        }

        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                this.name = value;
            }
        }

        public int Age
        {
            get
            {
                return this.age;
            }
            set
            {
                this.age = value;
            }
        }

        public string Breed
        {
            get
            {
                return this.breed;
            }
            set
            {
                this.breed = value;
            }
        }

        public string Type
        {
            get
            {
                return this.type;
            }
            set
            {
                this.type = value;
            }
        }

        //Create the Collection
        List<Shop> myShop = new List<Shop>();

        public String Display()
        {
            return (Name + "\n" + Age.ToString() + "\n" + Breed + "\n" + Type);
        }

        public String DisplayShop()
        {
            foreach (Shop tmp in myShop)
            {
                tmp.Display();
            }
        }
    }
}

Here is the Mainpage.xaml.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace Assignment_1
{
    public partial class MainPage : PhoneApplicationPage
    {
        List<Shop> myShop = new List<Shop>();

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            setUpShop();
        }

        //Add animals to the Shop
        private void setUpShop()
        {
            myShop.Add(new Shop("John", 3 ,"Labrador", "Dog"));
            myShop.Add(new Shop("Billy", 9, "Terrier", "Dog"));
            myShop.Add(new Shop("Sam", 2, "Persian", "Cat"));
            myShop.Add(new Shop("Molly", 3, "Siamese", "Cat"));
            myShop.Add(new Shop("Nemo", 1, "Clown Fish", "Fish"));
            myShop.Add(new Shop("Dory", 1, "Palette Surgeonfish", "Fish"));
            myShop.Add(new Shop("Keith", 1, "Bearded Dragon", "Lizard"));
            myShop.Add(new Shop("Ozzy", 1, "Gecko", "Lizard"));

            imgHolder1.Items.Add(myShop[1].DisplayShop());
        }
    }
}

The aim of this first part is to add the pets to an listBox in my windows app, if any of you could suggest a fix to this problem it would be much appreciated, I have included an image of the the way the phone app currently looks >>> http://gyazo.com/06217efae9265d0fef59cd2a44be7923 and the error code >>> http://gyazo.com/40c47628f1dfb7d735af4c72dde3a651
Thanks in advance,
Jason

A: Looks like you forgot to return value from DisplayShop funcion:
public String DisplayShop()
{
    List<string> shops = new List<string>();
    foreach (Shop tmp in myShop)
    {
        shops.Add(tmp.Display());
    }
    return string.Join(",", shops);
}

Join used here just to show the general idea, you can use whatever you want to construct the whole string.

A: You  are not returning anything from this function:
 public String DisplayShop()

You should return a string from it, or just change return type to void if you don't want to return anything:
  public void DisplayShop()

Update:
imgHolder1.Items.Add(myShop[1].DisplayShop());

In this line you are calling DisplayShop on a Shop instance,but you didn't add any elements to the list that is inside of the Shop class.You create a seperate list.So in this case even if it works myShop[1].DisplayShop() won't display anything because your initial myShop list is empty.If you want to display one Shop just call your Display method.Anyway,probably you don't need that initial list, if you want to add all Shops to the listBox then use a simple foreach loop:
foreach(var shop in myShop)
{
    imgHolder1.Items.Add(shop.Display());
}

A: public String DisplayShop()
{
    foreach (Shop tmp in myShop)
    {
        tmp.Display();
    }

}

your return type is a String but you aren't returning anything.  Not all code paths return a value is telling you exactly that


text:
Q: Use a short version of the Chapter title with fancyhdr Is there a way to implement a short and long version of a chapter title so to show the short version in the fancyhdr header?
Merci A
\documentclass[openany,11pt]{book}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{blindtext}
\usepackage{fancyhdr}
\fancypagestyle{plain}{%
\fancyhf{}
  \renewcommand{\headrulewidth}{0.5pt}
  \renewcommand{\footrulewidth}{0pt}
  \addtolength{\headheight}{0.5pt}
  \fancyhead[LE,RO]{\leftmark}
  \fancyhead[RE,LO]{version 1A}}

\begin{document}

\chapter{this chapter title is way way way and anyway to long}

\blindtext
\end{document}

A: In the traditional classes such as book \chapter[Short]{Long} will use Short in the ToC and the header and Long in the body of the document. Similarly for \section and figure/table captions such as \caption[Short]{Long} will use Short in the LoF/LoT and Long for the figure/table in the body of the document.
In the memoir class, which is an extension to the book, report, article classes sectional commands, such as \chapter, \section, \subsection, can take two optional arguments.
\chapter{title}                         % traditional memoir
\chapter[toc-head title]{title}         % traditional memoir
\chapter[toc-title][head-title]{title}  % memoir

which gives you the option of different texts in the ToC, header, and body.


text:
Q: IBM LDAP 6.4 - DB2 10.5: Failed to create database instance to run idsicrt command I'm working in RHEL 7.7 (AWS - RHEL-7.7_HVM-20190923-x86_64-0-Hourly2-GP2)
For install Security Directory Server V6.4 I folowed the below documentation
And according to this documentation for create a SDS instance, it's necessary to run this command:
cd /opt/ibm/ldap/V6.4/sbin
./idsicrt -I idsldap -a 3538 -c 3539 -e "EncryptionSeed123" -g "EncSalt12345" -p 389 -s 686

But tu run that command, I got the below
./idsicrt -I idsldap -a 3538 -c 3539 -e "EncryptionSeed123" -g "EncSalt12345" -p 389 -s 686
GLPWRP123I The program '/opt/ibm/ldap/V6.4/sbin/64/idsicrt' is used with the following arguments 'idsicrt -I idsldap -a 3538 -c 3539 -e ***** -g ***** -p 389 -s 686'.
You have chosen to perform the following actions:

GLPICR020I A new directory server instance 'idsldap' will be created.
GLPICR057I The directory server instance will be created at: '/home/idsldap'.
GLPICR013I The directory server instance's port will be set to '389'.
GLPICR014I The directory server instance's secure port will be set to '686'.
GLPICR015I The directory instance's administration server port will be set to '3538'.
GLPICR016I The directory instance's administration server secure port will be set to '3539'.
GLPICR019I The description will be set to: 'IBM Security Directory Server Instance V6.4'.
GLPICR021I Database instance 'idsldap' will be configured.

Do you want to....
 (1) Continue with the above actions, or
 (2) Exit without making any changes:1

GLPICR028I Creating directory server instance: 'idsldap'.
GLPICR025I Registering directory server instance: 'idsldap'.
GLPICR026I Registered directory server instance: : 'idsldap'.
GLPICR049I Creating directories for directory server instance: 'idsldap'.
GLPICR050I Created directories for directory server instance: 'idsldap'.
GLPICR043I Creating key stash files for directory server instance: 'idsldap'.
GLPICR044I Created key stash files for directory server instance: 'idsldap'.
GLPICR040I Creating configuration file for directory server instance: 'idsldap'.
GLPICR041I Created configuration file for directory server instance: 'idsldap'.
GLPICR034I Creating schema files for directory server instance: 'idsldap'.
GLPICR035I Created schema files for directory server instance: 'idsldap'.
GLPICR037I Creating log files for directory server instance: 'idsldap'.
GLPICR038I Created log files for directory server instance: 'idsldap'.
GLPICR088I Configuring log files for directory server instance: 'idsldap'.
GLPICR089I Configured log files for directory server instance: 'idsldap'.
GLPICR085I Configuring schema files for directory server instance: 'idsldap'.
GLPICR086I Configured schema files for directory server instance: 'idsldap'.
GLPICR073I Configuring ports and IP addresses for directory server instance: 'idsldap'.
GLPICR074I Configured ports and IP addresses for directory server instance: 'idsldap'.
GLPICR077I Configuring key stash files for directory server instance: 'idsldap'.
GLPICR078I Configured key stash files for directory server instance: 'idsldap'.
GLPICR046I Creating profile scripts for directory server instance: 'idsldap'.
GLPICR047I Created profile scripts for directory server instance: 'idsldap'.
GLPICR069I Adding entry to /etc/inittab (if supported) for the administration server for directory instance: 'idsldap'.
GLPICR070I Added entry to /etc/inittab for the administration server for directory instance: 'idsldap'.
GLPICR118I Creating runtime executable for directory server instance: 'idsldap'.
GLPICR119I Created runtime executable for directory server instance: 'idsldap'.
GLPCTL074I Starting admin server for directory server instance: 'idsldap'.
GLPCTL075I Started admin server for directory server instance: 'idsldap'.
GLPICR029I Created directory server instance: : 'idsldap'.
GLPICR031I Adding database instance 'idsldap' to directory server instance: 'idsldap'.
GLPCTL002I Creating database instance: 'idsldap'.
GLPCTL004E Failed to create database instance: 'idsldap'. The failure might have occurred because the system was not set up correctly before using the tool.
GLPICR033E Failed to add database instance 'idsldap' to directory server instance: 'idsldap'.
GLPIDP002I Deleting directory server instance: 'idsldap'.
GLPCTL077I Stopping admin server for directory server instance: 'idsldap'.
GLPCTL078I Stopped admin server for directory server instance: 'idsldap'.
GLPIDP072I Deleting the runtime executable for directory server instance: 'idsldap'.
GLPIDP073I Deleted the runtime executable for directory server instance: 'idsldap'.
GLPIDP035I Removing entry from /etc/inittab (if supported) for the admin server for directory server instance 'idsldap'.
GLPIDP036I Removed entry from /etc/inittab for the admin server for directory server instance 'idsldap'.
GLPIDP020I Deleting profile scripts for directory server instance: 'idsldap'.
GLPIDP021I Deleted profile scripts for directory server instance: 'idsldap'.
GLPIDP011I Deleting log files for directory server instance: 'idsldap'.
GLPIDP012I Deleted log files for directory server instance: 'idsldap'.
GLPIDP008I Deleting schema files for directory server instance: 'idsldap'.
GLPIDP009I Deleted schema files for directory server instance: 'idsldap'.
GLPIDP014I Deleting configuration file for directory server instance: 'idsldap'.
GLPIDP015I Deleted configuration file for directory server instance: 'idsldap'.
GLPIDP017I Deleting key stash files for directory server instance: 'idsldap'.
GLPIDP018I Deleted key stash files for directory server instance: 'idsldap'.
GLPIDP077I Deleting the ldapdb.properties file for directory server instance: 'idsldap'.
GLPIDP075I Deleted the ldapdb.properties file for directory server instance: 'idsldap'.
GLPIDP023I Deleting directories for directory server instance: 'idsldap'.
GLPIDP024I Deleted directories for directory server instance: 'idsldap'.
GLPIDP039I Unregistering directory server instance: 'idsldap'.
GLPIDP040I Unregistered directory server instance: 'idsldap'.
GLPIDP003I Deleted directory server instance: 'idsldap'.
GLPICR024W The program did not complete successfully. View earlier error messages for information about the exact error.

I can see the below in the logs file
cat db2icrt_local.log.25909
       Program name = db2idbm
Instance home dir = /home/idsldap,   Sysadm group = idsldap
Instance type = 1,  Auth type = server

DB21015E  The Command Line Processor backend process request queue or input
queue was not created within the timeout period.
Update DBM cfg SYSADM_GROUP errcode = 8
DBI1281E  The database manager configuration file could not be
      initialized.

Explanation:

An error occurred when attempting to initialize the database manager
configuration file. A DB2 instance could not be created or upgraded.

User response:

Refer to the log file for troubleshooting. Resolve the problem and try
the command again. If the problem persists, contact your IBM service
representative.

   Related information:
   Gathering diagnostic information for instance creation problems

and
at db2icrt.log.23965

DB2 Setup log file started at:  Wed Jan 11 09:17:23 PM 2023 UTC
============================================================

Operating system information: Linux 3.10.0-1160.76.1.el7.x86_64.#1 SMP Tue Jul 26 14:15:37 UTC 2022 x86_64
WARNING: Notification SMTP server has not been specified. Notifications cannot
be sent to contacts in your contact list until this is specified. For more
information see the DB2 administration documentation.

New instances:
    Instance name:                              idsldap
        Instance user information:
            User name:                          idsldap
        Fenced user information:
            User name:                          idsldap

Setting default global profile registry variables :.......Success
The maximum number of logical nodes was not specified for the instance
"idsldap". Default parameters will be used.

Initializing instance list :.......Success
ERROR:        Program name = db2idbm
Instance home dir = /home/idsldap,   Sysadm group = idsldap
Instance type = 1,  Auth type = server

DB21015E  The Command Line Processor backend process request queue or input
queue was not created within the timeout period.
Update DBM cfg SYSADM_GROUP errcode = 8
DBI1281E  The database manager configuration file could not be
      initialized.

Explanation:

An error occurred when attempting to initialize the database manager
configuration file. A DB2 instance could not be created or upgraded.

User response:

Refer to the log file for troubleshooting. Resolve the problem and try
the command again. If the problem persists, contact your IBM service
representative.

   Related information:
   Gathering diagnostic information for instance creation problems

ERROR: An error occurred while configuring the instance "idsldap".

Configuring DB2 instances :.......Failure
Updating global profile registry :.......Success

Post-installation instructions
-------------------------------

Required steps:
There were some errors detected during DB2 installation. To collect the information files from the system, run the "db2support -install" command with the proper options before reporting the problem to IBM service. For information regarding the usage of the db2support tool, check the DB2 Information Center.

DB2 Text Search has not been configured for the instance "idsldap".To automatically configure DB2 text search services, run the db2iupdt command (orthe db2nrupdt command for non-root installations) specifying the -j "TEXT_SEARCH" option.Manual configuration steps can be found in the DB2 Text Search documentation "http://publib.boulder.ibm.com/infocenter/db2luw/v10r5/topic/com.ibm.db2.luw.admin.ts.doc/doc/t0052968.html".

Optional steps:
To validate your installation files, instance, and database functionality, run the Validation Tool, /opt/ibm/db2/V10.5/bin/db2val. For more information, see "db2val" in the DB2 Information Center.

Open First Steps by running "db2fs" using a valid user ID such as the DB2 instance owner's ID. You will need to have DISPLAY set and a supported webbrowser in the path of this user ID.

Verify that you have access to the DB2 Information Center based on the choices you made during this installation. If you performed a typical or a compact installation, verify that you can access the IBM Web site using the internet. If you performed a custom installation, verify that you can access the DB2 Information Center location specified during the installation.

Ensure that you have the correct license entitlements for DB2 products and features installed on this machine. Each DB2 product or feature comes with a license certificate file (also referred to as a license key) that is distributed on an Activation CD, which also includes instructions for applying the license file. If you purchased a base DB2 product, as well as, separately priced features, you might need to install more than one license certificate. The Activation CD for your product or feature can be downloaded from Passport Advantage if it is not part of the physical media pack you received from IBM. For more information about licensing, search the Information Center (http://publib.boulder.ibm.com/infocenter/db2luw/v10r5/index.jsp) using terms such as "license compliance", "licensing" or "db2licm".

To use your DB2 database product, you must have a valid license. For information about obtaining and applying DB2 license files, see http://pic.dhe.ibm.com/infocenter/db2luw/v10r5/topic/com.ibm.db2.luw.qb.server.doc/doc/c0061199.html.

DB2 Setup log file finished at:  Wed Jan 11 09:49:38 PM 2023 UTC
============================================================

Looks like that something was wrong in the DB2 installation but running the validation I got that was successful
./db2val
DBI1379I  The db2val command is running. This can take several minutes.

DBI1335I  Installation file validation for the DB2 copy installed at
      /opt/ibm/db2/V10.5 was successful.

DBI1343I  The db2val command completed successfully. For details, see
      the log file /tmp/db2val-230111_215409.log.

I'll appreciate any recommendations
Thanks
Create a SDS LDAP server instance

A: Resolved by installing Db2 v10.5.0.11 (the final fixpack for Db2 v10.5)
and also by ensuring that the /etc/hosts entry for the hostname is correct, allowing the hostname to be both pingable and allowing nslookup to resolve the hostname.


text:
Q: Symfony2 Error 500 - Class does not exist on Dev Server - Works fine on production server I've been fighting a losing battle against issues with Symfony recently, and today it has decided not to work on my local development server at all.
Error message:

Class AppBundle\Controller\routeCleaner does not exist in /var/www/html/src/AppBundle/Controller/ (which is being imported from "/var/www/html/app/config/routing.yml").

The file exists in the directory and is chmod 777 as a last resort to no avail.
On the production server I have no error being thrown and it works fine, the exact same configuration on both machines; or at least should be unless something has gone wrong.

A: I sometimes ran into those kind of problems if the production or the development environment weren´t both case sensitive / case insensitive.
Can you double check that?


text:
Q: How can we import csv files actively into mongodb? I am developing an admin panel where I can add biological species data and their characteristic. The problem here is I have different selected users which have to enter data but some of the users don't have internet connectivity so either I have build localhost for the users with no internet connection where they can store data and when they get an internet connection the data should automatically get synced with the web server where we have main MongoDB database. I can do it this we but I don't know how can I do this?.... If this is soo complicated I can export the database from the localhost server and then upload it to the main server individually.
If we go in either of the ways, the issue is we have to overwrite the data which is already present also we have to update the database in the main server after the users update the data on a localhost server. How can I make this consistent?
I need to know two answers to the above scenario
1) Is it possible to build an offline MongoDB based system which will get synced with the online server after getting an internet connection? implicitly or explicitly whichever is possible
2) How can we make the database properly working when the multiple CSV files we upload should not make the database scrambled.
I would like to have as many answers as I can so that I can learn to make my admin panel as close to perfect.

A: The answer here is not technical one but you can do this way. For the systems with no internet connection, prepare the JSON data on their local machine. Add a PUSH button i.e when client local machine is connected to the internet they can press PUSH button which will push all the JSON data prepared on client local system to Sever.
Now on server side prepare an endpoint that should take JSONString as input and then you can identify which data to store in which collection and save the data to your database.
Another way you can convert this JSON to CSV format and then have a service that runs synchronously in the background which will upload the CSV data in the database.
Last but most important if you are lazier in doing all the stuff above then you can use Couchbase Lite.
This is not the best answer but probably this will work for you.
HTH Thanks!


text:
Q: How do 2 dimentional lists work in Python I am doing Project Euler Problem 15. I used the right algorithm, but it didn't seem to work. Here's my code:
f = [[0] * 21] * 21

# init the list
for i in range(21):
    f[0][i] = 1
    f[i][0] = 1

for i in range(21):
    for j in range(21):
        f[i][j] = f[i-1][j] + f[i][j-1]

print f[20][20]

when I finished initializing the list, I printed it. I expected it like [[1, 1, 1...], [1, 0, 0...]...], but it turned [[1, 1, 1...], [1, 1, 1...]...] and I can't figure why.
I used to use C-like language and I thought the list in Python is kind of like the array in C, so I used them in the same way.

A: When multiplying a list, you are not creating separate lists but rather create multiple references to the same list.
Instead, do this:
f = [[0 for _ in range(21)] for _ in range(21)]

You can see the difference when using the id() function:
>>> f = [[0]*21]*21
>>> for nested in f[:3]:
...     print id(nested)
...
4523317152
4523317152
4523317152
>>> f = [[0 for _ in range(21)] for _ in range(21)]
>>> for nested in f[:3]:
...     print id(nested)
...
4523317512
4523317440
4523317656

Separate objects have separate memory id values, while your lists have the same result for each id() call, showing they are all the same list.

A: In the first line, use this:
f = [[0] * 21 for _ in xrange(21)]

What you wrote will create a list of length 21 (that's what the inner [0]*21 does), and then create an outer list which contains the same inner list 21 times. This means that whenever you modify an element in the inner list, it is modified in all the copies, i.e. in every row of your matrix.
For what it's worth, you might want to check out the numpy module (install NumPy first of course), which gives you a "proper" n-dimensional array structure.


text:
Q: Voice / data connections between 2 portacabins ~50m apart Our business is taking over some new premises (currently housing multiple companies) and for at least the first year will be operating out of a pair of portacabins, around 50 metres apart.
Users in both cabins will need to be on our internal LAN, and our phone system. What's the most cost-effective way to link these buildings?
Stringing fibre between poles has been discussed but seems expensive; a trench/duct for underground fibre even more so (~£100/metre) -- so it seems like WiFi is my best option, but does this have reliability issues over this sort of range -- given there will be commercial vehicles and heavy plant crossing the direct LoS between the buildings, do I need to get the WiFi kit high off the ground, or can I just use high powered and/or directional wifi equipment?
Similarly, should I be looking at cordless handsets for one of the buildings, or should I be looking at just getting a data connection and using IPT for internal telephony?

A: It would seem to be hard to cost-justify a fiber link between the buildings for only a year's time. I'd probably go with WiFi, in such a case. I'd put the antennas as high as I could, and use directional antennas.
My main problems with WiFi in these kinds of situations have been interference from other systems (yes-- even with directional antennas), poor latency with crappy access points, and failures due to lightning. WiFi has worked very well, all things considered.
When I can get fiber into the budget, I push for it-- especially when the Customer is going to be in the facilities for a long time. In your case, that's not true...
If you can get a reliable WiFi connection, using the data network for the telephones is probably more cost-effective than cordless handsets. I'd compare the costs. For reliability, I might consider putting one cordless handset in the remote office even if I did use VoIP, just for fail-safe purposes. (If everyone on the site is carrying their own privately-owned wireless telephones that might be less of an issue...)
There are a variety of radios out there. I'll put in a plug for the Ubiquiti Bullet radios. I don't work for them or anything. I've used their radios in a couple of sites and rather like them (particularly the unfetted access to the Linux OS on the device). These particular radios are weatherproof and aimed at the outdoor point-to-point market. You attach an antenna to them, power-over-Ethernet on the other (with a lightning arrestor!) and you're good to go.

A: Jimbo, I've got a mate in Sheffield who specialises in laser-based point-to-point systems. They look like CCTV cameras, you just put one on each building, point them at each other and plug an ethernet cable into each one. They're not that cheap but given you only need them for a year I would imagine some kind of lease/rental package could be done. Let me know if you want me to put you in touch.

A: 100M is the limit for 100baseT, so you're well within spec to just run Cat5 before the two places.  (I'd run cat5e or cat6 to reduce the noise, though).  I'm not sure what the limit for gigE is, but I've run it a little over 100M without much problems -- we just put a switch at each end as soon as it entered the buildings.  If you can trench between the two points, this might be the easiest.
Call whatever utility companies to get the existing lines marked, rent a ditch digger (looks like a big chainsaw blade on a cart), glue some PVC conduit together (while running some pull line), and once it's all together, pull the copper and terminate it.  If you don't have other obstructions in the way, it'll take a team of two a day to complete, and a few hundred dollars of supplies.
...
If that fails:
I can't remember the name of the guy, or the name of the site where he put up all of his information, but there was someone in Hawaii who had a lot of information about squeezing longer range out of wireless ethernet.  I think he was using 802.11b, but it might've been 802.11a, this was before the term 'wifi' became popular, so I don't think it was 802.11g ... this would've been about the time when the pringles can trick was noticed (2001?2002?).
Hopefully, someone else can remember and provide a link.  I want to say he was connecting public schools in Hawaii, and they had a school bus that would act as an access point for laptops and had a long-haul link back to the school.
... it's possible, as it was older, that he was using other wireless technology (wavelan?), which might be harder to get ahold of this year, or difficult to put to use.
update: it might've been ALOHAnet, but from what I can find while wrestling with free airport wifi trying to frame my screen screwing up everything, it was out of service by the time I was remembering it (and I could've sworn it was ethernet-based).  It's possible that I'm remembering whatever was the followup to ALOHAnet.


text:
Q: Python to Javascript JSON objects (Flask) I am trying to create a simple Flask app where an array of integers is generated on the server and sent to the client. I want to view the array of integers in the console. Here is some sample (working) code in app.py:
from flask import Flask, render_template, request, url_for

import random, json

app = Flask(__name__)

@app.route('/',  methods=['GET'])
def form():
    json_helper = {}
    json_helper['randoms'] = [random.random() for _ in range(40)]
    json_object = json.dumps(json_helper)
    return render_template('sim0625.html', s_data=json_object)

if __name__ == '__main__':
  app.run(debug=True)

And here is a snippet of the Javascript frontend:
<script>

  var data_xyz = {{ s_data|tojson }};

  var JSONObject = JSON.parse({{data_xyz}});
  console.log(JSONObject.randoms);

 </script>

Unfortunately, none of the javascript works on my webpage, and the error message shown is "Uncaught SyntaxError: Unexpected token u".
Can someone please explain how to fix this? Thanks. My guess is the JSON objects are becoming strings.
Note: The code from the front-end was adapted from this SO question: Extracting data from json object in jQuery or JS

A: You're sending your JSON to the template through the variable s_data.
In the template, you're rendering that variable into a JavaScript variable called data_xyz. In the next line, you attempt to reference a Jinja variable instead of a JavaScript variable:
var JSONObject = JSON.parse({{data_xyz}});

Change that to:
var JSONObject = JSON.parse(data_xyz);


text:
Q: Merge two tables with different timestamps to one query output I have got two tables like this:
Table 1:
    id  timestamp              Volume    value
    1   2015-02-17 14:11:10     1220.62     0
    2   2015-02-17 14:13:48     1220.62     0
    3   2015-02-17 14:16:39     1220.62     0
    4   2015-02-17 14:17:22     1220.62     0
    5   2015-02-17 14:17:47     1220.62     0

Table 2:
    id  TimeDate    aussentemp
    1   2015-02-17 14:11:15     0
    2   2015-02-17 14:13:03     22.9
    3   2015-02-17 14:16:04     23
    4   2015-02-17 14:17:02     22.9
    5   2015-02-17 14:17:03     23

You can see the timestamps are nearly the same. Just want to merge this, that the SQL Query use the timestamp and data from table 1 and add a new columns with the "aussentemp" that is nearly there with the same timestamp.
Can someone help me?

A: Here is one method using a correlated subquery:
select t1.*,
       (select t2.aussentemp
        from table2 t2
        where t2.timedate <= t1.timedate
        order by t2.timedate desc
        limit 1
       ) as aussentemp
from table1 t1;

Note:  this takes the most recent value on or before the timestamp in table1.
If you also need the timestamp, you can repeat the subquery.