text:
Q: egrep -v match lines containing some same text on each line So I have two files.
Example of file 1 content.
/n01/mysqldata1/mysql-bin.000001
/n01/mysqldata1/mysql-bin.000002
/n01/mysqldata1/mysql-bin.000003
/n01/mysqldata1/mysql-bin.000004
/n01/mysqldata1/mysql-bin.000005
/n01/mysqldata1/mysql-bin.000006

Example of file 2 content.
/n01/mysqlarch1/mysql-bin.000004
/n01/mysqlarch1/mysql-bin.000001
/n01/mysqlarch2/mysql-bin.000005

So I want to match based only on mysql-bin.00000X and not the rest of the file path in each file as they differ between file1 and file2.
Here's the command I'm trying to run
cat file1 | egrep -v file2

The output I'm hoping for here would be...
/n01/mysqldata1/mysql-bin.000002
/n01/mysqldata1/mysql-bin.000003
/n01/mysqldata1/mysql-bin.000006

Any help would be much appreciated.

A: Just compare based on everything from /:
$ awk -F/ 'FNR==NR {a[$NF]; next} !($NF in a)' f2 f1
/n01/mysqldata1/mysql-bin.000002
/n01/mysqldata1/mysql-bin.000003
/n01/mysqldata1/mysql-bin.000006

Explanation
This reads file2 in memory and then compares with file1.

*

*-F/ set the field separator to /.

*FNR==NR {a[$NF]; next} while reading the first file (file2), store every last piece into an array a[]. Since we set the field separator to /, this is the mysql-bin.00000X part.

*!($NF in a) when reading the second file (file1) check if the last field (mysql-bin.00000X part) is in the array a[]. If it does not, print the line.

I'm having one problem that I've noticed when testing. If file2 is
  empty nothing is returned at all where as I would expected every line
  in file1 to be returned. Is this something you could help me with
  please? –  user2841861.

Then the problem is that FNR==NR matches when reading the second file. To prevent this, just cross check that the "reading into a[] array" action is done on the first file:
awk -F/ 'FNR==NR && argv[1]==FILENAME {a[$NF]; next} !($NF in a)' f2 f1
                 ^^^^^^^^^^^^^^^^^^^^

From man awk:

ARGV
The command-line arguments available to awk programs are stored in an
  array called ARGV. ARGC is the number of command-line arguments
  present. See section Other Command Line Arguments. Unlike most awk
  arrays, ARGV is indexed from zero to ARGC - 1


text:
Q: Why does Unity throw error CS0136 here while Visual Studio 2019 doesn't? Suppose you have this code in Unity (adapted from another SO question):
public class Test : MonoBehaviour {
    void Start() {
        int x = 0;
        void foo() {
            int x = 0;
            x = 1;
            Debug.Log(x);
        }
    }
}

In Visual Studio 2019, the compiler happily accepts this code, which makes sense given the explanation provided at the SO answer.
However Unity throws error CS0136, with the message:

error CS0136: A local or parameter named 'x' cannot be declared in
this scope because that name is used in an enclosing local scope to
define a local or parameter

This seems to reference local scopes  (not local functions), which indeed cannot redefine variables declared in the containing scope.
Local functions do seem to work in Unity (I can call foo after changing the variable names and get the expected Debug.Log output), so I'm wondering why this difference in compilers exists (and if there's acknowledgement/explanation for that difference somewhere in the docs).
Why does Unity throw an error here?
Unity Player Settings are set to Mono for Scripting backend and .NET Standard 2.0 for API compatibility (if that makes a difference).
EDIT: Unity version is 2019.3.0f6.

A: This seems to be the result of how Unity creates the csproj file, specifically the Language version it sets, and the mismatch between C# 8 and 7.3.
As a reference, this feature (hiding variable names in local functions) was introduced in C# 8. Here's the github link  to the change. As to why the Unity project uses C# 8, my best guess is below.
If you open up the csproj file created by Unity, you'll find
<PropertyGroup>
  <LangVersion>latest</LangVersion>
</PropertyGroup>

as well as a target to 4.7.1 (regardless of what your Unity project settings are)
<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>

and a defined constant: CSHARP_7_3_OR_NEWER, which is a Unity constant
From the C# docs on language versions, you can find that while .NET Standard 2.0 defaults to C# 7.3, the above <LangVersion> value seems to imply that the language version used in VS will be the latest one it has access to. Here's the relevant bit from the above link:

latest    - The compiler accepts syntax from the latest released version of
  the compiler (including minor version).

So in the end, it looks like if you've installed a compiler that supports C# 8, the Unity project will be setup in a way that allows that, even though it looks like internally, Unity is still using C# 7.3.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nodejs Put request throwing 400 Bad request Error Hi I am new to Nodejs and trying to make a put request to an API and end up getting HTTP 400 bad request error. Not sure where I am making a mistake.
function doSwitch(token) {
    var formData = querystring.stringify({
        name: 'region1',
        host: 'host1'
    });
    var put_options = {
        host: 'api.enterprise.xxx.com',
        port: '443',
        path: '/v1/updatehost/',
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token,
            'Content-Length': Buffer.byteLength(formData)
        },
    };
    var put_req = https.request(put_options, function (res) {
        if (res.statusCode != '200') {
            console.log(colors.red.bold("Error code :- " + res.statusCode));
            console.log(colors.red.bold("Error Message :- " + res.statusMessage));
            return;
        } else if (res.statusCode == '200') {
            console.log(colors.green.bold("API Switch Successful!! Error code :- " + res.statusCode));
        }
    });
    put_req.write(formData);
    put_req.end();
}
doSwitch(token);


text:
Q: How to construct a model object with form data in Spring MVC? I defined a model class Task with a member reference to another model class Product. I created a form, that has some fields of Task itself (like Task name) and a dropdown list of Product objects (product object). I have no idea how to pass the form data to the controller and controller will construct a Task object with these form data. Is there a nice feature of Spring Framework will fix it?
Task.java:
package com.lyn.model;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;

import com.lyn.model.enums.Priority;
import com.lyn.model.enums.Progress;
import com.lyn.model.enums.Stage;
import com.lyn.model.enums.TaskType;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
/**
 * @author    Yaning Liu
 *
 * @filename  Task.java
 *
 * @date      2019-02-16
 *
 */

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name="_Task")
@Getter @Setter @NoArgsConstructor
public class Task {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(nullable=false,unique=true)
    private long id;

    private String name;

    private String date;

    @Enumerated(EnumType.STRING)
    private Progress progress;

    @Enumerated(EnumType.STRING)
    private Stage stage;

    @Enumerated(EnumType.STRING)
    private TaskType task_type;

    @Enumerated(EnumType.STRING)
    private Priority priority;

    private int quality;

    @OneToOne
    private User user;

    @OneToOne
    private Product product;

    /**
     * @param id
     * @param name
     * @param date
     * @param progress
     * @param stage
     * @param task_type
     * @param priority
     * @param message
     * @param quality
     * @param user
     * @param product
     * @param type
     */
    public Task(long id, String name, String date, Progress progress, Stage stage, TaskType task_type,
            Priority priority, int quality, User user, Product product) {
        super();
        this.id = id;
        this.name = name;
        this.date = date;
        this.progress = progress;
        this.stage = stage;
        this.task_type = task_type;
        this.priority = priority;

        this.quality = quality;
        this.user = user;
        this.product = product;

    }

}

Product.java
package com.lyn.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

import com.lyn.model.enums.ProductType;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author    Yaning Liu
 *
 * @filename  Product.java
 *
 * @date      2019-01-25
 *
 */
@Entity
@Table(name="_Product")
@Setter
@Getter
@NoArgsConstructor
public class Product implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;

    private String name;

    private int quality;
    @Enumerated(EnumType.STRING)
    private ProductType product_type;

    /**
     * @param id
     * @param name
     * @param quality
     * @param product_type
     */
    public Product(long id, String name, int quality, ProductType product_type) {
        super();
        this.id = id;
        this.name = name;
        this.quality = quality;
        this.product_type = product_type;
    }

}

Controller.java
@ResponseBody
    @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST },value="insert")
    ModelAndView insertHandler(HttpServletRequest request, HttpServletResponse response,Task task) {

        if(task.getName()==null) {
            ModelAndView model = new ModelAndView("forward:insert_task.jsp");
            List<Product> products = this.productService.getProductList();
            model.addObject("products", products);

            return model;
        }
        long sessionUserid = Long.parseLong(String.valueOf(request.getSession().getAttribute("userid")));
        User user = this.userService.findUser(sessionUserid);

        this.taskService.addTask(task);
        ModelAndView model = new ModelAndView("forward:insert_task.jsp");
        return model;
    }

insert.jsp
 <select name="product" form="add_task_form" class="form-control m-bot15">
                                                <c:forEach items="${products}" var="product">
                                                         <option value="${product}" />${product.name}</option>
                                                </c:forEach>
                            </select>

form data:
name: Shiqi Zhang
date: 2028/10/20 13:00
priority: medium
quality: 1
product: com.lyn.model.Product@1e2115d9


text:
Q: Splitting lemma under assumption of the  axiom of choice The splitting lemma says:

Given a short exact sequence with maps $q$ and $r$:
$0 \rightarrow A \overset{q}{\rightarrow} B \overset{r}{\rightarrow} C \rightarrow 0$
then the following are equivalent:

*

*...

*there exists a map $u : C \rightarrow B$ such that $r \circ u = \mathrm{id}_C$

*$B \cong A \oplus C$

Now I figured, since $r(B) = \ker 0$, $r$ is surjective. Hence, for every $c \in C$ we have some $b \in B$ such that $r(b) = c$. Simply set $u(c) = b$ for one of these $b$s and you have your map $u$.
However, it turns out that this construction assumes the axiom of choice; it chooses one element from each of an infinite number of sets. So my question is: assuming the axiom of choice, is condition (2) always satisfied? Because this would imply that (3) holds for any such short exact sequence. Or am I making some mistake here?

A: I assume you are working in some fixed abelian category $\mathcal{A}$.
It is not true in general that every short exact sequence in $\mathcal{A}$ will split. The problem is that although you can pick a preimage for every 'element' $c\in C$ there is no guarantee that you can assemble this into a morphism in $\mathcal{A}$. It is true in the category of sets that every surjection splits if one assumes the axiom of choice but this is only a set map.
For instance in the category of abelian groups
$$0 \to \mathbb{Z}/2\mathbb{Z} \stackrel{2}{\to} \mathbb{Z}/4\mathbb{Z} \to \mathbb{Z}/2\mathbb{Z} \to 0$$
is exact but $\mathbb{Z}/4\mathbb{Z}$ is indecomposable.
Also if you are not in an abelian category it is not necessarily true that exact sequences display this symmetry. See for example this question where the notion is considered in the category of groups.

A: The mistake you're making is that your map $u$ is not a homomorphism of (whatever $A$, $B$, $C$ are---possibly groups or modules), it's just going to be a map of sets, if you define it the way you defined it. Read the proof of the lemma to see why this isn't good enough. Or think of $Z/2Z$ living in $Z/4Z$ with quotient $Z/2Z$.

A: For the record, the axiom of choice is not required to prove the splitting lemma. I can see why you might think it might; I once came to the same conclusion myself. To split the sequence on the right, you could start by finding a section of the surjection, invoking AC. Then you can project out the part of your section which doesn't lie in the kernel, which ensures the map is a homomorphism.
I asked about for clarification on math.SE, with a negative answer: no choice necessary. Basically, instead of starting by splitting the surjection, you recall that a retraction of the injection was part of your given data, and use it to construct the splitting of the surjection, without making any arbitrary choices.
https://math.stackexchange.com/questions/151438/does-the-splitting-lemma-hold-without-the-axiom-of-choice/

A: The axiom of choice may give you a map $u:C\to B$ as SETS.  However, it may not be a morphism in the category of $R$-modules.

A: This is right: a map $f:A \rightarrow B$ is surjectiv $\Longleftrightarrow$ $f$ has a right-inverse. The proof needs the axiom of choice, as you pointed out correctly. But this is just a map of sets.
EDIT: In the following I'm talking about groups (vector spaces, vector bundles, presheaves, sheaves,... should also do the job)
Every short exact seqeunce can be seen as a sequence
$$0 \overset{inc_0}\rightarrow A \overset{inc}{\rightarrow} B \overset{\pi}{\rightarrow} B/A \rightarrow 0$$
where $inc$ denotes the inclusion and $\pi$ the projection.
But (as for example Charles Siegel pointed out) surjectivity gives you just a rightinverse $u:C \rightarrow B$ as map of sets. So if you have further structures (let's say a group structure, vector space structure, etc.), this doesn't mean, that the map $u$ is an inverse with respect to these structures

A: It is not true: consider the exact sequence of abelian groups
$$0 \longrightarrow \mathbb{Z} \xrightarrow{x\mapsto 3x} \mathbb{Z} \xrightarrow{x\mapsto [x]_3} \mathbb{Z}/3 \longrightarrow 0 \quad$$ and note that the only homomorphism $\mathbb{Z}/3 \rightarrow \mathbb{Z}$ is the zero one. So the sequence does not split.
EDIT - As clarification, in the splitting lemma, the third condition should be:

*

*...

*...

*The sequence $0\rightarrow A \xrightarrow{q} B \xrightarrow{r} C\rightarrow 0$ and the canonical one $0\rightarrow A \xrightarrow{i} A \oplus C \xrightarrow{\pi} C\rightarrow 0$ are isomorphic (with the identities on A and on C).


text:
Q: When i click the Button nothing happen - android studio My application is about to find near hospital or bank etc.
But everytime when i click the button 'find' nothing happen on the map.
I am totally new to Android Studio, so I don´t know how to write my code that it will work the way I want it.Please can you help me to fix that..
This my mainActivity code :
    Spinner spType;
    Button btnFind;
    SupportMapFragment supportMapFragment;
    GoogleMap map;
    FusedLocationProviderClient fusedLocationProviderClient;
    double currentLat = 0, currentLong = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        spType = findViewById(R.id.sp_type);
        btnFind = findViewById(R.id.bt_find);
        supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.google_map);

        String[] placeTypeListe = {"atm", "bank", "hospital", "movie_theater", "restaurant"};
        String[] placeNameList = {"ATM", "Bank", "Hospital", "Movie Theatre", "Restaurant"};

        spType.setAdapter(new ArrayAdapter<>(MainActivity.this
                , android.R.layout.simple_spinner_dropdown_item, placeNameList));

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        if (ActivityCompat.checkSelfPermission(MainActivity.this
                , Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            getCurrentLocation();
        } else {
            ActivityCompat.requestPermissions(MainActivity.this
                    , new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44);

        }

        btnFind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int i = spType.getSelectedItemPosition();
                String url = "https://maps.googleapis.com/maps/api/..." + "?location=" + currentLat + "," + currentLong + "&radius=5000" + "&type=" + placeTypeListe[i] + "&sensor=true" + "&key=" + getResources().getString(R.string.google_map_key);

                new PlaceTask().execute(url);
            }
        });

    }

    private void getCurrentLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Task<Location> task = fusedLocationProviderClient.getLastLocation();
        task.addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null){
                    currentLat = location.getLatitude();
                    currentLong = location.getLongitude();
                    supportMapFragment.getMapAsync(new OnMapReadyCallback() {
                        @Override
                        public void onMapReady(@NonNull GoogleMap googleMap) {
                            map = googleMap;
                            map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                                    new LatLng(currentLat,currentLong),10
                            ));
                        }
                    });
                }
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 44) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getCurrentLocation();
            }
        }

    }

    private class PlaceTask extends AsyncTask<String,Integer,String> {
        @Override
        protected String doInBackground(String... strings) {
            String data = null;
            try {
                data = downloadUrl(strings[0]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return data;
        }

        @Override
        protected void onPostExecute(String s) {
            new ParserTask().execute(s);
        }
    }

    private String downloadUrl(String string) throws IOException {
        URL url = new URL(string);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        InputStream stream = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        StringBuilder builder = new StringBuilder();
        String line = "";
        while ((line = reader.readLine()) != null){
            builder.append(line);
        }
        String data = builder.toString();

        reader.close();
        return data;
    }

    private class ParserTask extends AsyncTask<String,Integer, List<HashMap<String,String>>> {

        @Override
        protected List<HashMap<String, String>> doInBackground(String... strings) {
            JsonParser jsonParser = new JsonParser();
            List<HashMap<String,String>> mapList = null;
            JSONObject object = null;
            try {
                object = new JSONObject(strings[0]);
                mapList = jsonParser.parseResult(object);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return mapList;
        }

        @Override
        protected void onPostExecute(List<HashMap<String, String>> hashMaps) {
            map.clear();
            for (int i=0;i<hashMaps.size();i++){
                HashMap<String,String> hashMapList = hashMaps.get(i);
                double lat = Double.parseDouble(hashMapList.get("lat"));
                double lng = Double.parseDouble(hashMapList.get("lng"));
                String name = hashMapList.get("name");
                LatLng latLng = new LatLng(lat,lng);
                MarkerOptions options = new MarkerOptions();
                options.position(latLng);
                options.title(name);
                map.addMarker(options);
            }
        }
    }
}

And this is my logcat errors that show me :
FATAL EXCEPTION: AsyncTask #1
                                                                                Process: com.example.add, PID: 13706
                                                                                java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(AsyncTask.java:415)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:920)

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:121)
at org.json.JSONTokener.nextValue(JSONTokener.java:98)
at org.json.JSONObject.<init>(JSONObject.java:168)
at org.json.JSONObject.<init>(JSONObject.java:185)
at com.example.add.MainActivity$ParserTask.doInBackground(MainActivity.java:174)
at com.example.add.MainActivity$ParserTask.doInBackground(MainActivity.java:166)
at android.os.AsyncTask$3.call(AsyncTask.java:394)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:920)


text:
Q: What do we call the process of cutting pencils down to expose more lead? We call the following a pencil cutter.

But what do we do with it? Do we cut the pencil? Cutting the pencil sounds odd to me, like it means actually we are cutting the pencil into pieces which is not something we do. So what do we do with it?
EDIT- In case anybody is in doubt what I mean to ask, here is an image of the process I want to know about.

What is this process called?

A: This is a pencil sharpener, which is used to sharpen pencils. The black stuff in the middle of a pencil is called graphite.

A: We don't call it a pencil cutter, we call it a pencil sharpener and we use it to sharpen the pencil.
This, too, is a pencil sharpener:

This, however, is not a pencil sharpener but a pencil sanding block, used to put a finer point on the pencil:

A: Just to provide a little diversity, let me mention that in some variants of English, e.g. Irish English, people often talk about paring the pencil, and call the device a pencil paper. I am not sure how widespread this is, however.
(In fact, according to this link
http://www.thejournal.ie/pencil-parer-sharener-topper-burning-question-1180841-Nov2013/
the term pencil topper is also popular in Ireland.)


text:
Q: modifying parameter prior to method invocation I have a parameter called "server" in several methods:
public synchronized Client getClientByStreamId(String streamId, Server server) {
  //some logic
}

public Client getClientByPublicSID(String publicSID, boolean isAVClient, Server server) {
  //some logic
}

What I want is that everytime those methods are called there is a check, that is performed to the param server before the method is called:
if (server == null) {
  server = someServer; //someServer is a variable I get somewhere else
}

From what I know there must be some trick with an annotation in Java6 so that you can do something like (pseudo code):
@ManipulateArgs(MyMethod);
public synchronized Client getClientByStreamId(String streamId, Server server) {
  //some logic
}

@ManipulateArgs(MyMethod);
public Client getClientByPublicSID(String publicSID, boolean isAVClient, Server server) {
  //some logic
}

private MyMethod(Server server) {
  if (server == null) {
    server = someServer; //someServer is a variable I get somewhere else
  }
}

Some kind of "pre-processor" that is called before the actual method is invoked with the params.
I just can't remember what the name of this pre-processing was. Or if it was annotaction based or something else. But I think it was an annotation.
Thanks
Sebastian

A: The general term of what you're looking for is a method interceptor. There are a variety of ways they are implemented. Aspect oriented programming is one way. See the tutorial http://www.javaworld.com/javaworld/jw-01-2002/jw-0118-aspect.html. If you're using a framework such as Spring or JBoss, there are interceptor annotations built in.


text:
Q: xmppStreamDidConnect not getting called I'm creating the framework in swift using Robbinson XMPP framework, I managed to set up the project, the delegate method bellow is getting called:
func xmppStreamWillConnect(_ sender: XMPPStream!) {
        print("will");
    }

but the delegate method below never gets called:
    func xmppStreamDidConnect(_ sender: XMPPStream!) {
            print("connected");
           /* auth func here*/
        }

i tried to put breakpoint in objc code, its hitting the // Notify delegates method (please ref screen shot ) but in my code its not get called ..Thanks

A: Catch the error while connecting to the server and check the error. Don't forget to set the jabbaerid before connecting.
let xmppStream = XMPPStream()
xmppStream.myJID = XMPPJID(string: "yourjabberID")
xmppStream.hostName = "yourxmppserver"
xmppStream.hostPort = 5222

do {
    try xmppStream.connect(withTimeout: XMPPStreamTimeoutNone)
    print("Connection success")
   }
catch let error
   {
    print(error)
   }


text:
Q: Using loop to run parallel builds using build-flow plugin in Jenkins I am using the build flow plugin to run tasks in parallel in Jenkins. Initially it was this that works:
parallel (
    { build("jobX", param: params["inputVal1"])
    },
    {build("jobX",  param: params["inputVal2"])
    }
)

However, my need now requires me to write this in some kind of loop since the number of jobs is dynamic. I want to do something like this (conceptually):
parallel
(
    for(int i=1; i<=numOfJobs; i++)
    {
        build("jobX", param: params["inputVal" + i])
    }
)

There is an answer provided in Jenkins Buildflow plugin: how to make variable numbers of jobs in parallel?, but it does not suit my need exactly.

A: You'll need something like:
parallel((1..numOfJobs).collect { index ->
    { -> build("job${index}", param: params["inputVal" + index]) }
})


text:
Q: Calculating the angle between a velocity (particles motion) and a line So I am creating a simulation of a bouncing ball, and the user can place lines the ball can collide with on the canvas by dragging from one point to another. There are essentially four lines that can be created:

So the object that stores a line is defined as such:
export interface pathSection {
    xfrom: number;
    yfrom: number;
    xto: number;
    yto: number;
    length: number;
}

The first and third lines in the image for example dont give the same value from
Math.atan2(yto - yfrom, xto - from);

So given the (relative) complexity of the surfaces, I need to find the angle between a moving object and that surface at the point of collision:

The ball strikes the surface at an angle a, which is what I want!
However I am having trouble finding the angle between the two vectors. This is what I understood would work:
var dx = this.path[index_for_path_section].xfrom - this.path[index_for_path_section].xto;
var dy = this.path[index_for_path_section].yfrom - this.path[index_for_path_section].yto;
var posX = this.particle.pos.x;
var posY = this.particle.pos.y;
var posNextX = posX + this.particle.v.x;
var posNextY = posY + this.particle.v.y;

var angleOfRamp = Math.atan2(dy, dx);
var angleOfvelocity = Math.atan2(posNextY - posY, posNextX - posX);
var angleBetween =  angleOfRamp - angleOfvelocity;

This is then used to calculate the speed of the object after the collision:
var spd = Math.sqrt(this.particle.v.x * this.particle.v.x + this.particle.v.y * this.particle.v.y);
var restitution = this.elasticity / 100;

this.particle.v.x = restitution * spd * Math.cos(angleBetween);
this.particle.v.y = restitution * spd * Math.sin(angleBetween);

However the angle calculated is around -4.5 Pi, about -90 degrees for the object directly down and the surface at what looks to be around 45-60 degrees…

The red arrow shows the path of the object moving through the surface - the white dots show where a collision has been detected between the surface and the object.
Any help on how to get the correct and usable angle between the two velocity and the line would be appreciated!
Note I have tried utilizing this solution, but have struggled to adapt it to my own work.

A: So it took me some time, and I am not 100% sure still of why it works because I think im finding the JavaScript angles system a bit tricky, but:
var dx = this.path[collided].xfrom - this.path[collided].xto;
var dy = this.path[collided].yfrom - this.path[collided].yto;
var spd = Math.sqrt(this.particle.v.x * this.particle.v.x + this.particle.v.y * this.particle.v.y);

var angleOfRamp = Math.atan2(dy, dx);
var angleOfvelocity = Math.atan2(this.particle.v.y, this.particle.v.x);
var angleBetween =  angleOfRamp * 2 - angleOfvelocity; // not sure why :)

if (angleBetween < 0) { angleBetween += 2*Math.PI; } // not sure why :)

const restitution = this.elasticity / 100;

this.particle.v.x = restitution * spd * Math.cos(angleBetween);
this.particle.v.y = restitution * spd * Math.sin(angleBetween);

Thanks to all who looked :)


text:
Q: Dynamic scan for a string : C Consider below code I have written:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

void dynamicScan(char** str)
{
 *str=(char*) malloc(10*sizeof(char));
 int i=0,j=1,k=0,c;
 do{
 c=getchar();
 *(*str+i)=c;
 i++;
 k++;
 if(k >=10)
 {
     j++;
     *str=(char*) realloc(*str,j*sizeof(char)); //Edited: Line 17 here
     assert(*str);
     printf("Resized to %d bytes\n",j*10);
     k=0;
 }
 }while(c != '\n');

 *(*str+i)='\0';
}

int main()
{

char* dynamicName,*dynAdd;

printf("-------------------------\n");
printf("Enter a Dynamic Name: ");
dynamicScan(&dynamicName);
printf("Dynamic Name: %s\n",dynamicName);
printf("Enter a Dynamic Address: ");
dynamicScan(&dynAdd);
printf("Dynamic Address: %s\n",dynAdd);

free(dynamicName);
free(dynAdd);

return 0;
}

I am trying to implement dynamic scannig of a character array. It works fine.
I have seen the code running to large arrays .e.g say resized to 80 bytes.
But many times code is crashing even for resizing to 20 bytes.
Below is the dgb output. I am not able to figure out, what is going wrong, Can any help to debug?
(gdb) run
    The program being debugged has been started already.
    Start it from the beginning? (y or n) y
    Starting program: /cygdrive/d/cPractice/getS.exe
    [New Thread 8820.0x102c]
    [New Thread 8820.0x3d0]
    -------------------------
    Enter a Dynamic Name: Andrew Thomas from UK
    Resized to 20 bytes
    Resized to 30 bytes
    Dynamic Name: Andrew Thomas from UK

    Enter a Dynamic Address: I was living in scotland; now in united kingdom
    Resized to 20 bytes
    Resized to 30 bytes

    Program received signal SIGABRT, Aborted.
    0x00401206 in dynamicScan (str=0xd0) at getS.c:17
    17               *str=(char*) realloc(*str,j*sizeof(char));
    (gdb)

A: It appears that you should change this line:
*str=(char*) realloc(*str,j*sizeof(char));

to this:
*str=(char*) realloc(*str,j*10*sizeof(char));


text:
Q: Unexpected behavior of KeyTake list = {{a, b, c, e}, {1, 2, b, h}, {"a", "h", 3, 5}};
asso = GroupBy[list, {#[[1]], #[[2]]} &]

<|{a, b} -> {{a, b, c, e}},
  {1, 2} -> {{1, 2, b, h}},
  {"a","h"} -> {{"a", "h", 3, 5}}|>

There is a problem in this code, since "a" and "h" might be two keys.  However, KeyExistsQ is not Listable, but KeyTake is.
KeyExistsQ[asso, {"a", "h"}]

True

KeyTake[asso, {"a", "h"}]

<||>

So I wrap Key around {"a", "h"} to eliminate ambiguity.
KeyTake[asso, Key[{"a", "h"}]]

<||>

Contrast the above with
KeyDrop[asso, Key[{"a", "h"}]]

<|{a, b} -> {{a, b, c, e}}, {1, 2} -> {{1, 2, b, h}}|>

Have I found a bug? Tested on V10.4

A: The behavioral discrepancy can be shown with a very simple example.
assoc = <|1 -> 1, 2 -> 2|>;
{KeyTake[assoc, 1], KeyTake[assoc, Key[1]], KeyTake[assoc, Key[1][assoc]]}

{<|1 -> 1|>, <||>, <|1 -> 1|>}

{KeyDrop[assoc, 1], KeyDrop[assoc, Key[1]], KeyDrop[assoc, Key[1][assoc]]}

{<|2 -> 2|>, <|2 -> 2|>, <|2 -> 2|>}

Surely the behavior of KeyTake[assoc, Key[1]] and KeyDrop[assoc, Key[1]] should be more consistent. Personally, I feel it is the behavior of KeyDrop that is wrong.
Update
I reported this issue to Wolfram tech support. Yesterday, 2016-Jul-7, I received a reply from which I quote the relevant section.

It does appear that KeyDrop is not behaving consistently. I have forwarded an incident report to our developers with the information you provided. If I receive any progress on this issue, you will be posted regarding the same.

This confirms my suspicion that it is KeyDrop and not KeyTake that is behaving badly.


text:
Q: Goodness-of-fit for Discrete Distributions I've been doing some data analysis with Scipy. So far I accomplished this with continuous distributions:

*

*I can fit a probability distribution to a set of data points using a maximum likelihood fit. For example using stats.chi2.fit(data_points).

*I can test if my samples comes from a specific distribution. For example using stats.kstest(data_points, 'norm')
I tried to do the same analysis with discrete distributions (like Poisson, Binomial and Geometric), but it seems like Scipy doesn't offer similar functionality for discrete distributions. What's the standard approach for fitting and testing for discrete distributions?


text:
Q: Java 1.7.21 install via GPO fails on Win 8 Attempting to distribute Java runtime 7 update 21 via GPO to Windows 8.
Problem is the GPO fails with:

The install of application Java 7 Update 21 (64-bit) from policy
  Workstation 64-bit failed. The error was: %%1612

Then try running it manually but that fails with:

There was a problem starting C:\Program Files\Java\jre7\bin\installer.dll
  The specified module could not be found.

Is anyone else having difficulties with this version of Java?


text:
Q: Django "__init__() keywords must be strings" error while running "runserver" I just set up virtualenv to start django project. I installed everything fine.
when I issue "python manage.py runserver" it spits out this error. I tried all kind of django runserver error through out and no one seems to have this. Anyone have insight into it?
Validating models...

Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.commands.runserver.Command object at 0x1016bb0d0>>
Traceback (most recent call last):
  File "/usr/local/bin/django-hari/lib/python2.6/site-packages/Django-1.5.4-py2.6.egg/django/core/management/commands/runserver.py", line 92, in inner_run
    self.validate(display_num_errors=True)
  File "/usr/local/bin/django-hari/lib/python2.6/site-packages/Django-1.5.4-py2.6.egg/django/core/management/base.py", line 280, in validate
    num_errors = get_validation_errors(s, app)
  File "/usr/local/bin/django-hari/lib/python2.6/site-packages/Django-1.5.4-py2.6.egg/django/core/management/validation.py", line 35, in get_validation_errors
    for (app_name, error) in get_app_errors().items():
  File "/usr/local/bin/django-hari/lib/python2.6/site-packages/Django-1.5.4-py2.6.egg/django/db/models/loading.py", line 166, in get_app_errors
    self._populate()
  File "/usr/local/bin/django-hari/lib/python2.6/site-packages/Django-1.5.4-py2.6.egg/django/db/models/loading.py", line 72, in _populate
    self.load_app(app_name, True)
  File "/usr/local/bin/django-hari/lib/python2.6/site-packages/Django-1.5.4-py2.6.egg/django/db/models/loading.py", line 96, in load_app
    models = import_module('.models', app_name)
  File "/usr/local/bin/django-hari/lib/python2.6/site-packages/Django-1.5.4-py2.6.egg/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/usr/local/bin/django-hari/lib/python2.6/site-packages/Django-1.5.4-py2.6.egg/django/contrib/auth/models.py", line 21, in <module>
    from django.contrib.contenttypes.models import ContentType
  File "/usr/local/bin/django-hari/lib/python2.6/site-packages/Django-1.5.4-py2.6.egg/django/contrib/contenttypes/models.py", line 127, in <module>
    class ContentType(models.Model):
  File "/usr/local/bin/django-hari/lib/python2.6/site-packages/Django-1.5.4-py2.6.egg/django/db/models/base.py", line 97, in __new__
    new_class.add_to_class('_meta', Options(meta, **kwargs))
TypeError: Error when calling the metaclass bases
    __init__() keywords must be strings

A: It's a known issue. Django 1.5 requires Python 2.6.5 or newer. You have an older version of Python installed on your computer. You need to install a newer version of Python, for example Python 2.7.x.


text:
Q: WPF Binding to dictionary with classes I am new to WPF programming and not a professional in C# coding.
So I have the following problem:
I have a lot of different comboboxes and textboxes.
I want to bind them to a variable in the background, because I want to fill the comboboxes with Data from a Database.
So I created the following in the file
liste.xaml.cs:
private Dictionary<string, Filter> _ctrlFilter;

public Dictionary<string, Filter> ctrlFilter {
    get { return _ctrlFilter; }
    set { _ctrlFilter = value; }
}

When I load liste.xaml it initializes the ctrlFilter Dictionary with the following code:
ctrlFilter = new Dictionary<string, Filter>
{
  //ComboBox
  {"hersteller", new Filter("Hersteller", typeof(ComboBox)) },
  {"fahrzeugart", new Filter("Fahrzeugart", typeof(ComboBox), false) },

  //TextBox
  {"baujahr", new Filter("Baujahr", typeof(TextBox), true, typeof(short)) },
  {"anschaffungswert", new Filter("Anschaffungswert", typeof(TextBox), true, typeof(decimal)) },
  {"finanz_restwert", new Filter("Restwert", typeof(TextBox), true, typeof(decimal)) },

  //Others
  {"zugelassen", new Filter("Zugelassen", typeof(DatePicker), true, typeof(DateTime)) },
  {"vstabzug", new Filter("Vorsteuerabzug", typeof(CheckBox), true, typeof(bool)) },
};

So the filter class (which is also in liste.xaml.cs) looks like this:
public class Filter
{
    public string FilterName;
    public Type ControlType;
    public Type FromToType;
    public bool Load;
    public ObservableCollection<object> Items;
    public object SelectedFilter;
    public object From;
    public object To;

    public Filter( string name, Type type, bool load = true, Type ftType = null)
    {
        Reset();
        FilterName = name;
        ControlType = type;
        Load = load;
        FromToType = ftType;
    }

    public void Reset()
    {
        From = null;
        To = null;
        SelectedFilter = null;
        Items = new ObservableCollection<object>();
    }
}

Now i dynamically load other xaml-files into the liste.xaml file. For example the Fahrzeug_Allgemein.xaml
There I have the comboboxes, which looks like this:
            <StackPanel>
                <Label Content="Hersteller:" Target="{Binding ElementName=cmb_hersteller, Mode=OneWay}"/>
                <ComboBox x:Name="cmb_hersteller" Fahrzeuge:FilterExtension.FilterName="hersteller"  Width="120" ItemsSource="{Binding ctrlFilter[hersteller].Items}" SelectedIndex="0" SelectionChanged="cmb_hersteller_SelectionChanged"/>
            </StackPanel>

You see that I tried to get the Items property from the Filter class, but it doesn't work. In the Visual Studio 2015 output it says:
System.Windows.Data Error: 40 : BindingExpression path error: 'Items' property not found on 'object' ''Filter' (HashCode=44888241)'. BindingExpression:Path=ctrlFilter[hersteller].Items; DataItem='liste' (Name=''); target element is 'ComboBox' (Name='cmb_hersteller'); target property is 'ItemsSource' (type 'IEnumerable')

I already read something about INotifyPropertyChanged but I do not know how to use it in my case.
It would be cool, if you could help me.
Thank you.

A: I haven't thought that the answer is so simple. I just had to add { get; set; } to the Items property.
So the code looks like this now:
public class Filter
{
    public string FilterName;
    public Type ControlType;
    public Type FromToType;
    public bool Load;
    public ObservableCollection<ComboBoxItem> Items { get; set; }
    ...

I think it means, that the Items property is able to bind only with this addition.

A: I have too low repuatation to just comment this but you should read up on properties in c# and data binding if you have yet to do so.  I read these links plus the extra links they contain and it helped increase my understanding significantly.


text:
Q: Raising a FileNotFoundError I have a function that takes a source file containing times (a csv file), reads it, then sorts the lines in order and writes them in a destination file. However, if the source csv file does not exist, I need to raise a FileNotFoundError. I've raised exceptions before, for example, if a parameter wasn't an integer I had to raise ChangeParameterError by using:
class ChangeParameterError(Exception):
    pass

and then raising that in my function.
For my problem, my function is as follows:
def times(src,dst):
    s = open(src,'r')
    d = open(dst,'w')
    lines = s.readlines()
    s.close()
    lines.sort()
    for i in lines:
        print((str(i).strip()), file = d)
    d.close()

Any help is appreciated!

A: If the specified file is not found, the FileNotFoundError will be raised automatically by the open call when trying to open the file.

A: The exception is automatically raised by python. But you may need to wrap your open with a try-except to catch the exception without breaking your code:
try:
    s = open(src,'r')
except FileNotFoundError:
    print('file not found')


text:
Q: Characterizing the A-module M/S I've been working through this for a little while, and I'm not 100% sure I understand what I'm supposed to be doing here, or maybe I'm not grasping correctly what they mean by "Characterize".
Characterize each of the following quotient $A$-modules $M/S$ (sorry if translation is a little bit off).

*

*$M = A^n$ and $S=\{(a_1,...,a_n) : \sum_{i=1} ^n a_i=0\}$.

I would imagine this one to be the easiest one, but I'm not sure how to approach it. I can imagine a few obvious elements of this module, but I can't really see it in a general sense.

*$M = A[X]$ and $S=\{f \in M : f(1) = 0 \}$.

Unless I'm missing something, $f$ is in the same class as 0 if $ x - 1 | f$ and the class of $f$ is made up by $f + p(x)(x-1)$. Is this "characterization" enough?
I also understand that this very similar to the quotient in the first item, which I imagine is the point.
Edit: Ok, so this is isomorphic to $A$ with $\phi : A[X] \rightarrow A$ so that $\phi(f) = f(1) $ since it's obvious that $Ker\phi = S$ and $Im \phi = A$.

*$M = M_n (A)$ and $S= \{ (a_{ij}) \in M : a_{i1} = 0 \forall 1 \leq i \leq n \}$

Here since $ \begin{bmatrix}
    0 & x_{12} & x_{13} & \dots  & x_{1n} \\
    0 & x_{22} & x_{23} & \dots  & x_{2n} \\
    \vdots & \vdots & \vdots & \ddots & \vdots \\
    0 & x_{n2} & x_{n3} & \dots  & x_{nn}
\end{bmatrix} $ is in the same class as $0$, $f$ and $g$ are in the same class if their first columns coincide. As I understand it, this is isomorphic to $A^n$ since it's just taking the projection of the first column.
Any help would be greatly appreciated.

A: The problem asks to find an $A$-module $N$ (eventually you already know from class) such that $M/S\simeq N$ (eventually by using a well known isomorphism theorem).
Hints.

*

*Define $f:A^n\to A$ by $f(a_1,\dots,a_n)=\sum_{i=1}^na_i$.

*Define $f:A[X]\to A$ by $f(p(X))=p(1)$.

*Define $f:M_n(A)\to A^n$ by $f((a_{ij})_{i,j})=(a_{11},\dots,a_{n1})$.

A: To augment user26857's answer, note that:

*

*$(a_1,a_2,\dots,a_n) + S$

$= (a_1+a_2+\cdots+a_n,0,\dots,0) + (a_1-a_2-\cdots-a_n,a_2,\dots,a_n) + S$
$= (a_1+a_2+\cdots+a_n,0,\dots,0) + S$.

*If $p(X) = q(X)(X - 1) + r$ (for $r \in A$), then $p(X) + S = r + S$.

*If $B = \begin{bmatrix}
    x_{11} & x_{12} & x_{13} & \dots  & x_{1n} \\
    x_{12} & x_{22} & x_{23} & \dots  & x_{2n} \\
    \vdots & \vdots & \vdots & \ddots & \vdots \\
    x_{n1} & x_{n2} & x_{n3} & \dots  & x_{nn}
\end{bmatrix}$,

then $B + S = \begin{bmatrix}x_{11}&0&0&\dots&0\\x_{12}&0&0&\dots&0\\ \vdots&\vdots&\vdots&\ddots&\vdots\\x_{n1}&0&0&\dots&0\end{bmatrix} + \begin{bmatrix}
    0 & x_{12} & x_{13} & \dots  & x_{1n} \\
    0 & x_{22} & x_{23} & \dots  & x_{2n} \\
    \vdots & \vdots & \vdots & \ddots & \vdots \\
    0 & x_{n2} & x_{n3} & \dots  & x_{nn}
\end{bmatrix} + S$
$= \begin{bmatrix}x_{11}&0&0&\dots&0\\x_{12}&0&0&\dots&0\\ \vdots&\vdots&\vdots&\ddots&\vdots\\x_{n1}&0&0&\dots&0\end{bmatrix} + S$.


text:
Q: How to reverse each word in a text file with linux commands without changing order of words There's lots of questions indicating how to reverse each word in a sentence, and I could readily do this in Python or Javascript for example, but how can I do it with Linux commands? It looks like tac might be an option, but seems like this would likely reverse lines as well as words, rather than just words? What other tools can do this? I literally have no idea. I know rev and tac and awk all seem like contenders...
So I'd like to go from:
cat dog sleep
pillow green blue

to:
tac god peels
wollip neerg eulb

**slight followup
From this reference it looks like I could use awk to break each field up into an array of single characters and then write a for loop to reverse manually each word in this way. This is quite awkward. Surely there's a better/more succinct way to do this?

A: Try this on for size:
sed -e 's/\s+/ /g' -e 's/ /\n/g' < file.txt | rev | tr '\n' ' ' ; echo

It collapses all the space and counts punctuation as part of "words", but it looks like it (at least mostly) works.  Hooray for sh!


text:
Q: How to query for accounts which have contacts only being a new learner im unable to fetch accounts which have contacts only with this Query==> select name,(select lastname form contacts) from account<== with this getting all accounts

A: Use this query - the outer query looks for Accounts only in the set of Contacts that have an AccountId populated.
select id, name from Account where ID IN (select accountId from Contact)


text:
Q: Published and waiting for response on a topic with RabbitMQ / EasyNetQ - how to get only yours? When a publisher expects an answer to a message, how to ensure it will get only relevant answers (to its own messages) when you scale it out?
We have a client process that publishes a message for a server process to answer. Additionally, we have a "listener" process that just needs to consume both the questions and the answers without publishing anything. Also, the server process might be broken to several ones on the future, creating a message cascade. We can't use the request/response, since we need the listener and then again, when we will have the cascade... Besides, we will have several question/answer categories, and request/response in EasyNetQ doesn't support topics.
Our solution with EasyNetQ was simple topic-based publish/subscribe: client publishes to "question" topic, subscribes to "answer", server subscribes to "question" and publishes to "answer", and the listener just subscribes to both.
The problem is when you scale out the client. Two instances of it now publish questions, but since they are both subscribed to a single "answer" topic, one might get the answer to the question published by the other instance, and not get his own.
The solution we found is to have the client use a uniquely named queue when subscribing to "answer" - this way each client will get all of the answers, and just needs to ignore the ones that are not his. However, this solution has some performance drawbacks and also results in uniquely named queues accumulating in RabbitMQ each time a client crashes (or just restarted during development, etc.).
Client, sending an object msg:
string corrId = Guid.NewGuid().ToString();

// Register the corrId in a dictionary
//...

var myMessage = new MyMessage {correlationId =corrId, realMessage = msg};
easyNetQBus.Subscribe<MyMessage>("mqClient"+uniqueSuffix, HandleMsg, x => x.WithTopic("answer"));
easyNetQBus.Publish(myMessage, "question");

// In HandleMsg, we see if we have issued questions with the correlation id that came with the answer (lookup in the dictionary) and if not, ignore it

Server:
easyNetQBus.Subscribe<MyMessage>("mqServer", HandleMsg, x => x.WithTopic("question"));

// In HandleMsg, we publish the answer back to "answer" with the correlation id from the question

Is there another pattern we should be using? We could put inside each message a unique topic/queue to send the answer to, but this complicates the lives of the listener and the flexibility of the future participants in the cascade I mentioned...

A: One way to solve your problem would be to use the Remote Procedure Call pattern. This provides an easy, scalable way to give each client a unique queue.
From the example:

*

*When the Client starts up, it creates an anonymous exclusive callback
queue. For an RPC request, the Client sends a message with two
properties: ReplyTo, which is set to the callback queue and
CorrelationId, which is set to a unique value for every request.

*The request is sent to an rpc_queue queue.  The RPC worker (aka:
server) is waiting for requests on that queue. When a request
appears, it does the job and sends a message with the result back to
the Client,    using the queue from the ReplyTo property.

*The client waits for data on the callback queue. When a message
appears, it checks the CorrelationId property. If it matches
the value from the request it returns the response to the
application.

If your callback queues are auto-deleting, exclusive queues (RabbitMQ queue documentation), then they should not pile up when either the clients or the server restart.

With some workloads queues are supposed to be short lived. While
clients can delete the queues they declare before disconnection, this
is not always convenient. On top of that, client connections can fail,
potentially leaving unused resources (queues) behind.
There are three ways to make queue deleted automatically:

*

*Exclusive queues (covered below)

*TTLs (also covered below)

*Auto-delete queues

An auto-delete queue will be deleted when its last consumer is
cancelled (e.g. using the basic.cancel in AMQP 0-9-1) or gone
(closed channel or connection, or lost TCP connection with the
server).
If a queue never had any consumers, for instance, when all consumption
happens using the basic.get method (the "pull" API), it won't be
automatically deleted. For such cases, use exclusive queues or queue
TTL. (RabbitMQ queue documentation)


text:
Q: Unable to save data using hibernate in java I am trying to create Many to one mapping between two entity named as
a) Flight
b) airservice_company.
But when I am trying to save the data using session.save() method I am getting following error:-
Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not execute statement
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
    at Service.Service_Class.add_Company(Service_Class.java:65)
    at ManyToOne.App.main(App.java:15)
Caused by: java.sql.SQLException: Field 'company_Id' doesn't have a default value
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1084)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4232)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4164)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2776)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2838)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2334)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2262)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2246)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
    ... 23 more

A: The error message states that you try to insert a new record into your table without filling a field which is required to be filled.
In your case, that field seems to be your primary key or so called "id" which is normally auto-generated by incrementing it. So if you have 3 records, they have id 1, 2 and 3.
In Hibernate, you can do that by adding @GeneratedValue(strategy=GenerationType.AUTO)
In MySQL, this automatically results in auto incrementing your id field. In other database servers, this can also result in having a seperate table for id's.
For further information about GeneratedValue, just take a look into Hibernate documentation: http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping-identifier
I hope my post helped.


text:
Q: How to extract content of each superpixel and resize them? SuperPixeled image
This is the image and I want to save only the non-black region superpixels after resizing them to 56x56. I am working on superpixel classification.

A: You can use skimage.measure.regionprops.
from skimage.segmentation import slic
from skimage.measure import regionprops

# Assume image is given
segments = slic(image, n_segments=numSegments, compactness=0.1,enforce_connectivity=True)
props = regionprops(segments,intensity_image=image)

segmentsToExclude = []
for s, segment in enumerate(segments):
    if props[s].mean_intensity < 5: # basically black
        segmentsToExclude.append(s)

Something along those lines.  Check out this skimage link for more information on regionprops.


text:
Q: Is there a ScenarioContext in WebdriverIO- how do we set a value to a key and then use this data across test scenarios? Is there a ScenarioContext in WebdriverIO- how do we set a value to a key and then use this data across test scenarios?
I would like to do something like this using WebdriverIO- Java script-
 public ScenarioContext(){
        scenarioContext = new HashMap<String, Object>();
    }

    public void setContext(Context key, Object value) {
        scenarioContext.put(key.toString(), value);
    }

    public Object getContext(Context key){
        return scenarioContext.get(key.toString());
    }

    public Boolean isContains(Context key){
        return scenarioContext.containsKey(key.toString());
    }
}

A: So you want a variable to have a value which can be shared between scenarios and edited between scenarios.
If yes, then please look at the https://webdriver.io/docs/shared-store-service.html
WDIO team have came up with module to achieve your task.
There is one other way as well:
In your beforeSession hook on wdio.conf.js file, you can define a global variable like global.scenarioContext = {}.
And now anywhere in your code(including stepDefinitions) you can access this variable as like scenarioContext(NOTE: do not prefix with global.) and assign value or read value or edit value.
Please let us know if this helps.
Thanks,
Naveen

A: I used the shared stored services and it solved my problem- https://webdriver.io/docs/shared-store-service.html
Additionally have to update the wdio.conf.js file to add the 'shared-store' in the services section like this-
 services: [
['selenium-standalone', {
logFileName: 'wdio-chromedriver.log', // default
outputDir: 'driver-logs', // overwrites the config.outputDir
args: ['drivers']
}], ['shared-store']
],


text:
Q: Setting expiration in IIS 7 I have to set expiration for my static files of my application in IIS 7. Using the dialog below: I set it to 10 days.

But when I look at my page analysis using PageSpeed add-on in Chrome, I see that there is no expiration on the files.

Do I have to do something in my application configuration too?

A: You can do this pure in your web.config file :
<?xml version="1.0"?>
<configuration>
  <!-- Cache Settings -->
  <location path="data">
    <system.webServer>
      <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="10.00:00:00"/>
      </staticContent>
    </system.webServer>
  </location>
</configuration>

For the path value, you can do something like : images\interface (example)
For the cacheControlMaxAge : 10 = days = DD.HH:MM:SS


text:
Q: How to combine lists of tables with similar structures and matched named elements? I have two lists of tables, named Observed, and Expected which contain tables with corresponding names, and matching r*2 tables.
For example, in Observed list for AgeGroup element:
            0     1
  18-34 49841  8740
  0      4440  1687
  1-4   14537  2735
  13-17 11531  1656
  35-54 41580 11206
  5-12  17091  1798
  55-74 27807 16417
  75+   16068 22866

And in Expected list for AgeGroup element:
                0         1
  18-34 42856.688 15724.312
  0      4482.391  1644.609
  1-4   12635.850  4636.150
  13-17  9647.345  3539.655
  35-54 38617.182 14168.818
  5-12  13818.815  5070.185
  55-74 32353.394 11870.606
  75+   28483.336 10450.664

I would like to create a new list which combines columns for matching elements together from the two lists, so the new element table for AgeGroup, say in a new list called CombinedOE, the table (or better if possible, data frame), would look like this.

With the numbers for expected possibly rounded to whole numbers.
Sample of data:
Observed <- list(AgeGroup = structure(c(49841, 4440, 14537, 11531, 41580,
17091, 27807, 16068, 8740, 1687, 2735, 1656, 11206, 1798, 16417,
22866), .Dim = c(8L, 2L), .Dimnames = structure(list(c("18-34",
"0", "1-4", "13-17", "35-54", "5-12", "55-74", "75+"), c("0",
"1")), .Names = c("", "")), class = "table"), Sex = structure(c(92576,
90319, 32101, 35004), .Dim = c(2L, 2L), .Dimnames = structure(list(
    c("Male", "Female"), c("0", "1")), .Names = c("", "")), class = "table"),
    EthnicGroup = structure(c(140393, 10225, 4708, 20687, 2452,
    4430, 57125, 2456, 1139, 5055, 518, 812), .Dim = c(6L, 2L
    ), .Dimnames = structure(list(c("White", "Asian", "Black",
    "Check", "Mixed", "Other"), c("0", "1")), .Names = c("",
    "")), class = "table"))
Expected <- list(AgeGroup = structure(c(42856.68798, 4482.39066, 12635.84976,
9647.34546, 38617.18188, 13818.81462, 32353.39392, 28483.33572,
15724.31202, 1644.60934, 4636.15024, 3539.65454, 14168.81812,
5070.18538, 11870.60608, 10450.66428), .Dim = c(8L, 2L), .Dimnames = structure(list(
    c("18-34", "0", "1-4", "13-17", "35-54", "5-12", "55-74",
    "75+"), c("0", "1")), .Names = c("", ""))), Sex = structure(c(91211.19966,
91683.80034, 33465.80034, 33639.19966), .Dim = c(2L, 2L), .Dimnames = structure(list(
    c("Male", "Female"), c("0", "1")), .Names = c("", ""))),
    EthnicGroup = structure(c(144500.21844, 9277.16598, 4277.54826,
    18832.33236, 2172.7926, 3834.94236, 53017.78156, 3403.83402,
    1569.45174, 6909.66764, 797.2074, 1407.05764), .Dim = c(6L,
    2L), .Dimnames = structure(list(c("White", "Asian", "Black",
    "Check", "Mixed", "Other"), c("0", "1")), .Names = c("",
    ""))))

A: library(tidyverse)

# update column names
Obs = map(Observed, ~{as.data.frame.matrix(.x) %>% setNames(paste0("Obs_", names(.)))})

Exp = map(Expected, ~{as.data.frame.matrix(.x) %>% setNames(paste0("Exp_", names(.)))})

# bind columns of updated lists
# round columns
# reorder columns
map2(Obs, Exp, cbind) %>%
  map(~{.x %>% mutate_all(round) %>% select(matches("0"), everything())})

# $`AgeGroup`
#   Obs_0 Obs_1 Exp_0 Exp_1
# 1 49841  8740 42857 15724
# 2  4440  1687  4482  1645
# 3 14537  2735 12636  4636
# 4 11531  1656  9647  3540
# 5 41580 11206 38617 14169
# 6 17091  1798 13819  5070
# 7 27807 16417 32353 11871
# 8 16068 22866 28483 10451
#
# $Sex
#   Obs_0 Obs_1 Exp_0 Exp_1
# 1 92576 32101 91211 33466
# 2 90319 35004 91684 33639
#
# $EthnicGroup
#   Obs_0 Obs_1  Exp_0 Exp_1
# 1 140393 57125 144500 53018
# 2  10225  2456   9277  3404
# 3   4708  1139   4278  1569
# 4  20687  5055  18832  6910
# 5   2452   518   2173   797
# 6   4430   812   3835  1407


text:
Q: How to set up SVN repository in xCode 9.0 With xCode 9.0, I am facing problem with SVN setup.
I could not find any option to add SVN repository which was working
 proper with earlier versions of xCode.
In source control, I am getting GIT everywhere. I am using SVN for
 long time and was properly working with earlier versions of xCode but
 this is not working with xCode 9.0.

A: If you have older version of xcode and above method of upgrade is not working or cannot be used then Terminal can be used to upgrade.

*

*Go to Terminal

*change directory to the project folder base, using cd  command

*To verify if you are at the base run the command "ls -l". You should see a folder named .svn

*run the command "svn upgrade"

*If you see Upgraded message then all done OK. Restart Xcode to see the SVN commands under Source Control menu.

A: I could checkout a SVN repository from Xcode 9.2
I went to source control->clone->choose option svn and authentication and checkout.

A: I am adding this answer as I found work around for this (Not as a full fledge solution)
If you have upgraded your xCode version to 9.0, and could not find anything to attach your code to SVN repository then following steps will help you out:

*

*Take latest checkout from Terminal

*Open you code in xCode8 (> 8.0 and < 9.0)

*GO to Source Control

*You may get an alert to upgrade subversion to 1.9

*Click on upgrade

*Now open same code in xCode9.0, you are now ready for all svn commits and updates.

A: All mentions of subversion seem to be gone from XCode 9, but it still works, and it's actually terribly simple:
(tested with XCode 9.4.1)

*

*Go to Source Control->Clone...

*You've probably seen this screen and stopped, because it says GitHub prominently. BUT, notice the "Enter repository URL" text bar at the top! You can just write your subversion URL there and hit Clone!

*Like so. As you hit the Clone button, you'll be asked to enter your svn credentials (if needed), and the directory where the repo will be cloned.

*After that, just open your project or workspace from the cloned dir, and you're all set. Even the new Source Control Navigator (command+2), should work right away.

I haven't figured out how to add things to a subversion repo, but for existing repos, this works. I've not tried this on XCode 10 beta at this time, either.


text:
Q: Search Records in RDLC Report FromDate to ToDate I have a report,the data of the report is coming from a Table Tbl_Orders in which i have a column named CreatedDate.
I have a search above the report in which i need to search by Name and search by FromDate to ToDate.
For example if i select any date from FromDate and a Date from ToDate records should be displayed between selected dates.
Below is my Query
CREATE PROC Sp_Search_RatingAndReviewsReport (@Name nvarchar(200),
                                              @FromDate nvarchar(200),
                                              @ToDate nvarchar(200))
AS
BEGIN

    SELECT a.*,
           b.Name,
           CONVERT(nvarchar(20), a.CreatedDate, 105) AS Date
    FROM Tbl_CustomerRating a
         LEFT JOIN Tbl_Customer b ON a.CustomerId = b.CustomerId
    WHERE (b.Name LIKE '%' + @Name + '%'
        OR @Name = '')
      AND (CONVERT(nvarchar(20), a.CreatedDate, 101) BETWEEN (@FromDate) AND (@ToDate));

If I'm using the above query its working fine for searching by
FromDate to ToDate but i'm unable to search by name and if i remove
this line
(convert(nvarchar(20),a.CreatedDate,101)between(@FromDate)and(@ToDate))

then its working fine for searching by name but i'm unable to search by FromDate to ToDate
Please help me solve this issue

A: What you have here is known as a Catch-all or "Kitchen Sink" query. These are best handled with parametrised dynamic SQL.
I assume that all your parameters are optional (although if @FromDate is pass then so should @ToDate). Therefore most likely what you want is something like this:
--Removed prefix, per comment under question
CREATE PROC dbo.Search_RatingAndReviewsReport (@Name nvarchar(200) = NULL, --I ASSUME that Tbl_CustomerRating.Name is an nvarchar too?
                                               @FromDate date = NULL, --Why was this an nvarchar? How many dates exist with unicode characters?
                                               @ToDate date = NULL)
AS BEGIN

    DECLARE @SQL nvarchar(MAX);

    SET @SQL = N'SELECT CR.{List your columns}, --If you''re seeing braces, you haven''t replaced this as directed' + NCHAR(13) + NCHAR(10) + --Replace this with your columns, don't use * in a precompiled object
               N'       C.[Name]' + NCHAR(13) + NCHAR(10) +
               --Created Date is already in your previous a.*, therefore no need to repeat it.
               --If you want it in a specific format, then get your presentation layer to do that, not SQL Server
               N'FROM dbo.Tbl_CustomerRating CR' + NCHAR(13) + NCHAR(10) + --Customer and Rating start with C and R, not "a"
               N'     JOIN dbo.Tbl_Customer C ON CR.CustomerId = C.CustomerId' + NCHAR(13) + NCHAR(10) + --Customer starts with C, not b. Also changed to a JOIN due to the WHERE
               N'WHERE ';
    --Now for the fun part, the dynamic WHERE
    DECLARE @WHERE nvarchar(MAX) = N'';

    IF @Name IS NOT NULL --If @Name isn't NULL, add it to the WHERE
        SET @WHERE = @WHERE + NCHAR(13) + NCHAR(10) + N'  AND C.[Name] = @Name'
    IF @FromDate IS NOT NULL OR @ToDate IS NOT NULL --If either of the dates aren't NULL add it to the WHERE (note that is one is NULL then no results will be returned)
        SET @WHERE = @WHERE + NCHAR(13) + NCHAR(10) + N'  AND CR.CreatedDate BETWEEN @FromDate AND @ToDate'
    SET @WHERE = STUFF(NULLIF(@WHERE,''),1,8,''); --The NULLIF will turn the value to NULL if no parameters were supplied
    SET @SQL = @SQL + @WHERE + N';';

    PRINT @SQL; --Your best friend
    --EXEC sp_executesql @SQL, N'@Name nvarchar(200), @FromDate date, @ToDate date', @Name, @FromDate, @ToDate; --Uncomment to run the dynamic statement
END;

Note there are alot of comments in that SQL you need to digest, and also you need to change the section in braces ({}) (per the adjacent comment).
You can then test run this and you get the below results:
EXEC dbo.Search_RatingAndReviewsReport;

Returns nothing (no PRINT, not dataset), as no parameters
EXEC dbo.Search_RatingAndReviewsReport @Name = N'John Smith';

Would run the SQL below:
SELECT CR.{List your columns}, --If you're seeing braces, you haven't replaced this as directed
       C.[Name]
FROM Tbl_CustomerRating CR
     JOIN Tbl_Customer C ON CR.CustomerId = C.CustomerId
WHERE C.[Name] = @Name;

EXEC dbo.Search_RatingAndReviewsReport @FromDate = '20190101', @ToDate = '20190601';

Returns the SQL below:
SELECT CR.{List your columns}, --If you're seeing braces, you haven't replaced this as directed
       C.[Name]
FROM Tbl_CustomerRating CR
     JOIN Tbl_Customer C ON CR.CustomerId = C.CustomerId
WHERE CR.CreatedDate BETWEEN @FromDate AND @ToDate;

And finally:
EXEC dbo.Search_RatingAndReviewsReport @Name = N'Jane Bloggs', @FromDate = '20190101', @ToDate = '20190601';

Would run the SQL:
SELECT CR.{List your columns}, --If you're seeing braces, you haven't replaced this as directed
       C.[Name]
FROM Tbl_CustomerRating CR
     JOIN Tbl_Customer C ON CR.CustomerId = C.CustomerId
WHERE C.[Name] = @Name
  AND CR.CreatedDate BETWEEN @FromDate AND @ToDate;

dbo. does not appear in the printed SQL above, as I added it to the SP's definition after I had pasted the executed values above.


text:
Q: Loading html file, javascript disappears I changed the menu on my website so it replaces the main content on my page with html files using jquery instead of just href-ing the html pages. Something like:
$(function() {
  $('.new_page_title').on('click', function (e) {
      e.preventDefault();
      $('.main_content').load('new_page.html');
      $('body').scrollTop(0);
  });
});

For one of my pages I want to have a rotating sentence that gets randomly chosen from an array. Before, I was just doing it on page load, but now I have added a line to the above function to call the randomizer which looks like:
    function make_a_sentence() {
        var sentenceArray = [
            'digging holes in the back yard',
            'eating our vegetables',
            'doing something important',
            'building the future',
            'watering my plants',
            'propogating succulents',
            'watching Call the Midwife',
            'looking outside and dreaming of salvation',
            'poopin\'',
            'providing for my family',
            'watching you through your window',
            'digging around craigslist',
            'rotating my tires',
            'settling lawsuits'
        ];

        var selected = Math.floor(sentenceArray.length * Math.random());
        $("#id_of_div").html(sentenceArray[selected]);
}

And then calling make_a_sentence() at the end of the click function. When I just load the page, the sentence doesn't show up, and when I debug it inserts the sentence into the div until it gets to the end of the debug and then the sentence disappears. Any ideas?

A: The load function is asynchronous, you need to run code dependent on the loaded page's content in load's callback (otherwise your changes gets rewritten as they occur before the load is completed), like:
$(function() {
  $('.new_page_title').on('click', function (e) {
    e.preventDefault();
    $('.main_content').load('new_page.html', function () {
      $('body').scrollTop(0);
      make_a_sentence()
    });
  });
});

See jQuery.load for reference.


text:
Q: Suggestion of Visual stuido 2019, background is transparency Sometimes, Visual studio's suggestion's background is transparency, it makes me hard to read
I attach some picture.
Anyone have a idea to solve this problem?


text:
Q: Swift 3 audio won't play Basically I am trying to incorporate speech recognition into an app that I am building. I want to be able to play a sound when the microphone button is pressed and then start recording and recognizing the audio. The problem is that when I press the button, no sound plays. Also when I run the app on my physical iPhone the sound slider in the control panel disappears. Can anybody help?
Here is my code:
class VoiceViewController: UIViewController, SFSpeechRecognizerDelegate, UITextViewDelegate {

private let speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!
private var speechRecognitionRequest: SFSpeechAudioBufferRecognitionRequest?
private var speechRecognitionTask: SFSpeechRecognitionTask?
private let audioEngine = AVAudioEngine()

var audioPlayer: AVAudioPlayer = AVAudioPlayer()
var url: URL?
var recording: Bool = false

let myTextView = UITextView()

func startSession() throws {

    if let recognitionTask = speechRecognitionTask {
        recognitionTask.cancel()
        self.speechRecognitionTask = nil
    }

    let audioSession = AVAudioSession.sharedInstance()
    try audioSession.setCategory(AVAudioSessionCategoryRecord)

    speechRecognitionRequest = SFSpeechAudioBufferRecognitionRequest()

    guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") }

    speechRecognitionRequest?.shouldReportPartialResults = true

    speechRecognitionTask = speechRecognizer.recognitionTask(with: speechRecognitionRequest!) { result, error in

        var finished = false

        if let result = result {
            print(result.bestTranscription.formattedString)
            finished = result.isFinal
        }

        if error != nil || finished {
            self.audioEngine.stop()
            inputNode.removeTap(onBus: 0)

            self.speechRecognitionRequest = nil
            self.speechRecognitionTask = nil
        }
    }

    let recordingFormat = inputNode.outputFormat(forBus: 0)
    inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in

        self.speechRecognitionRequest?.append(buffer)
    }

    audioEngine.prepare()
    try audioEngine.start()
}

func stopTranscribing() {
    if audioEngine.isRunning {
        audioEngine.stop()
        speechRecognitionRequest?.endAudio()
    }
}

func btn_pressed() {
    print("pressed")

    if recording {
        url = URL(fileURLWithPath: Bundle.main.path(forResource: "tweet", ofType: "mp3")!)
    } else {
        url = URL(fileURLWithPath: Bundle.main.path(forResource: "gesture", ofType: "mp3")!)
    }

    do {
        try(audioPlayer = AVAudioPlayer(contentsOf: url!))
    } catch let err {
        print(err)
    }
    audioPlayer.play()
    recording = (recording == false)
    if recording == false {
        stopTranscribing()
    } else {
        try! startSession()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    let button = UIButton()
    button.setTitle("push me", for: UIControlState())
    button.frame = CGRect(x: 10, y: 30, width: 80, height: 30)
    button.addTarget(self, action: #selector(btn_pressed), for: .touchUpInside)
    self.view.addSubview(button)

    myTextView.frame = CGRect(x: 60, y: 100, width: 300, height: 200)
    self.view.addSubview(myTextView)

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

A: The docs say:

AVAudioSessionCategoryRecord
  The category for recording audio; this category silences playback audio.

That is the only audio session category you are using, and you are setting it as soon as you start trying to play your AVAudioPlayer, so naturally you cannot hear anything. You need to think some more about being nimble and correct with your audio session. If you want to play a sound and then start recording, use a Playback category for playing the sound, and don't start recording until you are told (through the AVAudioPlayerDelegate) that the sound is finished.

A: Use AVAudioSessionCategoryMultiRoute and it will keep playing your audio.


text:
Q: ¿Cómo hacer una expresión regular que rechace 2 consonantes seguidas? Quiero formular una expresión regular que rechace todas las palabras de un lenguaje cuando se repitan 2 letras consecutivas.
Adjunto el ejercicio:

El lenguaje de todas las cadenas no vacı́as que se pueden formar con las letras minúsculas a, b y c sin que haya dos consonantes seguidas. Por ejemplo, baaaca pertenecerá a este lenguaje, pero no λ, abc o bb.

Lo que llevo actualmente es:
a?(b|c)a*|(b|c)?a*

A: Prueba con lo siguiente:
^(?:[bc]?a)*[bc]?$

Tienes una demo aquí.


text:
Q: Android react-native app not picking up font I am trying to use a font "Verveine Corp Regular' inside my react-native app.
The font works in the iOS build, but not in the Android build.
The font is in .tff format and is placed in the root of my work (linked in the package.json and I have run react-native link) and inside "android/gradle/src/main/assets/fonts" but it's still not picking the font up. I have also cleaned and rebuilt the app multiple times.
When inspecting an element which uses the font in the android debugger, it says it's using the font. But the font is still the default font.
Could anyone offer some help or guidance on this issue?
Thanks!

A: The other answers helped me get this working for me, thank you. This manuever is probably only necessary when the font has capital letters in the filename. A more complete answer:
Add the font as normal in react native, for example:
{react-native-project}/fonts/GovtAgentBB.ttf
Run react-native link and this will put the font in
{react-native-project}/android/app/src/main/assets/fonts/GovtAgentBB.ttf
{react-native-project}/android/app/src/main/assets/fonts/GovtAgentBB_ital.ttf
But android, bring robotic and not human, doesn't like this.  So rename the file with all lower case letters and an underscore before the variant, like:
{react-native-project}/android/app/src/main/assets/fonts/govtagentbb.ttf
{react-native-project}/android/app/src/main/assets/fonts/govtagentbb_ital.ttf
Then, you have to change the font name in the style depending on the platform. For iOS, use the human name that is the name of the font that would be displaying in the title of the window of the Mac Font menu (or just the name you see on the web).  For android, you have to, robotically, use the name of the file you just renamed.
      {Platform.OS === 'ios' ? (
        <Text style={styles.welcome}>
          Hello World!
        </Text>
      ) : (
        <Text style={styles.welcomeAndroid}>
          Hello World
        </Text>
      )}
      const styles = StyleSheet.create({
      ...
      welcome: {
          fontFamily: 'Government Agent BB',
      },
      welcomeAndroid: {
          fontFamily: 'govtagentbb',
      },

A: This is how I used custom font in my project
//sampleStyle.js
import overrideStyles from '/sampleoverridestyles';
iconTextStyle: {
  color: '#FFFFFF',
  fontSize: 16
}

//sampleoverridestyles.ios.js
export default {
  iconTextStyle: {
    fontFamily: 'FaktSoftPro-Medium'
  }
}

//sampleoverridestyles.android.js
export default {
  iconTextStyle: {
    fontFamily: 'faktsoftpro_medium'
  }
}

since I cannot set the font name same for iOS and android I have overridden it as above and it worked.

A: Guys if you are following all other solution and still no update then try following the steps

*

*add react-native-config.js file

*then add fonts in assets/fonts/your font

*rename it with lowercase like OpenSans_Regular to opensans_regular

*react-native link in terminal in your project folder

*after all build your project again using react-native run-android

*fontFamily: Platform.OS === "ios" ? 'opensans_regular' : 'cassandrapersonaluseregular_3bjg',

I was also getting the same issue the font was not reflecting changes then I build my project again that was my mistake because we adding fonts in our android folder so we need to compile that again.
I hope someone may save their time

A: I added font in react-native android from here:
https://medium.com/@gattermeier/custom-fonts-in-react-native-for-android-b8a331a7d2a7#.40vw3ooar
Follow all the steps it will work fine.
After adding run react-native run-android

A: First, make sure you are up to version 0.16+ with react-native.
Your fonts should be *.ttf or *.otf files and must be located in: /projectname/android/app/src/main/assets/fonts
Make sure the fonts are lowercase only and follow this pattern: fontname.ttf, fontname_bold.ttf, fontname_light.ttf, fontname_bold_italic.ttf

A: Have you defined another font in your AppTheme (styles.xml), that overrides your preferred font?
Have you tested your font with a "Hello World"-App as a minimal test?
Have you implemented your ttf as shown here for example?: How to use custom font in Android Studio


text:
Q: Error with scala-2.8 and scalacheck: Prop has wrong version scala
Welcome to Scala version 2.8.0.final (Java HotSpot(TM) Client VM, Java 1.6.0_20).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import org.scalacheck.Prop.forAll
error: error while loading Prop, Scala signature Prop has wrong version
 expected: 5.0
 found: 4.1 in /opt/scala-2.8/lib/scalacheck.jar(org/scalacheck/Prop.class)

It's the the actual scala-2.8, and scalacheck was updated with sbaz immediately before (sbaz update; sbaz upgrade).
Is scalacheck for scala-2.8 under development, and not suitable for 2.8, or what might be the problem?
Do I have to get the sources, and recompile scalacheck by myself?

A: You can get it from the project page. It seems that it is not updated to 1.7 in sbaz yet.

A: ScalaCheck 1.7 for Scala 2.8 should be available in sbaz now.


text:
Q: How to optimize tcp stack for low latency when throuput is not a priority? I have a wireless link with packet loss of up to 10%. It has to carry one rtp stream, nothing else. Datarate of the stream is <100kb/s so the lowest datarate offered (1 mbit/s) by wlan (802.11b) is more than enough. To counter the packet loss I would like to try to take advantage of the arq algorithm offered by tcp. The setup looks like this: So one machine, which is the source of the rtp stream, will run a tcp-server (first end point of the tcp session) and a soft ap (hostapd running on linux). The second machine which is identical to the first one will be the end point of the tcp session an a wlan client (running wpa_supplicant) on linux. So the tcp sessiono won't span any routers or switches, just a single wireless link. Winth no routers/switches in between congestion control won't have much to do, but it won't hurt either hopefully. With both machines being identical and sufficiently powerfull flow control should not be an issue either. Especially as the rtp stream has a rather low data rate (< 100kb/s).
So my questions are: What paramaters/variables (/proc/sys/net/ipv4/tcp*) should i tweak in which way to achieve lowest possible latency(like ack every packet and send data imiadetly even in small packets and not wait for enough data to gather...) I don't care if throuput suffers. What else am I missing?


text:
Q: Yii2 validation triggering incorrectly on form with repeated model records I have been working on this all day and this is the first time I have posted here so I hope someone can help me, please.
I have a form where the multiple records for one form are the same model. As a result, I set manually the name and id tags. I place the following code in a foreach loop and generate the tags in the view.
// updatemember.php view has these declarations

use kartik\widgets\ActiveForm;

...

        $form = ActiveForm::begin([
                'id' => 'tab-horizontal',
                'type' => ActiveForm::TYPE_HORIZONTAL,
                'formConfig' => ['labelSpan' => 4 ],
                'options' => ['enctype' => 'multipart/form-data'],
             ]
             );

...

// updatemember calls this subform _claimcontact.php
use kartik\builder\Form;

...

echo Form::widget([
    'model'=>$claimcontact,
    'form'=>$form,
    'columns'=>2,
    'attributes'=>[
            'phone_container'=>[
                    'label'=>'Phone',
                    'attributes'=>[
                            'phone'=>[
                                        'type'=>Form::INPUT_TEXT,
                                        'options'=>['name'=>"ClaimContact[$index][phone]", 'id'=>"claimcontact-phone_$index",    ],
                                        'container' => ['class'=>$col_width],
                                        ],
                        ],
                ],

            'email_container'=>[
                    'label'=>'Email',
                    'attributes'=>[
                            'email'=>[
                                        'type'=>Form::INPUT_TEXT,
                                        'options'=>['name'=>"ClaimContact[$index][email]", 'id'=>"claimcontact-email_$index",   ],
                                        'container' => ['class'=>$col_width],
                                        ],
                        ],
                ],
        ],
]);

?>
      </div>
    </div>
  </div>
</div>

I set up a rule in the ClaimContact model and the validation triggers correctly the error message and css when I leave the field and it does it properly for record 3 but not for record 2, so that is good as email 3 is blank and email 2 is not blank.
[['first_name', 'last_name', 'position', 'phone', 'email' ] , 'required',

Unfortunately, when I click the Submit button the filename validation triggers for ALL the records, including the populated filename field. I have attached a sample image.
Invalid validation
It seems the Yii validation script generated at the bottom of the source html page has duplicate tags id and name which may be causing the issue.
  {"id":"claimcontact-email","name":"email","container":".field-claimcontact-email_0","input":"#claimcontact-email_0","validate":function (attribute, value, messages, deferred, $form) {yii.validation.required(value, messages,
  {"message":"Email cannot be blank."});}},

...
  {"id":"claimcontact-email","name":"email","container":".field-claimcontact-email_1","input":"#claimcontact-email_1","validate":function (attribute, value, messages, deferred, $form) {yii.validation.required(value, messages,
  {"message":"Email cannot be blank."});}},

...
  {"id":"claimcontact-email","name":"email","container":".field-claimcontact-email_2","input":"#claimcontact-email_2","validate":function (attribute, value, messages, deferred, $form) {yii.validation.required(value, messages,
  {"message":"Email cannot be blank."});}},

I think if the "id" tag was set to claimcontact-email_0, claimcontact-email_1 and claimcontact-email_2 respectively I bet the validation would work.
I have tried setting inputOptions and the jquery selector option but this does not work.
I have read and used the multiple model article (http://www.yiiframew...ple-models.html) and it worked up to a point but I had a lot of issues with it from another project so I have decided to follow the above approach for more control but there is a bit of a hitch in the validation I need help with, please.
Thanks for taking the time to read my issue.

A: I found the solution.  One needed to set the name with an $index and then the validation created was unique.
eg.
'email_container'=>[
            'label'=>'Email',
            'attributes'=>[
                "[$index]email"=>[
                    'type'=>Form::INPUT_TEXT,
                    'options'=>['name'=>"ClaimContact[$index][email]", 'id'=>"claimcontact-email_$index",   ],
                    'container' => ['class'=>$col_width],
                    ],
            ],
        ],

NOTE: the "[$index]email"
generates this
{
  "id":"claimcontact-0-email",
  "name":"[0]email",
  "container":".field-claimcontact-email_0",
  "input":"#claimcontact-email_0","validate":function (attribute, value, messages, deferred, $form) {
      ...
      (attribute, value)) { yii.validation.required(value, messages, {"message":"Email cannot be blank."});
}
{
  "id":"claimcontact-1-email",
  "name":"[1]email","container":
  ".field-claimcontact-email_1",
  "input":"#claimcontact-email_1","validate":function (attribute, value, messages, deferred, $form) {
      ...
      (attribute, value)) { yii.validation.required(value, messages, {"message":"Email cannot be blank."});
}

which then results in what I want-validation on only one field.


text:
Q: Python socket.io locally emit an event I would like to emit a local event instead of using one from the server. Basically, locally call events. The reason would be is to process data which then can be used by another function.
Related questions:
Can the socket.io client emit events locally? - This only supports node.js and no python implementation of it.
Code:
await self.sio.connect(SOCKET_IP, namespaces=['/'], transports=['websocket'])
await sio.emit("connection")
await sio.emit('authentication', {'token': new_token})

@sio.event
async def auth_err(data):
    authErr = True
    await sio.disconnect()

@sio.event
async def alive_status(data):
    await sio.emit("alive_status_return", "alive")

@sio.on('connected')
async def on_connect(data):
    print("Connected")

I know for sure sio.emit() will broadcast to the server which I do not want.
Looking at doing sio.call() but ended up with await sio.call("on_new_data") giving Sending packet MESSAGE data 21["on_new_data"]
Then the function doesn't get the data
@sio.event
async def on_new_data():
    print("2")

A: I ended up having to write a custom function within the asyncio_client.py of python socket.io for this
    async def _call_event(self, event, namespace, data=None):
        namespace = namespace or '/'
        self.logger.info('Received custom event "%s" [%s]', event, namespace)
        try:
            if data:
                r = await self._trigger_event(event, namespace, data)
            else:
                r = await self._trigger_event(event, namespace)
        except Exception as e:
            print(traceback.format_exc())


text:
Q: How to use fetchBalance() parameters with ccxt I'm new to ccxt and I'm trying to fetch my balance in USDT.
This information is included in what the following code returns to me:
(async () => {
    console.log (await exchange.fetchBalance ())
}) ()

But it also returns a lot of other data that I don't need.
The documentation includes this code:
fetchBalance (params = {})
I don't understand how to use "params".
The corresponding extract from the manual is here: https://ccxt.readthedocs.io/en/latest/manual.html#querying-account-balance

A: The params argument on fetchBalances() is for passing exchange specific data to the request. As each exchange offers different endpoints, CCXT offers a unified API for the most common use cases. It covers a lot, but not everything on every exchange. This is true of most of the methods in the unified API.
So to answer your question, we need more information, like which exchange you're fetching balances from to use the params arg?
Something like this should get you over the line for now though:
const currency = 'USDT';

async function fetchBalance(currency) {
  const balance = await exchange.fetchBalance(); // returns huge object with all balances
  return balance.free[currency]; // returns 'free' or available balance of USDT
}

You can read about the unified API here -
https://ccxt.readthedocs.io/en/latest/manual.html#overriding-unified-api-params
If you're not happy with the unified API for your use case, you can use the implicit API. Again I can't offer an example without more info, but this allows you to use the CCXT library and call exchange endpoints as documented on the exchange. There is still a CCXT abstraction over these native endpoints, however this will get you out of a bind if the CCXT integration with your chosen exchange is incomplete.
Check out the implicit API here -
https://ccxt.readthedocs.io/en/latest/manual.html#implicit-api-methods


text:
Q: Passing data between tabbed views in swift I have a project that has a tabbed bar controller that is linked to a FirstViewController.swfit and a SecondViewController.swift.
I have a textbox in the first view, and in the second view I have a label and a button. I want the user to be able to type something in the textbox in the first view, then switch over to the second tab, and press the button and have whatever they typed in the textbox appear in the label.
I have tried researching all over the place and I came across segues and singletons, but I am not sure how to exactly apply those or if they are even necessary for what I'm trying to achieve.
Thank you!
EDIT
My SecondViewController.swift code based on razor's reply:
import UIKit

class SecondViewController: UIViewController {

var firstViewController: FirstViewController?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBOutlet weak var label: UILabel!

@IBAction func button(sender: AnyObject) {

    if let fvc = firstViewController {
        self.label.text = fvc.textbox.text
    }

}
}

A: A common practice is for SecondViewController to have a reference to FirstViewcontroller.  So within the ViewController class, you'd have e.g. an optional variable like:
var firstViewController: FirstViewController?
Then, when you handle the button press, you can do something like
if let fvc = firstViewController {
  self.label.text = fvc.textbox.text
}


text:
Q: Equations on Free Groups I was trying to read an old paper concerning equations on free groups and immediately came to a puzzling statement which made me wonder whether I am fundamentally misunderstanding something or if I am unaware of some notational convention.

The "trivial example" that if $w(x)=xa_1 a^{-1} a_1^{-1}$, the solutions $u$ are all elements $a_1^v$ where $v$ is an integer does not make sense to me. Firstly, what is $a$ as it was never formally defined? Apparently we are working with the free group on $\{x,a_1,\ldots, a_r\}$ and considering solutions in the free subgroup generated by $\{a_1,\ldots, a_r\}$. So, is $a$ just an arbitrary element in that free subgroup? If so, I do not see how the equation could hold for $x=a_1^v$. It seems to me that $w(x)=1$ and $x=a_1^v$ requires $a$ to be $a_1^{-v}$. But, I thought that the only variable is $x$, with the other letters representing fixed group elements.
What am i missing?