text:
Q: Expose Properties file to Java via Spring I am trying to use Spring to allow my Java classes to access a properties file.  I have done quite a bit of googleing and there seems to be several ways of doing this.  I have tried to use two of the different ways, and they are both failing.
Attempt 1
XML
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="location" value=classpath:config.properties />
    <property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>

Java
public class App
{
    @Autowired
    private static Environment env;

    public static void main(String[] args)
    {
        System.out.println(env.getProperty("DatabaseName"));
    }
}

Attempt 2
XML
<util:properties id="myProperties" location="classpath:config.properties"/>

Java
public class App
{
    @Resource(name="myProperties")
    private static Properties myProperties;

    public static void main(String[] args)
    {
        System.out.println(myProperties.getProperty("DatabaseName"));
    }
}

In both cases I get a Null Pointer Exception when calling the "getProperty" method.  I am new to Spring and am guessing I am missing something simple.  In addition to getting these attempts to work, I would like to know what is the "best" way to expose a properties file with Spring.
Thank you in advance for any help.

A: ==applicationContext.xml==
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="location" value=classpath:config.properties />
    <property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>

<bean class="my.pckg.App">
  <property name="databaseName" value="${database.name}"/>
</bean>

==config.properties==
database.name=blah

==my.pckg.App==
public class App {

  private String databaseName;

  public void setDatabaseName(String databaseName) {
    this.databaseName = databaseName;
  }

  public String toString() {
    return "App (databaseName=" + databaseName + ")";
  }

}

==my.pckg.Main==
public class Main {
  public static void main(String [] args) {
    ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    App app = appContext.getBean(App.class);
    System.out.println(app);
  }
}

A: Here is your other way of doing it which seems to be what you want.
==applicationContext.xml==
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">

    <util:properties id="myProperties" location="classpath:config.properties"/>

    <bean class="my.pckg.App">
        <property name="appProperties" ref="myProperties" />
    </bean>
</beans>

==config.properties==
database.name=blah

==my.pckg.App==
package my.pckg;

import java.util.Properties;

public class App {

      private Properties appProperties;

      public void setAppProperties(Properties appProperties) {
          this.appProperties = appProperties;
      }

      public String toString() {
        return "App (databaseName=" + appProperties.getProperty("database.name") + ")";
      }

}

==my.pckg.Main==
package my.pckg;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        App app = appContext.getBean(App.class);
        System.out.println(app);
    }
}


text:
Q: How to serialize a Marshmallow field under a different name I want a Marshmallow Schema  with the following output json -
{
  "_id": "aae216334c3611e78a3e06148752fd79",
  "_time": 20.79606056213379,
  "more_data" : {...}
}

Marshmallow doesn't serialize private members so this is as close as I can get -
class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number()
    id = fields.String()

But I do need the underscores in the output json.
Is there a way to tell Marshmallow to serialize the fields using different names?

A: The accepted answer (using attribute) didn't work for me, possibly because:

Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute. In most cases, you should use data_key instead.

However data_key worked nicely:
class ApiSchema(Schema):
    class Meta:
        strict = True

    _time = fields.Number(data_key="time")
    _id = fields.String(data_key="id")

A: https://marshmallow.readthedocs.io/en/2.x-line/quickstart.html#specifying-attribute-names
Even though the docs are for version 2, this seems to still work as of 3.5.1. The stable version 3 docs will not have this example.
class ApiSchema(Schema):
  class Meta:
      strict = True

  _time = fields.Number(attribute="time")
  _id = fields.String(attribute="id")

A: You can override the dump method to prepend underscores to selected fields before returning the serialised object:
class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number()
    id = fields.String()

    def dump(self, *args, **kwargs):
        special = kwargs.pop('special', None)
        _partial = super(ApiSchema, self).dump(*args, **kwargs)
        if special is not None and all(f in _partial for f in special):
            for field in special:
                _partial['_{}'.format(field)] = _partial.pop(field)
        return _partial

api_schema = ApiSchema(...)
result = api_schema.dump(obj, special=('id', 'time'))

You can also use the post_dump decorator on a separate custom method without having to override dump, but then, you may have to hardcode the fields to-be-modified as part of the class, which may be inflexible depending on your use case.

A: The answer's well documented in Marshmallows api reference.
I need to use dump_to :
class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number(dump_to='_time')
    id = fields.String(dump_to='_id')

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get async await work in airtable api with node js to get all records in the airtable before sending resolve? I am trying to get my record from airtable using async await. What i want is that once airtable has fetched all the records it should return a value 1 which will be assigned to a variable counter. Once value of counter is 1 it can be used to access other data as well. The problem is that since airtable api has a record limit of 1. Even before it reaches all the elements it sets the value of counter to 1. I know this is weird because page function should be called in airtable api before done function unless it has traversed across all the records. Here is my code :
var counter = 0;

async function FirstCall(){
    counter = await backlinksubmissionChecker.getData();
    console.log("Counter value is ",counter);
    if(counter==1){
        counter = await codequalityXP.getData();
        console.log("Counter value is ",counter);
    }
}

my code for airtable api access  is like this
async function getData()
{
    return new Promise((resolve, reject) => {
            console.log("Inside Backlink submission checker");
            var i=0;
            let value =  base("Program XP").select({
            }).eachPage(function page(records, fetchNextPage) {
                records.forEach(function(record) {
                    let recordID =  record.get("RecordID");
                    let email = record.get("Email Address");
                    ConnectStudents(recordID,email);
                 i++;
                });
                fetchNextPage();
            }, function done(err) {
                if (err) {
                console.error(err);
                reject("Promise rejected");
                }else{
                resolve(1);
            }
            });
      });
}

How do I ensure that my airtable api has brought me all the records before it sends a resolve promise which tells that it has traversed through all records.

A: It looks like you are using Airtable's NodeJS SDK.  There's a built in function for selecting all records which I think simplifies your code greatly and decreases the risk of other errors.
async function getData() {
  console.log("Inside Backlink submission checker");
  const records = await base('Program XP').select().all();

  var i = 0;
  records.forEach(function(record) {
      let recordID =  record.get("RecordID");
      let email = record.get("Email Address");
      ConnectStudents(recordID,email);
      i++;
  });

  return 1;
}

getData()
  .then((res)=>console.log("DONE: ", res))
  .catch((err)=>{console.log("ERR: ", err)});

The problem is that since airtable api has a record limit of 1

The GET method for Airtable's API returns 1 page at a time with a default of 100 records per page.  If you have less than 100 records in the table you are making the GET request to, then it will return all records in a single call.
If your ConnectStudents function is asynchronous, it may not be fully processing each record, but it does look like the Airtable API is returning all of the records to your system.


text:
Q: Crashlytics: integrating a crash reporter into an Appgyver Steroids JS application How would we integrate the cordova crashlytics plugin to our steroids application. We are developing the application using eclipse sts and we've already installed it with crashlytics plugin. We also created an account on fabric but we are stuck on step 2 which is to launch your app. It seems that steroids application is not considered as android application. What shall we do to incorporate crashlytics?

A: Check out this documentation for plugins.
You need to build a scanner app using the Appgyver build service with your custom cordova plugin included.
Then you can scan the QR code generated by steroids connect and the plugin will be there.
You can test to see if it's there by debugging in the dev tools of your browser (Chrome for Android builds and Safari for iOS builds).
You can type typeof navigator.crashlytics or however the plugin is referenced in JS. Maybe window.plugins.navigator.crashlytics.
Based on the documentation it looks like it should be part of the navigator object after installing.
One example of including a plugin in a build is to go to the build settings for your application for the device you want to target (Android build in your case or iOS build) and scroll down to the plugins area. Add the plugin like this:
[
    "source":"https://github.com/4sh-projects/cordova-crashlytics-plugin.git"
]


text:
Q: Postfix: "Relay access denied" I've been trying to set up a mail server, with dovecot, postfix, opendkim, and spamassassin. After some hassle I managed to get incoming mail working (I signed up for this account with the email!). However, outgoing mail just doesn't work--I tested this by sending from this new email to my old Protonmail account and got an error. Again, it works with incoming mail--sending from that old email to my new one. Sending was tested with Neomutt using msmtp as its mail sending command.
I've got a relayhost that goes to port 587 of my domain. This is because my ISP is fat and blocks port 25 for some reason. Anyways, here's the log messages I get when sending an email:
postfix/submission/smtpd[57255]: NOQUEUE: reject: RCPT from unknown[192.168.86.1]: 454 4.7.1 <my@oldema.il>: Relay access denied; from=<swurl@newdoma.in> to=<my@oldema.il> proto=ESMTP helo=<mail.doma.in>
postfix/smtp[57263]: E45589003B2: to=<my@oldema.il>, relay=MY.IP[MY.IP]:587, delay=0.2, delays=0.14/0.02/0.02/0.02, dsn=4.7.1, status=deferred (host MY.IP[MY.IP] said: 454 4.7.1 <my@oldema.il>: Relay access denied (in reply to RCPT TO command))
postfix/submission/smtpd[57255]: disconnect from unknown[192.168.86.1] ehlo=2 starttls=1 mail=1 rcpt=0/1 data=0/1 rset=1 quit=1 commands=6/8

postconf -n:
alias_database = $alias_maps
alias_maps = hash:/etc/postfix/aliases
command_directory = /usr/bin
compatibility_level = 3.6
daemon_directory = /usr/lib/postfix/bin
data_directory = /var/lib/postfix
debug_peer_level = 2
debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5
home_mailbox = Mail/Inbox/
html_directory = no
inet_protocols = ipv4
mail_owner = postfix
mailbox_command = /usr/lib/dovecot/deliver
mailq_path = /usr/bin/mailq
manpage_directory = /usr/share/man
meta_directory = /etc/postfix
milter_default_action = accept
milter_protocol = 6
mydestination = $myhostname, $mydomain, localhost, localhost.localdomain, 127.0.0.1, MY.IP
mydomain = doma.in
myhostname = mail.doma.in
mynetworks = , 127.0.0.0/8 [::1]/128 MY.IP/32 MY.PRIVATE.IP MY.IP
newaliases_path = /usr/bin/newaliases
non_smtpd_milters = inet:127.0.0.1:12301
queue_directory = /var/spool/postfix
readme_directory = /usr/share/doc/postfix
relay_domains = $mydestination
relayhost = [MY.IP]:587
sample_directory = /etc/postfix
sendmail_path = /usr/bin/sendmail
setgid_group = postdrop
shlib_directory = /usr/lib/postfix
smtp_tls_CAfile = /etc/letsencrypt/live/doma.in/cert.pem
smtp_tls_loglevel = 3
smtp_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtp_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtp_tls_security_level = may
smtpd_milters = inet:127.0.0.1:12301
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = private/auth
smtpd_sasl_security_options =
smtpd_sasl_tls_security_options =
smtpd_sasl_type = dovecot
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /etc/letsencrypt/live/doma.in/fullchain.pem
smtpd_tls_exclude_ciphers = aNULL, LOW, EXP, MEDIUM, ADH, AECDH, MD5, DSS, ECDSA, CAMELLIA128, 3DES, CAMELLIA256, RSA+AES, eNULL
smtpd_tls_key_file = /etc/letsencrypt/live/doma.in/privkey.pem
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtpd_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtpd_tls_security_level = may
tls_preempt_cipherlist = yes
unknown_local_recipient_reject_code = 550

it's listening on port 587:
# lsof -i -P -n|grep 587
...
master    57239      root   94u  IPv4 970320      0t0  TCP *:587 (LISTEN)
smtpd     57364   postfix    6u  IPv4 970320      0t0  TCP *:587 (LISTEN)
smtpd     57367   postfix    6u  IPv4 970320      0t0  TCP *:587 (LISTEN)
smtpd     57371   postfix    6u  IPv4 970320      0t0  TCP *:587 (LISTEN)
smtpd     57374   postfix    6u  IPv4 970320      0t0  TCP *:587 (LISTEN)

why am I getting this error? I've gone through several other questions where this was asked, notably:

*

*https://serverfault.com/questions/42519/how-to-correct-postfix-relay-access-denied

*https://serverfault.com/questions/711588/postfix-relay-access-denied-how-to-fix-it

*Relay access denied when using SMTP to external recipients POSTFIX FREEBSD
None of those helped, though

A: I finally fixed this by adding 192.168.86.0/24 to mynetworks. I've got another problem but I'll open up a new question for that.


text:
Q: Find the area bounded with the curve $x=1+t-t^3, \ \ y=1-15t^2.$
Find the area bounded with the curve $$x=1+t-t^3, \ \ y=1-15t^2.$$

I drew its graph and looks like this:

It seems to be symmetric about $x=1$. So, the idea that came to me was to cut by half and study any of the pieces. However, I don't know how... Any help is appreciated.

A: If $1+t-t^3=1+u-u^3,\,1-15t^2=1-15u^2,\,t\ne u$ then$$t\ne0,\,u=-t,\,1+t-t^3=1-t+t^3\implies 2t(1-t^2)=0\implies t=\pm1.$$So the area is from $t=-1$ to $t=1$. As $t$ increases from $-1$ to $0$, we trace out the left-hand part of the area's circumference; from $t=0$ to $t=1$, we follow the right-hand part. The shape vertically stretches from $t=\pm1,\,y=-14$ to $t=0,\,y=1$. From $y$ to $y+dy=y-30tdt$, a strip exists of width $2t(1-t^2)$, so the area is$$\int_0^160t^2(1-t^2)dt=60\int_0^1(t^2-t^4)dt=8.$$As a sanity check, the area fits in a rectangle of height $15$ and width $4/(3\sqrt{3})$ (because $x$ is extremised at $t=\pm1/\sqrt{3},\,x=1\mp2/(3\sqrt{3})$), so of area $20/\sqrt{3}>8$.

A: Cut the curve into left and right values for $x$ at each $y$ and make use of the symmetry.
$$ {{\int_{-14}^{1} x_r-x_\ell\,\mathrm d y }={2\int_0^1 (x(t)-1)\,\left\lvert\frac{\mathrm d y(t)}{\mathrm d t}\right\rvert\,\mathrm  d t}}$$


text:
Q: Is it possible to access connection string which defined in a C# class using Entity Framework? I need to use entity framework in a application and I need to set username and password in connection string within web.config file from user inputs.Now I need to know how I can access to connection string where placed in web.config from a C# class that I define to reads inputs and set them in connection string?
Can I define a connection string within a C# class and entity framework use it?

A: I've not tested this code, but I think it's pretty close to the solution:
public static class ConnectionStrings
{
    public const string MyConnectionStrinGoesHere = "My connection string goes here";
}

public class Context : DbContext
{
    public Context(string connectionString) : base(connectionString) { }
}

public class ConnectionStringFromClassContext : Context
{
    public ConnectionStringFromClassContext() : base(ConnectionStrings.MyConnectionStrinGoesHere)
    {

    }
}

In your program you can than use:
private static void Main(string[] args)
{
    ConnectionStringFromClassContext context = new ConnectionStringFromClassContext();
}

And you'll pass the connectionstring defined in the static class.


text:
Q: Failed to run zmq I have a java code but I need to enhance it using zmq libraries.
After adding the relevant libraries, I get the below error when running the code. The image (libjzmq.dylib) which they say is not found is present under the lib directory.
Has anyone faced this issue before and point me in the right direction. I am running this on my Mac. The files present in the Lib dir relevant to zmq are  :

libjzmq.0.dylib libjzmq.a libjzmq.dylib libjzmq.la libthrift-0.9.0.jar
  jython-2.5.2.jar zmq.jar


text:
Q: Solr and Lucene, including in web application I want to add simple search functionality into an existing Java web application.
Search should be done on existing database fields.
It is an web-applicaiton deployed on wildfly, REST-Services and MySql-DB.
After some research, my first impression was, using Solr I will get what I want.
BUT: As I'am not allowed to deploy one more application to customers environments, Solr doesn't fit any more.
As I understood, there are two ways to fix this:

*

*Using EmbeddedSolr

*"Self-build solr" (http://javaskeleton.blogspot.de/2011/07/adding-solr-to-existing-web-application.html)

Which way should I go, to implement search to my web-app ?
Or should I switch to Lucene ?

A: The 2nd way seems old and although the post seems to be removed I think I got what the author meant, from the title.
IMO the 1st way is better because you will be using Solr as it should be used, as a black box, without mixing up things with your webapp.
Having said that, keep in mind that the embedded solr isn't a good choice for a production environment because it is a standalone module, mainly not scalable.
I suggest you to write your Solr client code in a decoupled way: your webapp should deal only with SolrServer abstract class. Behind the scenes  you'll instantiate an EmbeddedSolrServer at the moment. Later, if you want to scale your search service, this design will let you to switch to another impl (LBHttpServer, SolrCloud) with a small refactoring effort.

A: So I will describe my way that I've chosen.
First of all, yes Lucene is my friend.
In my web-app I creaded an @WebListener. This will create one Index, and delete it if already exists, at start of my web-app.
The content of the Index are some database-filed values of three Objects, that have to be searched.
In my SearchService(REST) I build up my QuerySearch, and acces this Index.
Additonally I want extend existing REST-Services (not yet done). So when editing objectTypes (CUD) included in Index, the Index have to be update.
Feel free, to give me some suggestions or best practices.


text:
Q: Euler equation: momentum conservation in terms of enthalpy? So I stumbled upon this equation:
$\frac{\partial h v}{\partial t}= - \nabla(hv \cdot v)- \nabla P$
where $h$ is enthalpy, $v$ is fluid velocity, $t$ time, and $P$ pressure.
It seems to have the form of the momentum conservation equation in hydrodynamics. However I don't understand the use of enthalpy here. It makes sense to me to replace enthalpy in energy density but not in momentum. I can't find anything online about this.
The source of this equation is equations 2 and 3 in http://arxiv.org/pdf/1008.4806v1.pdf

A: The enthalpy flux balance equation is in essence a transport equation. Its use over the more familiar enthalpy balance equation has to do with a breakdown of the diffusive approximation for transport phenomena in cases where the mean free-path of the fluid particles becomes comparable to the typical length-scale of fluid. That is, transport phenomena can be well approximated by diffusive processes, to which the usual enthalpy balance equation applies, only as long as the diffusion velocity in the fluid is much lower than the particle velocity in the fluid flow. The problem considered in the paper lies well outside this regime, hence their use of the enthalpy flux equation instead.


text:
Q: Java-Sandbox example throwing java.lang.NoClassDefFoundError Anyone with experience using Java-Sandbox, I have implemented one of the basic examples found in the documentation but i cant get it working.
Code:
SandPlayground.java
import java.util.concurrent.TimeUnit;
import net.datenwerke.sandbox.*;
import net.datenwerke.sandbox.SandboxContext.AccessType;
import net.datenwerke.sandbox.SandboxContext.RuntimeMode;
import net.datenwerke.sandbox.SandboxedEnvironment;

public class SandPlayground {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("Running...");

        SandboxService sandboxService = SandboxServiceImpl.initLocalSandboxService();

        // configure context
        SandboxContext context = new SandboxContext();
        //context.setRunRemote(true);
        context.setRunInThread(true);
        context.setMaximumRunTime(2, TimeUnit.SECONDS, RuntimeMode.ABSOLUTE_TIME);
        context.addClassPermission(AccessType.PERMIT, "java.lang.System");
        context.addClassPermission(AccessType.PERMIT, "java.io.PrintStream");

        //run code in sandbox
        SandboxedCallResult<String> result = sandboxService.runSandboxed(MyEnvironment.class, context, "This is some value");

        // output result
        System.out.println(result.get());

    }

}

MyEnvironment.java
import net.datenwerke.sandbox.SandboxedEnvironment;
public class MyEnvironment implements SandboxedEnvironment<String> {

    private final String myValue;

    public MyEnvironment(String myValue){
       this.myValue = myValue;
    }

    @Override
    public String execute() throws Exception {
       /* run untrusted code */
       System.out.println(myValue);

       /* return some value */
       return "This is a different value";
    }
}

And I'm getting the error:
EDIT: I've included the dependencies, but I'm still getting some errors:
With the code above I get:
Exception in thread "main" net.datenwerke.sandbox.exception.SandboxedTaskKilledException: killed task as maxmimum runtime was exceeded
    at net.datenwerke.sandbox.SandboxMonitorDaemon.testRuntime(SandboxMonitorDaemon.java:82)
    at net.datenwerke.sandbox.SandboxMonitorDaemon.run(SandboxMonitorDaemon.java:57)
    at java.lang.Thread.run(Thread.java:724)

and when i remove the context.setMaximumRunTime() call, I get:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/map/IdentityMap ...

Any help is much appreciated.

A: most likely you are missing the javassist library (see the documentatio of the sandbox for dependencies: http://blog.datenwerke.net/p/the-java-sandbox.html). You'll find the javassist library on sourceforge at: https://sourceforge.net/projects/jboss/files/Javassist/
The javaassist library is used to remove finalizers in loaded code. This can be turned off in the sandbox context:
contex.setRemoveFinalizers(false)

Hope this helps.


text:
Q: Is there any way to still use APIs lower than 26 as target SDK in Android Studio Specifically I wanted to use API 24 for my project. So this is what I set in build.gradle.

Now as you can see, Android Studio is forcing the use of API level 26 or higher. I only have API 24 and below installed. I don't want to download more APIs because what I am trying to develop is an in-house app and won't be needed to be uploaded in Google Play.
So is there a procedure so that Android Studio can accept this settings and override the requirement?

A: From official documentation, https://developer.android.com/distribute/best-practices/develop/target-sdk

Why target newer SDKs? Every new Android version introduces changes
that bring significant security and performance improvements as well
as enhance the user experience of Android overall. Some of these
changes only apply to apps that explicitly declare support through
their targetSdkVersion manifest attribute (also known as the target
API level).
Configuring your app to target a recent API level ensures that users
can benefit from these improvements, while still allowing it to run on
older Android versions. Targeting a recent API level also allows your
app to take advantage of the platform's latest features to delight
your users. Furthermore, as of Android 10 (API level 29), users see a
warning when starting an app for the first time if the app targets
Android 5.1 (API level 22) or lower.


text:
Q: Turning $\frac{2x-y}{2x+y}\frac1{\left(1-\frac{y}{2x}\right)^2}$ into $\frac1{\frac{y}{x}(1-\frac{y}{2x})+(1-\frac{y}{2x})^2}$ I stopped at this equality in the solution of a question in my book
$$\left(\frac{2x-y}{2x+y}\right)\left(\frac{1}{\left(1-\frac{y}{2x}\right)^2}\right) = \frac{1}{\big( \frac{y}{x}\big) \Big(1-\frac{y}{2x} \Big) +\Big( 1-\frac{y}{2x}\Big)^2}$$
I already verified that starting in R.H.S will give the L.H.S but I am wondering how can we simplify the "L.H.S" to arrive to the R.H.S ?

A: Hint:
Let $t= {y\over 2x}$ and express $y= t\cdot 2x$. Now put this $y$ in to your equation...

Now $$LHS = {2x-2xt\over 2x+2xt}\cdot {1\over (1-t)^2} = {1\over 1-t^2} $$
and $$RHS = {1\over 2t(1-t)+(1-t)^2} = {1\over (1-t)(2t+1-t)}=...$$

A: Divide top and bottom by $2x-y$. The numerator becomes 1 and the denominator becomes
$$\frac{2x+y}{2x-y}\left(1-\frac{y}{2x}\right)^2$$
$$=\frac{1-\frac{y}{2x}+\frac{y}{x}}{1-\frac{y}{2x}}\left(1-\frac{y}{2x}\right)^2$$
$$=\frac{y}{x}\left(1-\frac{y}{2x}\right)+\left(1-\frac{y}{2x}\right)^2$$


text:
Q: Web server is shut down - jqGrid behaves as if nothing were wrong I use jqGrid 4.5.4 for data editing: records are edited in a dialogue (i.e. it's not inline editing).
In the edit options I have reloadAfterSubmit:false and closeAfterEdit:true. When a user attempts to modify a record, and an error happens on the server, the dialogue stays open and shows an error message to the user (it's a correct behaviour).
However, when the web server is down (i.e. I open the page and then I shut down the web server), the grid behaves as if there is no problem at all: the dialogue gets closed and the new values appear in the grid. It's a very confusing behaviour: the user may think that s/he updated the data in the DB. I have the same problem with adding and deleting records.  Is there a way to fix it?

A: When web server is shut down, all HTTP responses have the Aborted status in Firebug. In JavaScript code, they can be recognized by the 0 HTTP status code.
One way to fix the problem described in the question is catching all Aborted responses in the jQuery's global ajaxError event handler and displaying an error page. I use code similar to the following:
var documentIsUnloaded = false;

$(document).ready(function() {
    $(document).ajaxError(ajaxErrorHandler);

    // `Aborted` responses can also happen when a user leaves a
    // page before an AJAX request is completed. We need to avoid these instances.
    $(window).bind('beforeunload', function(){
        // The user left the page; there is no need to show the error page
        documentIsUnloaded = true;
    });
});

function ajaxErrorHandler(event, jqxhr, settings, exception) {

    if(documentIsUnloaded) {
        return; // the user left the page; there is no need to show the error page
    }

    if(jqxhr.status == 0) {
        // display error page here!
    }
}

Another way to fix the problem is using jqGrid's afterSubmit callback:
function afterSubmitCallback(response, postdata) {
    if(response.status == 0) {
        return [ false, "Cannot connect to the server.", 0 ];
    }
    else {
        return [ true, "", 0 ];
    }
}

This callback should be registered in Add, Edit and Delete options in jqGrid (afterSubmit:afterSubmitCallback). jqGrid will show the error message in the Add/Edit/Delete dialogue.


text:
Q: how to locate fxml from another package? I have created a simple JavaFX application.

It has two packages the main class is JFXTest2.java  is in good package and the fxml and it's controller are in JFXTest2 package.
now the problem is that i can not load the fxml in the main class. I tried loading the
fxml like this:
Parent root = FXMLLoader.load(getClass().getResource("jfxtest2.Screen.fxml"));

and
Parent root = FXMLLoader.load(getClass().getResource("jfxtest2/Screen.fxml"));

and also
Parent root = FXMLLoader.load(new URL("/jfxtest2/Screen.fxml"));

but none of them worked.So how should i load the fxml from JFXTest2 package in the the JFXTest2 class which is the main class or application class.

A: You need to use
getClass().getClassLoader().getResource("/jfxtest2/Screen.fxml")

A: Try
Parent root = FXMLLoader.load(getClass().getResource("/jfxtest2/Screen.fxml"));

A: For me nothing worked besides this:
Parent root = FXMLLoader.load(getClass().getResource("..//jfxtest2//Screen.fxml"));


text:
Q: Is it possible to pass a String parameter to viewModel from Android xml Is it possible to pass a String parameter on a button click of XML file to  the methods of the ViewModel file as like below
 android:onClick="@{v -> viewModel.postFeedRequest(@string/show_details)}"

I tried like above I am getting the binding error.
Can anyone post an example on this?

A: Try this:
 android:onClick="@{() -> viewModel.postFeedBackRequest(AppConstant.WithStringResource)}"

where AppConstant is your class and WithStringResource is your String constant with the value you want to send.
Update:
You can also directly send the string like this:
android:onClick='@{() -> viewModel.postFeedBackRequest("WithStringResource")}'

Or
 android:onClick="@{() -> viewModel.postFeedRequest(@string/show_details)}"

A: Do like this
In viiew model
  fun onClickFunction(num:String) {
            edExtnNumber.set(edTextField.get()+""+num)
        }

and in xml
android:onClick="@{() -> viewModel.onClickFunction(@string/value)}">


text:
Q: How detect NFC payment on app? Is it possible to detect when an Android, with payment app on it, is used to make a payment by tapping the NFC reader?  (For example, going on a bus or train.)
Can you register or detect in some way such NFC events/payments on the phone (ie, payments processed by some other app on the phone)?


text:
Q: At what mode does a stretched string oscillate in a free oscillation? I am unclear that when a stretched string oscillates , does it oscillate in its fundamental or in its overtones. And I want to know whether there are any instances where a stretched string oscillate in one of its overtones as its natural frequency?

A: A string played on a musical instrument will oscillate in a mix of its harmonics, although its fundamental frequency will usually be the loudest single component. The exact mix of harmonics will depend on whether the string is plucked, bowed or struck with a hammer; the place on the string where it is plucked, bowed or struck; and the force with which it is plucked, bowed or struck (the "velocity"). In addition, the body of the instrument (known as its "sound box") will resonate with certain frequencies and amplify them, changing the quality or "timbre" of the note.


text:
Q: How to set home directory mount point for drive I have 2 drives on my machine, but one is unused. I would like to use the unused drive for the home partition (as in moving my current home directory into the unused drive). Is this possible without reinstallation and if so how do I go about doing it?

A: During this process, you should avoid using directory /home by any application, so it's best to not login from GUI, but from the text console (available after pressing Ctrl+Alt+F3 key).
Perform everything with root permissions (run sudo -i first).
Create a partition on the unused drive (using fdisk) and format it (create a filesystem) using mkfs.
Rename directory /home to /old_home. Create a new, empty
directory /home, with the same owner and permissions as /old_home.
Mount the new partition you just formatted under /home, For example if the new partition is /dev/sdb1, use the command mount /dev/sdb1 /home.
Copy everything from /old_home to /home, preserving ownership, permissions etc. (you may use rsync for that as mentioned in the comment above: rsync -a /old_home/ /home/).
Edit /etc/fstab file so that your new /home will be automatically mounted when the system reboots. Your /etc/fstab currently contains a line for the drive you are already using, it might be something like this (I'm making this one up now, yours may be different):
/dev/sda1 / ext4 defaults 0 1

Add a similar line for your new partition that says for example:
/dev/sdb1 /home ext4 defaults 0 2

(if your file has something else instead of "defaults" just copy these parameters to the new line).
Reboot your system (shutdown -r now) and after reboot check if everything is working properly (ie. everything that should be under /home is there). If yes, then delete the /old_home directory - it's not needed anymore.


text:
Q: Solution of $u_t=\mathcal{F}u$ I tried to solve the equation $u_t=\mathcal{F}u$, where $\mathcal{F}$ denotes the Fourier transform, with initial data $u(x,0)=u_0(x)$. The solution should be given by
$$
u(x,t)=e^{\mathcal{F}t}u_0=\left(\sum_{j\geq0}\frac{\mathcal{F}^jt^j}{j!}\right)u_0(x)
$$
and I looked for an explicit expression of it in terms of $u_0$. Since $\mathcal{F}^2=(\cdot)^\check{}$ (the operator that maps $v(x)\mapsto\check{v}(x):=v(-x)$), we have that $\mathcal{F}^3=\mathcal{F}^{-1}$ and $\mathcal{F}^4=id$. Suppose $u_0$ is a Schwartz function so all of this makes sense. Then we have
$$
u(x,t)=\left(\sum_{j\in4\mathbb{N}}\frac{t^j}{j!}+\sum_{j\in1+4\mathbb{N}}\frac{t^j}{j!}\mathcal{F}+\sum_{j\in2+4\mathbb{N}}\frac{t^j}{j!}(\cdot)\check{}+\sum_{j\in3+4\mathbb{N}}\frac{t^j}{j!}\mathcal{F}^{-1}\right)u_0(x)
$$
Next i wrote the function $u_0=\phi+\psi$, where $\phi$ is even and $\psi$ is odd, namely
$$
\phi(x)=\frac{1}{2}(u_0(x)+u_0(-x))\quad\text{and}\quad\psi(x)=\frac{1}{2}(u_0(x)-u_0(-x))
$$
In this way (recalling that Fourier transform of an even function is odd and viceversa) one computes
$$
u(x,t)=\sum_{j\in\mathbb{N}}\frac{t^{2j}}{(2j)!}\phi(x)+\sum_{j\in\mathbb{N}}(-)^j\frac{t^{2j}}{(2j)!}\psi(x)+\sum_{j\in\mathbb{N}}(-)^j\frac{t^{2j+1}}{(2j+1)!}\mathcal{F}\phi(x)+\sum_{j\in\mathbb{N}}\frac{t^{2j+1}}{(2j+1)!}\mathcal{F}\psi(x)
$$
which equals
$$
u(x,t)=\cosh(t)\phi(x)+\cos(t)\psi(x)+\sin(t)\mathcal{F}\phi(x)+\sinh(t)\mathcal{F}\psi(x).
$$
The problem is that now, trying to check
$$
u_t(x,t)=\sinh(t)\phi(x)-\sin(t)\psi(x)+\cos(t)\mathcal{F}\phi(x)+\cosh(t)\mathcal{F}\psi(x)
$$
and
$$
\mathcal{F}u(x,t)=\cosh(t)\mathcal{F}\phi(x)+\cos(t)\mathcal{F}\psi(x)+\sin(t)\phi(x)-\sinh(t)\psi(x)
$$
they are not equal. Is my calculation wrong? Every help is extremely appreciated.

A: As you noted, $\mathcal{F}^4=I$. So
$$
   (1-\lambda^4)I=(\mathcal{F}^4-\lambda^4 I)=(\mathcal{F}-\lambda I)(\mathcal{F}^3+\lambda\mathcal{F}^2+\lambda^2\mathcal{F}+\lambda^3I)
$$
which gives
$$
    (\lambda I-\mathcal{F})^{-1}=\frac{1}{\lambda^4-1}(\mathcal{F}^3+\lambda \mathcal{F}^2+\lambda^2\mathcal{F}+\lambda^3 I)
$$
So, the following is evaluated by computing residues at $1,i,-1,-i$:
$$
    e^{t\mathcal{F}}=\frac{1}{2\pi i}\oint_{C}e^{\lambda t}(\lambda I-\mathcal{F})^{-1}d\lambda \\
  =\frac{1}{2\pi i}\oint_{C}\frac{e^{\lambda t}(\mathcal{F}^3+\lambda\mathcal{F}^2+\lambda^2\mathcal{F}+\lambda^3I)}{(\lambda-1)(\lambda-i)(\lambda+1)(\lambda+i)}d\lambda
$$


text:
Q: Remove block from ArrayList of blocks that are being drawn to the screen without crashing I am a beginner Android developer and I am trying to make a game where you move a bat (catcher) along the bottom of the screen and you have to catch falling blocks.
I am struggling currently with the collision detection. The collision detection itself is working correctly but when I then try to remove the block that is falling the game crashes.
The problem code is the line under the "remove block" comment in the checkCollisions() method but I have posted the whole GameView below for clarity.
Here is the code:
package com.mattdrewery.supercatch;

import android.view.View;
import android.view.MotionEvent;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import java.util.Random;
import java.util.ArrayList;

public class GameView extends View
{
private Catcher catcher;
private ArrayList<NormalBlock> blocks;
private Random rand;
private int screenWidth;
private int screenHeight;
private boolean gameOver;
private int updateCount;

public GameView(Context context)
{
    super(context);
    setFocusable(true);

    updateCount = 1;

    // Set gameOver to false
    gameOver = false;

    // Create the ArrayList of normal blocks
    blocks = new ArrayList<NormalBlock>();

    // Create a random number generator
    rand = new Random();

    // Create the catcher
    catcher = new Catcher(context, R.drawable.catcher, 230, 250);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
    screenWidth = this.getWidth();
    screenHeight = this.getHeight();
}

@Override
protected void onDraw(Canvas canvas)
{
    updateCatcher();
    checkCollisions();
    updateBlocks();

    // Draw the catcher to the canvas
    canvas.drawBitmap(catcher.getImage(), catcher.getPosX(), catcher.getPosY(), null);

    // For each normal block in the block array
    for (NormalBlock block : blocks)
    {
        // Draw block to the canvas
        canvas.drawBitmap(block.getImage(), block.getPosX(), block.getPosY(), null);
    }

    // Redraw the screen
    invalidate();
}

@Override
public boolean onTouchEvent(MotionEvent event)
{
    // Get the action from the touch screen
    int eventAction = event.getAction();

    int X = (int) event.getX();

    // If the user presses on the screen....
    if (eventAction == MotionEvent.ACTION_DOWN)
    {
        if (X < screenWidth / 2)
        {
            catcher.setMovingLeft(true);
            catcher.setMovingRight(false);
        }
        else
        {
            catcher.setMovingLeft(false);
            catcher.setMovingRight(true);
        }
    }

    if (eventAction == MotionEvent.ACTION_MOVE)
    {
        if (X < screenWidth / 2)
        {
            catcher.setMovingLeft(true);
            catcher.setMovingRight(false);
        }
        else
        {
            catcher.setMovingLeft(false);
            catcher.setMovingRight(true);
        }
    }

    if (eventAction == MotionEvent.ACTION_UP)
    {
        catcher.setMovingLeft(false);
        catcher.setMovingRight(false);
    }

    return true;
}

private void updateCatcher()
{
    // Check whether the catcher is moving and update position accordingly
    if (catcher.isMovingLeft())
    {
        catcher.moveLeft();
        if (catcher.getPosX() < 0)
        {
            catcher.setPosX(0);
        }
    }
    else if (catcher.isMovingRight())
    {
        catcher.moveRight();
        if (catcher.getPosX() > (screenWidth - catcher.getImage().getWidth()))
        {
            catcher.setPosX(screenWidth - catcher.getImage().getWidth());
        }
    }
}

private void updateBlocks()
{
    updateCount++;

    if (updateCount >= 100)
    {
        updateCount = 1;
        blocks.add(new NormalBlock(getContext(), R.drawable.nblock,
                rand.nextInt(screenWidth - 20), 0));
    }

    // For each normal block in the block array
    for (NormalBlock block : blocks)
    {
        // Check if block has hit the bottom of the screen
        if (block.getPosY() + block.getImage().getHeight() > screenHeight)
        {
            gameOver = true;
        }
        else
        {
            // Drop the block down
            block.dropDown();
        }
    }
}

private void checkCollisions()
{
    // Get Rectangle for the catcher
    Rect catcherRect = new Rect(catcher.posX, catcher.posY,
            catcher.posX + catcher.image.getWidth(),
            catcher.posY + catcher.image.getHeight());

    // For each block in the array
    for (NormalBlock block : blocks)
    {
        // Get Rectangle for the current block
        Rect blockRect = new Rect(block.posX, block.posY,
                block.posX + block.image.getWidth(),
                block.posY + block.image.getHeight());

        if (Rect.intersects(catcherRect, blockRect))
        {
            // Remove block
            blocks.remove(block);
        }
    }

}

public int getScreenHeight()
{
    return screenHeight;
}

public int getScreenWidth()
{
    return screenWidth;
}

}
Thanks in advance,

A: Try replacing for (NormalBlock block : blocks) with this:
int count = blocks.size();
 for (int i=0;i<count;i++){
    Block block = blocks.get(i);

I'm guessing you were getting a ConcurrentModificationException there.


text:
Q: Unable to parse Json Object in Java Below is the sample code:
    import org.json.JSONArray
    import org.json.JSONObject

    JSONObject jsonObject = new JSONObject("{\"Status\":200,\"Description\":\"Success\",\"Result\":\"{\\\"Id\\\":\\\"ABCD123\\\",\\\"clientId\\\":\\\"0c34c71c\\\",\\\"status\\\":\\\"Finished\\\",\\\"message\\\":\\\"Done\\\",\\\"type\\\":\\\"registration\\\"}\"}")

    /*
     here I want to do something like:
       JSONObject innerJsonObj = (JSONObject) jsonObject.get("Result");
       String id = innerJsonObj.get("clientId");
    */

On executing JSONObject innerJsonObj = (JSONObject) jsonObject.get("Result"); - it gives:
Exception in thread "main" java.lang.ClassCastException: Cannot cast object '{"Id":"ABCD123","clientId":"0c34c71c","status":"Finished","message":"Done","type":"registration"}' with class 'java.lang.String' to class 'org.json.JSONObject'
So what modification I need to do for fetching the values present in nested JsonObject( i.e Result)

A: Your JSON:
{
    "Status": 200,
    "Description": "Success",
    "Result": "{\"Id\":\"ABCD123\",\"clientId\":\"0c34c71c\",\"status\":\"Finished\",\"message\":\"Done\",\"type\":\"registration\"}"
}

As you can see, the value of Result is a string, not a JSON object.
So you'd need to create a new JSONObject from that string:
JSONObject jsonObject = new JSONObject("{\"Status\":200,\"Description\":\"Success\",\"Result\":\"{\\\"Id\\\":\\\"ABCD123\\\",\\\"clientId\\\":\\\"0c34c71c\\\",\\\"status\\\":\\\"Finished\\\",\\\"message\\\":\\\"Done\\\",\\\"type\\\":\\\"registration\\\"}\"}");

JSONObject innerJsonObj = new JSONObject(jsonObject.getString("Result"));
String id = innerJsonObj.getString("clientId");


text:
Q: Iterate over string array I'm getting this string[]

but when I iterate over it
subUrl(arr) {
        for(let i of arr) { console.log(i); }
}

It isn't logging anything. What's wrong?

A: Your data is an array inside array,  you need two loops
   for (let firstarray of arr){
       for (let i of firstarray ){
          console.log(i);
       }
    }


text:
Q: Sound device in Ubuntu through VMWare (Windows 7 host) I am using VMWare on Windows 7 to run Ubuntu 10.10.
I'm trying to interact with the sound device through Ubuntu, but there is no /dev/dsp or /dev/audio or similar. I do hear sound coming from the system so somehow VMWare is piping it through, but I do not know what device to use to generate my own from my program, or how to get the system to create one that I can use.  Has anyone dealt with this issue before?
Many thanks!

A: Turns out this problem is due to pulseaudio being used in the latest versions of Ubuntu.  The solution that worked for me is to use padsp to run my executable which tricks it into thinking there's a /dev/dsp device for it to use, while it's actually redirecting sound to itself.
The issue had nothing to do with VMWare, but with an update in Ubuntu!
http://linux.die.net/man/1/padsp

A: May be that VMWare is presenting a soundcard supported by ALSA, in which case it is at /dev/snd/
I've never tried developing sound software in VMWare... TBH I think its sound support is a little squirrelly.  I like VirtualBox's sound support better, even if it does have 1/10th second or so latency.  I found VMWare's sound tended to crackle and occasionally play at the wrong speed on my HP DV7 laptop when running Vector as a browsing appliance.


text:
Q: Unable to consume JSON REST WS I have an api which is working fine when it comes to XML post request. the XML is recieved in the Post body and processed accordingly. Here is the header of method
@POST
@Path ("{"+num+"}/"+STATUS+"."+XML)
@Consumes (MediaType.APPLICATION_XML)
@Produces (MediaType.APPLICATION_XML)
public Response getStatusXML (@PathParam(num) String num,
        JAXBElement<OrderStatusRequestType> jaxbOrderStatusRequestType,
        @Context UriInfo requestUriInfo,
        @Context SecurityContext securityContext){

    OrderStatusRequestType orderStatusRequestType = jaxbOrderStatusRequestType.getValue();

    return processRequest (num, XML, orderStatusRequestType, securityContext);
}

This WS is called with this POST body
<orderStatusRequest>
    <vendor>32658</vendor>
    <key>232X1</key>
</orderStatusRequest>

I have XML schema for that and this request is working fine as per requirement. I get the jaxbObject and i get the orderStatusRequest as well. However, When i try to call my json webservice, I get null orderStatusRequest. I have a separate method to consume json.
@POST
@Path ("{"+num+"}/"+STATUS+"."+JSON)
@Consumes (MediaType.APPLICATION_JSON)
@Produces (MediaType.APPLICATION_JSON)
public Response getStatusJSON(@PathParam(num) String num,
        JAXBElement<OrderStatusRequestType> jaxbOrderStatusRequestType,
        @Context UriInfo requestUriInfo,
        @Context SecurityContext securityContext){
    OrderStatusRequestType orderStatusRequestType= jaxbOrderStatusRequestType.getValue();

    return processRequest (num, JSON, orderStatusRequestType, securityContext);
}

I am sending following json in post request
{"orderStatusRequest":{"vendor":"32658","key":"232X1"}}

I get null object in my jaxbElement .. I am unable to understand why. For convenience, here is my XML Schema
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified" attributeFormDefault="unqualified">

    <xs:complexType name="orderStatusRequestType">
        <xs:sequence>
            <xs:element name="vendor" type="xs:string" minOccurs="1" maxOccurs="1"/>
            <xs:element name="key" type="xs:string" minOccurs="1" maxOccurs="1"/>
        </xs:sequence>
    </xs:complexType>

            <xs:element name="orderStatusRequest" type="orderStatusRequestType"/>

</xs:schema>

I wrote a client and send the JSON request
    ClientResponse clientResponse = service.path("api")
    .path("v1")
    .path("personal")
    .path("orders")
    .path(num)
    .path("status.json").accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, jaxbOst);

And it gave me error status 415 i.e content type isn't supported. However, with only 2 modification i.e. status.xml and MediaType.APPLICATION_XML works fine.

Update 2:
With Fiddler, I am able to hit the webservice with JSON. But Jersey isn't marchling the input POST body into specific objects. I am getting null in vendor and key fields.

UPDATED 3
I am able to consume the JSON from Fiddler. The JSON is {"vendor":"32658","key":"232X1"}. I was wrapping it under another object earlier. BUT I am still unable to send a request using Jersey Client. What i am guessing is that my JAXB Object is giving XML when i try to post. How can i make sure that when I use objectFactory.createOderRequestStatus, it will be translated into JSON and not XML ?

A: The 415 indicates that your client is not sending the correct content type in the request.  If you look at your path, for both the XML and the JSON methods, they are identical so you'll need to ensure your client sends the correct content path in order to distinguish which method will service your request. Otherwise Jersey will just pick the first one, which is what is happening here.
There is discussion on this topic in another thread. I haven't tried it myself however can you add some headers to your client to see if that works? Perhaps something like the following:
ClientResponse clientResponse = service.path("api")
                                .path("v1")
                                .path("personal")
                                .path("orders")
                                .path(num)
                                .path("status.json")
                                .accept(MediaType.APPLICATION_JSON)
                                .header("content-type", MediaType.APPLICATION_JSON)
                                .post(ClientResponse.class, jaxbOst);


text:
Q: Simple file transfer Given two Linux boxes on a LAN, what's the simplest way to transfer files between them?

A: I usually mount a directory through ssh via FUSE and sshfs.
Mount:
$ sshfs name@server:/path/to/dir /path/to/mount/point

Unmount:
$ fusermount -u /path/to/mount/point

A: I use netcat (if I don't need security)
nc -l -p 1234 < send_file   # 'server'
nc x.y.z.t 1234 > receive_file  # 'client'

A: nfs could be useful.
The Network File System (NFS) allows a client node to perform   transparent file access over the network.  By using NFS, a client node operates on files residing on a variety of servers and server architectures, and across a variety of operating systems.  File access calls on the client (such as read requests) are converted to NFS protocol requests and sent to the server system over the network.
You might require help from your Unix Admin to setup it first time but its very useful.

A: I use scp.
scp source desthost:/path/to/dest/.

to copy from the local machine to the remote machine, or
scp srchost:/path/to/file/file .

to copy from a remote machine to the local machine.
If the username is not the same on the remote machine,
scp user@srchost:/path/to/file/file .

A: For one off file transfers, I usually use SFTP or an existing samba share.
For keeping in sync, I suggest you try rsync or unison (for 2-way synchronization)
Edit: scp would be better then sftp, since it would work on all SSH enabled hosts

A: For doing backups I often use rsync.  If I want to backup onto a remote machine I'll put a line in /etc/fstab to keep the remote machine mounted by NFS or CFIS (Samba).
192.168.0.101:/ /mnt/backup nfs rsize=8192,wsize=8192,timeo=14,intr 0 0

Then have a line in my crontab using rsync.
rsync -av /home/user/sourcedir/ /mnt/backup/destinationdir > /home/user/backup.log

A: Giver is a simple file sharing desktop application. Other people running Giver on your network are automatically discovered and you can send files to them by simply dragging the files to their photo or icon shown in Giver.
In Ubuntu:
sudo apt-get install giver

A: netcat is simple but not all versions close connection reliably.
Here is thread about using socat:
socat reliable file transfer over TCP
To sum it up:
Proposed:

Server sending file:
server$ socat -u FILE:test.dat TCP-LISTEN:9876,reuseaddr
client$ socat -u TCP:127.0.0.1:9876 OPEN:out.dat,creat

Server receiving file:
server$ socat -u TCP-LISTEN:9876,reuseaddr OPEN:out.txt,creat && cat out.txt
client$ socat -u FILE:test.txt TCP:127.0.0.1:9876

Proposed enhancements:

*

*OPEN:out.txt,creat,trunc will delete all the bytes in out.txt before writing to it.  This option mimics what you'd expect from cp,
  and is probably what you want.

*OPEN:out.txt,creat,excl will refuse to write out.txt if it already exists.  Use this option for extra safety.

*OPEN:out.txt,creat,append will append data to out.txt.

A: Also you could use Giver program. Using it you could transfer files over LAN with 2 clicks or by "drag'n'dropping" file to recipient. Recipients (which also have to run giver) are discovered via Zeroconf, so you don't have to know even their IP. Here's video on how Giver works.

A: If you do not have an account (password) on the receiving host you can use woos (web offer one stream):
woos file-or-directory ...
http://fex.belwue.de/fstools/woos.html

A: There are a lot of good answers here, and some mention Giver and how it has trouble with large files. A very similar tool which handles large files seamlessly and gzips the transfer is portal.
(NOTE: I wrote this!)
How to use it
Alice wants to send <folder1> and <file.txt> to Bob, who can be behind the same NAT for direct transfer or anywhere on the internet for relayed transfer. Portal will use direct transfer if it's possible.
Alice initializes the file transfer by executing the following in her shell
$ portal send <folder1> <file.txt>
This outputs a temporary password, which Alice communicates to Bob via some other secure channel.
# the output of the send command, use this password to receive the files
> 1-supernova-gamma-ray

Bob executes the following command to receive folder1 and file.txt
$ portal receive 1-supernova-gamma-ray
The file transfer will now begin!
Pros

*

*e2e encryption

*fast gzip (de)compression

*simple protocol aids transfer speed

*handles folders of any sort and depth

*direct communication if ports are open or behind same NAT

Cons

*

*does not do NAT traversal so transfer goes through a relay if direct communication cannot be established

*it's a new tool so it is untried in different systems and might have weird bugs


text:
Q: Retrofit 2 image upload success but image uploads as corrupted file So heres the thing, the file is successfully uploaded as a "photo.png" but when i open the photo from the browser the photo is corrupted. When i download the photo to open it locally in my computer, the photo is corrupted.
No idea why.
Heres the retrofit endpoint:
@Multipart
@POST("alerts/{alertId}/photo/")
Call<Object> uploadPhotoStill(@Header("Authorization") String credentials, @Path("alertId") int alertId,
                              @Part("photo\"; filename=\"picture_taken.jpeg\" ") RequestBody photo);

Here is how i am using it: i am grabbing the byte array that comes back from taking a picture with the camera object.
private void initCamera() {
    if (camera == null) {
        camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);

        Camera.Parameters params = camera.getParameters();
        params.setPictureFormat(ImageFormat.JPEG);

        camera.setParameters(params);
    }
}

/**
 * Called when image data is available after a picture is taken.
 * The format of the data depends on the context of the callback
 * and {@link Camera.Parameters} settings.
 *
 * @param data   a byte array of the picture data
 * @param camera the Camera service object
 */
@Override
public void onPictureTaken(byte[] data, Camera camera) {
    Log.d(TAG, "onPictureTaken() called with: " + "data = [" + Arrays.toString(data) + "], camera = [" + camera + "]");
    handleTakenStill(data);
}

private void handleTakenStill(byte[] data) {
    Log.d(TAG, "handleTakenStill() was called");

    RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), data);

    havenApi.uploadPhotoStill(Utils.encodeUserCredentials(), getCurrentAlert().getId(), requestBody).enqueue(new Callback<Object>() {
        @Override
        public void onResponse(Response<Object> response, Retrofit retrofit) {
            if (response.isSuccess()) {
                Log.d(TAG, "handleTakenStill.onResponse success: " + response.body().toString());
            } else {
                Log.e(TAG, "handleTakenStill.onResponse error: " + response.message());
            }
        }

        @Override
        public void onFailure(Throwable t) {
            Utils.logOnFailureRequest(TAG, t);
        }
    });
}

The success is always called after uploading the photo. But the photo always uploads corrupted and i have no idea why.

A: I also had this issue. instead of using a MultiPart form, I used a simple RequestBody for the image data which works for me. I'm using Kotlin in an Android project.
My Retrofit API:
interface FilesApi {
    @PUT("/files/attachments/{parentId}")
    fun uploadAttachment(
        @Path("parentId") parentId: String,
        @Header("Content-Type") contentType: String,
        @Header("Name") name: String,
        @Header("Description") description: String?,
        @Body image: RequestBody
    ): Single<Response<FileUploadResponse>>
}

Creating the request object:
the imageData var is a ByteArray
val requestFile = imageData.toRequestBody(contentType.toMediaTypeOrNull(), 0, imageData.size)

return filesApi.uploadAttachment(parentId, contentType, name, description, requestFile)
            .map { response ->
                response.code()
                response.errorBody()
                response.body()?.Result
            }

A: 1) Check the Photo type as said in comments. Sometimes swith to JPG format solve problem.
2) Try to put as parameters to RequestBody just file, or path to file (Another constructor of RequestBode object)
I use code below without problem, But i sending file as Form Data:
@Multipart
    @POST("/api/tour/upload")
    Call<MainFileModel> uploadTourFiles(@PartMap Map<String, RequestBody> params);

    File mainFile = new File(fileLoad.getFile());
    Map params = new Map<>();
    params.put("file\"; filename=\"" + mainFile.getName(),
      RequestBody.create(MediaType.parse("multipart/form-data"),                                 mainFile));;

//And Make call here!

A: I never got to get this working with retrofit. But i was able to do it with OkHttp.
If you are wondering how here is the solution:
/**
 * Called when image data is available after a picture is taken.
 * The format of the data depends on the context of the callback
 * and {@link Camera.Parameters} settings.
 *
 * @param data   a byte array of the picture data
 * @param camera the Camera service object
 */
@Override
public void onPictureTaken(byte[] data, Camera camera) {
    Log.d(TAG, "onPictureTaken() called with: " + "data = [" + Arrays.toString(data) + "], camera = [" + camera + "]");
    handleTakenStill(data);
}

private void handleTakenStill(byte[] data) {
    Log.d(TAG, "handleTakenStill() was called");

    Observable.create(uploadPhoto(data))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<com.squareup.okhttp.Response>() {
                @Override
                public void onCompleted() {
                    Log.d(TAG, "onCompleted() was called");
                }

                @Override
                public void onError(Throwable e) {
                    Utils.logOnFailureRequest(TAG, e);
                }

                @Override
                public void onNext(com.squareup.okhttp.Response response) {
                    if (response.isSuccessful()) {
                        Log.d(TAG, "handleTakenStill.onResponse success: " + response.body().toString());
                    } else {
                        Log.e(TAG, "handleTakenStill.onResponse error: " + response.message());
                    }
                }
            });
}

@NonNull
private Observable.OnSubscribe<com.squareup.okhttp.Response> uploadPhoto(final byte[] data) {
    return new Observable.OnSubscribe<com.squareup.okhttp.Response>() {
        @Override
        public void call(Subscriber<? super com.squareup.okhttp.Response> subscriber) {
            OkHttpClient client = new OkHttpClient();

            RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                    .addFormDataPart("camera", "picture_taken.jpg", RequestBody.create(MediaType.parse("image/jpeg"), data))
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .addHeader("content-type", "multipart/form-data")
                    .addHeader("authorization", Utils.encodeUserCredentials())
                    .addHeader("accept", "application/json")
                    .addHeader("cache-control", "no-cache")
                    .build();

            try {
                com.squareup.okhttp.Response response = client.newCall(request).execute();
                subscriber.onNext(response);
                subscriber.onCompleted();
                if (!response.isSuccessful()) {
                    subscriber.onError(new Exception("Error uploading photo"));
                }
            } catch (IOException e) {
                subscriber.onError(e);
            }
        }
    };
}


text:
Q: Is it mandatory to implement self.instances and self.prefetch methods for a Puppet provider we are writing a Puppet module for a networked storage device. We are implementing custom types and providers and for one of the type we will have on an average around 40k objects.
Getting these many resources thru pre-fetch and self.instances will be very performance intensive. Is it mandatory to implement self.instances and pre-fetch methods for a provider? What will we lose if we do not implement them?

A:
Is it mandatory to implement self.instances and pre-fetch methods for
  a provider?

No, it is not.

What will we lose if we do not implement them?

You'll not be able to use a Resources resource to purge unmanaged resources of the type in question.  But with so many resources, I'm inclined to think that you'll be actively managing only a few, and will not want to purge the others anyway.
You'll not be able to use the puppet resource command to enumerate all resources of your custom type.
You'll also need either to retrieve individual resource properties on demand, when the provider's getter methods are invoked, or else to track whether each individual resource's state has been retrieved and have each getter first load the state if needed.  Either is doable.
For comparison, consider File resources, which seem conceptually similar to what you have in mind.  Puppet makes no attempt to prefetch all File resources of a given system, and there's no practical way it could do.


text:
Q: My job quote calculator is returning "X is not a function" This is a corporate massage job quote calculator.
From the user, we collect:

*

*Start time

*End time

*Number of clients needing a massage

We then use those variables in conjunction with our business rules of time needed per person and hourly rate for a therapist to determine how many therapists are needed and how much it will cost the client to staff those therapists.
When ran, my console displays an error message "timeStr.split is not a function". I thought there was an issue with the .map() method but I've tried resolving to no avail. I am new to JS and could really use some help, please. Here is the code
HTML

    Start Time

    <input id="starttime" type="time" name="starttime" placeholder="Start time">

    End Time

    <input id="endtime" type="time" name="endtime" placeholder="End time">

    # of people needing massage

    <input id="clients" type="number" name="clients" id="">

    <input  type="button" value="Submit" id="inputbtn" onclick="calc()">

JS
/*User Inputs*/
        const start = document.getElementById("starttime").value;
        const end = document.getElementById("endtime").value;
        const people = document.getElementById("clients").value;
        let timeStart = new Date("01/02/2020" + start);
        let timeEnd = new Date("01/02/2020"+end);

        /*constants*/
        const rate = 80;
        const allot = "00:20:00";

        /*Time converter*/

        function convTime(timeStr){
            arr = timeStr.split(":");
            arr = arr.map(Number=> Number);

            let theHours = arr[0];
            let theMinutes = arr[1]/60;
            let timeDec = theHours+theMinutes;

            return timeDec;

        }

        /*formulas*/
        const ogTime = timeEnd - timeStart;
        const givenTime = convTime(ogTime);
        const convAllot = convTime(allot)
        const realTime = people*convAllot;
        const therapists = realTime/givenTime;
        const price = therapists*rate*givenTime;

        console.log(price);

A: *

*Moved declare variables of users inputs into Calc() Method to get the value after user insert it, not only on Document Load

*use MomentJs Library to calc diff dates and get Hours, minutes, ...

*set inputs default values for DEMO only

/*constants*/
var dateStr = "01/02/2020";
const rate = 80;
const allot = moment(new Date(dateStr)).add("+20m"); // 20 minutes

/*Time converter*/
function convTime(t) {
  t = moment(t);
  let theHours = t.format('h');
  let theMinutes = t.format('mm');
  let timeDec = Number(theHours) + Number(theMinutes);

  return timeDec;
}

function calc() {
  /*User Inputs*/
  const start = document.getElementById("starttime").value;
  const end = document.getElementById("endtime").value;
  const people = document.getElementById("clients").value;
  var timeStart = new Date(dateStr + " " + start);
  var timeEnd = new Date(dateStr + " " + end);

  /*formulas*/
  const ogTime = moment(timeEnd).diff(timeStart);
  const givenTime = convTime(ogTime);
  const convAllot = convTime(allot);
  const realTime = people * convAllot;
  const therapists = realTime / givenTime;
  const price = therapists * rate * givenTime;

  console.log(price);
}

calc(); // call it on load -- remove this if you want onclick only
Start Time

<input id="starttime" type="time" name="starttime" placeholder="Start time" value="07:00">

End Time

<input id="endtime" type="time" name="endtime" placeholder="End time" value="08:00">

# of people needing massage

<input id="clients" type="number" name="clients" value="1">

<input type="button" value="Submit" id="inputbtn" onclick="calc()">


text:
Q: Vertically stack 4 tables in matplotlib I need to recreate this structure in matplotlib

import matplotlib.pyplot as plt

fig, (ax1, ax2, ax3, ax4) = plt.subplots(ncols=1, nrows=4)
# fig.tight_layout()
ax1.axis("off")
ax2.axis("off")
ax3.axis("off")
ax4.axis("off")

ax1.table(cellText=[["A", "B", "C", "D", "E", "F"]])

ax2.table(cellText=[[1, 1, 1, 1, 1, 1],
                    [2, 2, 2, 2, 2, 2],
                    [3, 3, 3, 3, 3, 3],
                    [4, 4, 4, 4, 4, 4],
                    [5, 5, 5, 5, 5, 5],
                    [6, 6, 6, 6, 6, 6],
                    [7, 7, 7, 7, 7, 7],
                    [8, 8, 8, 8, 8, 8],
                    [9, 9, 9, 9, 9, 9]])

ax3.table(cellText=[[1, 2, 3, 4, 5, 6],
                    [1, 2, 3, 4, 5, 6]])

ax4.table(cellText=[[1, 2, 3, 4, 5, 6]])

plt.show()

Here is what I have so far, but the tables are overlapping and it's not useable.
So my question is how can I achieve make this table structure in matplotlib?

A: The problem you're running into is that subplots assumes that all of your tables will be the same size. Since this is not the case, you end up with tables that are larger the the underlying Axes objects.
If your case you have your tables in advance so you can estimate their sizes based on the number of rows. You can pass this information into the subplots constructor to proportionally resize the returned Axes such that each table should fit into their own axes.
Here I predefine all of the tables in an overarching list (for convenience mainly). I can then get the number of rows in each table and pass that to the height_ratios gridspec argument such that each produced Axes has a size that is proportional to the number of rows in its respective table.
Then I can zip the returned axes with the tables and actually insert the values.
Lastly, you should pass loc='center' so each table is actually drawn into the Axes instead of below, above, or off to the side.
import matplotlib.pyplot as plt

tables = [
    [["A", "B", "C", "D", "E", "F"]],

    [[1, 1, 1, 1, 1, 1],
     [2, 2, 2, 2, 2, 2],
     [3, 3, 3, 3, 3, 3],
     [4, 4, 4, 4, 4, 4],
     [5, 5, 5, 5, 5, 5],
     [6, 6, 6, 6, 6, 6],
     [7, 7, 7, 7, 7, 7],
     [8, 8, 8, 8, 8, 8],
     [9, 9, 9, 9, 9, 9]],

    [[1, 2, 3, 4, 5, 6],
     [1, 2, 3, 4, 5, 6]],

    [[1, 2, 3, 4, 5, 6]]
]

table_rows = [len(tbl) for tbl in tables]
fig, axes = plt.subplots(
    ncols=1, nrows=len(tables),
    gridspec_kw={'height_ratios': table_rows}
)
for tbl, ax in zip(tables, axes.flat):
    ax.table(cellText=tbl, loc='center')
    ax.axis('off')

plt.show()


text:
Q: app[web.1]: Warning: connect.session() MemoryStore is not .Heroku is not working
pls help me,heroku application error, this is heroku view log:
2020-03-25T00:13:32.809756+00:00 app[web.1]: Warning: connect.session() MemoryStore is not
2020-03-25T00:13:32.809769+00:00 app[web.1]: designed for a production environment, as it will leak
2020-03-25T00:13:32.809770+00:00 app[web.1]: memory, and will not scale past a single process.
2020-03-25T00:13:32.821438+00:00 app[web.1]: Server started on8000
2020-03-25T00:13:32.958702+00:00 app[web.1]: veritabanına bağlandı

A: You've got a few options here.
1st: You created a user session using express-session but forgot to add the session secret to the vars in heroku config vars
Ex:
app.use(
session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: true,

Using process.env.SESSION_SECRET and not adding the secret to heroku vars will give you this error (that was my case)
2nd: You didn't specify where to store the session. You should add a storing system that store sessions into your database. This helps your app to manage sessions.
For example, in mongodb you can use connect-mongo, you should found a store package and for other databases.
Ex:
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);

app.use(session({
    secret: 'foo',
    store: new MongoStore(options)
}));

By doing this you're storing the session in mongo.
3rd: Last option if all fails, i do not recommend tho, is storing the cookis client-side instead of server-side. To do this you must replace express-session (if you're using it) with cookie-session.
Ex:
npm i cookie-session
var session = require('cookie-session');

Then writing the app.use as normally


text:
Q: Collections as decorators in C# We've been hit with a pretty "obvious" problem while designing a collections infrastructure: suppose you need to implement many (sub)types of collections. One of the aspects is storage-related: list, array etc, while the other is behavior-related: ordered, remove only, observable (the one that fires an event upon every change) etc.
Obviously (again), the requirement maps directly to the well-known Decorator design pattern (list, array), where the storage-related aspect will be decorated by multiple behavioral (ordered, observable etc).
It would be great to know about something similar that had been already implemented by someone. Hence, if possible - please recommend/refer to any well-maintained third-party library that would meet the requirements, mentioned above.
Thanks so far :)

A: I think you misunderstood something:
Decorators are used to modify and add behaviour primarily at runtime. But the properties of collections that you cited need to be available at compile time. A decorator is completely unsuited to add more methods to an existing class.
While it is possible to decompose these traits of collections into interfaces (and indeed has been done 1)), this isn't really what a decorator is about: a decorator wraps an existing class implementing the same interface. For collections, inheritance will make more sense (or may indeed be required) instead of composition.

1) A few years, I started developing my own such library, Containers.NET but since preliminary benchmarks showed just how much faster the native .NET containers were, even though Containers.NET did not have any added overhead, I stopped the project before it got very far.


text:
Q: Sidekiq jobs aren't firing in development mode, only in production Edit: I was just told by our team that docker is not even used for production. So it seems the issue is limited to Docker and not the environments that Rails is launching into.
I have a project I'm working on sidekiq jobs seem to run fine in our production environment, but in my local development machine I get a bunch of console errors for sidekiq and I'm not sure why.
Here are my sidekiq errors:
sidekiq_1  | 2017-03-15T17:16:24.346Z 1 TID-gq075lic0 INFO: Booting Sidekiq 4.2.3 with redis options {:url=>"redis://redis:6379/"}
sidekiq_1  | 2017-03-15T17:16:25.240Z 1 TID-gq075lic0 INFO: Running in ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]
sidekiq_1  | 2017-03-15T17:16:25.240Z 1 TID-gq075lic0 INFO: See LICENSE and the LGPL-3.0 for licensing details.
sidekiq_1  | 2017-03-15T17:16:25.241Z 1 TID-gq075lic0 INFO: Upgrade to Sidekiq Pro for more features and support: http://sidekiq.org
sidekiq_1  | 2017-03-15T17:16:25.260Z 1 TID-gq075lic0 INFO: Loading Schedule
sidekiq_1  | 2017-03-15T17:16:25.260Z 1 TID-gq075lic0 INFO: Schedule empty! Set Sidekiq.schedule
sidekiq_1  | 2017-03-15T17:16:25.264Z 1 TID-gq075lic0 INFO: Schedules Loaded
sidekiq_1  | 2017-03-15T17:16:25.266Z 1 TID-gq075lic0 WARN: {"context":"Exception during Sidekiq lifecycle event.","event":"startup"}
sidekiq_1  | 2017-03-15T17:16:25.266Z 1 TID-gq075lic0 WARN: TypeError: can't dup NilClass
sidekiq_1  | 2017-03-15T17:16:25.267Z 1 TID-gq075lic0 WARN: /usr/local/bundle/gems/sidekiq-scheduler-2.0.19/lib/sidekiq-scheduler/schedule.rb:126:in `dup'
sidekiq_1  | /usr/local/bundle/gems/sidekiq-scheduler-2.0.19/lib/sidekiq-scheduler/schedule.rb:126:in `block in prepare_schedule'
sidekiq_1  | /usr/local/bundle/gems/sidekiq-scheduler-2.0.19/lib/sidekiq-scheduler/schedule.rb:125:in `each'
sidekiq_1  | /usr/local/bundle/gems/sidekiq-scheduler-2.0.19/lib/sidekiq-scheduler/schedule.rb:125:in `prepare_schedule'
sidekiq_1  | /usr/local/bundle/gems/sidekiq-scheduler-2.0.19/lib/sidekiq-scheduler/schedule.rb:40:in `schedule='
sidekiq_1  | /gathrly/config/initializers/scheduler.rb:5:in `block (2 levels) in <top (required)>'
sidekiq_1  | /usr/local/bundle/gems/sidekiq-4.2.3/lib/sidekiq/util.rb:54:in `block in fire_event'
sidekiq_1  | /usr/local/bundle/gems/sidekiq-4.2.3/lib/sidekiq/util.rb:52:in `each'
sidekiq_1  | /usr/local/bundle/gems/sidekiq-4.2.3/lib/sidekiq/util.rb:52:in `fire_event'
sidekiq_1  | /usr/local/bundle/gems/sidekiq-4.2.3/lib/sidekiq/cli.rb:79:in `run'
sidekiq_1  | /usr/local/bundle/gems/sidekiq-4.2.3/bin/sidekiq:12:in `<top (required)>'
sidekiq_1  | /usr/local/bundle/bin/sidekiq:17:in `load'
sidekiq_1  | /usr/local/bundle/bin/sidekiq:17:in `<top (required)>'
sidekiq_1  | /usr/local/bundle/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:74:in `load'
sidekiq_1  | /usr/local/bundle/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:74:in `kernel_load'
sidekiq_1  | /usr/local/bundle/gems/bundler-1.14.6/lib/bundler/cli/exec.rb:27:in `run'
sidekiq_1  | /usr/local/bundle/gems/bundler-1.14.6/lib/bundler/cli.rb:335:in `exec'
sidekiq_1  | /usr/local/bundle/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run'
sidekiq_1  | /usr/local/bundle/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'
sidekiq_1  | /usr/local/bundle/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor.rb:359:in `dispatch'
sidekiq_1  | /usr/local/bundle/gems/bundler-1.14.6/lib/bundler/cli.rb:20:in `dispatch'
sidekiq_1  | /usr/local/bundle/gems/bundler-1.14.6/lib/bundler/vendor/thor/lib/thor/base.rb:440:in `start'
sidekiq_1  | /usr/local/bundle/gems/bundler-1.14.6/lib/bundler/cli.rb:11:in `start'
sidekiq_1  | /usr/local/bundle/gems/bundler-1.14.6/exe/bundle:32:in `block in <top (required)>'
sidekiq_1  | /usr/local/bundle/gems/bundler-1.14.6/lib/bundler/friendly_errors.rb:121:in `with_friendly_errors'
sidekiq_1  | /usr/local/bundle/gems/bundler-1.14.6/exe/bundle:24:in `<top (required)>'
sidekiq_1  | /usr/local/bundle/bin/bundle:22:in `load'
sidekiq_1  | /usr/local/bundle/bin/bundle:22:in `<main>'
sidekiq_1  | 2017-03-15T17:16:25.268Z 1 TID-gq075lic0 INFO: Starting processing, hit Ctrl-C to stop
web_1      | Puma starting in single mode...
web_1      | * Version 3.6.0 (ruby 2.3.1-p112), codename: Sleepy Sunday Serenity
web_1      | * Min threads: 5, max threads: 5
web_1      | * Environment: development
web_1      | * Listening on tcp://0.0.0.0:3000

It says:
sidekiq_1  | 2017-03-15T17:16:25.260Z 1 TID-gq075lic0 INFO: Loading Schedule
sidekiq_1  | 2017-03-15T17:16:25.260Z 1 TID-gq075lic0 INFO: Schedule empty! Set Sidekiq.schedule
sidekiq_1  | 2017-03-15T17:16:25.264Z 1 TID-gq075lic0 INFO: Schedules Loaded

But then I get a NilClass error.
Here is my scheduler.rb file:
require 'sidekiq/scheduler'

Sidekiq.configure_server do |config|
  config.on(:startup) do
    Sidekiq.schedule = YAML.load_file(File.expand_path('../../sidekiq_scheduler.yml', __FILE__))
    Sidekiq::Scheduler.reload_schedule!
  end
end

and my sidekiq-scheduler.rb file:
UpdateEventbriteJob:
  cron: "*/15 * * * *"
UpdateMeetupJob:
  cron: "*/15 * * * *"
PostEventEmailJob:
  # cron: "0 9 * * *"
  # cron: "*/1 * * * *"
UpdateStatusJob:
  cron: "*/1 * * * *" # Every minute for testing. Plan on every 24 hours

I'm testing the UpdateStatusJob locally. The other jobs working production and seem to work fine. But Nothing in this scheduler ever fires in develop mode. I would like to test the job out before I kick it up to production. What am I doing wrong?
I should also note I'm running things in docker. Something I don't use too often so I'm not sure if that's impeding things.
Here is the relevant information in my docker-compose file:
version: '2'
services:

  ...

  sidekiq:
    build: .
    command: bundle exec sidekiq -C config/sidekiq.yml
    env_file: .env
    links:
      - db
      - redis

  ...

A: In the scheduler.yml PostEventEmailJob doesn't have any values, only commented out lines.
If you change the file to:
UpdateEventbriteJob:
  cron: "*/15 * * * *"
UpdateMeetupJob:
  cron: "*/15 * * * *"
PostEventEmailJob:
  cron: "0 9 * * *"
UpdateStatusJob:
  cron: "*/1 * * * *" # Every minute for testing. Plan on every 24 hours

it will parse correctly and start Sidekiq.


text:
Q: Can I use grep to pull out a particular pattern from a file / number of files, using regex perhaps? I have a file with a load of errors in it. I used grep to pull out all the JSONExcpetion Errors and save them in a new file like this:
sudo grep -Hrn "JSONException" 2016-* >> jsonexception.txt

Now I have a file with a lot of JSONExceptions in it. Some of those exceptions contain IDs. I'd like to pull out the ID's and save them to another file.
In my Java code, I use the following regex to identify the correct ID formatting in a String:
^([A-Fa-f0-9]{24})$

Can I use something similar with grep to pull IDs from jsonexception.txt and save them to another file?
A sample from the log:
2016-02/server-2016-02-11-3.log:17425:11/Feb/2016 12:08:35,519 [ERROR] [Thread-3] - WorkerRunnable: Worker 2: A JSONException occurred, on the string: {"DEVICE":[{"
ID":"32584305d2ff32051d06dfff"},{"TimeStamp":1455185304,"Event":"Boot","BuildDate":"Feb 11 2016","BuildTime":"10:48:00","Reason":"Power on Reset","FSHigh":485,"FSLow":475
,"VerMajor":0,"VerMinor":9,"VerRevision":2,"VerPatch":2,"MAC":"00:06:66:3a:26:5c","WlanVersion":"4.75","WlanModuleType":"RN131","BoardRev":"RevD1","DisinfectSeconds":0},{
"TimeStamp":1455185316,"Event":"CurrentSettings","IssuedTime":0,"FSHigh":535,"FSLow":425,"Duty":100,"Frequency":1000,"Current":80,"IdlePeriod":30,"StillOnPeriod":20,"Auto
OnPeriod":43200,"AutoOnDuration":10,"MaxOnTime":14400,"FlowSensitivity":50,"LidSwitches":1,"UvFluxWarn":70,"UvFluxInsufficient":40,"Firm
Server":"���^A.^B�^B.^P�^K�^G�^C�JF^M�        �H�O�zp^HI����^C�^G�^C�^M�B�^N�^R���    ����O^B�pG�^D","FirmPort:1,"DeviceTypeName":"","WlanTimeZone":25,"LedRegArray":[{"Bo
ardId":"A","LedNo":0,"RegState":"Regulate"},{"BoardId":"A","LedNo":1,"RegState":"Regulate"}]},{"TimeStamp":1455185316,"Event":"CurrentWlanSettings","SettingsArray":[{"WlanSettingsId":1},{"WlanSettingsId":2},{"WlanSettingsId":3}]},{"TimeStamp":145518531
5,"Event":"Connect","WlanSettingsId":1,"MAC":"00:06:66:3a:26:5c","IP":"192.168.1.125","WLAN":"TEST1","RSSI":-52,"Version":"4.75","AP-MAC":"ac:9e:17:ea:0f:3c"},{"End
":100}]}^M

A: If your grep supports -o, you can use the following:
grep -o '"ID":"[a-f0-9]\{24\}"' | cut -d\" -f4

The first part extracts only the "ID":"..." part, the second one selects the 4th column, using " as the separator, i.e. the id itself.
It's much safer to include the "ID": in the query, otherwise you can accidentally match a different part of the line.


text:
Q: Is it possible to detect when a node module is running as a Google Cloud Function? Is there any way to check if a node function/module is running as a Google Cloud Function other than setting an environment variable via the console and checking for that?

A: There are a few environment variables that are set automatically. You could check if they are defined. If so, you are running in google cloud environment. More Info.
Example
// Other variables FUNCTION_REGION, FUNCTION_IDENTITY, FUNCTION_TIMEOUT_SEC, etc;
const isGoogleCloudEnv = !!process.env.GCP_PROJECT
// ...


text:
Q: AngularJS - Bind click event to element I have the following partial being inserted into an ng-view.  I'm only pasting the part of the partial that is relevant.

    {{ group.name }}
    {{ group.members.length }}
    {{ 5 }}

        <select class="enhanced-select ps-settings restaurant-group-select" restaurant_group_id="1">
            <option value="actions">Actions</option>
            <option value="edit">Edit</option>
            <option value="edit">Restaurants</option>
            <option value="delete">Menus</option>
            <option value="edit">Delete</option>
        </select>
        Actions

I would like to bind a click event to each of the anchor elements above. I've tried this with a custom directive named create-link. In my app.js file I have the following code.
adminApp.directive("create-link", function($location, $timeout, $rootScope) {
    console.log("I fired the directive!");
    return {
        restrict: "A",
        link: function(scope, element) {
            $timeout(function(){
                element.on("click", function(e) {
                    console.log("Clicked!");
                });
            });
        }
    };
});

However, the event is never bound. In fact, the "I fired the directive!" never actually gets written to the console. What am I missing here? Binding events to DOM elements that are created while loading the view would seem to be a common use case.  Surely there is an easy way to go about doing it.
Thanks for any help.
Andrew

A: Change the directive name in js to the camelcased version of your directive name declared in view part:
adminApp.directive("createLink", function($location, $timeout, $rootScope) {
    console.log("I fired the directive!");
    return {
        restrict: "A",
        link: function(scope, element) {
            $timeout(function(){
                element.on("click", function(e) {
                    console.log("Clicked!");
                });
            });
        }
    };
});


text:
Q: OpenCV - Closing contours (Java) I'm currently trying to close the contours on the right of this picture:
Sample.
The reason for the opened contour lies in kabeja, a library to convert DXF files to images. It seems that on some images it doesn't convert the last pixel column (or row) and that's why the Sample picture is open.
I had the idea to use Core.copyMakeBorder() in Opencv, to add some space to the picture. After that I tried to use Imgproc.approxPolyDP() to close the contour, but this doesn't work. I tried this with different Epsilon values: Pics EDIT: Can't post more than 2 links
The reason for that is maybe that the contour surrounds the line. It never closes the contour where i want it to do.
I tried another method using Imgproc.convexHull(), which delivers this one: ConvexHull.
This could be useful for me, but i have no idea how to take out the part of the convex hull i need and merge it together with the contour to close it.
I hope that someone has an idea.
Here is my method for  Imgproc.approxPolyDP()
public static ArrayList<MatOfPoint> makeComplete(Mat mat) {
    System.out.println("makeComplete: START");
    Mat dst = new Mat();
    Core.copyMakeBorder(mat, dst, 10, 10, 10, 10, Core.BORDER_CONSTANT);

    ArrayList<MatOfPoint> cnts = Tools.getContours(dst);
    ArrayList<MatOfPoint2f> opened = new ArrayList<>();

    //convert to MatOfPoint2f to use approxPolyDP
    for (MatOfPoint m : cnts) {
        MatOfPoint2f temp = new MatOfPoint2f(m.toArray());
        opened.add(temp);
        System.out.println("First loop runs");
    }

    ArrayList<MatOfPoint> closed = new ArrayList<>();
    for (MatOfPoint2f conts : opened) {
        MatOfPoint2f temp = new MatOfPoint2f();
        Imgproc.approxPolyDP(conts, temp, 3, true);
        MatOfPoint closedTemp = new MatOfPoint(temp.toArray());
        closed.add(closedTemp);
        System.out.println("Second loop runs");
    }

    System.out.println("makeComplete: END");
    return closed;
}

And here the code for Imgproc.convexHull()
 public static ArrayList<MatOfPoint> getConvexHull(Mat mat) {
    Mat dst = new Mat();
    Core.copyMakeBorder(mat, dst, 10, 10, 10, 10, Core.BORDER_CONSTANT);

    ArrayList<MatOfPoint> cnts = Tools.getContours(dst);
    ArrayList<MatOfPoint> out = new ArrayList<MatOfPoint>();
    MatOfPoint mopIn = cnts.get(0);
    MatOfInt hull = new MatOfInt();
    Imgproc.convexHull(mopIn, hull, false);

    MatOfPoint mopOut = new MatOfPoint();
    mopOut.create((int) hull.size().height, 1, CvType.CV_32SC2);

    for (int i = 0; i < hull.size().height; i++) {
        int index = (int) hull.get(i, 0)[0];
        double[] point = new double[]{
                mopIn.get(index, 0)[0], mopIn.get(index, 0)[1]
        };
        mopOut.put(i, 0, point);
    }

    out.add(mopOut);
    return out;
}

Best regards,
Brk

A: Assuming the assumption is correct, that the last row (for column it is similar) isn't converting (i.e. missing), then try the following. Assume x goes from left to right and y from top to bottom. We add one row of empty (white?) pixels at the image bottom and then go from left to right. Below is pseudo code:
// EMPTY - value of backgroung e.g. white for the sample image
PixelType curPixel = EMPTY;
int y = height - 1; // last row, the one we added
for (int x = 0; x < width; ++x)
{
    // img(y,x) - current pixel, is "empty"
    // img (y-1, x) - pixel above the current
    if (img(y-1, x) != img(y, x))
    {
        // pixel above isn't empty, so we make current pixel non-empty
        img(y, x) = img(y-1, x);
        // if we were drawing, then stop, otherwise - start
        if (curPixel == EMPTY)
            curPixel = img(y-1, x);
        else
            curPixel = EMPTY;
    }
    else
    {
        img(y, x) = curPixel;
    }
}


text:
Q: How to Add Time stamp when using ffmpeg Video Recorder? Is there any option , that let a user record a video with a time stamp .
I use many web-cam recording and i didn't found this option .
Program i used Guvcview , Cheese .
Any Help ?


text:
Q: Execute return then call another function in PHP I have a function to execute some database input then send notification to a user, the problem is when i execute the send notification to a user is taking some time, i need this process to run in background but i don't know how to do it, here is my code:
public function execute(){
 $data = $this->insertToDatabase();
 $this->sendNotification($data); //this function takes a lot of time
 return $data;
}


text:
Q: React reselect - toJS is not a function I am getting an error in the selectors of a react application when using toJS with the reselect library.
I tried importing toJS as well as not importing it and I get the error no matter what.

nodeCreationWindow.get(...).toJS is not a function

import { createSelector } from 'reselect'
import { toJS } from 'immutable'

const selectNodeCreationWindow = () => (state) => state.get('nodeCreationWindow')

const selectNodes = () => createSelector(
  selectNodeCreationWindow(),
  (nodeCreationWindow) => {
    return nodeCreationWindow.get('nodes').toJS()
  }
)

const selectTags = () => createSelector(
  selectNodeCreationWindow(),
  (nodeCreationWindow) => nodeCreationWindow.get('tags').toJS()
)

const selectSuggestions = () => createSelector(
  selectNodeCreationWindow(),
  (nodeCreationWindow) => nodeCreationWindow.get('suggestions').toJS()
)

export {
  selectNodes,
  selectTags,
  selectSuggestions
}

A: I think that value returned by nodeCreationWindow.get('nodes') is already a pure JS object so it doesn't have toJS method.
Besides, remove this line:
import { toJS } from 'immutable'

because toJS is not exported by Immutable module but attached to Immutable objects


text:
Q: Triple Integral $F = \iiint_SGm\delta(x,y,z)f(x,y,z) \space dx \space dy \space dz$ Let $S$ be a basic solid and let $(a,b,c)$ be a point not in $S$. If $S$ has continuously varying mass density of $\delta = \delta(x,y,z)$ then $S$ attracts a point mass $m$ located at $a,b,c$ with a gravitational force $$F = \iiint_SGm\delta(x,y,z)f(x,y,z) \space dx \space dy \space  dz$$ where $$f(x,y,z) = \dfrac{(x-a)\textbf{i}+(y-b)\textbf{j}+(z-c)\textbf{k}}{[(x-a)^2+(y-b)^2+(z-c)^2]^{3/2}}$$ is the force experienced by a particle in an inverse square field Let $S$ be a solid right circular cylinder of constant density, with base radius $R$, height $h$ and mass $M$. A point mass $m$ is placed on the axis of $S$ at a distance $\alpha$ from the nearest base of the cylinder. Find the gravitational force exerted by the cylinder on the point mass.
Hint: In developing the integral $F$ you might like to consider only the non-zero components due to the gravitational symmetry of the problem.

How would you even go about starting this question? How would you setup the range for a triple integral like this? Any help would be appreciated.


text:
Q: how to assign labels to each token in my datafrmae? I want to change the structure of my data frame, I want to convert a data frame,

e.g first row is so
[Yes, it's annoying and cumbersome to separate your rubbish properly all the time., Three different bin bags stink away in the kitchen and have to be sorted into different wheelie bins., But still Germany produces way too much rubbish, and too many resources are lost when what actually should be separated and recycled is burnt., We Berliners should take the chance and become pioneers in waste separation!]

as you see in each row, column paragraph, I have a couple of sentences and in the column Label, I have corrpsp[edn label, I want to break assign to each token of sentences each  it is a label and it is Pos tags like this
[(Yes, UH, 0), (,, ,, 0), (it, PRP, 0), ('s, VBZ, 0), (annoying, JJ, 0), (and, CC, 0), (cumbersome, JJ, 0), (to, TO, 0), (separate, VB, 0), (your, PRP$, 0), (rubbish, NN, 0), (properly, RB, 0), (all, PDT, I0), (the, DT, 0), (time, NN, 0), (., ., 0),...]

i have kind  of done  to tokenized and assign pos tag using spacy
import spacy
nlp = spacy.load("en_core_web_sm")
def mapTokenPos(l):
    tokenlist=[]
    for x in l:
        doc=nlp(x)
        a=[(token.text,token.tag_) for token in doc]
        tokenlist.append(a)
    return tokenlist
df["IOB"]=df["Paragraph"].apply(mapTokenPos)

but I do not know how to assign the labels to


text:
Q: SQL Server - how to use like keyword in records that have period in the middle of value I have below records

but when i tried to do query where FullName like '%Gd. Mahendra%', it doesn't return any result.
Why ?
it should return the first row, shouldn't it ?

A: Your comparison should be fine:
where FullName like '%Gd. Mahendra%'

If you suspect the ., you can replace it with the single character wildcard:
where FullName like '%Gd_ Mahendra%'

In general, this type of problem is caused by "invisible" characters or characters that look the same (like zero and a capital O, or a tab and a space, or two spaces).  This can particularly occur with national character sets that extend the basic ASCII characters.
You can see the ASCII value of a character using the ASCII().  That can sometimes help you figure out what is happening.

A: Try this:
   WHERE FullName LIKE '%Gd.%Mahendra%'

A: Apparently the problem is:
The value that's been sent by the request is different from the actual record.
It's because the html doesn't use <pre> tag, which is able to render multiple spaces. Then the user just copyies the rendered value that doesn't have multiple spaces. That's why it can't get the correct result.


text:
Q: Read Email from Gmail inbox as it arrives I've a drupal 7 site, and requires a functionality by which I can read emails from gmail inbox whenever they arrives. Currently I'm achieving it with php imap by running it on cron.
But I want something, which can read email from inbox as soon as it arrives.
Please suggest, thanks

A: This would be a bit of a round-the-houses approach but create an account with mailgun.com. Within Mailgun you can then direct incoming emails to a URL you specify. Mailgun parses the email and sends it to you in a structured format.
You could then set up your Gmail account to send a copy of all incoming emails to your Mailgun account.


text:
Q: AJAX not rendering on django template So I am trying to render some text dynamically on a webpage using AJAX. I created an empty div and attempted to fill it with some data but it renders nothing. Firstly, my question is how do I pass extra data to the AJAX call? Below is the HTML

{% for user in searched_users %}

{{ user.user.username }}

 Follow Unfollow Perform Match?

 {% endfor %}

  {% endblock %}

it has a couple of href-s used for following, unfollowing a user. When a user clicks on the follow href, I want to display the HTTPresponse of this view.
 def follow(request, name):
    sender = User.objects.get(username = request.session["username"]).userprofile
    display = User.objects.get(username=name)
    receiver = User.objects.get(username= name).userprofile
    if receiver not in sender.get_friends() and sender != receiver:
        relationship = Relationship.objects.get_or_create(
        from_person=sender,
        to_person=receiver,
        status = 1
        )
    return HttpResponse (f" added {display.username}")
    elif sender == receiver:
       raise ValidationError("Can't follow yourself")
    else:
         return HttpResponse("Already following")

One probable cause of failure is the extra argument, name not being passed into the AJAX call. How do I pass it to the AJAX call? Can I use user.user.username in AJAX? Doesn't seem to work...

A: In your html code you have repeated ids so first change them to class . I am considering you are using jquery because you have $.ajax . So, now whenever your follow element is clicked use .data("name") to get username which is set as data-attribute in your a tag(added by me) .
Then , pass this to your backend code i.e : data : {"username":your_value} . Now , there can be mutliple display divs because its under for-loop so you need to display result only to particular display div where follow element is clicked so use .closest(".links").next().text("mesage return from ajax").
You html will look like below  :

{% for user in searched_users %}

{{ user.user.username }}

 Follow Unfollow Perform Match?

 {% endfor %}

Demo Code  :

$(".follow").on('click', function(e) {
  e.preventDefault() //to prevent default redirect
  var username = $(this).data("name")
  console.log(username)
  var selector = $(this).closest(".links").next() //get display div
  /* $.ajax({
     url: "/follow/",
     data: {
       "name": username //pass data here
     },
     success: function(data) {
       if (data) {
         console.log(data);*/
  // Add the http response to element
  selector.text("Ok ok "); //use data
  /* }
    }
  })*/
});

Abcd

    Follow Unfollow Perform Match?

Abcds

    Follow Unfollow Perform Match?