text:
Q: Magmi seems to update correctly but products grid doesn't reflect changes Magmi says for updating products two columns are necessary:

*

*sku

*store
As it's not obvious what store should contain I use store code which is english. I went for updating two products as following:
"sku","store","name"
"100000000001","english","Test1"
"100000000008","english","Test2"

Selected the file containing above rows in var/import then chose Update existing items only.... It then took a few seconds to finish.
Runtime infos
Initialized attribute_set_infos!
Skus imported OK:2/2

Now as I see in both products edit pages, name fields are updated. But products grid in admin (admin/catalog_product/index/) doesn't reflect changes. It still shows previous values. This is where I ended:
mysql> select * from catalog_product_entity_varchar where entity_id = 5000 and attribute_id = 71;
+----------+----------------+--------------+----------+-----------+-------+
| value_id | entity_type_id | attribute_id | store_id | entity_id | value |
+----------+----------------+--------------+----------+-----------+-------+
|   601412 |              4 |           71 |        0 |      5000 | MS506 |
|   602135 |              4 |           71 |        1 |      5000 | Test1 |
+----------+----------------+--------------+----------+-----------+-------+
2 rows in set (0.33 sec)

I tried to add store_id column in CSV header line with corresponding 0 values but it didn't change the one with store_id=0 in above result set.
What am I missing in updating products with Magmi?

A: Did you try to launch reindex via System > Index Management > Select All > Reindex Data > Submit?
It seems to be index issue, as the values in the grid you're viewing are retrieved from the index tables in the DB, not from the ..._varchar, etc, tables.

A: There are two store views and I had to update both: admin store which default values are stored in and english which is my current store code. Fortunately, Magmi accepts store codes separated by comma the same as below:
"sku","store","name"
"100000000001","english,admin","Test1"
"100000000008","english,admin","Test2"


text:
Q: Apache Camel Exception Generated when routing to a route I am pretty new to spring-boot and  apache camel.  I am trying to create an application which will ivoke a rest end point which I am hosting locally using Camel for routing.
When I run the app, I get the error : CamelExecutionException: Exception occurred during execution on the exchange  and HttpOperationFailedException: HTTP operation failed invoking http://localhost:8080/myservice with statusCode: 415 and errorDescription":"Unsupported Media Type"
POM:
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-spring-boot-starter</artifactId>
      <version>2.22.0</version>
   </dependency>
   <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-http</artifactId>
      <version>3.2.0</version>
   </dependency>

MsgRouteBuilder:
public void configure() throws Exception {
    from("direct:firstRoute")
    .setHeader(Exchange.HTTP_METHOD, simple("GET"))
    .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
    .to("http://localhost:8080/myservice");
}

MainApp.java:
package me.ad.myCamel;

import org.apache.camel.CamelContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import me.ad.myCamel.router.MessageRouteBuilder;

@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableCaching
public class MeAdApp implements CommandLineRunner {

  private static final Logger LOG = LoggerFactory.getLogger(MeAdApp.class);

  public static void main(String[] args) {
    try {
      SpringApplication.run(MeAdApp.class, args);
    } catch (Exception ex) {
      LOG.error(ex.getMessage(), ex);
    }
  }

  @Override
  public void run(String... args) throws Exception {
    LOG.info("Starting MeAdApp...");
  }
}

MyController.java :
@GetMapping(value = "/routing")
public boolean sendMyData() {
    sendMyInfo.startRouting();
    return true;
}

SendMyInfo.java :
MsgRouteBuilder routeBuilder = new MsgRouteBuilder();
CamelContext ctx = new DefaultCamelContext();

public void startRouting(){

    try {
        ctx.addRoutes(routeBuilder);
        ctx.start();
        ProducerTemplate producerTemplate = ctx.createProducerTemplate();
        producerTemplate.sendBody("direct:firstRoute", "Hello WFS");
        ctx.stop();
    }
    catch (Exception e) {
        e.printStackTrace();
    }

}

So, whenever I call my rest end point: /routing, I get the error :  CamelExecutionException: Exception occurred during execution on the exchange  and HttpOperationFailedException: HTTP operation failed invoking http://localhost:8080/myservice with statusCode: 415 and errorDescription":"Unsupported Media Type, content type: null not supported"
Can some one help me out here ?

A: The issue was wrong camel version . Once I started using 3.2.0 as an uniform version it all worked out in the end .

redpajama_set_name: RedPajamaStackExchange


text:
Q: Returning a variable after actionPerformed I am trying to make a simple class where the user can change the value of the string test by clicking the button and then return the changed string.
public class TestTest
{
    private JFrame mainFrame;
    private JPanel panelX;
    private String test;

    public static void main(String[] args)
    {
        TestTest run = new TestTest();
        run.GUIinit();
        run.addButton();
        System.out.println(run.returnData());  // This returns null
    }

    // Method to return string value
    public String returnData()
    {
        return test;
    }

    // Method to set string value
    public void setData(String data)
    {
        test = data;
    }

    private void GUIinit()
    {
        mainFrame = new JFrame("Text");
        mainFrame.setSize(200, 200);
        mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent)
            {
                System.exit(0);
            }
        });
        panelX = new JPanel();
        mainFrame.add(panelX);
        mainFrame.setVisible(true);
    }

    // Problematic part
    private void addButton()
    {
        JButton testButton = new JButton("Text");
        panelX.add(testButton);
        testButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                setData("STRING BLABLA");
            }
        });
    }
}

I know that I am doing something horribly wrong but I cannot grasp what,
my only guess is that the code skips to the println part without waiting for the actionEvent.
My question is: Am I assigning a value to the string with the actionEvent when I click the button and if not, how could I do that?
Could I implement some sort of delay or another class to get the result I want?

A: To answer your question - yes, you are assigning the value to the variable "test", but the main thread doesn't wait for you to click the button. That's why it prints null. You could make the main thread wait until the value is set, but that is a wrong way to use Swing. There are three kinds of threads in a Swing program:

*

*Initial thread, the thread that executes initial application code. In your case this is the thread that runs the main() method.

*Event dispatch thread (EDT), the thread where all event-handling code is executed. All program logic (unless it is time consuming) should be executed on this thread. In your case, whatever you need to do with the "test" variable, you should probably do it on this thread. Since action events are processed on this thread, you should do it in the actionPerformed() method of the listener.

*Worker threads. If the work is time consuming, you should create a new thread and do the work on it. Even so, you should start it from EDT (event dispatch thread), not the main (initial) thread.

You can read more here: Lesson: Concurrency in Swing
If, however, for some unlikely reason you really need to access the "test" variable from the main (initial) thread, you can implement a waiting mechanism with Lock and Condition like so:
public class TestTest
{
    private JFrame mainFrame;
    private JPanel panelX;
    private String test;

    private static final Lock lock = new ReentrantLock();
    private static final Condition valueAssigned  = lock.newCondition();

    public static void main(String[] args) throws InterruptedException
    {
        TestTest run = new TestTest();
        run.GUIinit();
        run.addButton();

        // Acquire the lock.
        lock.lock();
        try {
            while (run.returnData() == null) {
                // Release the lock and wait for signal.
                valueAssigned.await();
            }
            // Once String value is set, print it.
            System.out.println(run.returnData());
        } finally {
            lock.unlock();
        }
    }

    // Method to return string value
    public String returnData()
    {
        return test;
    }

    // Method to set string value
    public void setData(String data)
    {
        test = data;
    }

    private void GUIinit()
    {
        mainFrame = new JFrame("Text");
        mainFrame.setSize(200, 200);
        mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent)
            {
                System.exit(0);
            }
        });
        panelX = new JPanel();
        mainFrame.add(panelX);
        mainFrame.setVisible(true);
    }

    // Problematic part
    private void addButton()
    {
        JButton testButton = new JButton("Text");
        panelX.add(testButton);
        testButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                setData("STRING BLABLA");

                // Acquire the lock.
                lock.lock();
                try {
                    // Send a signal to all waiting threads.
                    valueAssigned.signalAll();
                } finally {
                    lock.unlock();
                }
            }
        });
    }
}

Read more about Locks and Conditions here:
Lock Objects


text:
Q: How to compare two dataframes with different indices, and print out the duplicate rows? I am attempting to compare two dataframes by their respective UniqueID column. The code for the following dataframes can be seen below.
# Define first dataframe
list1 = {'UniqueID': [13579, 24680, 54678, 1169780, 1195847, 23572],
        'Name': ['Joe', 'Pete', 'Jessica', 'Jackson', 'Griffin', 'Katie'],
        'Level': ['Beginner', 'Beginner', 'Intermediate', 'Advanced', 'Intermediate', 'Advanced']}
df1 = pd.DataFrame(list1, columns=['UniqueID','Name','Level'])

# Define second dataframe
list2 = {'UniqueID': (88922,13579, 24680, 54678, 1169780, 1195847, 23572, 54895, 478952, 45921),
        'Name': ('Zain','Joe', 'Pete', 'Jessica','Griffin','Jackson','Katie', 'Gaby', 'Haley', 'Caden'),
        'Level': ('Beginner', 'Intermediate', 'Intermediate', 'Advanced', 'Intermediate','Advanced','Advanced',
                  'Beginner', 'Intermediate', 'Novice')}
df2 = pd.DataFrame(list2, columns=['UniqueID','Name','Level'])

It can be seen above that the dataframes have a differing length in regards to their index. This is what leads to my next problem. My process to find the duplicates goes as follows.
# Define new column which displays Match iff the UniqueID of the first dataframe is equal to that of the second
df1['UniqueMatch'] = np.where(df1.UniqueID == df2.UniqueID, 'Match','Ignore') #Create

# Simplify the list to only display rows that are duplicates
df_match = df1[df1['UniqueMatch'] =='Match']

I run into an error whenever I try to find where the dataframes UniqueID's are equal to each other. The error i receive is 'ValueError: Can only compare identically-labeled Series objects'. Which, from my understanding, means that the process I am using can only be achieve if the indices of the two dataframes are equal to each other. I figure their has to be a way around this, if not then how could you compare dataframes of different sizes.

A: df1 (5 rows) & df2 (9 rows) are different - that the reason:
df1.equals(df2) -> false

For printing duplicates use that piece of code:
df_merge = pd.merge(df1, df2, on=['UniqueID','Name','Level'], how='inner')

You can define in on - the proper data, which You want duplicates.
eg. ['Name] & ['Level'] (if U want duplicates only in Name - that in on should be only that column name.
returns more duplicates:

A: Update according your comment:

After I find the duplicated, I would then like to iterate through each cell of level, and update df1 from the updated level listed in df2. For example, Joe goes from beginner to intermediate from df1 to df2. I would like to auto update those instances.

Concatenate your 2 dataframes and keep the last values (df2) from duplicates:
df3 = pd.concat([df1, df2], ignore_index=True) \
        .drop_duplicates(['UniqueID', 'Name'], keep='last')

>>> df3
    UniqueID     Name         Level
3    1169780  Jackson      Advanced
4    1195847  Griffin  Intermediate
6      88922     Zain      Beginner
7      13579      Joe  Intermediate  # Joe is now Intermediate
8      24680     Pete  Intermediate  # Pete is now Intermediate
9      54678  Jessica      Advanced  # Jessica is now Advanced
10   1169780  Griffin  Intermediate
11   1195847  Jackson      Advanced
12     23572    Katie      Advanced
13     54895     Gaby      Beginner
14    478952    Haley  Intermediate
15     45921    Caden        Novice

Old answer
Find duplicates with merge and query:
dup = pd.merge(df1, df2, on='UniqueID') \
        .query("(Name_x == Name_y) & (Level_x == Level_y)")

>>> dup
   UniqueID Name_x   Level_x Name_y   Level_y
5     23572  Katie  Advanced  Katie  Advanced


text:
Q: Слетает Docker образ причины Подскажите пожалуйста в чем причина почему после команды из командной строки docker-compose up -d docker-machine заново начинает скачивать все для образа и разворачивать вместо того чтобы брать его из памяти. Может у него время стоит или что то там ломается? Я закачал образ, развернул там дамп базы и хочу чтобы он после этой команды стартовал, а не скачивал заново. Периодически это происходит примерно раз в 1,5 недели. Где посмотреть о сбоях? Или это его нормальное поведение?
Windows 8.1 Docker TollBox

нужно хотя бы начать с того чтоб показать сам docker-compose.yml – zalex

version: '3.7'

services:
  db:
    #build: ./postgres
    image: postgres:9.5
    restart: always
    #command: ["postgres", "-c", "log_statement=all", "-c", "log_destination=stderr"]
    command: ["postgres", "-c", "logging_collector=on", "-c", "log_filename=postgresql.log", "-c", "log_statement=all"]
    ports:
      - 5432:5432
    environment:
      - POSTGRES_PASSWORD=example
      - PGDATA=/var/lib/postgresql/data/pg-data
    volumes:
      #- ./data/postgres:/var/lib/postgresql/data
      - pgdata:/var/lib/postgresql/data
      - pgconf:/etc/postgresql
      - ./logs:/var/lib/postgresql/data/pg_log
      - ./data/backup:/opt/demo
  pinba:
    image: pdffiller/pinba
    restart: always
    ports:
      - 30002:30002/udp
      - 3306:3306
    environment:
      - MYSQL_ROOT_PASSWORD=example

  redis:
    image: redis
    restart: always
    ports:
      - 6379:6379

  pinboard:
    image: pdffiller/pinboard
    restart: always
    ports:
      - 8081:80
    volumes:
      - ./pinboard:/opt/pinboard/config
    links:
      - pinba

  rabbit:
    image: rabbitmq:3.8-management
    hostname: "rabbitmq"
    environment:
      - RABBITMQ_USE_LONGNAME=true
      - RABBITMQ_LOGS=/var/log/rabbitmq/rabbit.log
    ports:
      - 15672:15672
      - 5672:5672
    volumes:
      - ./data/rabbit:/data
      - ./logs:/var/log/rabbitmq

  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080
    links:
      - pinba

  nginx:
    # используем последний стабильный образ nginx
    image: nginx:latest
    # маршрутизируем порты
    ports:
      - 80:80
      - 443:443
    # монтируем директории, слева директории на основной машине, справа - куда они монтируются в контейнере
    volumes:
      - ./hosts:/etc/nginx/conf.d
      - ..:/var/www
      - ./logs:/var/log/nginx
    # nginx должен общаться с php контейнером
    links:
      - php

  php:
    build: ./php
    volumes:
      - ..:/var/www
      #- ./php/ini:/usr/local/etc/php/conf.d
    links:
      - db
      - pinba
      - redis
      - rabbit
    environment:
      - PHP_IDE_CONFIG=serverName=Docker
      #XDEBUG_CONFIG: remote_host=host.docker.internal remote_port=9000 remote_enable=1 xdebug.profiler_enable=1 xdebug.profiler_output_dir="/var/www"
volumes:
  pgdata:
    driver: local
  pgconf:
    driver: local
  pglog:
    driver: local
  mysqldata:
    driver: local

networks:
  default:
    driver: bridge

То что DOCKER tools будет брать самое последнее при сборке меня устраивает, не устраивает то что всё слетает
похоже слетела машина и каждый раз когда слетает появляется еще одна машина, как этот процесс остановить?


text:
Q: this statement in my javafx program is causing a nullpointerexception and I don't know why import javafx.application.*;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.text.*;
import javafx.stage.*;

public class Drawing extends Application{
private BorderPane mainPane;
private HBox statusBox;
private Text statusText;

public void start(Stage primaryStage) {

    statusText = new Text("OFF");
    statusBox = new HBox(statusText);
    statusBox.setAlignment(Pos.CENTER);
    mainPane.setTop(statusBox);          //nullPointerException here

    Scene scene = new Scene(mainPane, 1000, 1000);
    primaryStage.setTitle("Draw Something");
    primaryStage.setScene(scene);
    primaryStage.setResizable(false);
    primaryStage.show();
}

public static void main(String args[]) {
    launch(args);
}
}

I want to create a BorderPane and set the top portion for some text. I created an HBox to put inside. I don't know why this error occurs.

A: Your mainPane.setTop(statusBox) has not been instantiated yet. Instantiate mainPane first by mainPane = new BorderPane() before using it.


text:
Q: Error with MySQL Subquery I have a MySQL query to produce a view which displays two columns, the two columns are sub query's but for some reason I am getting error.
SELECT
(SUM(cards_required) FROM `orders` WHERE statuses = 1) As Count,
(SUM(cards_required) FROM `orders` WHERE statuses = 2) As Count
FROM `orders` WHERE user_id = 1

error message

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near 'FROM orders WHERE statuses = 1) As Count, (SUM(cards_required)
  FROM orders ' at line 3

A: The syntax you're using isn't quite right. You can use IF to conditionally sum:
SELECT
SUM(IF(statuses = 1,cards_required,0)) As status_1,
SUM(IF(statuses = 2,cards_required,0)) As status_2
FROM `orders` WHERE user_id = 1


text:
Q: Update / Deleting Custom Site Templates I have created a custom site template in sharepoint online using the modern experience. However, there have been changes made that would impact future sites created with that template. Is there a way i can update the site template to accommodate the changes i have made?
Otherwise, if i delete the site template, will it delete the sites i created using said template? It would work just as well for me if i could delete the template, whilst retaining the sites utilizing it, and create a new template based on the changes I've made.
Thanks

A: There is no way to apply a site template to an existing site.
In addition, site Owner can only deactivate and delete the Site Template that already not used.
Site Collection Administrator is responsible for the entire site collection and can deactivate and delete a Site Template that already used or not.
So you should be a Site Collection Administrator to be able to delete Site Template that already used.


text:
Q: Is there a way to install GeoIP from source code on Mac OS X? I want to install the MaxMind GeoIP C library, so that I can use GeoIP as part of Django. I'm working on Mac OS X.
I've downloaded GeoIP-1.4.8.tar.gz from here and run:
./configure
make
make check
make install

Without any problems. I've also downloaded GeoIP.dat.gz and GeoLiteCity.dat.gz, unzipped them and put them in a local directory.
Then I've set the following paths in my settings.py:
GEOIP_PATH = 'path_to_dat_files'
GEOIP_LIBRARY_PATH = 'path_to_c_files'

Now I'm trying to run python manage.py migrate (which has a reference to GeoIP in a project I'm using), but I'm still getting this error:
from django.contrib.gis.utils import GeoIP
ImportError: cannot import name GeoIP

Any ideas?

A: I realize at this point this question is about 4+ years old, but I wanted to add additional details on how users of more current versions of Mac OS X—like Mac OS X 10.7 (Lion), Mac OS X 10.8 (Mountain Lion) and Mac OS X 10.9 (Mavericks)—can install GeoIP on their machines. This has been tested by me up until Mac OS X 10.9.5, but I believe the exact same instructions should work well for Mac OS X 10.10 (Yosemite).
As far as Python/Django integration goes, I am fairly sure that if the GeoIP binary—and related databases—are properly installed systemwide, you don't have to futz with GEOIP_PATH or related settings. But would be open to hearing from others in the comments if my assumption is wrong.
Prerequisites.
First, one needs to have Xcode installed. And since Xcode—since at least version 4.3 I believe—no longer includes the GNU versions of autoconf, automake and libtool those need to be installed as well. I provide details on how to install autoconf, automake and libtool in this answer. The rest of this answer assumes your system already has that setup.
Installing GeoIP from source.
With the prerequisites covered, you can install MaxMind's GeoIP as follows.
Set the working directory to your home directory:
cd

Get the source code and decompress it:
curl -O http://www.maxmind.com/download/geoip/api/c/GeoIP-latest.tar.gz
tar -xvzf GeoIP-latest.tar.gz

Go into the uncompressed source code directory:
cd ./GeoIP*

Run libtoolize on the source code:
libtoolize -f

When that is done, run the configure script on the source code:
./configure

Now run make to compile it:
make

Then run make check to check all is good:
make check

Now install it:
sudo make install

Check it's installed by running the geoiplookup command whose output should be something like this:
Usage: geoiplookup [-h] [-?] [-d custom_dir] [-f custom_file] [-v] [-i] [-l] <ipaddress|hostname>

Now you have the GeoIP source code compiled, but you don't have any GeoIP databases installed for it to to use/reference. So let's install them.
Installing GeoIP databases.
So we're going to get the three (3) major GeoIP databases that are available out there with curl like this. Set the working directory to your home directory:
cd

And now use curl to get the GeoIP.dat.gz, GeoLiteCity.dat.gz and GeoIPASNum.dat.gz databases:
curl -O http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
curl -O http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
curl -O http://geolite.maxmind.com/download/geoip/database/asnum/GeoIPASNum.dat.gz

With that done, let's move them into the proper directory for the GeoIP program to reference them which is /usr/local/share/GeoIP/. If that directory doesn't exist on your system, you can make it like this:
sudo mkdir -p /usr/local/share/GeoIP/

Now with that done, move the downloaded GeoIP.dat.gz, GeoLiteCity.dat.gz and GeoIPASNum.dat.gz databases into that directory:
sudo mv ~/GeoIP.dat.gz /usr/local/share/GeoIP/
sudo mv ~/GeoLiteCity.dat.gz /usr/local/share/GeoIP/
sudo mv ~/GeoIPASNum.dat.gz /usr/local/share/GeoIP/

And decompress them in place:
sudo gzip -d -f /usr/local/share/GeoIP/GeoIP.dat.gz
sudo gzip -d -f /usr/local/share/GeoIP/GeoLiteCity.dat.gz
sudo gzip -d -f /usr/local/share/GeoIP/GeoIPASNum.dat.gz

We also need to rename GeoLiteCity.dat to GeoIPCity.dat like this:
sudo mv /usr/local/share/GeoIP/GeoLiteCity.dat /usr/local/share/GeoIP/GeoIPCity.dat

Final GeoIP binary testing.
With the GeoIP binary compiled from source and installed as well as having the databases in place, geoiplookup should work as expected. For example, let's do a GeoIP lookup on Google:
geoiplookup google.com

The output of that command if all went well should be:
GeoIP Country Edition: US, United States
GeoIP City Edition, Rev 1: US, CA, California, Mountain View, 94043, 37.419201, -122.057404, 807, 650
GeoIP ASNum Edition: AS15169 Google Inc.

A: I just follow the same procedure and found nothing wrong
./configure
make
make check
make install

and put the geo unzip-ed database in django project's root dir, add the following to settings.py:
GEOIP_PATH = "./"

here is what I run and got:
% python manage.py shell
>>> from django.contrib.gis.utils import GeoIP
>>> g = GeoIP()
>>> g.country('google.com')
{'country_name': 'United States', 'country_code': 'US'}
>>>>

A: After compiling it should print the library path:
----------------------------------------------------------------------
Libraries have been installed in:    /usr/local/lib

Set the path to the dylib file:
GEOIP_LIBRARY_PATH = '/usr/local/lib/libGeoIP.dylib'
GEOIP_PATH = GEOIP_DATA_FILE


text:
Q: Get all string in one variable after space in javascript what i am doing
for example i have a name

 var nameofuser = 'John Constantine vayo';
    var values = nameofuser.split(" ");
    var f_name = values[0];
    var l_name = nameofuser.substr(nameofuser.indexOf(' ') + 1);
    console.log(f_name);
    console.log(l_name);

it is working fine when user entering his last name and other title or so on, it is all going in l_name but when a user enterned only first name like only 'John' then l_name is also populated with 'john' :(,
i want IF a user type last name and so on then only l_name should be populated.
if user type only first name then only f_name with first name should be populated

A: var nameofuser = 'John Constantine vayo';
var values = nameofuser.split(" ");
var f_name = values[0];
var l_name = values[1] ? nameofuser.substr(nameofuser.indexOf(' ') + 1) : '';
console.log(f_name);
console.log(l_name);

A: Regular expressions are the usual tool for this kind of decomposition:
var nameofuser = str.match(/^\s*(\S+)\s*(.*?)\s*$/).slice(1);

'John Constantine vayo' gives ["John", "Constantine vayo"]
and 'John' gives ["John"].
But be careful of this kind of guesses. In a multicultural world it's safer to just take what the user provides.

A: When searching for a space over a string that doesn't have a space -1 would be returned. So -1 + 1 will be evaluated to 0 and the substring is returning the entire string.
var nameofuser = 'John Constantine vayo';
var values = nameofuser.split(" ");
var f_name = values.shift();
var l_name = values.length ? values.join(" ") : undefined;
console.log(f_name);
console.log(l_name);

A: It Is because You have to make sure there is more than one word for that line:

var l_name = nameofuser.substr(nameofuser.indexOf(' ') + 1);

Your code should look something like this:
var nameofuser = 'John Constantine vayo';
var values = nameofuser.split(" ");
var f_name = values[0];
var l_name = (values.length > 1) ? nameofuser.substr(nameofuser.indexOf(' ') + 1) : '';
console.log(f_name);
console.log(l_name);

A: When you do .indexOf(), if value is not matches, you will get index as -1 so indexOf() + 1 would interpret as -1 + 1 = 0. So you end up doing namesofuser.substring(0)
Try something like this:
string.split + array.shift and array.join

function getNames(str) {
  var values = str.split(" ");
  var f_name = values.shift();
  var l_name = values.join(' ');
  console.log(f_name);
  console.log(l_name);
}

getNames('John Constantine vayo')
getNames("Foo")

string.substring

function getNames(str) {
  var index = str.indexOf(' ');
  index = index > -1 ? index : str.length;
  var f_name = str.substring(0, index);
  var l_name = str.substring(index + 1);
  console.log(f_name);
  console.log(l_name);
}

getNames('John Constantine vayo')
getNames("Foo")

A: Just check if there is more than one word in the values array?
Hope this helps :)
var values = nameofuser.split(" ");
var f_name = values[0];
if (values.lenght >= 2) {
  var l_name = nameofuser.substr(nameofuser.indexOf(' ') + 1);
} else { //let lastname empty or do something else}

  console.log(f_name);
  console.log(l_name);
}

A:

var nameofuser = 'john';
var f_name = '';
var l_name ='';
var values = nameofuser.split(" ");
var f_name = values[0];
if(values.length > 1){
     var l_name = nameofuser.substr(nameofuser.indexOf(' ') +1);
  }
console.log(f_name);
console.log(l_name);

A: this works as well and fixes the problems you'll have if nameofuser begins with a space
var nameofuser = 'John Constantine vayo';
var values = nameofuser.trim().split(" ");
var f_name = values[0];
var l_name = values.slice(1).join(" ")
console.log(f_name);
console.log(l_name);


text:
Q: Cannot find module 'metro-core' when starting expo project Whenever i start expo with expo start command, this error appears
Error: Cannot find module 'metro-core'
Require stack:
- /usr/local/lib/node_modules/expo/node_modules/@expo/cli/build/src/start/server/metro/instantiateMetro.js
- /usr/local/lib/node_modules/expo/node_modules/@expo/cli/build/src/start/server/metro/MetroBundlerDevServer.js
- /usr/local/lib/node_modules/expo/node_modules/@expo/cli/build/src/start/server/DevServerManager.js
- /usr/local/lib/node_modules/expo/node_modules/@expo/cli/build/src/start/startAsync.js
- /usr/local/lib/node_modules/expo/node_modules/@expo/cli/build/src/start/index.js
- /usr/local/lib/node_modules/expo/node_modules/@expo/cli/build/bin/cli

I have tried to reinstall metro-core, but with no effect.
So, does anyone know the solution ?

A: I had uninstalled React Native and installed it again. Then, it worked!
Also, there were some network issues when I scan the QR code using expo go app. The solution was to change the connection from LAN to tunnel using expo start --tunnel command.

A: you are running expo start, try run
npx expo start

This should work.
Let me know if this works.


text:
Q: How to display an HTML email in a web email client? Hi I am building a small web based email client. I am facing problems in displaying HTML mails. What are the best practices involved in displaying an HTML mail? Some things I found

*

*Css Reset

*Strip body tag in the mail

A: First of all, it's important to not allow all the CSS and HTML tags. I would look for the file and allow a defined set of HTML tags and CSS attributes.
For example, if you reset the CSS, you can still send stuff like <iframe>, <form> and all other possible malicious tags.
So I would start of thinking what kind of HTML tags would you like to support, and strip all other ones out of it. And then the same for the CSS.
This is by no means easy. I mean you also would have to take in account things like people trying to break your interpreter...
You could look into this Sitepoint Blogpost, it describes how people should code HTML-emails. So it might be a good idea to start there and see what's usually supported.

A: The one sentence answer would be "1. Use table-based layouts, 2. only inline CSS, and 3. test in every email client possible."
The client testing is probably the most important because every email client (and client + browser combination) may have its own quirks and many are just learned along the way; such as using HTML attributes width & height because Outlook won't always follow the inline styles for width & height, or that Gmail tends to add margins around images unless you explicitly set margin:0 for the HTML elements, etc. etc.
When fixing the look of an HTML email in one client ends up breaking it in another client, don't keep adding more and more styling: try to simplify the HTML/CSS, even if it means writing more markup. For example, if padding and margins don't look right, the same look could be achieved by adding more rows or columns to the table and fixing their heights/widths. More  tags is simpler than worrying about how all the email clients will render the CSS box model.
There's a lot of articles and blog posts on HTML-for-email such as http://articles.sitepoint.com/article/code-html-email-newsletters that are helpful -- though a lot are out of date with newer versions of clients.


text:
Q: How to deduce that $1\cdot 1 + 2\cdot 1 + 2\cdot 2 + 3\cdot 1+3\cdot 2+3\cdot 3 +...+(n\cdot n) = n(n+1)(n+2)(3n+1)/24$ I know how to reason $$1\cdot2 + 2\cdot3 + 3\cdot4 + n(n-1) = \frac{1}{3}n(n-1)(n+1)$$
However, I'm stuck on proving $$1\cdot1 + (2\cdot1 + 2\cdot2) + (3\cdot1+3\cdot2+3\cdot3) + \cdots +(n\cdot 1+...+n\cdot n) = \frac{1}{24}n(n+1)(n+2)(3n+1).$$
Could somebody shed some light on me?

A: You can do as the following :$$\begin{align}\sum_{k=1}^{n}k(1+2+\cdots+k)&=\sum_{k=1}^{n}k\cdot\frac{k(k+1)}{2}\\&=\frac 12\sum_{k=1}^{n}k^3+\frac 12\sum_{k=1}^{n}k^2\\&=\frac 12\left(\frac{n(n+1)}{2}\right)^2+\frac 12\cdot\frac{n(n+1)(2n+1)}{6}.\end{align}$$

A: Base case:
Prove true for n=1
$ 1 * 1 = \frac{1(1 + 1)(1 + 2)(3(1) + 1)}{24} $
Inductive step:
Assume for n = k, prove for n = k+1. If we let the property be equal to P(n)
$ P(k+1) = P(k) + ((k+1) * 1 + ... +(k+1)*(k+1)) $
$ P(k+1) = \frac{k(k + 1)(k + 2)(3k + 1)}{24} + ((k+1) * 1 + ... +(k+1)*(k+1)) $
From here you should be able to do the rest, ask if you have any more issues

A: A similar but slightly different variation of Jack's proof above.
$$\begin{align}
&1\cdot (1)\\
+&2\cdot(1+2)\\
+&3\cdot(1+2+3)\\
+&4\cdot(1+2+3+4)\\
+&\vdots\qquad\vdots \; \quad\ddots\quad \ddots\\
+&n\cdot(1+2+3+\cdots+n)\\
&=\sum_{i=1}^ni\sum_{j=1}^i j=\sum_{i=1}^ni\sum_{j=1}^i {j\choose 1}\\
&=\sum_{i=1}^ni{i+1\choose 2}\\
&=\sum_{i=1}^n\left[(i+2){i+1\choose 2}-2{i+1\choose 2}\right]\\
&=\sum_{i=1}^n\left[3{i+2\choose 3}-2{i+1\choose 2}\right]\\
&=3{n+3\choose 4}-2{n+2\choose 3}\\
&={n+2\choose 3}\left[3\left(\frac{n+3}4\right)-2\right]
\qquad\qquad\text{using }{n+3\choose 4}=\frac{n+3}4{n+2\choose 3}\\
&=\frac{(n+2)(n+1)n}{1\cdot 2\cdot 3}\cdot \left[ \frac{3n+1}4\right]\\
&=\frac1{24}n(n+1)(n+2)(3n+1)\qquad\blacksquare
\end{align}$$

NB - the above makes use of the identity
$$\sum_{i=1}^n{i+m\choose m+1}={n+1+m\choose m+2}$$

A: The combinatorial identity:
$$ \sum_{k=0}^{K}\binom{n+k}{n}=\binom{n+K+1}{n+1}\tag{1}$$
can be easily proved by induction. It gives:
$$\sum_{j=1}^{n-1}j(j+1) = 2\sum_{j=1}^{n-1}\binom{j+1}{2} = 2\binom{n+1}{3} = \frac{(n+1)n(n-1)}{2}\tag{2}$$
as well as:
$$\begin{eqnarray*} \sum_{k=1}^{n}k(1+2+\ldots+k) &=& 2\sum_{k=1}^{n}k\binom{k+1}{2}=2\sum_{k=1}^{n}\binom{k+1}{2}+6\sum_{k=1}^{n}\binom{k+1}{3}\\&=&2\binom{n+2}{3}+6\binom{n+2}{4}.\tag{3}\end{eqnarray*}$$


text:
Q: text File I/O and Regular Expressions
*

*so my objective is to create a class that Reads the name of a file to
create as the first command line argument. (Overwrite any file with
the same name).

*I am then supposed to read an integer value as the second command
line argument.

*The  program  should  generate as  many random numbers as  are
specified  in  the  second  command  line  argument with  magnitudes
between 1  and 1000  and  write  them  to  the  file.

*The last step to finishing the program is that You must write only 5
numbers on each line and then begin a new line. (The last line may
have  less  than  5  numbers.)  Delimit  the  numbers  on  a  line
with  the  &character.  The  end  of  a  line  should  be  delimited
by  the  #character.  No  other  delimiters should be explicitly
used.
this is my code:
import java.util.*;
import java.io.*;
public class RandomNumGen{
static final int SEED=152;
public static void fileStore( String file, int number )
{
    if (file == null || number <=0){
        throw new IllegalArgumentException("Error");
    }

    String line = "%s&%s&%s&%s&%s#\n";
    BufferedWriter buffWriter = null;
    Random rand = new Random(SEED);

    try{
        buffWriter = new BufferedWriter(new FileWriter(file));

        int x = number / 5;
        int j = number - x * 5;
        for (int i=0; i<x; i++)
        {
            int number1 = rand.nextInt(1000-1+1)+1;
            int number2 = rand.nextInt(1000-1+1)+1;
            int number3 = rand.nextInt(1000-1+1)+1;
            int number4 = rand.nextInt(1000-1+1)+1;
            int number5 = rand.nextInt(1000-1+1)+1;
            String str = String.format(line,number1,number2,number3,number4,number5);

            buffWriter.write(str);
            System.out.println(str);

        }

        StringBuilder str = new StringBuilder();
        for (int i=0; i<j; i++)
        {
            str.append(rand.nextInt(1000-1+1)+1);
            str.append("&");

        }
        str.deleteCharAt(str.length()-1);
        str.append("#");
        String lineStr = str.toString();
        buffWriter.write(lineStr);

        System.out.print(lineStr);

        buffWriter.close();

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

public static void main(String[]args){
    fileStore("output.txt",14);
}
}

my program seems to work fine however when I use an int that ends in 5 or 0
I get an java.lang.StringIndexOutOfBoundsException: String index out of
range: -1.
this is my output:
286&112&602&201&763#

318&820&768&787&897#

707&54&927&40#

any tips for improving my code would be great.

A: Well, using a format isn't a bad idea, but I would say KISS:
    try{
        BufferedWriter buffWriter = new BufferedWriter(new FileWriter(file));
        StringBuilder str = new StringBuilder();
        for (int i=0; i<number; i++)
        {
            int n = rand.nextInt (1000) + 1;
            if (i % 5 == 4 || i == number-1)
                str.append (n + "#\n");
            else
                str.append (n + "&");
        }
        String lineStr = str.toString();
        buffWriter.write (lineStr);
        System.out.print (lineStr);
        buffWriter.close ();
    }

For counting from 0
(i % 5 == 4 || i == number-1)

This will be true for the last element of each line and for the very last number.


text:
Q: Mass dimension of coupling constants in various dimensions Just a quick question: Suppose I want to consider QED or YM in 4 dimensions we always say that the coupling constants are dimensionless and that the field then has a specific mass dimension. What happens if we change the dimensions we are considering? Do the mass dimensions of the fields then change or do the coupling constants become dimensionful?

A: The action $S$ must always be dimensionless. In $d$ dimensions it looks like:
$$
S = \int d^dx \mathcal{L},
$$
with $\mathcal{L}$ the Lagrange density. Recall that $[x] = -1$, this follows from $[x,p]=i$ (commutator with $\hbar := 1$), such that $[x] = -[p] = -1$, thus we must have: $[\mathcal{L}] = d$. A standard mass term would be $m^2\phi^2$, so the dimension of the field becomes $[\phi] = 1/2(d-2)$.

A:
Do the mass dimensions of the fields then change or do the coupling
  constants become dimensionful?

As checked by @Funzies, the mass dimension of the fields change, for instance the mass dimension for scalar bosonic fields is $[\phi]=\frac{d-2}{2}$. This is because you have always a kinetic term $(\partial \phi)^2$ in the Lagrangian, and that the Lagrangian hass mass dimension $d$, such as the mass dimension of the action is zero.
When you have in the Lagrangian , an interacting term of kind $\alpha ~\phi^p$, you must have $[\alpha]+ p [\phi]= d$, so finally $[\alpha] = d - \frac{p(d-2)}{2}$
For instance, in $d=4$ dimensions, a interacting term in $\alpha ~\phi^4$ has a dimensionless coupling constant $\alpha$. For other dimensions, this coupling constant is dimensionfull, for instance, in $d=6$ dimensions, $[\alpha]=-2$


text:
Q: Webpack is looking for react in global directory Here's my webpack-dev-server configuations
module.exports = {
  entry: './main.js',
  output: {
    path: './',
    filename: 'bundle.js'
  },
  devServer: {
    inline: true,
    port: 9000
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: '/(node_modules)/',
      loader: 'babel',
      query: {
        presets: ['es2015', 'react']
      }
    }]
  }
};

Why would I get the following error when I run the server

ERROR in (webpack)-dev-server/~/strip-ansi/index.js
  Module build failed: Error: Couldn't find preset "react" relative to directory "/Users/ecco/.nvm/versions/node/v5.4.0/lib/node_modules/webpack-dev-server/node_modules/strip-ansi"

my package.json
"devDependencies": {
"babel-core": "^6.4.5",
"babel-loader": "^6.2.2",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"webpack": "^1.12.13"
}

A: You don't appear to have the webpack-dev-server installed as a local node module (it's not in your package.json
You can see which modules are installed locally and globally with npm list and npm list --global. To look for specific modules, pipe that command into grep i.e. npm list --global | grep webpack-dev-server
I'd suggest installing the dev server as a devDependency of your project. As a general rule, try to avoid installing modules with -g unless absolutely necessary. Also, use npm scripts (in your package.json) to run modules in your local directory, without having to reference them explicitly e.g.
{
  "scripts": {
    "serve": "webpack-dev-server --config your.config.js"
  }
}

then run npm run serve rather than running ./node_modules/.bin/webpack-dev-server --config your.config.js (or worse, installing it globally)


text:
Q: Confusing derivations of Planck's Law in different books I was studying the derivation of Planck's Law. But I found confusing texts in different books.
In the book "Quantum Physics of Atoms" by Eisberg and Resnick, it states that Planck considered the cavity radiation to be composed of electromagnetic standing waves and then calculated the number density of those standing waves. He then found the average total energy of all those standing waves by multiplying the possible discrete energies by the weights, using Boltzmann probabilty distribution $P(\epsilon)=\frac{\exp(-\frac{\epsilon}{kT})}{kT}$ and computing the summation to get the Planck's Blackbody distribution. It is written below.

In the book "A Treatise on Heat" by Saha and Srivastava and also in my professor's lecture notes, it states that Planck considered the cavity radiation to be composed of simple harmonic hertzian oscillators and then calculated the number density of those oscillators. He then found the average total energy of all those standing waves by multiplying the possible discrete energies by the weights, using Maxwell probabilty distribution $P(\epsilon)=\exp(-\frac{\epsilon}{kT})$ and computing the same summation to get the Planck's Blackbody distribution.
$$N=\sum_{i=1}^\infty N_i$$ $$\bar E=\frac{1}{N}(N_1\cdot\epsilon+N_2\cdot2\epsilon+\ldots)=\frac{\epsilon}{N}\sum_{r=1}^\infty rN_r$$ $$N_r=N_1\exp(-\frac{\epsilon}{kT})$$
In Kenneth Krane's book on Modern Physics, it states the radiation is composed of resonators and that Planck used the Maxwell-Boltzmann probabilty distribution $P(\epsilon)=\frac{N\exp(-\frac{\epsilon}{kT})}{kT}$ for his corresponding calculations.

QUESTION:
All these however correctly yield the same result. So which is the correct assumption regarding the form of radiation in the cavity? Which one did Planck use? And which probability distribution did he use? Are any of the books wrong?
I am eagerly waiting for an answer. Thanks!

A: All of your sources are correct.

*

*The Boltzmann distribution states that the probability of a single state being occupied is proportional to $e^{-E/kT}$.

*To get the probability of a range of energies to be occupied, we have to integrate this, giving the Maxwell-Boltzmann distribution $e^{-E/kT}/kT$.

*Some sources give different names to these two distributions, but it don't make a difference.

*There are various prefactors you can add, but they don't make a difference.

As for the language about what they're calculating, they're all the same thing. Individual modes of the electromagnetic field are standing waves, and they are harmonic oscillators too.


text:
Q: Sample Size for Exponential Distribution I'm having a bit of trouble with a simple question.
I have data for a product, amount and days on which it was sold, that when plotted as a cumulative histogram follows an exponential cdf. I want to predict how many items are sold in the next x days. For this I sample my exponential cdf x times and sum up the result.
I would now like to reduce the deviation by repeating the above process a number of times and taking the mean of the different results. Until now I have used a large hard-coded number but there has to be a formula for calculating my sample size, i.e. the minimum number of times I need to rerun my simulation to obtain a certain confidence interval.
Any help is appreciated.

A: The mean of the sum of $k$ iid variables is just $k$ times the mean of each variable, so you can simply take the expectation of your fitted exponential distribution and multiply by $k$.
If you are interested in confidence intervals for this mean, the uncertainty comes exclusively from the uncertainty in your estimates for the exponential. I don't think there is a closed formula for how this carries through, and in any case, if I understand you correctly, you are treating your fitted exponential as fixed, so under this assumption, there is no relevant CI any more. If you want to relax that assumption (and you probably should), then I would bootstrap the entire estimation procedure before taking means.
It may also be helpful to note that the sum of $k$ iid exponentials with mean $\lambda$ is Erlang distributed with parameters $k$ and $\lambda$. The quantiles from the Erlang may be what you are looking for.
Finally, I do a lot of demand forecasting. My first reaction was, to be honest, that assessing CIs for an iid assumption is not what you should be doing. In sales, you typically have strongly nonstationary series, which include all kinds of multiple-seasonalities, price/promotion as a driver etc. Are you sure you are complexifying your approach in the right direction?


text:
Q: ACF not displaying sub field Hi guys I am using ACF pro with Repeater addon and custom Post type UI Plugin.
I created Custom post type "course library" and there I added few fields and sub field using repeater
first field is main heading field name main_heading  "which is currently displaying"
the second is "Your topic title 1" field name "your_title_field_1" and using repeater which has field label "list" and and field name "list_items" which is not displaying anything
here is my code

<?php $loop = new WP_Query( array( 'post_type' => 'course_library', 'orderby' => 'post_id', 'order' => 'ASC')); ?>
<?php while ($loop->have_posts() ) : $loop->the_post(); ?>

<?php echo the_field('main_heading'); ?>

<?php echo the_sub_field('list_items'); ?>

<?php endwhile; ?>

please help to fix this and I can display my list items too.

A: Try this

<?php $loop = new WP_Query( array( 'post_type' => 'course_library', 'orderby' => 'post_id', 'order' => 'ASC')); ?>
<?php while ($loop->have_posts() ) : $loop->the_post(); ?>

<?php echo the_field('main_heading'); ?>

<?php $your_topics = get_field('your_topic_title_1'); ?>

<?php foreach($your_topics as $your_topic) { ?>

<?php echo $your_topic['list_items']; ?>

<?php } ?>

<?php endwhile; ?>

A: Also the
<?php echo the_field('main_heading'); ?>
 is quite ugly cause it echo's two times (the_field() echo's, get_field() returns) so I would change that one as well if I was you


text:
Q: What is the relation between user, group, role, policy and AWS services? A policy can be attached to a user or group. This controls what the users are able to do in AWS.
Policy can be attached to an AWS service? What is the relation between policy and AWS service?
And where does the concept of Role fit in all this?

A: In Amazon Web Services (AWS), a user is a person or system that interacts with the AWS platform. Users can have different levels of access to AWS services and resources, depending on their permissions.
A group is a collection of users that share the same permissions. Groups can be used to manage the permissions of multiple users at once, making it easier to manage and control access to AWS services and resources.
A role is a set of permissions that can be assumed by a user or system. Roles are used to grant users and systems access to AWS services and resources, without having to share or manage long-term credentials. Roles can be temporary or permanent, and can be assumed by users, applications, or services.
A policy is a document that defines the permissions for a user, group, or role. Policies are written in the AWS Identity and Access Management (IAM) policy language, and specify the actions and resources that a user, group, or role is allowed to access.
AWS services are the core components of the AWS platform, and include a wide range of cloud-based services for computing, storage, networking, analytics, machine learning, and more. AWS services can be accessed by users, groups, and roles, depending on the permissions granted by policies.
In summary, the relation between user, group, role, policy, and AWS services is as follows:
A user is a person or system that interacts with AWS services.
A group is a collection of users that share the same permissions.
A role is a set of permissions that can be assumed by a user or system.
A policy is a document that defines the permissions for a user, group, or role.
AWS services are the core components of the AWS platform, and can be accessed by users, groups, and roles with the appropriate permissions.

A: Think of role like a container holder for permissions which can be used to delegate access to users, applications, or services that don't normally have access to your AWS resources.
From docs

An IAM role is an IAM identity that you can create in your account that has specific permissions. An IAM role is similar to an IAM user, in that it is an AWS identity with permission policies that determine what the identity can and cannot do in AWS. However, instead of being uniquely associated with one person, a role is intended to be assumable by anyone who needs it.

A: A policy is an object in AWS that, when associated with an identity or resource, defines their permissions. AWS evaluates these policies when an IAM principal (user or role) makes a request. Permissions in the policies determine whether the request is allowed or denied


text:
Q: partition text with no fixed width I have some text like this
blue chile               green   morning dawn
red  turkey              pink    morning dawn
white south africa       red     evening midst & more

I would like to split it like this (notice the pipe delimiter)
blue child | green morning dawn
red turkey | pink morning dawn
white south africa | red evening midst & more

There aren't fixed width so I am having trouble partitioning the text

A: This MIGHT be what you're looking for:
$ sed -E 's/ {3,}/ | /; s/  */ /g' file
blue chile | green morning dawn
red turkey | pink morning dawn
white south africa | red evening midst & more

The above assumes your 2 "fields" are separated by 3 or more blank chars as in your posted sample input. It will work in GNU or OSX sed for -E to enable EREs.
Otherwise, if the fields really ARE fixed width as it appears in your posted input then for improved robustness consider using GNU awk for FIELDWIDTHS:
$ awk -v FIELDWIDTHS='25 8 999' -v OFS=' | ' '{print $1, $2, $3}' file
blue chile                | green    | morning dawn
red  turkey               | pink     | morning dawn
white south africa        | red      | evening midst & more

$ awk -v FIELDWIDTHS='25 8 999' -v OFS=' | ' '{print $1, $2 $3}' file
blue chile                | green   morning dawn
red  turkey               | pink    morning dawn
white south africa        | red     evening midst & more

$ awk -v FIELDWIDTHS='25 8 999' -v OFS=' | ' '{$0 = $1 OFS $2 $3; gsub(/ +/," ")} 1' file
blue chile | green morning dawn
red turkey | pink morning dawn
white south africa | red evening midst & more

A: if you want to normalize spaces in addition to the pipe delimiter
$ sed -r 's/(.{25})/\1 | /' file | tr -s ' '

blue chile | green morning dawn
red turkey | pink morning dawn
white south africa | red evening midst & more

this matches your output but note that the extra space in red  turkey is removed as well.  If you want to preserve it, it will require extra steps.


text:
Q: Switch parent and child process I am wondering whether it is possible to transform a child process (created via fork) into the parent process?
I want to implement a transaction concept in which each transaction forks a snapshot of the current memory state. If a transaction commits successfully, the corresponding process should become the new parent process and the old parent process should be terminated.
Is that possible at all?


text:
Q: How can I encrypt a string in a portable class library without using PCLContrib? I am building a portable library targeting Windows 8.1. I need to encrypt a password to send it across an http connection. The problem is that System.Security.Cryptography is not available in portable libraries.
The only solution that I've been able to find is the PCL Contrib, but it seems far too bulky to add that to my project. I was also getting some runtime exceptions in PCL Contrib that I couldn't resolve.
I am sure that there has to be a simple solution out there, but I haven't been able to find any that doesn't use System.Security.Cryptography. Does anyone know of a simple to use encryption that can be used in a portable library?

A: Use PCLCrypto. It offers WinRT-like APIs for cryptography, but it works on all the modern platforms.


text:
Q: How to add Total Row in Order Grid I have installed magento 1.9.2.3 version.
My client requirements is to take the Order Amount total in a Day.
Let say he want to know how many order comes in a day and what is the Order Amount.
Can anybody let me know how can we do this because i am new in magento?
thanks

A: In default magento this type functionality available in admin end
Go admin side top menu Reports -> Sales -> Orders


text:
Q: App loses all settings when app update is installed This is an issue that only happens for some users. Whenever I release a new version of my app in Marketplace I get emails from users saying that all the settings in the app are lost.
I can't reproduce this myself and I have no code that can wipe the IsolatedStorage.
Would be great if anyone out there had a clue on what might be causing this.

A: Update: Not sure if the following applies to WP7 apps - I'll leave it here just in case. I have only tried this for normal apps.
You will need to "upgrade" the old settings file.
You also need to know when you need to do this (i.e. only when a new version is installed).
To know when you need to upgrade settings, add a boolean called (say) NeedSettingsUpgrade to your settings, and default it to true.
Then call the following function somewhere near the start of Main():
/// <summary>Upgrades the application settings, if required.</summary>
private static void upgradeApplicationSettingsIfNecessary()
{
    // Application settings are stored in a subfolder named after the full #.#.#.# version number of the program. This means that when a new version of the program is installed, the old settings will not be available.
    // Fortunately, there's a method called Upgrade() that you can call to upgrade the settings from the old to the new folder.
    // We control when to do this by having a boolean setting called 'NeedSettingsUpgrade' which is defaulted to true. Therefore, the first time a new version of this program is run, it will have its default value of true.
    // This will cause the code below to call "Upgrade()" which copies the old settings to the new.
    // It then sets "NeedSettingsUpgrade" to false so the upgrade won't be done the next time.

    if (Settings.Default.NeedSettingsUpgrade)
    {
        Settings.Default.Upgrade();
        Settings.Default.NeedSettingsUpgrade = false;
    }
}

Note: You will of course need to call Settings.Default.Save() before your program exits, otherwise the settings change won't be persisted.

A: My approach to this has been to use the assembly version number as the trigger for the upgrade. On first run it save settings in the format required for v1.0 and the assembly version number 1.0.0.0. When an upgrade occurs it compares the saved setting number (1.0.0.0) with the upgraded assembly number 1.1.0.0 and decides that an upgrade is needed.
I discovered that doing a redeploy for visual studio did not guarentee to do an upgrade, sometimes it did an uninstall, reinstall which was not as good. So I changed to using Windows Phone Powertools to test my "upgrade" path as it seems to reliably do upgrades.


text:
Q: How to show matplotlib windows in WSL2 under Win11? When I try to show a matplotlib window from Python 3 via show() I get the following error:

UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.

So following various threads here on SO I tried the following:
import matplotlib
matplotlib.use("TkAgg")

Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running

I also tried it with matplotlib.use("QtAgg"), which leads to a similar error:

Cannot load backend 'QtAgg' which requires the 'qt' interactive framework, as 'headless' is currently running

So it seems regardless of what backend I try, matplotlib thinks its in headless mode. However, I can run other X apps from that WSL installation under Win11 just fine, for example xclock or sqlitebrowser. They all work with the X server built into Win11. The DISPLAY env. variable is set to:
$ echo $DISPLAY
:0

Any ideas how I can get matplotlib windows working under Win11?

A: For the records, if someone faces the same problem in WSL under Win11:
The .show() function of matplotlib was working fine when called directly from the console. It turned out that even though :0 is valid as value, the DISPLAY variable was not set when I ran my program from VS Code. After setting that env. variable in the IDE's run configuration everything works fine.


text:
Q: Can not use PrimeNG in Angular CLI I try to use the PrimeNG in angular CLI but It doesn't work @@!
Component.ts
import { Component, OnInit } from '@angular/core';
import { ToolbarModule } from 'primeng/primeng';
@Component({
  selector: 'app-marketing-menu-bar',
  templateUrl: './marketing-menu-bar.component.html',
  styleUrls: ['./marketing-menu-bar.component.css']
})
export class MarketingMenuBarComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}

Here is the Component.html

    <button pButton type="button" icon="fa-search"></button>

    <button pButton type="button" icon="fa-refresh"></button>
    <button pButton type="button" icon="fa-trash"></button>

After I run ng serve:

Unhandled Promise rejection: Template parse errors:
  'p-toolbar' is not a known element:
  1. If 'p-toolbar' is an Angular component, then verify that it is part of this module.
  2. If 'p-toolbar' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]

           ; Task: Promise.then ; Value: SyntaxError {_nativeError: Error: Template parse errors:
  'p-toolbar' is not a known element:
  1. If 'p-toolbar' is an Angular co…} Error: Template parse errors:
  'p-toolbar' is not a known element:
  1. If 'p-toolbar' is an Angular component, then verify that it is part of this module.
  2. If 'p-toolbar' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]

A: Did you import ToolbarModule inside your app.module.ts ?
import { ToolbarModule } from 'primeng/toolbar';

A: The error message tells you what needs to be done. In the module which declares your component, add CUSTOM_ELEMENTS_SCHEMA to your imports, eg:
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

(You will already be importing NgModule from @angular/core, so just add the new import to this line, separated by a comma.)
Then add the following line somewhere within the @NgModule decorator:
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]


text:
Q: painting multiple images to a jpanel I'm having an issue with drawing multiple images from objects on to a custom JPanel.  I've been able to successfully paint one image representation of an object on the JPanel.  Adding more objects only paints on top of the other Image, I believe, since they use the same Graphics2D object.
So I've decided to create a custom JComponent that contains the Shapes, Image, and Object, but unfortunately it isn't working any better.  My thinking was this would allow the JPanel to use a for loop for each object and create a new Graphics2D object to paint with.
This is for a game I'm programming, FYI.  The objects I'm trying to paint are the units on screen that need to be manipulated.
public class ShipGraphic extends JComponent{

private Shape       shipShape, combatShape;
private Image       shipImage;
private ImageIcon   si;
private int         shipX = 0, shipY = 0, shipW, shipH, combatH, combatW, combatR;
private Ship        ship;

public ShipGraphic(Ship ship)
{
    this.ship = ship;
    setImageIcon();
    shipImage = si.getImage();
    shipW = shipImage.getWidth(null);
    shipH = shipImage.getHeight(null);
    combatH = shipH * 2;
    combatW = shipW * 2;
    combatR = -(shipW * 2);
    shipShape = new Rectangle2D.Double(shipX, shipY, shipW, shipH);
    combatShape = new Ellipse2D.Double(combatR, combatR, combatW, combatH);
}

@Override
public void paintComponent(Graphics g)
{
    super.paintComponents(g);

    Graphics2D g2 = (Graphics2D) g;
    Graphics2D g3 = (Graphics2D) g;
    Graphics2D g4 = (Graphics2D) g;

    g2.drawImage(shipImage, shipX, shipY, null);
    g3.setColor(new Color(0,0,0,0));
    g3.drawRect(shipX, shipY, shipW, shipH);
    g4.draw(combatShape);
}

The ShipGraphic uses a Rectangle to check if the user has clicked on the Image and will use the Circle to determine if it intersects another rectangle for combat.  These two shapes are drawn opaque under the Image.
The custom JPanel then adds them to the panel using this for loop:
    for ( Ship s : sector.getShips() )
    {
        ShipGraphic ship = new ShipGraphic(s);
    }

A:
Adding more objects only paints on top of the other Image, I believe, since they use the same Graphics2D object.

The problem is not because you use the same Graphic object. All Swing components on a given frame are painted with the same Graphics object. If they paint on top of each other then that would be because you don't specify a proper x/y position for each object.

So I've decided to create a custom JComponent that contains the Shapes

That is a good approach. However, in this case you would always paint your object at location (0, 0) of the component. Then you would position each component by invoking setLocation(...) on the component.
You would also need to override the getPreferredSize() method of the component to make sure it returns the appropriate size of your component.
The example code you posted has a typing mistake. Get rid of the "s" on super.paintComponents(g).


text:
Q: Two Kinects on one PC with SDK 1.7 in C#/WPF I am trying to get two kinects running from within one C#/WPF project. The kinects are connected to different USB-controllers (with different controllers i do NOT mean different ports).
In XAML my code is as follows:
<Window x:Class="Microsoft.Samples.Kinect.ColorBasicsind file .MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Color Basics" Height="290" Width="770" Loaded="WindowLoaded" Closing="WindowClosing">
    <Grid>
        <Image Name="Image1" Width="320" Height="240" Margin="10,10,432,458"/>
        <Image Name="Image2" Width="320" Height="240" Margin="432,10,10,63"/>
    </Grid>
</Window>

In C# the code-behind file is as follows:
namespace Microsoft.Samples.Kinect.ColorBasics
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.Windows;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using Microsoft.Kinect;

    public partial class MainWindow : Window
    {
        private KinectSensor sensor1;
    private KinectSensor sensor2;

    private WriteableBitmap colorBitmap1;
    private WriteableBitmap colorBitmap2;

    private byte[] colorPixels1;
    private byte[] colorPixels2;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void WindowLoaded(object sender, RoutedEventArgs e)
    {
        //init sensor 1
        this.sensor1.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
        this.colorPixels1 = new byte[this.sensor1.ColorStream.FramePixelDataLength];
        this.colorBitmap1 = new WriteableBitmap(this.sensor1.ColorStream.FrameWidth, this.sensor1.ColorStream.FrameHeight, 96.0, 96.0, PixelFormats.Bgr32, null);
        this.Image1.Source = this.colorBitmap1;
        this.sensor1.ColorFrameReady += this.SensorColorFrameReady1;
        this.sensor1.Start();

        //init sensor 2
        this.sensor2.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
        this.colorPixels2 = new byte[this.sensor2.ColorStream.FramePixelDataLength];
        this.colorBitmap2 = new WriteableBitmap(this.sensor2.ColorStream.FrameWidth, this.sensor2.ColorStream.FrameHeight, 96.0, 96.0, PixelFormats.Bgr32, null);
        this.Image2.Source = this.colorBitmap2;
        this.sensor2.ColorFrameReady += this.SensorColorFrameReady2;
        this.sensor2.Start();
    }

    //sensor 1 new-frame-event-handler
    private void SensorColorFrameReady1(object sender, ColorImageFrameReadyEventArgs e)
    {
        using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
        {
            if (colorFrame != null)
            {
                colorFrame.CopyPixelDataTo(this.colorPixels1);
                this.colorBitmap1.WritePixels(
                    new Int32Rect(0, 0, this.colorBitmap1.PixelWidth, this.colorBitmap1.PixelHeight),
                    this.colorPixels1,
                    this.colorBitmap1.PixelWidth * sizeof(int),
                    0);
            }
        }
    }

    //sensor 2 new-frame-event-handler
    private void SensorColorFrameReady2(object sender, ColorImageFrameReadyEventArgs e)
    {
        using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
        {
            if (colorFrame != null)
            {
                colorFrame.CopyPixelDataTo(this.colorPixels2);
                this.colorBitmap2.WritePixels(
                    new Int32Rect(0, 0, this.colorBitmap2.PixelWidth, this.colorBitmap2.PixelHeight),
                    this.colorPixels2,
                    this.colorBitmap2.PixelWidth * sizeof(int),
                    0);
            }
        }
    }

    private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        if (null != this.sensor1)
        {
            this.sensor1.Stop();
        }
    }
}
}

Still, one of the XAML-image-objects remains black, while the other shows a motionless picture.
Could you tell me why this is the case ?
(P.S.: Please don't dive into discussions why the code i posted is not object-oriented! I know what DRY, KISS, Coherence and Cohesion are.)


text:
Q: Problem while using links() and nav tabs : Redirecting to page 2 of other tabs while it does not exist I'm using nav tabs of bootstrap (I have 5 tabs) and paginate function links(). If I have 2 page in the first tab, and I click on next to go to the 2nd page, and then I'm going to another tab, it will be display nothing even if I have data inside it. Why ? Because inside the url, there is the ?page=2 of the 1st tab. It does not erase when I'm changing tabs.
Does someone know how can I be able to resolve this please ?
Example :

    Test1
    Test2

Content of the tab pane :

test 1 i'm here

    @foreach($tests as $test1)
        {{ $test1->name }}
    @endforeach
    {!! $tests->links() !!}

test 2 i'm here

    @foreach($tests as $test2)
        {{ $test2->name }}
    @endforeach
    {!! $tests->links() !!}

I have a paginate(1), so if inside my test1 tab, I have more than 1 line (imagine 4), and I go to the page 4, and then I click to the tab test2, it will display that I do not have data even if I have 1 or more (less than 4).
Cordially
EDIT SOLUTION :
I've found the solution, here is an example to put into your controller where I use the paginate function :
$users = User::paginate(10, ['*'], 'users');

$posts = Post::paginate(10, ['*'], 'posts');

doc: https://laravel.com/api/8.x/Illuminate/Database/Eloquent/Builder.html#method_paginate


text:
Q: UITabbarController Inside UINavigationController I am using a UITabBarController inside a UINavigationController.Inside The UITabBarController there is 2 UITableViewController , the first table view (which is selected by default )shows correctly while the other tableview are partially hidden behind the navigation bar , when adding
self.tableView.contentInset = UIEdgeInsetsMake(64.0f, 0.0, 0.0, 0.0);

this fix the problem but the weird thing when adding action to present a new view controller modally using
    [self presentViewController:viewcontroller animated:YES  completion:nil]

and then the user dismiss this view controller using
[self dismissViewControllerAnimated:YES completion:nil];

the second TableView is shifted down by 64 + 64 ,,, how to fix that to keep the second tableView shifted by only 64


text:
Q: Laravel - how to deal with controller extends another controller I'm having Laravel app that have two controllers UserController an AdminController , ofcourse Admin have more credentials than user and here comes my question:
I want User to be able to:

*

*fetch and view account

*fetch and view mail

and Admin to be able to:

*

*fetch and view account

*fetch and view mail

*manage account

*manage mail

obviously there is redundant in the fetching and viewing functionality for both, so I tried to creating two controllers. the AdminController extends UserController:
UserController:
?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use DB;
use App\Http\Requests;
use App\User;
use App\Account;
use App\Mail;

class UserController extends Controller
{
        /*******************
         * Helper functions
         * retrieving data
         ***/

        //retrieving data from database
        protected function getaccount($userId){
            //fetch data from database
        }
        protected function getmail($userId){
            //fetch mail from database
        }

        /*******************
         *other controller functions
         ***/
 }

AdminController:
?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use DB;
use App\Http\Requests;
use App\User;
use App\Account;
use App\Mail;

class AdminController extends Controller, UserController
{
        /*******************
         * Helper functions
         * retrieving data
         ***/

        //retrieving data from database
        protected function manageaccount($userId){
            //manage
        }
        protected function managemail($userId){
            //manage
        }

        /*******************
         *other controller functions
         ***/
 }

how can I use the fetching and viewing functions of UserController in AdminController?

A: You may want to put your getaccount and getmail methods on your User model class.


text:
Q: neo4j - Count the number of duplicates in result Community,
I am new to neo4j and I'm trying to get a list of nodes (that has not a specific relation) and count node name duplicates.
Query:
MATCH (e:ExampleNode)
WHERE NOT exists((e)-[:EXAMPLE_REL]->())
RETURN e.name as name, count(e.name) as count

Result:

name
count

name1
3

name23
1

name8
4

So far so good...
Beside the name of the node I also need some more values. This value makes each result unique and returns every node separately even (if the name is the same).
Query:
MATCH (e:ExampleNode)
WHERE NOT exists((e)-[:EXAMPLE_REL]->())
RETURN e.name as name, count(e.name) as count, e.property as someValue

Result:

name
count
someValue

name1
1
abc

name1
1
cba

name1
1
xyz

name23
1
abc

name8
1
123

name8
1
321

name8
1
987

name8
1
789

...
...
...

But...this is the result I would like to have:

name
count
someValue

name1
3
abc

name1
3
cba

name1
3
xyz

name23
1
abc

name8
4
123

name8
4
321

name8
4
987

name8
4
789

...
...
...

I would like to return every node that hasn't the specific relation and count all duplicates by the name.
So, is it possible to get the result I would like to have?

A: Yess it is possible. When calculating the count, collect the property values in a list using collect function and then use UNWIND on the previous list, to get distinct rows for each property. Like this:
MATCH (e:ExampleNode)
WHERE NOT exists((e)-[:EXAMPLE_REL]->())
WITH e.name as name, count(e.name) as count, collect(e.property) as properties
UNWIND properties as property
RETURN name, count, property


text: Q: Is it possible to have my app accessible from the iphone lock screen the same way *Medical Id is available? I want to know if it is possible for my app to display information to the user EVEN if they haven't unlocked their iphone lock screen.   I want it to act similar to the way the Medical ID information can be displayed (if enabled) on a locked iphone.


text:
Q: In h5 page I want to open app(had schema already) when the iPhone install the app if not jump to appstore As I said in title,I used the following JS Code:
openApp


text:
Q: Vba: vlookup for entire column I have column B with cost centre codes and column D with department. i need to do a vlookup to fill in the department name of the relevant cost centre code.
The current code is like this:
Dim MyStringVar1= Application.Vlookup(Range("B7"),_
Worksheets("VLOOKUP Table").Range("A2:B1000"),2,True)
However, i dont just want to do vlookup for D7 only but rather the entire column. My range is not fixed(there may be 100 or 200rows in Column B,depending on the number of projects.)
How do I apply the formula for the entire column? Instead of D7 only

A: let's say you want to add formula =VLOOKUP(B2,'VLOOKUP Table'!A$2:B$1000,2,TRUE)
to range D3:D10, where 'B2' will increment after every row, then the code would be :
Range("D3:D10").Formula= "=VLOOKUP(B2,'VLOOKUP Table'!A$2:B$1000,2,TRUE)"

A: Dim This As Worksheet

Set This = ThisWorkbook.Sheets(1)

This.Activate
    This.Range("D7", Range("A2").End(xlDown).Offset(0, 3)).Formula = "=VLOOKUP(B2,[INSERT SHEET]!$A:$D,2,FALSE)"

If the data is in sheet2, you just insert sheet2 in the [INSERT SHEET]. It doesn't matter if the name is sheet2 or named something else, just call it sheet2

A: You could use relative references in an R1C1 formula, then just paste it to your destination range, you'd need to find the destination range first, perhaps using something like .end(xldown).row
See this for reference on the general idea:
http://macromatician.blogspot.co.uk/2013/02/how-to-add-formula-to-worksheet-range.html


text:
Q: Создать CSV строку из списка, заменив последний разделитель на другую строку (например " and ") Приветствую!
Я новичок в Python, знаю, что одну задачу можно решить многими способами, хотелось бы увидеть изящные и интересные решения следующей задачи:
Требуется написать функцию, которая принимает список в качестве аргумента и возвращает строку, в которой все элементы разделены запятой и пробелом, а перед последним элементом вставлено слово and. Например: если вводится список [aa, bb, cc, dd], то на выходе должно получиться 'aa, bb, cc and dd'
Я решил это так:
#!/usr/bin/env python3
def delim(spis):
  b = spis.split()
  x = ((' '.join(b[:-1])).split())
  print(', '.join(x) + ' and ' + str(b[-1]))
spis = delim(input('Input own list: '))

A: Можно так:
def delim(lst, sep=', ', last_sep=' and '):
    return last_sep.join(sep.join(lst).rsplit(sep,1))

Примеры использования:
In [24]: l = ['aa', 'bb', 'cc', 'dd']

In [25]: delim(l)
Out[25]: 'aa, bb, cc and dd'

In [26]: delim(l, sep=',')
Out[26]: 'aa,bb,cc and dd'

In [27]: delim(l, last_sep=' but not ')
Out[27]: 'aa, bb, cc but not dd'

A: spis = ['a','b','c',100]
def anac(spis):
    a = ' ,'
    while True:
        q = str(spis[0]) + a
        b = str(spis[1]) + a
        c = str(spis[2]) + a
        d = 'and' + ' ' + str(spis[3])
        print(q, b, c, d)
        break

anac(spis)


text:
Q: Calculating future dates based on curent date within inline editor for Dialogflow I am using the inline editor for Dialogflow to manipulate user data and query my database in.js, with that, I also want the chatbot to answer questions like:
"When is my next Art test."
As the admin I know Art tests are every 3 weeks on Wednesday throughout the year, but how do I translate that into a chatbot response, something like;
"Your next art test is Wednesday 8th August", Or even, "Your next test is Today!"
I have looked at this which is different ways to initiate js times, but none seem to fit what I'm looking for.
I have created a function for time as below, which is where I assume I'd have to make the calculation:
  function getDate(agent){
      var today = new Date();
  }

And the response would be something like:
function getTestDate(agent){
        agent.add('Your next test date is' + today); #etc
}

Lastly I have seen this other post on stack calculating days between two dates, whilst this could work I'm not too sure how I can implement this into a Dialogflow environment.
I don't think moment.js can work within the inline editor, but if it did, It looks like it would be easy, per the example here:
moment([2007, 0, 29]).fromNow();     // 4 years ago
moment([2007, 0, 29]).fromNow(true); // 4 years

Then I could simply do the fromNow() command in each function for different dates, and idea how something like this could be interpreted to normal js?
UPDATE
Not got anywhere with this yet but had another idea, is there anyway to identify the month and from there trigger a response? For example can I create a function that identifies the date right now, then i'll be able to write the 3/4 test dates as a text response:
function (getTestDate(agent){
        if(date) == May
} agent.add('Tests for May are....etc')

A: Okay, not exactly what I wanted but the closest I can get to what I want is declaring a test date, then creating if statements to suggest IF today is before a certain date, then i know to respond with the next closest date, and so on.
function getTestDate(agent){
        var today = new Date();
        var testDate= new Date("08/08/2018");
        var timeDiff = Math.abs(testDate.getTime() - today.getTime());
        var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

        if (today < testDate){
            agent.add('Your next test date is in ' + diffDays + 'days, at 9pm on Wednesday');
        }else if (today > testDate) {
            agent.add('Your test date was on Wednesday 8th August 2018');
        }else if (today == testDate){
            agent.add('Your test is today, Wednesday 8th August 2018');
        }

Again, not ideal as I know have to create a variety of functions for different times, but get's the job done.
If you have any other suggestions please feel free to suggest.


text: Q: Is there any solution for generating Business Logic Classes and Database logic classes from MYSQL database table? I am looking for a  solution for creating BO and DAL classes as well as the Stored procedure from MYSQL database using phpmyadim. I have solution for the mssql server database but i needed a good solution for the MYSQL database. There are many solution but there are not good enough for this kind of work.


text:
Q: Accessing global file in the user defined function I am trying to access file which is opened globally as below:
with open("number.txt") as num:
    val=int(num.read())

consider number.txt will be having some number
After the above lines of code if I use the above file pointer inside a method as below:
def updateval():
    global num
    num.write(numb)

I am getting error as :ValueError: I/O operation on closed file
If I open file inside function then there wont be any issue.But I want to open file only once so in many opther function I can perform file operation without opening again and again
Please help me in resolving this!!
Many thanks in advance..

A: You have two problems:

*

*with closes the file when the enclosing code block exists.

*You open the file for reading, so even if you don't close the file, you can't write to it.

Solution 1:
with open('number.txt') as num:  # opens for read-only by default
    val = int(num.read())
# file is closed here

def updateval(numb):
    with output('number.txt','w') as num:  # re-opened for writing
        num.write(numb)
    # file is closed here

Solution 2 (if you really want to open the file once):
num = open('number.txt','r+')  # Open for reading and updating.
val = int(num.read())

def updateval(numb):
    # You don't need "global" when you mutate an object,
    # only for new assignment, e.g. num = open(...)
    num.seek(0)           # make sure to write at the beginning of the file.
    num.truncate()        # erase the current content.
    num.write(str(numb))  # write the number as a string
    num.flush()           # make sure to flush it to disk.

Obviously, the second solution you have to micromanage what you are doing.  Use solution 1.

A: The whole point of a with statement is that the file is closed when you leave that scope. The advantage of this is that if you get errors, the file is closed properly.
So when you do the following:
with open("number.txt") as num:
    val=int(num.read())

you assign the contents of number.txt to val and then close the file.
So therefore, when you try and write to it later (no matter if you are in a function or not), you will get the error that you posted in the question:
ValueError: I/O operation on closed file

So if you really want to be able to write to the file inside any function without having to keep opening it, you just have to not use a with statement, just open the file for writing ('w') explicitly and close it at the end of the program.
So the main outline of your code would look something like:
with open("number.txt") as num:
    val=int(num.read())

file = open("number.txt", "w")

def writeToFile(data):
    global file
    #more code
    file.write(data)
    #more code

#more code

file.close()

note this is not good practice, you should pass the file object into the function and remove the use of global variables


text:
Q: ActiveModel dirty to ignore milliseconds How can I make ActiveModel::Dirty ignore milliseconds when comparing datetime in Rails.
     news.publish_at
     => Fri, 16 Nov 2018 17:05:37 CET +01:00

     news.publish_at = news.publish_at.to_s
     => "2018-11-16 17:05:37 +0100"

     news.publish_at_changed?
     => true

But if I add milliseconds to the above datetime, changed? is false.
     news.publish_at = "2018-11-16 17:05:37.517 +0100"
     => "2018-11-16 17:05:37.517 +0100"

     news.publish_at_changed?
     => false

I am using Rails 5.2.1

A: I think the simplest workaround might be to just add a custom setter to that model that truncates the milliseconds everytime when assigning a new value.
def publish_at=(value)
  if value
    time_without_usec = DateTime.parse(value).change(usec: 0)
    value = time_without_usec.to_s
  end

  super(value)
end


text:
Q: A stuck up problem of floatation I am stuck with a question. Please help:

A metal block is weighed in the air, the spring balance shows 20 N. Then a beaker with water is taken weighing 40 N. The metal block is immersed in the liquid, the apparent weight being 16 N. Thus the buoyancy recorded is 4N.
  So, what is the weight of beaker with water and block now?

NOTE added for clarification: While floating, the metal block remains attached to the spring balance in such a way that the spring continues to carry a load of 16 N.
In some books i have seen that they say to add the buoyant force to the original weight of beaker. But, I argue if Two blocks of different masses but same volume sink in water in separate beakers of equal weight. Then, would the weight of the beakers be the same?

A: The buoyant force is the amount of force that the liquid is exerting on the object.  It takes 4 N less to keep the object from falling down when it is in the liquid, so the buoyant force is 4 N.
Due to the nature of "equal and opposite reactions", this means the mass is also exerting 4 N of force on the fluid.  That 4 N force on the liquid will make the beaker weight 4 N more (only 4 N of the weight is actually pushing down on the liquid).
Therefore the beaker will have the weight original weight plus the 4 N buoyant force; for 44 N total.
It's different if the objects aren't being held by a spring or rope.  If they can sink then the beaker would weigh 20 N more, since the entire mass will be pushing down on the beaker.  In this case we measured the force on the beaker to be only 4 N of those 20 N.


text:
Q: Log4j 2 JSON Configuration I have a configuration in XML that I would like to convert to JSON. The JSON version is not being loaded by Log4j and I cannot find any typos. My test code simply logs an ERROR level and a DEBUG level message. Only ERROR messages are being displayed and no file output is being generated - I'm assuming the framework falls back to the default initialization instead of the JSON file.
Note: The log4j2-test.json file is on the classpath.
I'm using apache-log4j-2.0-beta9 binary found here.
The XML configuration is the following:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration name="Test">
    <Properties>
        <Property name="Directory">${sys:user.home}/logs</Property>
        <Property name="Filename">test.log</Property>
    </Properties>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <RollingFile name="File"
            fileName="${Directory}/${Filename}"
            filePattern="${Directory}/${date:yyyy-MM}/test-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout>
                <pattern>%d %p %logger{36} [%t] %m%n</pattern>
            </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="1 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="File"/>
        </Root>
    </Loggers>
</Configuration>

and the JSON configuration is:
{
   "configuration": {
      "name": "Default",
      "properties": {
         "property": {
            "name":"Directory",
            "value":"${sys:user.home}/logs"
         },
         "property": {
            "name":"FileName",
            "value":"test.log"
         }
      },
      "appenders": {
         "Console": {
            "name":"Console",
            "target":"SYSTEM_OUT",
            "PatternLayout": {
               "pattern":"%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"
            }
         },
         "RollingFile": {
            "name":"File",
            "fileName":"${Directory}/${FileName}",
            "filePattern":"${Directory}/${date:yyyy-MM}/test-%d{MM-dd-yyyy}-%i.log.gz",
            "PatternLayout": {
               "pattern":"%d %p %logger{36} [%t] %m%n"
            },
            "Policies": {
               "SizeBasedTriggeringPolicy": {
                  "size":"1 MB"
               }
            },
            "DefaultRolloverStrategy": {
               "max":"10"
            }
         }
      },
      "loggers": {
         "root": {
            "level":"debug",
            "appender-ref": {
               "ref":"Console"
            },
            "appender-ref": {
              "ref":"File"
            }
         }
      }
   }
}

A: I believe that I have an additional correction to the JSON configuration that was posted.  For me, this part produces problems:
  "properties": {
     "property": {
        "name":"Directory",
        "value":"${sys:user.home}/logs"
     },
     "property": {
        "name":"FileName",
        "value":"test.log"
     }
  },

On my setup, this will output ~/logs/${FileName} or ~/${Directory}/test.log, which means that it is only interpolating one of the properties instead of both.
I concluded from this that the properties were not specified correctly in JSON form. To fix it, I specified the properties as a JSON array
    "properties": {
        "property": [{
            "name":"Directory",
            "value":"${sys:user.home}/logs"
        },
        {
            "name":"FileName",
            "value":"test.log"
        }]
    },

With this in place, it seems to fix the problem and correctly outputs to ~/logs/test.log
My setup is log4j2 2.0.2 on Mac with tomcat 7.0.55

A: You have another flaw in there that might catch you, that I've run into with log4j json.
"appender-ref": {
    "ref":"Console"
},
"appender-ref": {
    "ref":"File"
}

Try this instead, as it is now, it will only catch one appender.
"appender-ref": [{
    "ref":"Console"
},
{
    "ref":"File"
}]

A: I found a solution to the problem.
It turns out that the Log4j 2 Configuration doesn't document all the required dependencies:

The JSON support uses the Jackson Data Processor to parse the JSON
  files. These dependencies must be added to a project that wants to use
  JSON for configuration:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.7</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.7</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.8.7</version>
</dependency>


text:
Q: All subgroups of a symmetric group I am very new to the theory of groups and am writing a program that generates all subgroups of the symmetric group $S_n$; the idea is to find the generators for each subgroup.
With this thread, I was hoping to get some ideas about the following questions:

*

*Does there exists a way to pick the generators beforehand to avoid
recomputing the same subgroups?

*If so, what would be a could starting point for me?

Currently, I am picking the set of generators by some arbitrary set of permutations from $S_n$.


text:
Q: Is there a way to solve any linear equation and system of linear equations all in one? Note: I made this a while ago and have learned a lot more since then, enough to understand why what I was asking for was unrealistic. I also should have done more research into sympy before asking this question.
I want to create a program where you enter a linear equation or system of linear equations as a string and in return you get the value of the variable(s) you entered, like so:
equation = input('Expression: ')
# Code to solve your linear equation here
print(answer)

Just to be clear, I want to be able to solve things like x+5=10, or things like 2x+3y=29, and get an output that looks something like "5", or "4, 7" respectively.
I've tried searching multiple websites and some stack overflow questions, but all I've come up with are ways to solve systems of linear equations like 2x+3y=29 using numpy or ways to solve normal linear equations like x+5=10 but none that can do both.
Here's a list of 3 answers I found and why they didn't help:

*

*https://www.mybluelinux.com/how-solve-any-linear-equation-in-python/

*

*Offers a solution to solve normal linear equations, but cannot solve systems of linear equations

*https://stackabuse.com/solving-systems-of-linear-equations-with-pythons-numpy/

*

*Solves systems of linear equations, but can't solve linear equations like x+5=10

*Is there a python module to solve linear equations?

*

*Same reason as 2, most answers suggested NumPy, and the other answers there didn't solve my problem either.

I also searched some other websites and stack overflow questions, but they didn't work either for the same reasons as the 3 examples I listed.

A: There are plenty of existing packages to solve linear equations.  However, they won't do your normalization work.  You have to first transform your existing equations into standard form: an augmented matrix.
If you want to accept arbitrary linear equations, then you have to write code to do the preprocessing, such as turning
3*x + 10 = y - 5

into the standard form
 v1  v2   c
(3, -1, -15)

Once you have every equation in canonical form, you pass the coefficients and constants to the existing package.


text:
Q: Equi-continuous sequence of functions bounded at $0$ is uniformly bounded Question: Suppose $f_n : [0,1] \rightarrow \mathbb{R}$ is an equi-continuous sequence of functions and suppose $\lvert f_n(0) \lvert \leq 1$ for all $n$. Then, $\{f_n\}$ is uniformly bounded.
Work so far: Given $\varepsilon>0$, there exists a $\delta > 0$ such that for all $\lvert x \lvert <\delta$, we have: $$\lvert f_n(x) \lvert = \lvert f_n(x) - f_n(0) + f_n(0) \lvert \leq \lvert f_n(x) - f_n(0) \lvert + \lvert f_n(0) \lvert \leq \varepsilon + 1$$
However, this seems like it could potentially bound $\lvert f_n(x) \lvert$ for only a small portion of $[0,1]$, i.e. $x \in (-\delta,\delta)$.
Is there some way to extend this to a cover of open intervals on which $\lvert f_n(x) \lvert$ is bounded, so that we can take advantage of the compactness of $[0,1]$?
At this point I am a bit lost. Any direction would be much appreciated.
Edit: The family of functions is uniformly equi-continuous on $[0,1]$.

A: Hint.
A point $x \in [0,1]$ can be reached by a chain of points starting at $0$ $$0 \le \delta \le 2\delta \le \dots \le n\delta \le x <(n+1) \delta$$ Moreover for all $x \in [0,1]$, you can bound $n$ with $\frac{1}{\delta}+1$.
Note: I would suggest that rather than saying "given $\epsilon > 0$", you pickup one $\epsilon$, like $1$, $\pi$... Or whatever you want as here you only need one $\epsilon$ to work with.

A: You'll want to show that an equicontinuous family of functions on a compact space is uniformly equicontinuous, i.e. that for all $\varepsilon > 0$, there is some $\delta$ such that for all $n$ and $|x-y| \leq \delta$, $|f_n(x)-f_n(y)| < \varepsilon$, that is $\delta$ is independent of $x$. The proof should be similar to proving uniform continuity of continuous functions on compact spaces.
This way, you can keep the $\delta$ the same throughout and chain it to your initial bound. That is, given $\varepsilon > 0$, choose a corresponding $\delta > 0$ and let $n = \lceil \frac{1}{\delta} \rceil$. Then for $x \in [0,1]$, $$|f(x)| \leq \sum_{k=1}^{n}|f(\tfrac{kx}{n})-f(\tfrac{(k-1)x}{n})| + |f(0)| \leq n\varepsilon + 1$$ and so the $f_n$ are uniformly bounded.


text:
Q: Syntax errors creating an ASP.NET page using MonoDevelop I'm using MonoDevelop on Ubuntu to create ASP.NET pages. My code is producing syntax errors.
<%@ Page Language="C#" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
    1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

            <title>index</title>

            <form id="form1" runat="server">

Hello Word!

            </form>

1:/home/ublinuxyu/program/c#/index.aspx(0,0): Error CS1525: Unexpected symbol `<' (CS1525) (index)
    2:/home/ublinuxyu/program/c#/index.aspx(4,4): Error CS1646: Keyword, identifier, or string expected after verbatim specifier: @ (CS1646) (index)

What have I done wrong here?

A: It looks like you set the build action of the aspx file to "Compile" instead of "Content".
You can fix it using the context menu on the file in the solution pad, or by using the property pad when that file is selected.


text:
Q: How can I hide the API calls that a c# app makes? I want to hide Api calls which is used in my c# program from the programs like API Monitor.    (Windows)
whether packers can do this?
I search about this alot but i cant find any thing that can help .
Thanks in advance .

A: You basically bake VPN code into your app.
Make a connection to anywhere in your country, perhaps a list that your code picks one at random each time the app is loaded.
Then when the app makes the calls there all encrypted by the vpn.
For a website you can use Azure or AWS with something like Cloudflare.

A: Probably the only thing that will hide this sort of thing is an obfuscator...


text:
Q: Getting array from php exec() when result is array I have the following code:
$transcribe1 = exec('"C:\path\to\gcloud\gcloud.cmd" ml speech recognize "audio-file.flac" --language-code="en-GB"', $transcribe2);
echo '
'; print_r($transcribe1); echo '
';
echo '
'; print_r($transcribe2); echo '
';
$transcribeArray = json_decode($transcribe1, true);
echo '
'; print_r($transcribeArray); echo '
';

The result is:
Array
(
    [0] => {
    [1] =>   "results": [
    [2] =>     {
    [3] =>       "alternatives": [
    [4] =>         {
    [5] =>           "confidence": 0.880379,
    [6] =>           "transcript": "the text returned from google cloud"
    [7] =>         }
    [8] =>       ]
    [9] =>     }
    [10] =>   ]
    [11] => }
)

The first two print_rs return empty.
All I'm trying to do is get the json returned from gCloud into an array so I can reference it properly in the rest of the code. In other words, an array that looks like this:
[results] => Array(
  [alternatives] => Array(
    [confidence] => "0.880379",
    [transcript] => "the text returned from google cloud"
  );
);

What am I missing?

A: Figured this out with more StackOverflow searching.
exec returns a whole array of stuff it does
shell_exec returns only the result of the execution, in its original format.