text:
Q: SQLite: how to merge rows that match in alternating columns? So let's suppose that we're working with a sqlite table that looks (roughly) like this:
   id       date1     date2
+-------+----------+----------+
|  foo  |10/01/2010|01/01/2011|
+-------+----------+----------+
|  bar  |07/01/2010|10/01/2010|
+-------+----------+----------+
...      ...        ...

etc... I'm trying to somehow merge those rows with the same id and a combination of date1 and date2 values which happen to specify a range that would otherwise be continuous, were it not scattered over multiple rows. In other words, this:
   id       date1     date2
+-------+----------+----------+
|  foo  |07/01/2010|10/01/2010|
+-------+----------+----------+
|  foo  |10/01/2010|01/01/2011|
+-------+----------+----------+

would become:
   id       date1     date2
+-------+----------+----------+
|  foo  |07/01/2010|01/01/2011|
+-------+----------+----------+

and so on for cases where you have 3 (or more) bar's each mapped to three (or more) different, although altogether continuous, ranges. What'd such a query look like? I haven't been able to come up with any reasonable solutions so far, though I'm not much of a SQLista myself.

A: I realize sqlite does not support analytic functions, but... Here is a potential sql solution that uses analytic functions. I ran this in Postgresql.
CREATE TABLE test(id VARCHAR(16), date1 DATE, date2 DATE);

INSERT INTO test VALUES('foo', '2011-01-01', '2011-01-15');
INSERT INTO test VALUES('bar', '2011-01-02', '2011-01-04');
INSERT INTO test VALUES('bar', '2011-01-05', '2011-01-10'); -- not contiguous
INSERT INTO test VALUES('foo', '2011-01-25', '2011-01-30');
INSERT INTO test VALUES('foo', '2011-01-15', '2011-01-18'); -- contiguous
INSERT INTO test VALUES('foo', '2011-01-28', '2011-01-31'); -- overlap
INSERT INTO test VALUES('bar', '2011-01-07', '2011-01-08'); -- subset chopped

postgres=# SELECT * FROM test ORDER BY id, date1;
 id  |   date1    |   date2
-----+------------+------------
 bar | 2011-01-02 | 2011-01-04
 bar | 2011-01-05 | 2011-01-10
 bar | 2011-01-07 | 2011-01-08
 foo | 2011-01-01 | 2011-01-15
 foo | 2011-01-15 | 2011-01-18
 foo | 2011-01-25 | 2011-01-30
 foo | 2011-01-28 | 2011-01-31
(7 rows)

SELECT id
      ,MIN(date1) AS date1
      ,MAX(date2) AS date2
  FROM ( SELECT id, date1, date2, previous_date1, previous_date2
               ,SUM( CASE WHEN date1 > previous_date2 THEN 1 ELSE 0 END ) OVER(PARTITION BY id ORDER BY id, date1) AS group_id
           FROM ( SELECT id, date1, date2
                        ,COALESCE( LAG(date1) OVER (PARTITION BY id ORDER BY id, date1), date1 )  previous_date1
                        ,COALESCE( LAG(date2) OVER (PARTITION BY id ORDER BY id, date1), date2 )  previous_date2
                    FROM test
                    ORDER BY id, date1, date2
                ) AS x
       ) AS y
  GROUP BY id, group_id
  ORDER BY 1,2;

 id  |   date1    |   date2
-----+------------+------------
 bar | 2011-01-02 | 2011-01-04
 bar | 2011-01-05 | 2011-01-10
 foo | 2011-01-01 | 2011-01-18
 foo | 2011-01-25 | 2011-01-31
(4 rows)

EXPLANATION
Working from the inside out, first sort the rows by id and date, and add two extra columns to each row to indicate the previous row's date1 and date2 values.
 id  |   date1    |   date2    | previous_date1 | previous_date2
-----+------------+------------+----------------+----------------
 bar | 2011-01-02 | 2011-01-04 | 2011-01-02     | 2011-01-04
 bar | 2011-01-05 | 2011-01-10 | 2011-01-02     | 2011-01-04
 bar | 2011-01-07 | 2011-01-08 | 2011-01-05     | 2011-01-10
 foo | 2011-01-01 | 2011-01-15 | 2011-01-01     | 2011-01-15
 foo | 2011-01-15 | 2011-01-18 | 2011-01-01     | 2011-01-15
 foo | 2011-01-25 | 2011-01-30 | 2011-01-15     | 2011-01-18
 foo | 2011-01-28 | 2011-01-31 | 2011-01-25     | 2011-01-30
(7 rows)

Then flag every row that has an overlap (between date1 and previous_date1), summing these flags within the "id" grouping gives us a sub-grouping of the ids.
 id  |   date1    |   date2    | previous_date1 | previous_date2 | flag | group_id
-----+------------+------------+----------------+----------------+------+----------
 bar | 2011-01-02 | 2011-01-04 | 2011-01-02     | 2011-01-04     |    0 |        0
 bar | 2011-01-05 | 2011-01-10 | 2011-01-02     | 2011-01-04     |    1 |        1
 bar | 2011-01-07 | 2011-01-08 | 2011-01-05     | 2011-01-10     |    0 |        1
 foo | 2011-01-01 | 2011-01-15 | 2011-01-01     | 2011-01-15     |    0 |        0
 foo | 2011-01-15 | 2011-01-18 | 2011-01-01     | 2011-01-15     |    0 |        0
 foo | 2011-01-25 | 2011-01-30 | 2011-01-15     | 2011-01-18     |    1 |        1
 foo | 2011-01-28 | 2011-01-31 | 2011-01-25     | 2011-01-30     |    0 |        1
(7 rows)

Now we can group by id and the generated "group_id".
Maybe kind of crazy. I'm not sure that I would actually want to use this kind of solution because it could be hard to test, verify, document, and especially maintain a few years down the road. But I still think it is neat the things that can be done with sql.

A: Do you specifically need to do this using a (single) SQL query? If not, my advice is to take your language of choice and write a one-off script to perform this transformation of your data.


text:
Q: Rails 4 has_one self reference column I have a Totem model and Totems table.
There will be many totems and I need to store the order of the totems in the database table.
I added a previous_totem_id and next_totem_id to the Totems table to store the order information. I did it via this
Rails Migration:
class AddPreviousNextTotemColumnsToTotems < ActiveRecord::Migration
  def change
    add_column :totems, :previous_totem_id, :integer
    add_column :totems, :next_totem_id, :integer
  end
end

Now in the Model I have defined the relationships:
class Totem < ActiveRecord::Base
  validates :name, :presence => true

  has_one :previous_totem, :class_name => 'Totem'
  has_one :next_totem, :class_name => 'Totem'
end

I created a couple of these totems through ActiveRecord and tried to use the previous_totem_id column like so:
totem = Totem.create! name: 'a1'
Totem.create! name: '1a'
totem.previous_totem_id = Totem.find_by(name: '1a').id
puts totem.previous_totem #This is NIL

However, the previous_totem comes back as nil, and I do not see a select statement in the mysql log when calling this line
totem.previous_totem

Is this relationship recommended? What is the best way to implement a self referencing column?

A: Changing direction of the association from has_one to belongs_to and specifying foreign keys, should make your code work as you expected:
class Totem < ActiveRecord::Base
  validates :name, :presence => true

  belongs_to :previous_totem, :class_name => 'Totem', foreign_key: :previous_totem_id
  belongs_to :next_totem, :class_name => 'Totem', foreign_key: :next_totem_id
end

However, good association should be properly named and declared on both sides - with matching has_one association; in this case it's impossible without naming conflicts :) Self join might be sometimes useful, but i'm not sure if it's the best solution here. I didn't use the gem moveson recommends, but an integer column to store position is something I use and IMHO makes reordering records easier :)

A: If the only reason for the self-reference is to store the order of the totems, please don't do it this way. It's your lucky day: This is a solved problem!
Use a position field and the acts_as_list gem, which will take care of this problem for you in a neat and performant way.

redpajama_set_name: RedPajamaStackExchange


text:
Q: webpack react ingress-nginx kubernetes shows Bad Gateway All the deployments are running, all the pods are healthy. ingress-nginx is running. when I run kubectl get ing:
NAME          CLASS    HOSTS       ADDRESS        PORTS   AGE
ingress-srv   <none>   myapp.com   192.168.49.2   80      13m

I set the hosts file for ingress.
this is the ingress-srv.yml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-srv
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/use-regex: "true"
spec:
  defaultBackend:
    service:
      name: nginx-ingress-default-backend
      port:
        number: 80

  rules:
    - host: myapp.com
      http:
        paths:
          - path: /posts
            pathType: Exact
            backend:
              service:
                name: query-srv
                port:
                  number: 4002
          - path: /?(.*)
            pathType: Exact // I tried "Prefix"
            backend:
              service:
                name: client-srv
                port:
                  number: 8080

the issue ingress api is not routing correctly. and react app is set up with webpack-dev-server.  it's port is set to 8080. this is client-depl.yml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: client-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: client
  template:
    metadata:
      labels:
        app: client
    spec:
      containers:
        - name: client
          image: kali/client
---
apiVersion: v1
kind: Service
metadata:
  name: client-srv
spec:
  selector:
    app: client
  ports:
    - name: client
      protocol: TCP
      port: 8080
      targetPort: 8080

webpack config for client:
module.exports = {
  mode: "development",
  entry: ["regenerator-runtime/runtime", "./index.js"],
  output: {
    path: path.resolve(__dirname, "public"),
    filename: "main-bundle.js",
    publicPath: "/",
  },
  module: {
    rules: [{ test: /\.js$/, loader: "babel-loader", exclude: /node_modules/ }],
  },
  devtool: "eval-cheap-source-map",
  devServer: {
    historyApiFallback: true,
    contentBase: path.resolve(__dirname, "public"),
    overlay: true,
  },
};

A: First a word a caution: The webpack dev server is not intended to be used to serve the react app in production. You might want to investigate an alternative like nginx.
You get an error of BadGateway from your ingress. That means that the ingress recognizes the configuration, but can not reach the real service. Usually this is caused by a problem of the port mapping, but since you stated that you run the dev server with port 8080 and configured that in the kubernetes services as well, it should be fine.
I noticed that your deployment does not declare the port, this should be fixed:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: client-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: client
  template:
    metadata:
      labels:
        app: client
    spec:
      containers:
        - name: client
          image: kali/client
          ports:
          - containerPort: 8080

But there is one more thing to consider when listening for connections beside the port: The network interface to use. The webpack dev server is preconfigured to listen only on the loopback (localhost) interface and to not be available externally. It is a dev server after all.
This can be changed using a different listen address, either in the webpack configuration or on the command line:
module.exports = {
  //...
  devServer: {
    host: '0.0.0.0'
  }
};

CLI: webpack serve --host 0.0.0.0

A: Because you are using pathType: Exact in your ingress definiton and exact expects that exact path like https://<url>//?(.*) . You need to change it to  pathType: Prefix ıf you are willing to use prefix /?(.*) to match and route with urls such as http://<url>/<sample>
Also you can check path types in official documentation


text:
Q: WPD/MTP PortableDevices, Content is always empty (Windows, VisualStudio 2012, VB.NET) Problem is tested with NuGet package PortableDevices and the solution from here: Accessing an MTP device in Visual Basic .NET
I want to get a file list from a Samsung Android Tablet. I can connect, but GetContents() returns no files (root.Files.Count = 0). Thanks in advance.
Dim Devices As New PortableDeviceCollection()
Devices.Refresh()
Dim tablet As PortableDevice
tablet = Devices.First()
tablet.Connect()
Dim root = tablet.GetContents()

A: For me, the problem is solved. First, let me explain the effect: in the list of portable devices in my windows 10 device manager are 4 devices from a Card Reader and the Samsung tablet inserted in position 2. The Interop.PortableDeviceApiLib.dll had the problem to retrieve more the one device describted here: Enumerating Windows Portable Devices in C#
With this issue, the GetDevices() returns ever only one device, in my case the last device from Card Reader with no files. When connecting one more device (another smartphone), it becomes the last device and the code (Windows Portable Devices.zip from Accessing an MTP device in Visual Basic .NET) works fine.
The solution: I fix the marshalling problem in the interop assembly as explained in the accepted answer (Enumerating Windows Portable Devices in C#) and copy the new Interop dll over all existing Interop.PortableDeviceApiLib.dll (set Embed Interop Types to False in Refs).
The code in PortableDeviceCollection.cs (zip package from here: Accessing an MTP device in Visual Basic .NET) i have changed as as follow:
public void Refresh()
{
    this._deviceManager.RefreshDeviceList();

    // Determine how many WPD devices are connected
    // new, according to https://learn.microsoft.com/en-us/windows/win32/wpd_sdk/enumerating-devices
    uint count = 1;
    string[] s = null;
    this._deviceManager.GetDevices(s, ref count);

    // Retrieve the device id for each connected device
    var deviceIds = new string[count];
    // old: this._deviceManager.GetDevices(ref deviceIds[0], ref count);
    this._deviceManager.GetDevices(deviceIds, ref count);
    foreach(var deviceId in deviceIds)
    {
        Add(new PortableDevice(deviceId));
    }
}

Unfortunately, the Interop.PortableDeviceApiLib.dlls must replaced with the new created dll after each Clean in Visual Studio. Edit: In the article from
Andrew Trevarrow, Fun with MTP in C# (http://andrewt.com/2013/06/15/fun-with-mtp-in-c.html), is a hint to prevent this problem: when all done, remove the referenece to PortableDeviceApiLib Type Library from C# project "PortableDevices" and add a reference to the new Interop.PortableDeviceApiLib.dll (in separate folder) and change "Embed Interop Types" for the dll to False.


text:
Q: NSTextField Line Spacing in Swift How do you set the line-spacing for a multi-line NSTextField programmatically with Swift or within the Interface Builder?

A: You can use NSAttributedString to modify this (Swift 4 example):
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 10.0  // sets the space BETWEEN lines to 10 points
    paragraphStyle.maximumLineHeight = 12.0 // sets the MAXIMUM height of the lines to 12 points

    let text = "Your text"
    let attributes = [.paragraphStyle: paragraphStyle]
    textField.attributedStringValue = NSAttributedString(string: text, attributes: attributes)


text:
Q: HashSet storing equal objects Below is the code for finding duplicate objects from a list of object. But for some reason the hashset is storing even the equal objects.
I am certainly missing out something here but when I check the size of hashset it comes out 5.
import java.util.ArrayList;
import java.util.HashSet;

public class DuplicateTest {

public static void main(String args[]){
    ArrayList<Dog> dogList = new ArrayList<Dog>();
    ArrayList<Dog> duplicatesList = new ArrayList<Dog>();
    HashSet<Dog> uniqueSet = new HashSet<Dog>();

    Dog a = new Dog();
    Dog b = new Dog();
    Dog c = new Dog();
    Dog d = new Dog();
    Dog e = new Dog();

    a.setSize("a");
    b.setSize("b");
    c.setSize("c");
    d.setSize("a");
    e.setSize("a");

    dogList.add(a);
    dogList.add(b);
    dogList.add(c);
    dogList.add(d);
    dogList.add(e);

    if(a.equals(d)){
        System.out.println("two dogs are equal");
    }
    else System.out.println("dogs not eqal");

    for(Dog dog : dogList){
        uniqueSet.add(dog);
    }

    System.out.println("number of unique dogs="+ uniqueSet.size());
    /*for(Dog dog:uniqueSet){
        System.out.println("uniqueset ="+dog.getSize());
    }

    for(Dog dog : duplicatesList){
        System.out.println("duplicate dog="+dog.getSize());
    }*/

}

}

And here is the Dog class
public class Dog implements Animal, Comparable<Dog>{

String size;

public void makeNoise(){
    System.out.println("woof woof");
}

public String getSize() {
    return size;
}

public void setSize(String size) {
    this.size = size;
}

public int compareTo(Dog d){
    return this.size.compareTo(d.size);
}

public boolean equals(Dog d){
    return this.size.equals(d.size);
}

@Override
public int hashCode() {
    // TODO Auto-generated method stub
    return super.hashCode();
}
}

A: This code doesn't do what you need it to:
public boolean equals(Dog d){
    return this.size.equals(d.size);
}

That's not overriding Object.equals, which is what HashSet uses. You need:
@Override
public boolean equals(Object d){
    if (!(d instanceof Dog)) {
        return false;
    }
    Dog dog = (Dog) d;
    return this.size.equals(dog.size);
}

Note that by using the @Override annotation, you're asking the compiler to verify that you're actually overriding a method.
EDIT: As noted, you also need to override hashCode in a way which is compatible with your equals method. Given that you're checking equality based on size, the simplest option would be:
@Override
public int hashCode() {
    return size.hashCode();
}


text:
Q: Merging dask dataframes results in disk error due to temporary .partd files in /tmp I have been trying to merge 32 files with a common id column in dask. In total, the files are 82.4GB big. I am iteratively going through the files and doing an outer merge on some and then a left merge on the others. I did not set a distributed client as I wasn't sure it was needed. I also tried setting the id column as index and using it to merge but it wasn't working. I also tried pandas but got a memory error even though I thought this would fit into the RAM (524GB).
The problem is that dask creates so many big temporary .partd files that it fills up the 950GB available. It didn't look like it was making full use of the RAM. I suspect the workflow creates many temporary files and they don't get cleared during the process even if they are unused. They are cleared once the scripts fails with an error due to disk space.
Any suggestion to make this better would be helpful! Thank you very much!
Code looks like this:
#!/usr/bin/env python

import pandas as pd
import dask.dataframe as dd

if __name__ == '__main__':

    list_df=pd.read_csv("path_2_files.csv")
    for index, row in list_df.iterrows():
        print("Starting "+str(index))
        if (index==0):
            ddf = dd.read_csv(row['path']+row['filename'] , sep="\t",\
                              dtype={'id': 'object', \
                                     'data1': 'float64', \
                                     'data2': 'float64', \
                                     'data3': 'float64' \
                                     })
            #Check for duplicates and drop
            ddf=ddf.drop_duplicates()
            print(len(ddf))
        else:
            ddf2 = dd.read_csv(row['path'] + row['filename'], \
                                dtype={'id': 'object', \
                                       'data1': 'float64', \
                                       'data2': 'float64', \
                                       'data3': 'float64' \
                                       })
            #Check for duplicates and drop
            ddf2=ddf2.drop_duplicates()

            if (row['type']=='test1'):
                ddf = dd.merge(ddf, ddf2, on='id', how="outer")
                print(len(ddf))
                del ddf2
            elif (row['type']=='test2' or row['type']=='test3'):
                ddf = dd.merge(ddf, ddf2, on='id', how="left")
                print(len(ddf))
                del ddf2

    ddf.to_parquet("s3://some/path/merged_file.parquet", object_encoding='utf8')


text:
Q: Page Freezes When Redirecting User After Form Submit In php, I collect information from the form and build an email. I then have the following code redirect the user to a page after a 200 response code.
// Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Set a 200 (okay) response code.
        header('Location: https://my.website.com/wp-content/uploads/2015/07/a.pdf');
        exit;
    } else {
        // Set a 500 (internal server error) response code.
        header("HTTP/1.1 500 Internal Sever Error");
        echo "Oops! Something went wrong and we couldn't send your message.";
    }

Unfortunately, when I attempt to sumbit a form, Chrome freezes and I have to close the tab. Any explanation for the cause and fix of this issue?


text:
Q: Save a material in a slot to a new material library Using maxscript I want to know how to save a material in a slot to a material library.
I already know that I can get a slot material by:
myMaterial = meditMaterials[i]

Where i is the slot number.

A: You can use append to add a material or a texture to a material library, e.g.:
append currentMaterialLibrary meditMaterials[activeMeditSlot]


text:
Q: What is this "for" syntax called? So I was reading this sumitter's solution on codeforce , here is the link of his/her code
https://codeforces.com/contest/1714/submission/166585583
The "for" I asker is in main().I'm wondering what is this "for" syntax called or any keyword for me to look for it because it's different from the for(int i;i < Number;i++) I have learned.
cltstream::read(T);
    for (; T; --T)


text:
Q: added header in C, #include returns error I added a header in NetBeans 8.0.1 in my project.
But when I include it in a source file I get an error
test.c:12:24: fatal error: tester.h: No such file or directory

my folder where I save my project is c:\david\temp files\netbeansProjects
could it be because i have a folder name with a space "temp files"? If so how can I change
where all my projects are, without ruining everything.
If that is not the reason, does anybody have a suggestion?


text:
Q: How to pass values of partial view models on submit from another partial view i have this viewmodel
    public class RHAPostModel
     {
        public PostingMain PostMainData { get; set; }
        public List<MailingList> MailListData { get; set; }
        public List<MailingGroup> MailGroupData { get; set; }
     }

This is my get action
    public ActionResult Index()
    {
        var model = new RHAPostModel
        {

                    MailListData = _dbrepo.GetDefaultRecipient().ToList(),
                    MailGroupData = _dbrepo.GetDefaultGroup().ToList()

            };

        return View(model);

    }

this is my view
        @Html.Partial("_NavMenu",Model)

    @*side menu here*@
    @Html.Partial("_SideMenu",Model)

    @*wysiwyg container here*@

                                Complete Message Post Information

                        @Html.Partial("_PostingTool",Model)

When I hit submit inside the postingtool..it doesn't pass the other modeldata.
I'm new to partial views..I was able to pass them if not in partial views..but for proper and cleaner look I wanted to use partial.
this is the posting tool part
        @model RHA.RushPost.ViewModel.RHAPostModel

        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()

            @Html.TextAreaFor(model => model.PostMainData.MessageContent, new { @id = "RushPostContent", @style = "margin:20px;" })

          @foreach (var x in Model.MailListData)
         {
            @x.userEmail <<-- i use this for testing and value is passed
          }
          @Html.HiddenFor(m => m.MailListData)

         <button type="button" class="btn btn-primary" id="btnImageUpdate">UpdateImage</button>
        <button type="submit" class="btn btn-primary" id="btnSaveDraft" name="Command" value="Draft">Save as Draft</button>
        <button type="submit" class="btn btn-info" id="btnSaveTemplate" name="Command" value="Template">Save as Template</button>
        <button type="submit" class="btn btn-success" id="btnCampaign" name="Command" value="Send">Send Campaign</button>
        <button name="ClientCancel" class="btn btn-danger" type="button" onclick="document.location.href=$('#cancelUrl').attr('href');">Clear</button>

   }

but on submit..everythin is null except for the messagecontent data.
been searching..hard..

A:
Hi, your partial view is accepting RHAPostModel but I can't see any RHAPostModel inside your view model ?


text:
Q: Combine arguments using double quotes I'm making a TeamSpeak3 ServerQuery bot, command line style. I already have the commands down, but what I can't seem to wrap my head around is the arguments to a command. I use a reset() method to create a List of arguments so combining the string(s) would be easier.
For example, say I change a setting in memory for my bot name
set query name "Kyles Bot"

But the program takes "Kyles and Bot" as two different arguments. I want them as one. How would I go about doing this?
Fields needed for reset():
// Keep String[] and 3 strings null for now, they'll be changed.
private String command, to1, to2;
private String[] to3;
private List<String> args = new ArrayList<>();

The reset() method:
private void reset() {
            args.clear();
            to1 = line.getText();
            command = to1.split(" ")[0];
            if (to1.split(" ").length > 1) {
                to2 = to1.substring(command.length() + 1, to1.length());
                to3 = to2.split(" ");
                for (int i = 0; i < to3.length; i++) {
                    if (to3[i].isEmpty() || to3[i].startsWith(" ")) {
                        System.out.println("Argument null, command cancelled. [" + to3[i] + "]");
                        break;
                    } else {
                        args.add(to3[i]);
                    }
                }
                //EDIT2: Removed useless for loop,
                //it was my previous attempt to solve the problem.
            } else {
                //EDIT: This loop here is used to prevent AIOUB
                command = to1;
                for (int i = 0; i < 5; i++) {
                    args.add("NullElement");
                }
            }
        }

A: The problem is this line:
to3 = to2.split(" ");

it splits the read command on every space, including spaces inside quoted text.
You need to split the command line properly, for example using a Regular Expression:
    // matches either a "quoted string" or a single word, both followed by any amount of whitespace
    Pattern argumentPattern = Pattern.compile("(\"([^\"]|\\\")*\"|\\S+)\\s*");

    // loop over all arguments
    Matcher m = argumentPattern.matcher(to2);
    for (int start = 0; m.find(start); start = m.end()) {

        // get a single argument and remove whitespace around it
        String argument = m.group(1).trim();

        // handle quoted arguments - remove outer quotes and unescape inner ones
        if (argument.startsWith("\""))
            argument = argument.substring(1,  argument.length() - 1).replace("\\\"", "\"");

        // ... your code that uses the argument here

    }

Please note that this is not a complete implementation of a command line parser – if you receive arbitrary commands, you should look into libraries that do this parsing for you and can handle all the specifics properly.
PS: please use descriptive variable names instead of to1, to2, to3 etc., for example I used argument instead of to3 in my code.


text:
Q: No color is shown on my Material Design ActionBar or StatusBar in Lollipop devices, but is shown in ActionBar of Pre-Lollipop devices. Why? I am following this tutorial to use colors in (my ActionBar and StatusBar) in Android Material design. I did follow the tutorial but no color is reflected, and the same dark ActionBar and StatusBar are shown when I run the app in my API22 emulator, while color is shown in the ActionBar of Pre-lollipop devices The question is why and how can I fix this?
minimumSdkVersion is 8 and targetSdkVersion is 22. It compiles with 5.1.1 API 22. The emulator to test for Lollipop devices is Nexus One but customised to run API 22, whereas the emulator to test for Pre-lollipop devices is running API 08
MainActivity.java
public class MainActivity extends ActionBarActivity {

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.primaryColorDark));
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

res/values/color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primaryColor">#FF5722</color>
    <color name="primaryColorDark">#E64A19</color>
    <color name="accentColor">#9C27B0</color>
</resources>

res/values/styles.xml
<resources>

    <style name="AppTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar" ></style>

    <style name="AppTheme" parent="AppTheme.Base">
        <item name="colorPrimary">@color/primaryColor</item>
        <item name="colorPrimaryDark">@color/primaryColorDark</item>
        <item name="colorAccent">@color/accentColor</item>

    </style>

</resources>

The same (as ^) code is there in res/values-v11/styles.xml and res/values-14/styles.xml.
res/values-v21/styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:colorPrimary">@color/primaryColor</item>
        <item name="android:colorPrimaryDark">@color/primaryColorDark</item>
        <item name="android:colorAccent">@color/accentColor</item>
    </style>

</resources>

The same (as ^) code is there in res/values-v22/styles.xml.

EDIT The left one is running API 22, and the right one is running API 08.

A: in MainActivity.java
change
public class MainActivity extends ActionBarActivity {
to
public class MainActivity extends AppCompatActivity {

in res/values/styles.xml
replace everything with this
<resources>

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">#e23c7f</item>
    <item name="colorPrimaryDark">#dae22b</item>
    <item name="colorAccent">#5863e3</item>
</style>

If none of the above works, add the following snippet inside the onCreate() method
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources()
.getColor(R.color.primaryColorDark)));

Finally you will get something like this:

A: It seems you are using api 22; in styles 21.xml change android:colorPrimary to colorPrimary just like in styles.xml for older devices, and all rest color values in styles from v21.xml


text:
Q: CRM 2015 Server Installation Error :- GrantAspNetServiceAccountAccessAction failed Has anyone come across this error before?
Microsoft.Crm.Setup.Server.GrantAspNetServiceAccountAccessAction failed
"The parameter is incorrect"

I can't find any information about the error.  We are attempting a clean installation of CRM 2015 on a new server. The installer is a system administrator so it wouldn't think its permission based.

A: Found the answer over in the Microsoft Server forums.
Unable to install crm 2013 on server 2012
In the Active Directory Organization Unit (OU) used for the Microsoft Dynamics CRM Install, we had a few "Account Unknown" entries.  Deleting these fixed our issue!  Note that to delete these, you can run as a Domain Administrator (or a user with rights to this organizational unit) the Active Directory Users and Computers program (DSA.MSC) and then navigate to this OU and select the invalid entries that are listed with "Account Unknown" to delete them.


text:
Q: Add reference to a downloaded dll in Visual studio and resolve in Github I have a visual studio solution which is synced on GitHub. I want to add a few dlls to one of the project. I downloaded those dlls on to my desktop, then right click on project and added those using "Add Reference->Browse". Then I pushed on to the repository.
But when my friend fetched the changes from the repository, it shows the reference, but says "could not resolve reference"? How do I make sure that the dlls actually get pushed to the repository and not just the path.

A: Add a folder to the project, add the dlls, reference from the new folder, and commit the folder to github.
Or, if the dlls are available as nuget packages you could install them through nuget and make sure the "packages" folder is committed with the project in github.
As Metro Smurf pointed out, you could also omit the nuget packages folder and use the package restore option. Here's a link to the nuget documentation on this option: Package Restore


text:
Q: Отправка логов от приложения разработчику У меня есть такой вопрос.
Допустим я написал свое супер-приложение и разместил его в Play Market. Его скачали тысячи пользователей и пользуются им. Однако приложение разумеется не без греха и время от времени в нем случаются ошибки.
Чтобы понимать что за ошибки, что нужно патчить и как дальше поддерживать?
Я в обработчике каждого исключения выполняю отправку неких данных на специально созданную для этого почту. Представим также, что большое количество сообщений не будет большой проблемой для меня.
Данные которые я хочу получать исключительно технического характера, никакой слежки за пользователями, никакого воровства паролей и прочих безобразий. Только те данные, что мне нужны для понимания причин возникновения ошибки и ее исправления.
А теперь вопрос
Как это делать правильно, чтобы не возникло много вопросов от пользователей?
Чтобы Google не забанил мое приложение в своем магазине и вообще избежать подобных проблем.
Правильным ли будет такой вариант:
В настройках есть галка, которая позволяет отключить эту отправку, и по умолчанию эта возможность включена. С одной стороны не хотелось бы тех самых проблем и претензий, а с другой стороны не хотелось бы лишать себя возможности определять источники проблем .

A: Не нужно изобретать велосипед, используйтей crashlytics от Fabric (от создалей Twitter)
Установка очень проста - все абсолютно бесплатно, регистрируетесь, устанавливаете плагин для среды разработки, он сам добавит в проект необходимый код (предварительно показав что он собирается добавить).
Далее при краше будет отправлено информация о девайсе и стектрейс ошибки, и прийдет уведомление вам на емейл.

A: Есть еще замечательный проект acra все бесплатное, интегрируется за пару минут.

A: Как вариант - можно использовать Google Analytics.
Вы можете настроить свои evets и зашить в них информацию, которую хотите получать из приложения. К примеру в поле Label (String) можно зашить JSON или XML в виде строки. Все зависит от того, какие данные Вам нужны.
Кроме этого, сможете получить массу другой статистической информации о пользователях, ошибках, приложении и т.д. Все это можно синхронизировать с Google Developer Console. Данные собираются даже в оффлайн режиме (отправляются при первой возможности на сервер).
И можете не бояться бана - это библиотека от самого Google.


text:
Q: The context is not currently tracking the entity I am using WCF DataService and the AutoMapper to Map the objects.
The below sample works fine when I get the single entity.
BOND contextBond = this.agent.Context.BONDS.Where(x => x.SECURITY_ID == Security.SECURITY_ID).FirstOrDefault();
Mapper.Map<BondItem, BOND>(this.Bond, contextBond);
this.agent.Context.UpdateObject(contextBond);

The below is the implementation for List Object. I am getting an exception "The context is not currently tracking the entity." at the last line
List<SECURITY_XREF> contextXREF = this.agent.Context.SECURITY_XREF.Where(x => x.SECURITY_ID == Security.SECURITY_ID).ToList();
Mapper.Map<List<SecurityXrefItem>, List<SECURITY_XREF>>(this.Xref, contextXREF);
this.agent.Context.UpdateObject(contextXREF);

Any Idea How can I resolve the issue? In other words how can I pass the List Objects to the UpdateObject Methods.
Thx

A: The DataServiceContext.UpdateObject only accept single entity object, you have to call it once on each object in the list. DataServiceContext.SaveChanges will save all changes to server with one call.
foreach (var entity in list)
{
    context.UpdateObject(entity);
}
context.SaveChanges()

A:

foreach (var entity in list)
{
    if(!context.IsAttached(entity)) context.Attach(entity);
    context.UpdateObject(entity);
}
context.SaveChanges()


text:
Q: BufferedReader.lines().foreach() never terminates I'm trying to read a HTTP request from a Bufferedreader, that gets Socket.getInputStream() as input. However, when I use Bufferedreader.lines().foreach(), it never terminates and it just gets stuck.
My code (simplified):
Socket socket = new ServerSocket(9090);
Socket newConnection = socket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(newConnection.getInputStream()));
reader.lines().forEach(s -> System.out.println(s));

A: You need to read more about the HTTP 1.1 protocol. Requests aren't terminated by end of stream. They are terminated by exhausting the byte count in the Content-length header, or of the cumulative chunks if chunked transfer mode is in use. If they were exhausted by end of stream, you could never send a response.

A: Try creating your socket with parameter-less constructor and use connect() method with port and timeout parameter. This will prevent endless freeze.


text:
Q: Voximplant: Not receiving message from "sendMessage" method I am trying to use Call.sendMessage method to send info from VoxEngine to WebSDK during the call.
VoxEngine scenario:
call.sendMessage("Test message");

Browser js:
voxAPI.addEventListener(VoxImplant.Events.MessageReceived, onMessageReceived);
function onMessageReceived(e){
    console.log("onMessageReceived");
    console.log(e.text);
}

VoxEngine log shows that everything is ok (Executing JS command: SendMessage), but browsers don't receive it .
Firefox shows warning "Invalid URI. Load of media resource  failed.". Chrome shows nothing.
What's wrong?

A: try add async first on your function onMessageReceived like this :
async function onMessageReceived(e){
    console.log("onMessageReceived");
    console.log(e.text);
}

A: I think that issue is related to the way you subscribe to the MessageReceived event.
This is a CallEvent: https://voximplant.com/docs/references/websdk/voximplant/callevents#messagereceived
So, you need to change your code to something like:
call.on(VoxImplant.CallEvents.MessageReceived, <your_handler>);


text:
Q: php regex replace clear span code I'm trying to build a PHP preg replace string when processing poorly written html, such that if I am given:

G#         Cm

       Yenilmedi

A#G#    Cm

Açık seçik sizle oynamadı

I want to delete span codes and between
Sample:

Yenilmedi

Açık seçik sizle oynamadı

A: preg_replace('/()/u', '', $str);


text: Q: how can I extract pores from an input binary fingerprint image using marker control watershed segmentation in MATLAB I am working on pore extraction from  binary fingerprint image, On using the watershed segmentation, I managed to get the gradient image but now I want to extract the pores(white blobs) from the ridges(the lines across the fingerprint).How do I go about?


text:
Q: Find desktop files in wubi disk Short question: where is the ~/Desktop/ files in the root.disk (wubi) ?
Details:
Hello, I've been using wubi in windows 7 x32 for a while and then had to change my main operating system to windows 8 x64.
Note: the wubi was x64.
So I formatted my OS partition (the wubi was installed in the other one) and then I couldn't open ubuntu anymore. And then found out that it was possible to nagivate through .disk files in this website, and installed the ext2explore and then found all documents that were in ~/Documents and ~/Downloads.
However, when I opened the ~/Desktop the folder was empty, and I am sure most of my files was/is there.
Am I missing something?

A: If you're booting from a live CD (which it sounds like you are), then ~/Desktop is the /home/ubuntu/Desktop folder on the live CD and it is empty.
If you mounted the Wubi root.disk file, then you need to reference it directly from the mountpoint. e.g. if you ran
sudo mount /dev/sda1 /media/win
sudo mount -o loop /media/win/ubuntu/disks/root.disk /mnt

Then you'll find your Desktop folder under /mnt/home/<your_username>/Desktop (replacing <your_username>with your user name from the Wubi install), not under ~/Desktop.


text:
Q: Is execution of stream lazy when using findAny() after multiple transformations? I have following code situation:
 return modulePatternPairs.stream()
                .filter(it -> it.matches(absoluteFilePath))
                .map(ModulePatternPair::getModule)
                .findAny()

My question: before find any, is map of all previous values performed, or is it done lazily - is only one variable mapped and then result returned? Should I rather use:
 return modulePatternPairs.stream()
                .filter(it -> it.matches(absoluteFilePath))
                .findAny()
                .map(ModulePatternPair::getModule)

What if I do mapping first, and then filter and findAny?

A: Note that your second snippet:
 return modulePatternPairs.stream()
            .filter(it -> it.matches(absoluteFilePath))
            .findAny()
            .map(ModulePatternPair::getModule)

really means:
 ModulePatternPair mp
    = modulePatternPairs.stream()
            .filter(it -> it.matches(absoluteFilePath))
            .findAny();
 mp.map(ModulePatternPair::getModule)...

Which I think should answer your question -- the first statement runs a complete stream pipeline, which results in a single ModulePatternPair.  The first pipeline does the minimal element generation / filtering it needs to find one.  Then the second stream pipeline (which is kind of silly, because you've got a stream of one element), proceeds to do the mapping.  As one of the commenters mentioned, you should just run it as one pipeline (your first snippet), and all will be good.


text:
Q: Why GADT/existential data constructors cannot be used in lazy patterns? Today, I got a compiler error when trying to use a lazy pattern when matching on an existential GADT constructor:

An existential or GADT data constructor cannot be used inside a lazy (~) pattern

Why is that limitation? What "bad" stuff could happen, if it were allowed?

A: Consider
data EQ a b where
  Refl :: EQ a a

If we could define
transport :: Eq a b -> a -> b
transport ~Refl a = a

then we could have
transport undefined :: a -> b

and thus acquire
transport undefined True = True :: Int -> Int

and then a crash, rather than the more graceful failure you get when trying to head-normalise the undefined.
GADT data represent evidence about types, so bogus GADT data threaten type safety. It is necessary to be strict with them to validate that evidence: you can't trust unevaluated computations in the presence of bottom.

A: With "normal" data, you can skip checking the constructor during pattern-matching, on the understanding that when you try to use the data from the pattern, it might turn out to not exist, thus throwing an exception at you.
With a GADT, the type signature potentially changes depending on which constructor is present. We need to know about types at compile-time; it's no good not checking the constructor until you need the values. If you do, you might have a type mismatch error. And that, potentially, means your program crashing with a segmentation fault (or worse). Haskell programs should never segfault.


text:
Q: Highcharts symbol covered by another line Is there a way to define a symbol that covers another symbol? Or the same with points? I have a symbol that is overdrawn by another symbol, but I want a particular one to appear on top. It appears "last drawn line wins" is the rule, but I may like one line to appear on top at one point, and another at a different time.
In this example fiddle from their page, the idea would be to display the cloud above the sun, z-index wise, without reordering the series data.
http://jsfiddle.net/5Les1k6j/1/
series: [{
            name: 'London',
            marker: {
                symbol: 'diamond'
            },
            data: [{
                y: 3.9,
                marker: {
                    symbol: 'url(https://www.highcharts.com/samples/graphics/snow.png)'
                }
            }, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, {
                    y: 26.5,
                marker: {
                    symbol: 'url(https://www.highcharts.com/samples/graphics/snow.png)'
                }
            }, 14.2, 10.3, 6.6, 4.8]
        },
        {
            name: 'Tokyo',
            marker: {
                symbol: 'square'
            },
            data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, {
                y: 26.5,
                marker: {
                    symbol: 'url(https://www.highcharts.com/samples/graphics/sun.png)'
                }
            }, 23.3, 18.3, 13.9, 9.6]

        }
        ]


text:
Q: Inserting _any_ unicode character in Latex document I am totally new to XeLaTex and LuaLaTex, but I have read that both allow to write LaTeX documents in UTF-8.
That actually works for some unicode characters, but not for all.
See the following example document:
\documentclass{scrartcl}

\usepackage{fontspec}

\setmainfont{Latin Modern Sans}

\begin{document}
A line with normal spaces.

A\,line\,with\,latex\,thin\,spaces.

A line with utf-8 thin spaces.

ÄÆÿ⇒☑ßдάრ你ん녕.
\end{document}

XeLaTeX generates the following:

LuaLaTex generates the following:

In the logfiles I see the following lines:
XeLaTeX:
Missing character: There is no   in font Latin Modern Sans 10 Regular/OT:script
=latn;language=DFLT;mapping=tex-text;!
Missing character: There is no   in font Latin Modern Sans 10 Regular/OT:script
=latn;language=DFLT;mapping=tex-text;!
Missing character: There is no   in font Latin Modern Sans 10 Regular/OT:script
=latn;language=DFLT;mapping=tex-text;!
Missing character: There is no   in font Latin Modern Sans 10 Regular/OT:script
=latn;language=DFLT;mapping=tex-text;!
Missing character: There is no   in font Latin Modern Sans 10 Regular/OT:script
=latn;language=DFLT;mapping=tex-text;!
Missing character: There is no ⇒ in font Latin Modern Sans 10 Regular/OT:script
=latn;language=DFLT;mapping=tex-text;!
Missing character: There is no ☑ in font Latin Modern Sans 10 Regular/OT:script
=latn;language=DFLT;mapping=tex-text;!
Missing character: There is no д in font Latin Modern Sans 10 Regular/OT:script
=latn;language=DFLT;mapping=tex-text;!
Missing character: There is no ά in font Latin Modern Sans 10 Regular/OT:script
=latn;language=DFLT;mapping=tex-text;!
Missing character: There is no რ in font Latin Modern Sans 10 Regular/OT:script
=latn;language=DFLT;mapping=tex-text;!
Missing character: There is no 你 in font Latin Modern Sans 10 Regular/OT:script
=latn;language=DFLT;mapping=tex-text;!
Missing character: There is no ん in font Latin Modern Sans 10 Regular/OT:script
=latn;language=DFLT;mapping=tex-text;!
Missing character: There is no 녕 in font Latin Modern Sans 10 Regular/OT:script
=latn;language=DFLT;mapping=tex-text;!

LuaLaTeX:
Missing character: There is no   (U+202F) in font LatinModernSans:mode=node;sc
ript=latn;language=DFLT;+tlig;!
Missing character: There is no   (U+202F) in font LatinModernSans:mode=node;sc
ript=latn;language=DFLT;+tlig;!
Missing character: There is no   (U+202F) in font LatinModernSans:mode=node;sc
ript=latn;language=DFLT;+tlig;!
Missing character: There is no   (U+202F) in font LatinModernSans:mode=node;sc
ript=latn;language=DFLT;+tlig;!
Missing character: There is no   (U+202F) in font LatinModernSans:mode=node;sc
ript=latn;language=DFLT;+tlig;!
Missing character: There is no ⇒ (U+21D2) in font LatinModernSans:mode=node;sc
ript=latn;language=DFLT;+tlig;!
Missing character: There is no ☑ (U+2611) in font LatinModernSans:mode=node;sc
ript=latn;language=DFLT;+tlig;!
Missing character: There is no д (U+0434) in font LatinModernSans:mode=node;scr
ipt=latn;language=DFLT;+tlig;!
Missing character: There is no ά (U+03AC) in font LatinModernSans:mode=node;scr
ipt=latn;language=DFLT;+tlig;!
Missing character: There is no რ (U+10E0) in font LatinModernSans:mode=node;sc
ript=latn;language=DFLT;+tlig;!
Missing character: There is no 你 (U+4F60) in font LatinModernSans:mode=node;sc
ript=latn;language=DFLT;+tlig;!
Missing character: There is no ん (U+3093) in font LatinModernSans:mode=node;sc
ript=latn;language=DFLT;+tlig;!
Missing character: There is no 녕 (U+B155) in font LatinModernSans:mode=node;sc
ript=latn;language=DFLT;+tlig;!

So, both are missing the same characters. XeLaTeX seems to replace them by spaces, whereas LuaLaTex just leaves them out.
Interestingly, XeLaTeX seems to actually correctly set the narrow non-breaking spaces (the third output line) even though it still complains about them in the log file.
Now, when I enter those very same input lines into LibreOffice, all these characters are correctly displayed in the same font:

So it seems that this font actually does provide those characters. And the same problem applies to other fonts I have tried, so it doesn't seem to be a font problem.
Now, what is wrong here?
What do I need to do to have arbitrary unicode characters int my LaTeX documents correctly set in the output?
Update
As the comments point out, it is actually a font problem. Latin Modern doesn't include all the glyphs. Google Noto does include some (like the narrow space), but not all (e.g. ⇒ and ☑ are still missing).
@LaTeXer metioned "fallback fonts". That is actually what I need here.
After some research I found this question and somewhere a reference to the ucharclasses package.
ucharclasses seems like a "clean" approach, but has the drawback, that I have to specify all the transitions. It doesn't allow me to say "if a character is not found in the main font, try to find it in the next fallback font". I would prefer using the glyphs from my main font if available, because the would look more consistent with the remaining glyphs. Also I would need to find out which unicode characters I actually use and which blocks they are defined in.
The above mentioned stackexchange link describes exactly, what I need. But unfortunately there doesn't seem to be an easy solution. This answer attracts me, but seems quite hacky.
So, what is your recommended approach to handle such "font fallback"?
Update 2
As the narrow space seems to not be available in Latin Modern, what does LaTeX use when it processes a \, sequence? Does it calculate the needed space by itself? I assume that could be different from a possible glyph contained in the font. Would it be better to rely on LaTeX to calculate such narrow spaces or is a font providing that space (like Google Noto) the better choice?
Update 3
As both XeLaTeX and LuaLaTeX fail silently and only mention the missing glyphs in the logfile, is there an option to have them emit a warning or even an error when glypths are missing, so that I can be aware of that problem?

A: In LuaLaTeX this can be done using the combofont package by Ulrike Fischer. This allows to specify fallback fonts, and fallback fonts for the fallback fonts.
MWE, mostly taken from the combofont manual:
\documentclass{scrartcl}
\usepackage{combofont}
\usepackage{fontspec}
\setmainfont{Latin Modern Sans}
\setupcombofont{multiscript-regular}
 {
  {file:lmsans10-regular.otf:\combodefaultfeat} at #1pt,
  {file:DejaVuSans.ttf} at #1pt,
  {file:NotoSansCJK-Regular.ttc(0)} at #1pt
 }
 {
   {} ,
   fallback,
   fallback
 }
\DeclareFontFamily{TU}{multiscript}{}
\DeclareFontShape {TU}{multiscript}{m}{n} {<->combo*multiscript-regular}{}
\begin{document}
A line with normal spaces.

A\,line\,with\,latex\,thin\,spaces.

A line with utf-8 thin spaces.

ÄÆÿ⇒☑ßдάრ你ん녕.

\rule{\textwidth}{1pt}

\fontfamily{multiscript}\selectfont
A line with utf-8 thin spaces.

ÄÆÿ⇒☑ßдάრ你ん녕.
\end{document}

Result:

Note that you need to specify which fonts you want to use as fallback. Also, Noto Sans CJK is a .ttc font, i.e., a TrueType Collection, for which you need to specify the index in the collection. JP-Regular is the first font in the collection, so index 0. You can find these indexes in different ways, for example by looking at the output of fc-list.

About the thin space: \, is defined as
\relax \ifmmode \mskip \thinmuskip \else \thinspace \fi

So, if in math mode, then \mskip, if in text mode, \thinspace. And \thinspace is defined as \kern .16667em, which is conditional on the current font size (1em is the size of a 'normal' character, which changes with the font size, and is defined in the font file). If the fonts are designed sensibly the result will most likely be fine when using \,.

About the missing character warnings: you can set \tracinglostchars=2 in your preamble to make the warnings show in the terminal output and not just in the logfile (from Getting xetex to complain when a character is missing).


text:
Q: Not able to get nested table input elements into jQuery array I know this shouldn't be this hard, but I need another pair of eyes because I'm beating my head against a wall.
I have a NESTED table with an ID such as:

        Total Wall Length:

        <input type="text" id="Msr_0_T1" class="dwInput" value="0"> Inches and

        <input type="text" id="Msr_0_T2" class="dwInput" style="margin-left:2px;" value="0"> 16ths

            <select id="ItemType_0_0">
                <option>Item Type</option>
                <option>Door</option>
                <option>Window</option>
                <option>Other</option>
            </select>

        L-Dim:

        <input type="text" id="Msr_0_0_A1" class="dwInput" value="0"> Inches and

        <input type="text" id="Msr_0_0_A2" class="dwInput" style="margin-left:2px;" value="0"> 16ths

//MORE ROWS HERE//

My jQuery to serialize the text inputs and select elements are as follows:
var MeasureRowCount = $("[id^='MeasureRow_']").length; //Populated by counting parent rows
var htmlOutput = '';
var rowInputs,rowSelects;
for(var r=0;r < MeasureRowCount;r++){
    rowInputs = $('#dwMeasurements_'+r+' :input').serializeArray();
    rowSelects = $('#dwMeasurements_'+r).find('select').serializeArray();

            $.each(rowSelects, function(i, eSelectItem){
        esName = eSelectItem.name;
        esVal = eSelectItem.value;

                     htmlOutput += //name and value from above with markup
            }
}

// htmlOutput to DOM here with markup

I've tried multiple methods to collect the input elements and none work. The arrays come up empty. Even though the table is nested, shouldn't it work since I'm directly calling the nested table ID?

A: This code:
for(var r=0;r < MeasureRowCount;r++){
    rowInputs = $('#dwMeasurements_'+r+' :input').serializeArray();

Will overwrite the value of rowInputs every time it loops.
Try using jQuery.merge to combine them instead:
var rowInputs=[],rowSelects=[];
for(var r=0;r < MeasureRowCount;r++){
    $.merge(rowInputs, $('#dwMeasurements_'+r+' :input').serializeArray());

A: The answer wasn't 100% intuitive, but I should've known...
The serializeArray() method defaults to using name:value pairs when collecting elements, and the elements I was collecting didn't have any "name" attributes, only id's. Once I added names, the arrays populated as desired.


text:
Q: Replace even numbers from the list that are multiples of 3 with factorials Good afternoon, I can say new to programming
The task is this: the user must enter a list, and it must be sorted in ascending order. further even numbers and simultaneously multiples of 3, are replaced by factorials. Please help me figure it out. The way I did is wrong
import math

a = list(input("Enter a list: "))

print( sorted(a))

for x in a:
    if x%2 == 0:
        a[x] == a[math.factorial(x)]

A: I am assuming that by even numbers and simultaneously multiples of 3 you mean that the numbers are multiples of 3 and 2.
Use ast.literal_eval() to convert the string list to a list, use enumerate for iterating over the list.
if x%2 == 0 and x%3==0 can also be replaced by x%6 == 0 as divisibility of 6 is if x is divisible by 2 and 3.
You cannot directly convert the input to a list because it will contain only  1 element - the value returned by input
import math
import ast
a = input("Enter a list: ")

a=sorted(list(ast.literal_eval(a)))

for b,x in enumerate(a):
    if x%2 == 0 and x%3==0:
        a[b] = math.factorial(x)

Output:
Enter a list: 1,4,3,6,5,3,12,18
[1, 3, 3, 4, 5, 720, 479001600, 6402373705728000]

A: Instead of doing a[x] where x is the value, you need to index the list and replace the value on that index as below:
for idx, x in enumerate(a):
    if x%2 == 0 or x%3==0:
        a[idx] == a[math.factorial(x)]

A: You can't convert an input result(which is actually a string) to list directly.
First make sure the separators of your input are the same, like  (space) or ,. Then use str.split to split elements out.
The elements are str now so transform them to numbers by loop and then sort them.
For example:
a = input("Enter a list: ").split(' ')
a = sorted([int(n) for n in a])

Then do your math trick.


text:
Q: c++ overloading plus in an efficient way I wrote a class like this:
class vector3D{
    public:
    double x,y,z;
}

and i overload + operator:
class vector3D{
    public:
    double x,y,z;
    vector3D operator+(const vector3D &lhs)
    {
        vector3D temp(x+lhs.x,y+lhs.y,z+lhs.z);
        return temp;
    }
}

but using C=A+B is slower than
C.x = A.x + B.x;
C.y = A.y + B.y;
C.z = A.z + B.z;

i think it is because defining a vector3D instance in + overloading function. is there anyway to avoid this?
(FYI: i build with this flags: -Wall -Wextra -Wunreachable-code -m32 -DNDEBUG -O2 -D_LARGEFILE64_SOURCE -D_REETRANT -D_THREAD_SAFE)
EDIT:
this is how i test speed of two approach(in main() ):
//test bench
vector3D A(0.0,0.0,0.0), B(1e-9,1e-9,1e-9);
clock_t c = clock();
//case A
for(long int i=0;i<1000000000;i++)
{
    A = A + B;
}
cout<<"case A took: "<<1.0*(clock()-c)/CLOCKS_PER_SEC<<A<<endl;
c = clock();
//case B
for(long int i=0;i<1000000000;i++)
{
    A._x = A._x+B._x;
    A._y = A._x+B._y;
    A._z = A._x+B._z;
}
cout<<"case B took: "<<1.0*(clock()-c)/CLOCKS_PER_SEC<<A<<endl;

and the result is:
case A took: 5.539[1, 1, 1]
case B took: 1.531[2, 2, 2]

A: Since you're creating an additional object, it will carry some overhead. This is inherent.
However, looking at the "payload lines" you want, they are very similar to what you'd have in the body of operator+= adding some other:
vector3D &operator+=(const vector3D &other) // Note - no objects created.
{
    x += other.x;
    y += other.y;
    z += other.z;

    return *this; // Note - return by reference.
}

Of course, operator+= modifies its left operand (which is exactly why you have operator+ with its object-creation overhead).
In general, you should prefer operator+= for heavy objects where it is applicable (see also this question).

A: You may actually get a performance boost by collapsing this to one line and taking advantage of return value optimization:
vector3D operator+(const vector3D &lhs)
    {
        return vector3D(x+lhs.x,y+lhs.y,z+lhs.z);
    }


text:
Q: The box '....' could not be found I'm on Ubuntu Linux 14. I have vagrant and virtual-box installed. And I have a file from a Vagrantfiile from a repository. However, I always get this error:
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
There are errors in the configuration of this machine. Please fix
the following errors and try again:

vm:
* The box 'hoatle/iorad' could not be found.

How can I fix it?

A: so vagrant cannot find your box in atlas, weird because it seems its there : https://atlas.hashicorp.com/hoatle/boxes/iorad
you can try to install the box directly with vagrant box add hoatle/iorad but I guess it will not work in your case neither.
try to download the box file directly from wget https://atlas.hashicorp.com/hoatle/boxes/iorad/versions/0.5.0/providers/virtualbox.box and then install the box in vagrant with vagrant box add hoatle/iorad <path to your downloaded box file>


text:
Q: GA 4: Send Hits To The Past In GA 3 (Universal Analytics) with the Queue Time parameter, you can instruct Google Analytics to process the hit so that it would appear as having occurred as many milliseconds ago from the collection moment as specified by the parameter.
For GA 4 I tried &ht (hit time in ms) parameter but it doesn't work.
How to implements this in GA 4?


text:
Q: Нижняя часть бэкграунда не меняется

.deflation {
  background: #f6f6f6;
  padding: 65px 0;
}

.deflation h1 {
  float: left;
}

.deflation .small_arrows {
  float: right;
}

.deflation .items {
  max-width: 1286px;
}

.what-is {
  background-color: #e9e9e9;
  padding: 70px 0;
}

.what-is>div {
  max-width: 1296px;
  margin: auto;
  background-color: #e9e9e9;
}

.what-is .what-is-inner {
  max-width: 828px;
  float: left;
}

.what-is .what-is-inner p {
  color: #6f6f6f;
  font-size: 14px;
  font-weight: 400;
}

.what-is .group {
  /* width: 330px; */
  background: white;
  float: right;
  padding: 14px;
}

.what-is .group a {
  text-transform: uppercase;
  font-size: 14px;
  font-weight: 700;
}

.what-is .group p {
  font-size: 13px;
}

.what-is .group img {
  border-radius: 100%;
}

.what-is .group button {
  margin: auto;
  padding: 7px 16px 8px;
  background-color: #507eb3;
  color: white;
  border: 0;
  display: block;
  width: 100%;
  border-radius: 4px;
  margin-top: 8px;
}

Снижение цен

            3$
            -9%

            3$
            -9%

            3$
            -9%

            3$
            -9%

Что такое Стимпэй?

В нашем интернет-магазине вы сможете гарантированно приобрести ключи к играм от Steam, Uplay, Battle.net и прочих популярных игровых платформ. Наш магазин делает все для того, чтобы ваши покупки проходили быстро, с максимальным удобством и безопасностью,
          а цены оставались максимально доступными. Для покупки достаточно лишь указать электронный адрес при оформлении заказа и выбрать удобный способ оплаты. После этого Вам на почту придет пароль доступа в личный кабинет, в котором Вы получите ключ
          активации.

        Читать дальше <svg xmlns="http://www.w3.org/2000/svg"
                        width="12" height="12" fill="#ff793a" class="bi bi-caret-down-fill float-right"
                        viewBox="0 0 16 16">
                        <path
                            d="M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z" />
                    </svg>

        steampay

        Игры на любой вкус по самым низким ценам

        1000 подписчиков

        <button>Подписаться на новости</button>

Когда я написал
.what-is {
    background-color: #e9e9e9;
}

я ожидал, что вся секция окрасится в цвет #e9e9e9. Но не тут то было... Только верхняя часть окрашивается, а нижняя - нет. Как пофиксить?
P.S. На фото вы можете посмотреть на проблему, о которой я говорю.

A: Нужно в секции указать
overflow: hidden;


text:
Q: How to detect changes on multiple SQL server tables? We have an issue where we need to send only changes made to certain columns and certain tables. We have a prod DB on one server A, which we can not run Jobs or procedures on. Then we have seperate server where we run Jobs and Stored Procedures, Server B. My question is what are some ways to automate detecting changes in prod db Server A tables?
CDC?
Compare Hashes?

A: You definitely do not want to use triggers. The software vendor could/will find them and use it as an excuse to stop supporting your app.
Using CDC will not slow down the system (that much) and will not affect the mechanics of the app. There will be several system tables that will be created/affected by CDC but they will be in parallel to your app.

A: Is there a reason you cannot use triggers, i.e. on update or insert?
Since triggers won't work for you perhaps add insert and update timestamp columns to the tables you want to monitor. You could then maintain a list of timestamps of the times the diff check was run. Anything with a "new" insert or update timestamp would be something you would then export to the B server.


text:
Q: 301 Redirects in WordPress - Some Work, Some Don't I am having a weird issue after transferring a client's website from HTML to a WordPress theme.
I'm using the plugin "Simple 301 Redirects" to forward all the old HTML pages to the updated WordPress URLs - about 50 total redirects.
This plugin has worked great for me on a number of other websites, but for some reason, the 301 redirect works for about half of those URLs, and the other half I receive a 404 Page Not Found error.
I attempted to remove one of the non-working redirects from the plug-in, and manually place this within the .htaccess file, but that didn't work either.
Any idea as to why that may be the case, and what is the best way to process a long list of 301 redirects for a WordPress website?
EDIT: Here is my .htaccess, and I actually got this one to work.  As of now, I have 42 redirects working using "Simple 301 Redirects" plug-in, and there are 17 that are not working using the same plug-in.
Options -Indexes

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteRule ^articles\.html$ http://www.magnuminvestigations.net/articles/ [R=301,L]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

And here is an example that is not currently working:
Old URL
http://www.magnuminvestigations.net/cheating_infidelity_investigators.html

New URL
http://www.magnuminvestigations.net/services/cheating-and-infidelity-investigations/


text:
Q: Problems with paste as values in VBA I have a problem in paste as values a multiple selection, this is what I have to do:
I have a spreadsheet, every cell has a formula in it and I want to create a macro which copy each cell and paste on itself as value (in order to remove every formula). The problem is that there are some cells which are locked, so if I try to copy and paste them excel returns an error and it stops the procedure.
Now I have two possibilities:
case 1: copy and past as values each cell individually, but I have a lot of cells and I have to do this procedure very often.
case 2: create a big selection which contains only the unlocked cells and then copy and paste them all togheter.
case 2 seems to be the better choice, but with excel I can't copy and paste multiple selection...does anyone have a tip for me?
I though to take the big fragmentary selection and copy and paste every block of the selection one by one, but I don't know if is it possible :(

A: Loop throught every cell in selection and check if they are locked like this:
For Each Z In Selection
  if Not Z.Locked Then
   'do copy paste here
  End If
Next Z


text:
Q: Python Unit test for method contains request I have a method, which contains external rest-api calls.
ex:
def get_dataset():
    url=requests.get("http://api:5001/get_trainingdata")
    filename=url.text[0]
    return filename

When I do @patch for this function, I can able to do unittest. But, coverage in not covering whole function.
How can write unittest case for this method with full coverage?
My testcase
@mock.patch('api.get_dataset')
def test_using_decorator1(self, mocked_get_dataset):
    file = [{"file":"ddddd"}]
    mocked_get_dataset.return_value = Mock()
    mocked_get_dataset.return_value.json.return_value = file
    filename = file[0]
    self.assertEqual(filename, file[0])


text:
Q: What is power of number like (power of 2, power of 10)? and how to calculate power of number. I know my question is very simple to somebody, but I'm still don't understand so far.
And now my questions about this subject is:
What is power of number (ex. 2^6, 4^4)?
What is the steps to calculate power of number?

Please I want very very easy explanation to understand.

A: In the expression a^b, let us assume that b is a positive integer.  Then the value of the expression is calculated by multiplying a by itself b times.  thus 2^6 means to multiply 2 by itself 6 times: 2*2*2*2*2**2 = 64.  4^4 is calculated as 4*4*4*4 = 256.  If b is not a positive integer, things become more complicated but I don't think you are ready for that.

A: Well you can take $2^6$ and break it into smaller powers such as $2^3*2^3$.That should make it easier for you.


text:
Q: How to display image from a URL in a JTable in Java I know this will be a duplicate question, but I can't find the answer on my case. I have an URL for a image (say like this https://i.imgur.com/VcV0SG.jpg) in MySQL database. So I need to render those images in a JTable. How can I do that?
Code
            java.lang.reflect.Type listType = new TypeToken<ArrayList<Products>>() {}.getType();
            List<Products> productsList = new Gson().fromJson(json, listType);

            for(Products pro : productsList)
            {
                DefaultTableModel model = (DefaultTableModel) productsTable.getModel();
                Vector<String> row = new Vector<String>();

                row.add(pro.getCode());
                row.add(pro.getName());
                row.add(pro.getPrice());
                //returns String (url of the image like `https://i.imgur.com/VcV0SG.jpg`)
                row.add(pro.getPic());
                model.addRow(row);
            }

A: I understand that you know how to extract data from MySQL. If you already have data, the remaining part is very simple. Use ImageIcon. Here is an example:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;

public class Main extends JPanel {

   public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
        try {
            showGui();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    });
   }

  public Main() throws MalformedURLException {
    Icon icon1 = new ImageIcon(new URL(
            "https://www.cleverpetproducts.com/wp-content/uploads/2018/03/tardar.jpg"));
    Icon icon2 = new ImageIcon(new URL(
            "https://www.cleverpetproducts.com/wp-content/uploads/2018/03/tardar.jpg"));
    Icon icon3 = new ImageIcon(new URL(
            "https://www.cleverpetproducts.com/wp-content/uploads/2018/03/tardar.jpg"));

    String[] columnNames = {"Picture", "Text"};
    Object[][] data = {
                    {icon1, "Text 1"},
                    {icon2, "Text 2"},
                    {icon3, "Text 3"},
     };

    DefaultTableModel model = new DefaultTableModel(data, columnNames) {
        public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }
    };
    JTable table = new JTable(model);
    table.setPreferredSize(new Dimension(500, 500));
    table.getColumn(columnNames[0]).setPreferredWidth(300);
    table.getColumn(columnNames[1]).setPreferredWidth(100);
    table.setRowHeight(0, 100);
    table.setRowHeight(1, 100);
    table.setRowHeight(2, 100);

    JScrollPane scrollPane = new JScrollPane(table);
    add(scrollPane);
 }

 private static void showGui() throws MalformedURLException {
    JFrame frame = new JFrame("Icon showcase");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new Main());
    frame.setLocationByPlatform(true);
    frame.pack();
    frame.setVisible(true);
 }

}


text:
Q: animate duration altering while using parameters The following code animation runs infinitely and runs perfectly every time:
function func(){
    $('.one').animate({width:'100%'},5000,function(){
        $('.two').animate({width: '100%'},1000,function(){
            $('div').width('0px');
            func();
        });
    });
}
func();

But now I wanted to use parameters for func() like this:
function func(one,two){
    $('.one').animate({width:'100%'},one,function(){
        $('.two').animate({width: '100%'},two,function(){
            $('div').width('0px');
            func();
        });
    });
}
func(5000,1000);

But this time animation duration is very faster (see from next time of animation).
Demo without parameters and demo with parameters.

A: You're not passing in any values when calling func(); within your $('.two').animate() function. By default, jQuery handles undefined animations for you by defaulting them to 400 - this is why the animation gets faster.
Change:
$('.two').animate({width: '100%'},two,function(){
    $('div').width('0px');
    func();
});

To:
$('.two').animate({width: '100%'},two,function(){
    $('div').width('0px');
    func(one, two);
});

A: See http://jsfiddle.net/9j69kz39/2/
Call func with the same parameters:
 func(one, two);


text:
Q: Listas não carregam junto ao model Meu model:
public class Grupo: ModelBase
  {
    public Grupo()
    {
      this.Itens = new List<Item>();
    }

    public Grupo(string nome): this()
    {
      this.Nome = nome;
    }

    public string Nome { get; set; }
    public virtual ICollection<Item> Itens { get; set; }

  }

Meu repository:
public virtual T BuscaPorId(int id)
{
  return _dbSet.Find(id);
}

E meu metodo na minha classe Service
public Grupo BuscarPorId(int id)
{
  return grupoRepository.BuscaPorId(id);
}

Quando eu chamo no controller ele vem as listas que estão no "Grupo"
public ActionResult Editar(int Id)
{
  if (Id == null)
  {
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
  }
  Grupo grupo = grupoService.BuscarPorId(Id);

Mas quando eu clico em salvar e passo para o meu Serviço que chama o meu método this.BuscarPorId, exatamente o mesmo método que chamei no controller, aqui ele não carrega as listas, apenas os dados "Nome,Id"

A: Find não garante carga de entidades dependentes aqui:
public virtual T BuscaPorId(int id)
{
    return _dbSet.Find(id);
}

Faça a carga explícita dos ítens para garantir que eles retornem como desejado:
public virtual T BuscaPorId(int id)
{
    return _dbSet.Include(g => g.Itens).SingleOrDefault(g => g.Id == id);
}


text:
Q: How to sort and filter backbone collection relatively new to backbone. I'm trying to filter and sort a collection before passing off to the template. I can easily sort OR filter, but I can't figure out how to do both. I tried chaining them, creating a variable to hold the filter then sort on that, but can't get anything to work. Any advice?? Thanks!
# Can filter like this:
monday =  @collection.where({ target: '#day-mon' })

# Can sort like this:
mondaySorted =  @collection.sortBy (t) -> t.get('order')

# Doesn't work:
mondayFilteredSorted = @collection.where({ target: '#day-mon' }).sortBy (t) -> t.get('order')

# Doesn't work:
mondaySorted = monday.sortBy (t) -> t.get('order')

A: Your problem is that where and sortBy return arrays — not collections — and arrays don't have where or sortBy methods. As soon as you where or sortBy, you lose access to the Backbone collection and Underscore utilities.
You can of course use Underscore directly on the array that where gives you:
_(@collection.where(target: '#day-mon')).sortBy (t) -> t.get('order')

or you could use chain and filter:
@collection.chain().filter((m) -> m.get('target') == '#day-mon').sortBy((m) -> m.get('order')).value()

where is a Backbone collection method so you have to drop down to Underscore's filter if you want to chain.
You could also use the standard Array::sort:
by_order = (a, b) ->
    [ a, b ] = [ a.get('order'), b.get('order') ]
    return  1 if(a > b)
    return -1 if(a < b)
    return  0
@collection.where(target: '#day-mon').sort(by_order)

I find this version a little easier on the eyes if you don't use an anonymous function with sort.
Demo: http://jsfiddle.net/ambiguous/N6AT7/1/


text:
Q: HOW TO Avoid git diff putting code block name in hunk header? Here is some parts from a diff file generated using git diff HEAD.
@@ -261,6 +261,13 @@ public class JSONServiceAction extends JSONAction {
                            return new double[0][0];
                    }
            }
+               /*
+                * Some changes made...
+                */
            else if (typeNameOrClassDescriptor.equals("[[F")) {
                    String[] values = request.getParameterValues(parameter);

@@ -587,4 +594,4 @@ public class JSONServiceAction extends JSONAction {
    private Map<String, Object[]> _methodCache =
            new HashMap<String, Object[]>();

-}
\ No newline at end of file
+}

I have two problems with this:

*

*look at the hunk header lines, there is a public class ... after the @@. So git diff is putting the code block name (here is a class defination) in the hunk header. Why is git diff doing this? Can I ask git diff not to put that part in the hunk header?

*Look at the second hunk part. It shows the last few lines of the class file, which is not modified at all. Why is git diff including this part in the diff file? Can I avoid it? (Actually the only modified part of this class is in the first hunk area, where I added three lines of comments before the else if)

I checked the git diff man page, but now I am still confusing because I don't quite understand some part of the manual; I also checked some related questions that SO recommended, but they are all about "HOW TO SHOW A METHOD NAME HERE INSTEAD OF A CLASS NAME", like this: Is there a way to ask git diff to show the method name instead of the class name?.
If there is not a method to disable the custom hunk head, please tell me as well so that I can try with some scripting.
Update: The reason why I want the hunk description off
In my job, the benchmark test, one step in the build script is to automatically collect the codebase info of the source folder if it is a svn working copy -- the info includes a diff file. Now we want it to support git. Of course we will save a pure-git diff file, however, we have to generate a svn-compitable diff at the same time. This is because the developers use git and the QAs (testers) use svn (the manager migrates reviewed code only from git to svn).
For the SVN client, (SmartSVN, which is not smart at all) in my work environment, it doesn't matter whether the diff file has certain SVN information lines. It does matter that the file path doesn't have a prefix, and the hunk header doesn't have a description...

A: *

*Git's putting those block names to make it easier for humans to determine which part of the file a given patch is affecting. In case of C it show a first line of a function definition, which is really useful. Apparently it's slightly less informative in case of Java. Why does it trouble you?

*You have added or removed a newline character at the end of the file. Git treats it as a difference. Hence it's listed in the diff.

A: For your point 2, you had a file with no newline at the end committed. Your current version has a newline at the end (a lot of editors add one for you). That's what the diff is showing.
$ git init
Initialized empty Git repository in ...
$ echo -n hello > file
$ git add file ; git commit -m test
[master (root-commit) 846c33e] test
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 file
$ echo hello > file
$ git diff
showing.diff --git a/file b/file
index b6fc4c6..ce01362 100644
--- a/file
+++ b/file
@@ -1 +1 @@
-hello
\ No newline at end of file
+hello

For your 1., see: Git format-patch to be svn compatible?

A: *

*As mentioned, the hunk header is for convenience. If you want to change what it displays, see the git attributes manpage section on defining a custom hunk-header and see an example for python here. If you define the regex so it won't match, then you won't get the hunk header. Before you do this, I'd suggest making sure you have a good reason to do so. It shouldn't harm anything, and if you're parsing the diff yourself, you ought to be capable of accepting a standard git diff.

*The \ No newline at end of file indicator is standard notation in a unified diff file and is used to indicate exactly that.


text:
Q: Faulty 2006 iMac - what is it useful for? I own a 2006 iMac, which, alas, has a known manufacturing fault. Because of the poorly-designed cooling system, the graphics card (soldered to the motherboard) has become defective and the system shuts down spontaneously minutes or seconds after being turned on.
I have used a different computer for three years and I have really no need of this iMac at the moment.
However, I'd like know if I can nevertheless do something with it. It has a processor, lots of RAM, and a good hard disk. Can I use its computational power and its hard drive without employing the graphics card? I'd like the idea of turning it into a file server and being able to run non-graphical programs in it. The best would be being able to run X11 programs in it and see their graphics on another computer.
Everytime I turn the computer on it only worsens the problem, damaging the graphic card even more. So far, it didn't shut down when I put it in "single user mode", but I am afraid that even this little workload could damage the graphics card more and more. Basically I do not want to use the graphics card at all. I am prepared even to install a different operating system. (But how would I do so when the computer keeps shutting down?)
Edit: The problem is also reported in this petiton

A: Recycle or sell it for parts. Since the GPU is soldered, you likely cannot bypass the temperature sensors that the system monitors to ensure safe operation with consumer skills at soldering. Have you looked into a logic board repair or buying a Mac with a shattered screen at low cost to assemble one workable Mac?
Operating a machine where you know the protection mechanisms are shutting it down to prevent overheating and persist in doing so, being frugal crosses a line into taking risks with fire if you don't go to great lengths to protect yourself and other property nearby.
Also - your characterization of design flaws seems unsupported with one link to a 540 entry discussion thread. A six year old computer having failures seems more like a car needing an engine rebuild after things start failing and not so much a design failure, but perhaps the link wasn't correct.


text:
Q: Dockerized Python Application is taking 100% CPU on EC2 I have deployed python application on EC2, but python is taking 100% CPU usage.
Below is the code snippet where i think the issue is.
@app.route("/refresh", methods=["POST"])
def preprocess():
    start_time = time.time()

    if flask.request.content_type == "application/json":
        input_data = flask.request.data.decode("utf-8")
    else:
        return flask.Response(
        response='{"Error: Request content type error, REQUIRED: application/json "}',
        status=415,
        mimetype="application/json")

    input_dictionary = ast.literal_eval(input_data)

    prepare_obj = Prepare()
    prepare_output = prepare_obj.preparation()

    end_time = time.time()
    return flask.Response(response=resp, status=200, mimetype="application/json")

Is the "time" module causing the issue? We have 2 EC2 instance. In one EC2 i am not getting this issue. But in another EC2 instance i am facing.


text:
Q: Noda Timezone issue with IDateTimeZoneSource.MapTimeZoneId I am trying to convert Windows to IANA time zone and below is the code that works most of the time. But when the windows time id = "Turks & Caicos" then below code returns NULL. I am using NODATIME Version 1.3.1
    Public Function ConvertID_WindowsToIana(strWindowsZoneID As String) As String
        If strWindowsZoneID.Equals("UTC", StringComparison.OrdinalIgnoreCase) Then
            Return "Etc/UTC"
        End If

        Dim tzdbSource = NodaTime.TimeZones.TzdbDateTimeZoneSource.[Default]
        Dim tzi = TimeZoneInfo.MapTimeZoneId(strWindowsZoneID)
        Return tzdbSource.CanonicalIdMap(tzi)
    End Function

Here when tzi = -4:00 Turks & Caicos, in this case the return is NULL.
Now when I updated to version 2.2.3, thought that it will fix the stuff, but as per the documentation

And now that function is taking a "Position Of Current String" as parameter.
So my code will look like below:
  Public Function ConvertID_WindowsToIana(strWindowsZoneID As String) As String

        Dim tzi = TimeZoneInfo.FindSystemTimeZoneById(strWindowsZoneID)
        Dim tzid = tzdbSource.GetSystemDefaultId(WHAT TO PUT HERE)
        // some logic
    End Function

Question 1: Why my first code does not work for "Turks and Caicos".
Question 2: I updated thinking it will fix that issue, but now that function is vanished and replaced, and I don't know what to use. Please help me.
P.S: For Eastern and many other time zones the First Code Snippet works fine.

A: GetSystemDefaultId doesn't replace all the functionality of MapTimeZoneId - you don't want to call that here.
Instead, use tzdbSource.WindowsMapping to get a WindowsZones that you can then use to find the TZDB ID. Here's some sample code:
using System;
using NodaTime.TimeZones;

public class Test
{
    static void Main()
    {
        var source = TzdbDateTimeZoneSource.Default;

        string windowsId = "Turks And Caicos Standard Time";

        var mapping = source.WindowsMapping.PrimaryMapping;
        if (mapping.TryGetValue(windowsId, out string tzdbId))
        {
            Console.WriteLine($"Mapped to {tzdbId}");
        }
        else
        {
            Console.WriteLine("Not found");
        }
    }
}

An alternative approach is to use Matt Johnson's TimeZoneConverter package, which can simplify things a bit more. If you're using Noda Time elsewhere, it probably makes sense to stick with Noda Time, but if you're only using it for time zone ID conversion, TimeZoneConverter is a better choice.
As for why "Turks and Caicos" doesn't work - I assume you mean "Turks And Caicos Standard Time" as the ID. That was only introduced into the CLDR mapping data in CLDR v30, which was released over a year later than 1.3.1. If you update to 1.3.5 or 1.4.2, both of those should be fine.


text:
Q: What is the JSON View class in Jackson and how does it work? I don't understand what is Jackson's @JsonView(Views.MyClass.class).
I know that I can annotate POJO's fields and methods in this way to filter non-annotated ones from being serialized with JSON. But what is the Views.Myclass class? Is it a template class for Jackson library?
And why can there be many classes inside the Views class? For example like this:
 class Views {
            static class Public { }
            static class ExtendedPublic extends PublicView { }
            static class Internal extends ExtendedPublicView { }
  }

Why is it needed and how does it work?

A: Use @JsonView to filter fields depending on the context of serialization. When returning data to a REST client, depending on which REST service was called, we need to limit which data will be serialized while using the same data model.
Lets say we want to create two REST services:
The first service returns some user information like first name and last name but not the messages attached to it.
The second service returns all information from the first service and also the messages attached to the current user.
Sample POJO classes with @JsonView annotation
User Pojo classs
@JsonView(User.Views.Public.class)
    public String getFirstname() {
        return firstname;
    }

 @JsonView(User.Views.Public.class)
    public String getLastname() {
        return lastname;
    }

Message Pojo class
@JsonView(User.Views.Internal.class)
    public List<Message> getMessages() {
        return messages;
    }

Rest controller
@RestController
public class SimpleRestController {

    @Autowired
    SimpleService simpleService;

    @RequestMapping(value = "/user/public", method = RequestMethod.GET)
    @JsonView(User.Views.Public.class)
    public User getUserWithPublicData() {
        return simpleService.loadUser();
    }

    @RequestMapping(value = "/user/internal", method = RequestMethod.GET)
    @JsonView(User.Views.Internal.class)
    public User getUserWithInternalData() {
        return simpleService.loadUser();
    }
}


text:
Q: Switching Chart types on the fly I'm working on a reporting app which displays incoming data as pie by default. We'd like to offer the user the ability to switch to bar, or column, or area, or any of the other charts with the click of a button. Since we already have the data in the app, it should be fairly simple no? Does anyone have an idea of how I might approach this?
andy

A: You can approach this a couple different ways.  If it was me I would either set up a view stack with each of the chart types you want the user to switch to and they you can simply change the viewstack selectedIndex.  Alternatively, you can have just a single chart holder container.  Then just make function to dynamically generate each chart (Example).  Then all you need to do is remove the existing and add the new chart.

A: I accomplish this by creating a state for each specific chart type. Then just change between states based on user input. You can use one data provider for each chart or create specific data providers for each.


text:
Q: If M is finitely generated module, then it has finite rank. I just want this result for something that I am proving. I am proving if you have $f : M \rightarrow N$ be a surjective homomorphism then N has a finite rank. I showed that $N \cong M/ker(f)$, since $M/ker(f)$ is finitely generated then N is finitely generated. But I don't right away for general rings that finitely generate implies finite rank.
Recall here: Finitely generated module is defined as follows
M is finitely generated R-module iff there exists a generating set $\{x_i\}$ such that every $m = \Sigma r_ix_i$.
M has finite rank iff there exists a generating set $\{x_i\}$ that is a basis, i.e every m can be written uniquely as above.

A: Take a finitely generated free module $M$ over a ring $R$. The existence of a surjection $M \twoheadrightarrow N$ to an $R$-module $N$ does not imply that $N$ is free. That would imply that every finitely generated module over $R$ is free.
For example $\mathbb{Z}$ is a finitely generated free module, and the quotient map $\mathbb{Z} \rightarrow \mathbb{Z} / n \mathbb{Z}$ is a surjection, but $\mathbb{Z} / n \mathbb{Z}$ is not free.
However, a finitely generated free module $M$ over $R$ has finite rank. Suppose $M$ has basis $\{b_i \}_{i \in I}$ and let $\{ x_i \}_{1 \leq i \leq n}$ be a finite set of generators. Express each $x_i$ as $\sum_{j \in F_i} b_{j}$ for a finite set $F_i \subset B$. $\left\{ b_j | j \in \cup_{i = 1}^n F_i \right\}$ is finite, and consists of linearly independent elements. But it also spans $M$ since each $x_i$ is contained in the submodule of $M$ it generates. Thus $\left\{ b_j | j \in \cup_{i = 1}^n F_i \right\}$ testifies to the fact that $M$ has finite rank.


text:
Q: skemitternode not working on IOS9? I am currently stuck in finding a solution on fixing SKEmitterNode in Objective-C and previously I did not have a problem at all in a older version of Xcode. The premise of the code performs a fruit ninja blade effect in which it use to have a thin blade effect and now it completely enlargers the particleTexture and looks just like bubbles now.
- (instancetype)initWithPosition:(CGPoint)position TargetNode:(SKNode    *)target  Color:(UIColor *)color
{
if (self = [super init])
{
    self.position = position;
    //Where the image node is and stacks on the blade effect
    self.tip = [SKSpriteNode spriteNodeWithImageNamed:@"Digsby.png"];

    self.tip.size = CGSizeMake(50, 50);

    self.tip.zRotation = 0.785398163;
    self.tip.zPosition = 10; //10
   self.tip.name = @"skblade";
    [self addChild:self.tip];

    SKEmitterNode *_emitter = [self EmitterNodeWithColor:color];
    _emitter.targetNode = target;
    _emitter.zPosition = 0;//0
    [self.tip addChild:_emitter];

    [self setScale:0.5]; //0.5
}

return self;
}

- (SKEmitterNode *)EmitterNodeWithColor:(UIColor *)color
{
SKEmitterNode *emitterNode = [SKEmitterNode new];
emitterNode.particleTexture = [SKTexture textureWithImage:[UIImage imageNamed:@"spark.png"]];
emitterNode.particleBirthRate = 2000; //3000

[emitterNode setScale:0.1];
emitterNode.particleLifetime = 0.2;
emitterNode.particleLifetimeRange = 0;

emitterNode.particlePositionRange = CGVectorMake(0.0, 0.0);

emitterNode.particleSpeed = 0.0;
emitterNode.particleSpeedRange = 0.0;

emitterNode.particleAlpha = 0.1;
emitterNode.particleAlphaRange = 0.2;
emitterNode.particleAlphaSpeed = -0.45;

emitterNode.particleScale = 0.5;
emitterNode.particleScaleRange = 0.001;
emitterNode.particleScaleSpeed = -1;

emitterNode.particleRotation = 0;
emitterNode.particleRotationRange = 0;
emitterNode.particleRotationSpeed = 0;

emitterNode.particleColorBlendFactor = 1;
emitterNode.particleColorBlendFactorRange = 0;
emitterNode.particleColorBlendFactorSpeed = 0;

emitterNode.particleColor = color;
emitterNode.particleBlendMode = SKBlendModeAdd;

return emitterNode;
}

sample code link: http://avionicsdev.esy.es/article.php?id=8&page=1


text:
Q: Is it possible to work in a model with query builder using Laravel? I would like to know if is it possible to work in a model using query builder to make a join between two tables, I don't want to use eloquent
this is my model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use DB;

class Tbl_Perimetro extends Model
{
puplic function perimetros(){
$carteras = DB::table('tbl_perimetros')
        ->join('tbl_equipo_postventaatcs', 'tbl_equipo_postventaatcs.id', '=', 'tbl_perimetros.postventaatc_id')
        ->join('tbl_lista_carteras', 'tbl_equipo_postventaatcs.carteras_id', '=', 'tbl_lista_carteras.id')
        ->get();

return $carteras;
}
}

A: If you just want to use query builder you could to do so. But I realy recomend to use eloquent methods.
Also, is important to look about mutators, appends and scopes options to models that could help you more than query builder alone.
Other appointments:

*

*DB::table('tbl_perimetros') could be replaced by $this in this model

*Do not forget return for the method.

*Try protect $appends = ['perimetros'] and rename method to getPermietrosAttribute to return perimetros as an item in model object.


text:
Q: How to check if controller response has link? What's a decent way of doing it? Preferably matching a regexp.
my current code is like this:
describe "get #show" do
  context "signed in" do
    it "should have a link to edit profile" do
      # i sign in the user
      get :show
      response # i don't know what to do here
    end
  end
end

Thanks for the help!

A: It seems like you're trying to do an acceptance test, which probably means you should defer to Capybara. Then you can do magic like
page.should have_css('edit_link', text: 'Edit me')


text:
Q: For each loop to display values from mysql table In my table courses I have several entries that share the same academy_id value. I am using a foreach loop to retrieve all the rows with the same academy_id. In the example below, there is an academy that has two courses. The values are displaying correctly but there are some unnecessary values shown. For example it creates two results. Is it possible to have one combined result like shown below on the wanted result to display section?
PHP
$academy_id = 123

$db_select  = $db_con->prepare("
SELECT ca.course_name,
       ca.course_start_date,
       ca.course_end_date
FROM courses_by_academy ca
WHERE ca.academy_id = :academy_id
");
$final_result = '';
if (!$db_select) return false;
    if (!$db_select->execute(array(':academy_id' => $academy_id))) return false;
    $results = $db_select->fetchAll(\PDO::FETCH_ASSOC);
    if (empty($results)) return false;
    foreach ($results as $value){
    $final_result .= "Academy Name: ".$value['name']."
Academy Type: ".$value['type']."
Status: ".$value['status']."
";
    $final_result .= "Course Name: ".$value['course_name']."
Start Date: ".$value['course_start_date']."
End Date: ".$value['course_end_date']."
";
    }
}

Table Values
+----+------------+----------------------+---------------+------------+
| id | academy_id |     course_name      |  start_date   |  end_date  |
+----+------------+----------------------+---------------+------------+
| 1  |        123 | Biology - Basic      | 2013-11-30    | 2013-12-25 |
| 2  |        123 | Biology - Nutrition  | 2014-01-15    | 2014-01-25 |
+----+------------+----------------------+---------------+------------+

Current Result Displaying
Academy Name: North Valley Schools
Academy Type: Post-Secondary
Status: INACTIVE
ID: 123
Course Name:  Biology - Basic
Start date: 2013-11-30
End date: 2013-12-25

Academy Name: North Valley Schools
Academy Type: Post-Secondary
Status: INACTIVE
ID: 123
Course Name:  Biology - Nutrition
Start date: 2014-01-15
End date: 2014-01

Wanted Result- Combined
Academy Name: North Valley Schools
Academy Type: Post-Secondary
Status: INACTIVE
ID: 123
Course Name:  Biology - Basic
Start date: 2013-11-30
End date: 2013-12-25
Course Name:  Biology - Nutrition
Start date: 2014-01-15
End date: 2014-01-25

A: your loop:
foreach ($results as $value){
   $final_result .= "Academy Name: ".$value['name']."
Academy Type: ".$value['type']."
Status: ".$value['status']."
";
    $final_result .= "Course Name: ".$value['course_name']."
Start Date: ".$value['course_start_date']."
End Date: ".$value['course_end_date']."
";
}

instead do:
$first = true;
foreach ($results as $value){
    if($first){
        $first = false;
        $final_result .= "Academy Name: ".$value['name']."
Academy Type: ".$value['type']."
Status: ".$value['status']."
";
    }
    $final_result .= "Course Name: ".$value['course_name']."
Start Date: ".$value['course_start_date']."
End Date: ".$value['course_end_date']."
";
}

it will execute the academy information only once. :)