问:
How to set listview in a add() order?
How to set listview in a add() order ?
Firstly this is code (not real code)

API_Interface.java

```<code>public interface API_Interface{
    @GET("/api/{buzz}")
    Call<Buzz> Buzz_API(@Path("buzz") String buzz);
}
</code>```

Buzz.java

```<code>public class Buzz{
    @SerializedName("buzz")
    @Expose
    private String buzz;

    public String getBuzz() {
        return buzz;
    }

    public void setBuzz(String buzz) {
        this.buzz = buzz;
    }
}
</code>```

MainActivity.class

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_main);

        ListView listView = (ListView) findViewById(R.id.list_view);
        BuzzArrayList<Buzz> buzzArrayList = new BuzzArrayList<Buzz>();
        BuzzAdapter buzzAdapter = new BuzzAdapter(this, 0, buzzArrayList);
        listView.setAdapter(buzzAdapter);

        Retrofit buzz_retro = new Retrofit.Builder()
            .baseUrl("https://buzz.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

        API_Interface buzz_service = buzz_retro.create(API_Interface.class);

        //Get data
        Call<Buzz> buzz1 = buzz_service.buzz_API("Apple");
        buzz1.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_1 = response.body().getBuzz();    //buzz_1="Apple"
            buzzArrayList.add(new Exchange(buzz_1));
            buzzAdapter.notifyDataSetChanged();
            }
        });

        Call<Buzz> buzz2 = buzz_service.buzz_API("Banana");
        buzz2.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_2 = response.body().getBuzz();    //buzz_2="Banana"
            buzzArrayList.add(new Exchange(buzz_2));
            buzzAdapter.notifyDataSetChanged();
            }
        });

        Call<Buzz> buzz3 = buzz_service.buzz_API("Rice");
        buzz3.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_3 = response.body().getBuzz();   //buzz_3="Rice"
            buzzArrayList.add(new Exchange(buzz_3));
            buzzAdapter.notifyDataSetChanged();
            }
        });
    }
</code>```

I just thought that listview displays in a add() order like this.

```<code>Apple
Banana
Rice
</code>```

However, in fact, listview displayed like this.

```<code>Banana
Rice
Apple
</code>```

or

```<code>Rice
Banana
Apple
</code>```

How do I change my code to display as intended ? I look forward to your response. Thank you.

答:
"Apple", "Banana", "Rice" are added to the list by asynchronous calls,
therefore the order in which they get added is not predictable.
It doesn't matter in what order you wrote the asynchronous enqueue calls.

To add the items in a specific order,
it will be best to change API_Interface and the Retrofit code to use synchronous method instead of asynchronous.
The syntax is different depending on your version of Retrofit,
follow the examples in the documentation:

https://futurestud.io/tutorials/retrofit-synchronous-and-asynchronous-requests

Unfortunately, as the documentation points out,
on Android 4.0 or newer the synchronous technique leads to crashes:

Warning: synchronous requests trigger app crashes on Android 4.0 or newer. You’ll run into the NetworkOnMainThreadException error.

Another alternative is to serialize the calls through some other way.
For example you could use a Semaphore s = new Semaphore(1),
call s.acquire() before each enqueue call and s.release() in each onResponse call.

That is:

```<code>Semaphore s = new Semaphore(1);

s.acquire();
Call<Buzz> buzz1 = buzz_service.buzz_API("Apple");
buzz1.enqueue(new Callback<Buzz>() {
    @Override
    public void onResponse(Call<Buzz> call, Response<Buzz> response) {
        String buzz_1 = response.body().getBuzz();    //buzz_1="Apple"
        buzzArrayList.add(new Exchange(buzz_1));
        buzzAdapter.notifyDataSetChanged();
        s.release();
    }
});

s.acquire();
Call<Buzz> buzz2 = buzz_service.buzz_API("Banana");
buzz2.enqueue(new Callback<Buzz>() {
    @Override
    public void onResponse(Call<Buzz> call, Response<Buzz> response) {
        String buzz_2 = response.body().getBuzz();    //buzz_2="Banana"
        buzzArrayList.add(new Exchange(buzz_2));
        buzzAdapter.notifyDataSetChanged();
        s.release();
    }
});

// ...
</code>```

Title: How to set listview in a add() order?

Body:
How to set listview in a add() order ?
Firstly this is code (not real code)

API_Interface.java

public interface API_Interface{
    @GET("/api/{buzz}")
    Call<Buzz> Buzz_API(@Path("buzz") String buzz);
}

Buzz.java

public class Buzz{
    @SerializedName("buzz")
    @Expose
    private String buzz;

    public String getBuzz() {
        return buzz;
    }

    public void setBuzz(String buzz) {
        this.buzz = buzz;
    }
}

MainActivity.class

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_main);

        ListView listView = (ListView) findViewById(R.id.list_view);
        BuzzArrayList<Buzz> buzzArrayList = new BuzzArrayList<Buzz>();
        BuzzAdapter buzzAdapter = new BuzzAdapter(this, 0, buzzArrayList);
        listView.setAdapter(buzzAdapter);

        Retrofit buzz_retro = new Retrofit.Builder()
            .baseUrl("https://buzz.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

        API_Interface buzz_service = buzz_retro.create(API_Interface.class);

        //Get data
        Call<Buzz> buzz1 = buzz_service.buzz_API("Apple");
        buzz1.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_1 = response.body().getBuzz();    //buzz_1="Apple"
            buzzArrayList.add(new Exchange(buzz_1));
            buzzAdapter.notifyDataSetChanged();
            }
        });

        Call<Buzz> buzz2 = buzz_service.buzz_API("Banana");
        buzz2.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_2 = response.body().getBuzz();    //buzz_2="Banana"
            buzzArrayList.add(new Exchange(buzz_2));
            buzzAdapter.notifyDataSetChanged();
            }
        });

        Call<Buzz> buzz3 = buzz_service.buzz_API("Rice");
        buzz3.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_3 = response.body().getBuzz();   //buzz_3="Rice"
            buzzArrayList.add(new Exchange(buzz_3));
            buzzAdapter.notifyDataSetChanged();
            }
        });
    }

I just thought that listview displays in a add() order like this.

Apple
Banana
Rice

However, in fact, listview displayed like this.

Banana
Rice
Apple

or

Rice
Banana
Apple

How do I change my code to display as intended ? I look forward to your response. Thank you.

Body:
"Apple", "Banana", "Rice" are added to the list by asynchronous calls,
therefore the order in which they get added is not predictable.
It doesn't matter in what order you wrote the asynchronous enqueue calls.

To add the items in a specific order,
it will be best to change API_Interface and the Retrofit code to use synchronous method instead of asynchronous.
The syntax is different depending on your version of Retrofit,
follow the examples in the documentation:

https://futurestud.io/tutorials/retrofit-synchronous-and-asynchronous-requests

Unfortunately, as the documentation points out,
on Android 4.0 or newer the synchronous technique leads to crashes:

Warning: synchronous requests trigger app crashes on Android 4.0 or newer. You’ll run into the NetworkOnMainThreadException error.

Another alternative is to serialize the calls through some other way.
For example you could use a Semaphore s = new Semaphore(1),
call s.acquire() before each enqueue call and s.release() in each onResponse call.

That is:

Semaphore s = new Semaphore(1);

s.acquire();
Call<Buzz> buzz1 = buzz_service.buzz_API("Apple");
buzz1.enqueue(new Callback<Buzz>() {
    @Override
    public void onResponse(Call<Buzz> call, Response<Buzz> response) {
        String buzz_1 = response.body().getBuzz();    //buzz_1="Apple"
        buzzArrayList.add(new Exchange(buzz_1));
        buzzAdapter.notifyDataSetChanged();
        s.release();
    }
});

s.acquire();
Call<Buzz> buzz2 = buzz_service.buzz_API("Banana");
buzz2.enqueue(new Callback<Buzz>() {
    @Override
    public void onResponse(Call<Buzz> call, Response<Buzz> response) {
        String buzz_2 = response.body().getBuzz();    //buzz_2="Banana"
        buzzArrayList.add(new Exchange(buzz_2));
        buzzAdapter.notifyDataSetChanged();
        s.release();
    }
});

// ...


来源: stackexchange

问:
Static URL for a JDK?
I'm building an NSIS installer to install my application under Windows, and it will check if a user has a JDK (>= 1.5) and download and launch the installer for it if they do not.

While I have seen URLs for use in downloading JREs, I have not seen ones for the JDK.  If I copy and paste the URL I finally get after clicking through several pages to get the Windows (32-bit) (with nothing else bundled) JDK, the URL changes every time.

My users are not technically savvy and may not be able to download the JDK themselves from the starting page, so making them do so is suboptimal.

Is there a URL I can consistently use to download the JDK?

答: It's a bit off topic, but for easily deploying java applications, you might look at java webstart.</p>

ContentLicense: CC BY-SA 2.5

Title: Static URL for a JDK?


问:
My java program is not working, I ran the code and the sorting is not right
Here is the question from my instructor:

Load the following items of data into an array interactively from the keyboard.

Print out the data in the order in which is was entered.

Sort the data in ascending order using the selection sort.

Print out the data in sorted order.

Sort the data in descending order using the bubble sort.

Print out the data in the sorted order.

These are the data items you’ll use:
  Honda, Chevrolet, Ford, Rolls-Royce, Mercedes Benz

```<code>import java.util.Scanner;

public class Example532 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        String[] list = new String[5];
        System.out.println("Enter data: ");
        for (int i=0; i<5; i++) {
            list[i] = scan.nextLine();
        }

        System.out.println("Current data:");
        for (int i=0; i<5; i++) {
            System.out.println(list[i]);
        }
        // call selection sort
        doSelectionSort(list);
        // print out current array
        System.out.println("Sorted data:");
        for (int i=0; i<5; i++) {
            System.out.println(list[i]);
        }
        // call bubble sort
        doBubbleSort(list);
        System.out.println("Bubble Sorted data:");
        for (int i = 0; i < 5; i++) {
            System.out.println(list[i]);
        }

    }

    public static String[] doSelectionSort(String[] arr){
        for (int i = 0; i < arr.length - 1; i++)
        {
            int index = i;
            for (int j = i + 1; j < arr.length; j++)
                if (arr[j].compareTo(arr[index]) < 0)
                    index = j;

            String smaller = arr[index];
            arr[index] = arr[i];
            arr[i] = smaller;
        }
        return arr;
    }

    public static void doBubbleSort(String[] arr) {
        boolean swapped = true;
        int j = 0;
        String tmp;
        while (swapped) {
            swapped = false;
            j++;
            for (int i = 0; i < arr.length - j; i++) {
                if (arr[i].compareTo(arr[i + 1]) < 0) {
                    tmp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = tmp;
                    swapped = true;
                }
            }
        }
    }
}
</code>```

答:
To sort by length, instead of

```<code>if (arr[j].compareTo(arr[index]) < 0)
</code>```

Use:

```<code>if (arr[j].length() < arr[index].length())
</code>```

(You need to do this update in multiple places.)

ContentLicense: CC BY-SA 3.0

Body:
Here is the question from my instructor:

Load the following items of data into an array interactively from the keyboard.

Print out the data in the order in which is was entered.

Sort the data in ascending order using the selection sort.

Print out the data in sorted order.

Sort the data in descending order using the bubble sort.

Print out the data in the sorted order.

These are the data items you’ll use:
  Honda, Chevrolet, Ford, Rolls-Royce, Mercedes Benz

import java.util.Scanner;

public class Example532 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        String[] list = new String[5];
        System.out.println("Enter data: ");
        for (int i=0; i<5; i++) {
            list[i] = scan.nextLine();
        }

        System.out.println("Current data:");
        for (int i=0; i<5; i++) {
            System.out.println(list[i]);
        }
        // call selection sort
        doSelectionSort(list);
        // print out current array
        System.out.println("Sorted data:");
        for (int i=0; i<5; i++) {
            System.out.println(list[i]);
        }
        // call bubble sort
        doBubbleSort(list);
        System.out.println("Bubble Sorted data:");
        for (int i = 0; i < 5; i++) {
            System.out.println(list[i]);
        }

    }

    public static String[] doSelectionSort(String[] arr){
        for (int i = 0; i < arr.length - 1; i++)
        {
            int index = i;
            for (int j = i + 1; j < arr.length; j++)
                if (arr[j].compareTo(arr[index]) < 0)
                    index = j;

            String smaller = arr[index];
            arr[index] = arr[i];
            arr[i] = smaller;
        }
        return arr;
    }

    public static void doBubbleSort(String[] arr) {
        boolean swapped = true;
        int j = 0;
        String tmp;
        while (swapped) {
            swapped = false;
            j++;
            for (int i = 0; i < arr.length - j; i++) {
                if (arr[i].compareTo(arr[i + 1]) < 0) {
                    tmp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = tmp;
                    swapped = true;
                }
            }
        }
    }
}

Body:
To sort by length, instead of

if (arr[j].compareTo(arr[index]) < 0)

Use:

if (arr[j].length() < arr[index].length())

(You need to do this update in multiple places.)


问:
how to get latest text file after searching all drive of a computer
I am trying to get the latest text file in my computer.
I need to go to each each drive of computer and searching for all the text file and need to get only one file which is latest.

I tried some code, getting one error and also not sure latest file from all of the drive will work or not

```<code>try
        {
            foreach (DriveInfo d in DriveInfo.GetDrives())
            {
                var X = GetLatestFiles(d.Name, "*.txt");

            }
        }
        catch (Exception ex) { Console.WriteLine(ex); }

public static FileInfo GetLatestFiles(string path, string searchPattern)
    {
        return Directory.EnumerateFiles(path, searchPattern).Union(
            Directory.EnumerateDirectories(path).SelectMany(d =>
            {
                try
                {
                    return GetLatestFiles(d, searchPattern);
                }
                catch (UnauthorizedAccessException)
                {
                    return Enumerable.Empty<String>();
                }
            })).OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime)).FirstOrDefault();
    }
</code>```

Error

The type arguments for method 'Enumerable.SelectMany(IEnumerable, Func>)'
  cannot be inferred from the usage. Try specifying the type arguments
  explicitly.   ConsoleApp1 C:\Users\H190733\source\repos\ConsoleApp1\ConsoleApp1\Program.cs    43  Active

答:
I think (and this is really hard to test on an iPhone, sorry) that if you

```<code>return (FileInfo)null;
</code>```

Instead of

```<code>return Enumerable.Empty<String>();
</code>```

Then the error will go away.

You might have to call .SelectMany<FileInfo> also. My comment stands; this is a terrible way to search your entire drive. Converting the following pseudocode to c# would be my recommendation:

```<code>//declare list<directoryinfo> dirs
//declare FileInfo latestText

//load all drives into the dirs list

//loop over the list with "while the list has more entries" type loop
while(dirs.Count>0){
  // load all the directories in dirs[0] onto the end of the list

  //For each fileinfo in dirs[0] if the create time
  //is more recent than latestText createTime,
  //set latestText to that fileinfo

  //remove first entry from dirs

}
</code>```

The "keep adding to the end of a list of dirs as you search through dirs will be. a lot easier to debug too

Body:
I am trying to get the latest text file in my computer.
I need to go to each each drive of computer and searching for all the text file and need to get only one file which is latest.

I tried some code, getting one error and also not sure latest file from all of the drive will work or not

try
        {
            foreach (DriveInfo d in DriveInfo.GetDrives())
            {
                var X = GetLatestFiles(d.Name, "*.txt");

            }
        }
        catch (Exception ex) { Console.WriteLine(ex); }

public static FileInfo GetLatestFiles(string path, string searchPattern)
    {
        return Directory.EnumerateFiles(path, searchPattern).Union(
            Directory.EnumerateDirectories(path).SelectMany(d =>
            {
                try
                {
                    return GetLatestFiles(d, searchPattern);
                }
                catch (UnauthorizedAccessException)
                {
                    return Enumerable.Empty<String>();
                }
            })).OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime)).FirstOrDefault();
    }

Error

The type arguments for method 'Enumerable.SelectMany(IEnumerable, Func>)'
  cannot be inferred from the usage. Try specifying the type arguments
  explicitly.   ConsoleApp1 C:\Users\H190733\source\repos\ConsoleApp1\ConsoleApp1\Program.cs    43  Active

Body:
I think (and this is really hard to test on an iPhone, sorry) that if you

return (FileInfo)null;

Instead of

return Enumerable.Empty<String>();

Then the error will go away.

You might have to call .SelectMany<FileInfo> also. My comment stands; this is a terrible way to search your entire drive. Converting the following pseudocode to c# would be my recommendation:

//declare list<directoryinfo> dirs
//declare FileInfo latestText

//load all drives into the dirs list

//loop over the list with "while the list has more entries" type loop
while(dirs.Count>0){
  // load all the directories in dirs[0] onto the end of the list

  //For each fileinfo in dirs[0] if the create time
  //is more recent than latestText createTime,
  //set latestText to that fileinfo

  //remove first entry from dirs

}

The "keep adding to the end of a list of dirs as you search through dirs will be. a lot easier to debug too


问:
TestCafe - How to check if a web element exists or does not exist without failing the test?
I'm trying to write a script that needs to adapt it's workflow behavior depending on whether a particular browser object found by CSS selector exists or does not exist.

I do not want to use a document.getElementByID method as this is not technically a CSS selector, and our entire enterprise is standardized on CSS selector so anything that walks the DOM other then a CSS selector won't make it past our code review process anyway.

```<code>var thing = await things.thingSelector(thingName);
if (await t.expect(thing.exists).notOk()) {
   await t.click(things.OpenThing(thingName));
} else {
   return false;
}
return true;
</code>```

Where thingSelector is:

```<code>const thingSelector = name =>
  Selector('p.thing-header-title span')
    .withText(name)
    .parent('div.thing');
</code>```

Where OpenThing is:

```<code>const OpenThing = name =>
    thingSelector(name)
        .find('a.thing-footer-item')
        .withText('Open');
</code>```

I need to be able to continue execution if the object is not there and I'm checking that it exists, or if the object is there and I'm checking that it does not exist, and also the cases where the object is not there and it does not exist and the object is not there and I'm checking that it does not exist.

In all cases I still need to proceed with the workflow.

I've tried both sides of the logic coin:

```<code>if (!await t.expect(thing.exists).ok())
</code>```

And

```<code>if (await t.expect(thing.exists).notOk())
</code>```

If one of the above doesn't fail in one scenario it will fail in the other, and the other one will fail in the scenario that the first one didn't fail. I need something that will give me the logic, but not ever fail the script execution and still allow me to return either True or False depending on if the object is present or not present.

Thank you in advance for helping me to solve this problem, and also to learn and grow in my Javascript skills!

答:
You can check the async exists property in the if condition in the following way:

```<code>if(await things.thingSelector(thingName).exists) {
    // do something
}
</code>```

Body:
I'm trying to write a script that needs to adapt it's workflow behavior depending on whether a particular browser object found by CSS selector exists or does not exist.

I do not want to use a document.getElementByID method as this is not technically a CSS selector, and our entire enterprise is standardized on CSS selector so anything that walks the DOM other then a CSS selector won't make it past our code review process anyway.

var thing = await things.thingSelector(thingName);
if (await t.expect(thing.exists).notOk()) {
   await t.click(things.OpenThing(thingName));
} else {
   return false;
}
return true;

Where thingSelector is:

const thingSelector = name =>
  Selector('p.thing-header-title span')
    .withText(name)
    .parent('div.thing');

Where OpenThing is:

const OpenThing = name =>
    thingSelector(name)
        .find('a.thing-footer-item')
        .withText('Open');

I need to be able to continue execution if the object is not there and I'm checking that it exists, or if the object is there and I'm checking that it does not exist, and also the cases where the object is not there and it does not exist and the object is not there and I'm checking that it does not exist.

In all cases I still need to proceed with the workflow.

I've tried both sides of the logic coin:

if (!await t.expect(thing.exists).ok())

And

if (await t.expect(thing.exists).notOk())

If one of the above doesn't fail in one scenario it will fail in the other, and the other one will fail in the scenario that the first one didn't fail. I need something that will give me the logic, but not ever fail the script execution and still allow me to return either True or False depending on if the object is present or not present.

Thank you in advance for helping me to solve this problem, and also to learn and grow in my Javascript skills!

Body:
You can check the async exists property in the if condition in the following way:

if(await things.thingSelector(thingName).exists) {
    // do something
}


问:
UINavigationBar BarButtomItem not dismissing the view controller swift
I have created UINavigationBar programatically and added barbuttonitem, the problem is when I click on that image, respective method is calling but view controller is not dismissing.

LocateVehicle

```<code>class LocateVehicle: UITableViewController{

let kCloseCellHeight: CGFloat = 130
let kOpenCellHeight: CGFloat = 488
let kRowsCount = 10
var cellHeights: [CGFloat] = []

let dataArr = ["Running", "Stopped", "Idle", "Running"]

@IBAction func backBarButton(_ sender: Any) {
}

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.contentInset.top = UIApplication.shared.statusBarFrame.height

    setup()
}

private func setup() {
    cellHeights = Array(repeating: kCloseCellHeight, count: kRowsCount)
    tableView.estimatedRowHeight = kCloseCellHeight
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "background"))
}

 }
// MARK: - TableView
extension LocateVehicle {

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dataArr.count
}

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    guard case let cell as CustomLocateVehicleCell = cell else {
        return
    }

    cell.backgroundColor = .clear

    if cellHeights[indexPath.row] == kCloseCellHeight {
        cell.unfold(false, animated: false, completion: nil)
    } else {
        cell.unfold(true, animated: false, completion: nil)
    }

    cell.number = dataArr[indexPath.row]
//        cell.statusLabel.text = dataArr[indexPath.row]
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FoldingCell", for: indexPath) as! CustomLocateVehicleCell

    let durations: [TimeInterval] = [0.26, 0.2, 0.2]
    cell.durationsForExpandedState = durations
    cell.durationsForCollapsedState = durations

//        cell.liveTrackButton.tag = indexPath.row;

   return cell
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return cellHeights[indexPath.row]
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath) as! FoldingCell

    if cell.isAnimating() {
        return
    }

    var duration = 0.0
    let cellIsCollapsed = cellHeights[indexPath.row] == kCloseCellHeight
    if cellIsCollapsed {
        cellHeights[indexPath.row] = kOpenCellHeight
        cell.unfold(true, animated: true, completion: nil)
        duration = 0.5
    } else {
        cellHeights[indexPath.row] = kCloseCellHeight
        cell.unfold(false, animated: true, completion: nil)
        duration = 0.8
    }

    UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: { () -> Void in
        tableView.beginUpdates()
        tableView.endUpdates()

    }, completion: nil)

  }
}
</code>```

LiveTrack

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    setNavigationBar()
  }

 func setNavigationBar() {
    let screenSize: CGRect = UIScreen.main.bounds
    let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.height, width: screenSize.width, height: 44))
    self.view.addSubview(navBar);
    let navItem = UINavigationItem(title: "AP 16 BD 5678");
    let image = UIImage(named: "ic_chevron_left_white")?.withRenderingMode(.alwaysOriginal)
    let doneItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.backAction));
    navItem.leftBarButtonItem = doneItem;
    navBar.setItems([navItem], animated: false);
 }

 @IBAction func backAction(_ sender: Any) {
    print("back working")
   //self.navigationController?.popViewController(animated: true)
     dismiss(animated: true, completion: nil)
 }
</code>```

I am navigation to view controller from tableview cell

```<code>let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let view = storyboard.instantiateViewController(withIdentifier: "LiveTrackStoryboard") as! LiveTrack
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    //show window
    appDelegate.window?.rootViewController = view
</code>```

Please help me to solve this. Thanks in advance

答:
Add button target in cellForRowAt

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FoldingCell", for: indexPath) as! CustomLocateVehicleCell

    let durations: [TimeInterval] = [0.26, 0.2, 0.2]
    cell.durationsForExpandedState = durations
    cell.durationsForCollapsedState = durations
    cell.yourButton.addTarget(self, action:#selector(buttonClicked()), for: .touchUpInside)
    return cell
}
</code>```

Perform Push on cell button action(You are making second controller root controller, so there is nothing to go back, so don't do that instead perform push, and add controller to stack) make sure your root controller is embedded to navigationController. -:

```<code>func buttonClicked(sender:UIButton){
      let storyboard = UIStoryboard(name: "Main", bundle: nil)
      let view = storyboard.instantiateViewController(withIdentifier: "LiveTrackStoryboard") as! LiveTrack
    // TO PUSH
        navigationController?.pushViewController(view,animated: true)
    // TO PRESENT
     present(view!, animated: true, completion: nil)
    }
</code>```

Now in second controller where you have leftBarButton pop to previous controller -:

```<code> override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setNavigationBar()
      }

     func setNavigationBar() {
        let screenSize: CGRect = UIScreen.main.bounds
        let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.height, width: screenSize.width, height: 44))
        self.view.addSubview(navBar);
        let navItem = UINavigationItem(title: "AP 16 BD 5678");
        let image = UIImage(named: "ic_chevron_left_white")?.withRenderingMode(.alwaysOriginal)
        let doneItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.backAction));
        navItem.leftBarButtonItem = doneItem;
        navBar.setItems([navItem], animated: false);
     }

     @IBAction func backAction(_ sender: Any) {
        print("back working")
   // TO POP
      self.navigationController?.popViewController(animated: true)
   // TO DISMISS
   dismiss(animated: true, completion: nil)
     }
</code>```

Perform any based on your need.

You also don't need to embed navigationController as root if you don't want to perform push.

Body:
I have created UINavigationBar programatically and added barbuttonitem, the problem is when I click on that image, respective method is calling but view controller is not dismissing.

LocateVehicle

class LocateVehicle: UITableViewController{

let kCloseCellHeight: CGFloat = 130
let kOpenCellHeight: CGFloat = 488
let kRowsCount = 10
var cellHeights: [CGFloat] = []

let dataArr = ["Running", "Stopped", "Idle", "Running"]

@IBAction func backBarButton(_ sender: Any) {
}

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.contentInset.top = UIApplication.shared.statusBarFrame.height

    setup()
}

private func setup() {
    cellHeights = Array(repeating: kCloseCellHeight, count: kRowsCount)
    tableView.estimatedRowHeight = kCloseCellHeight
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "background"))
}

 }
// MARK: - TableView
extension LocateVehicle {

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dataArr.count
}

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    guard case let cell as CustomLocateVehicleCell = cell else {
        return
    }

    cell.backgroundColor = .clear

    if cellHeights[indexPath.row] == kCloseCellHeight {
        cell.unfold(false, animated: false, completion: nil)
    } else {
        cell.unfold(true, animated: false, completion: nil)
    }

    cell.number = dataArr[indexPath.row]
//        cell.statusLabel.text = dataArr[indexPath.row]
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FoldingCell", for: indexPath) as! CustomLocateVehicleCell

    let durations: [TimeInterval] = [0.26, 0.2, 0.2]
    cell.durationsForExpandedState = durations
    cell.durationsForCollapsedState = durations

//        cell.liveTrackButton.tag = indexPath.row;

   return cell
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return cellHeights[indexPath.row]
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath) as! FoldingCell

    if cell.isAnimating() {
        return
    }

    var duration = 0.0
    let cellIsCollapsed = cellHeights[indexPath.row] == kCloseCellHeight
    if cellIsCollapsed {
        cellHeights[indexPath.row] = kOpenCellHeight
        cell.unfold(true, animated: true, completion: nil)
        duration = 0.5
    } else {
        cellHeights[indexPath.row] = kCloseCellHeight
        cell.unfold(false, animated: true, completion: nil)
        duration = 0.8
    }

    UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: { () -> Void in
        tableView.beginUpdates()
        tableView.endUpdates()

    }, completion: nil)

  }
}

LiveTrack

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    setNavigationBar()
  }

 func setNavigationBar() {
    let screenSize: CGRect = UIScreen.main.bounds
    let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.height, width: screenSize.width, height: 44))
    self.view.addSubview(navBar);
    let navItem = UINavigationItem(title: "AP 16 BD 5678");
    let image = UIImage(named: "ic_chevron_left_white")?.withRenderingMode(.alwaysOriginal)
    let doneItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.backAction));
    navItem.leftBarButtonItem = doneItem;
    navBar.setItems([navItem], animated: false);
 }

 @IBAction func backAction(_ sender: Any) {
    print("back working")
   //self.navigationController?.popViewController(animated: true)
     dismiss(animated: true, completion: nil)
 }

I am navigation to view controller from tableview cell

let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let view = storyboard.instantiateViewController(withIdentifier: "LiveTrackStoryboard") as! LiveTrack
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    //show window
    appDelegate.window?.rootViewController = view

Please help me to solve this. Thanks in advance

Body:
Add button target in cellForRowAt

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FoldingCell", for: indexPath) as! CustomLocateVehicleCell

    let durations: [TimeInterval] = [0.26, 0.2, 0.2]
    cell.durationsForExpandedState = durations
    cell.durationsForCollapsedState = durations
    cell.yourButton.addTarget(self, action:#selector(buttonClicked()), for: .touchUpInside)
    return cell
}

Perform Push on cell button action(You are making second controller root controller, so there is nothing to go back, so don't do that instead perform push, and add controller to stack) make sure your root controller is embedded to navigationController. -:

func buttonClicked(sender:UIButton){
      let storyboard = UIStoryboard(name: "Main", bundle: nil)
      let view = storyboard.instantiateViewController(withIdentifier: "LiveTrackStoryboard") as! LiveTrack
    // TO PUSH
        navigationController?.pushViewController(view,animated: true)
    // TO PRESENT
     present(view!, animated: true, completion: nil)
    }

Now in second controller where you have leftBarButton pop to previous controller -:

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setNavigationBar()
      }

     func setNavigationBar() {
        let screenSize: CGRect = UIScreen.main.bounds
        let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.height, width: screenSize.width, height: 44))
        self.view.addSubview(navBar);
        let navItem = UINavigationItem(title: "AP 16 BD 5678");
        let image = UIImage(named: "ic_chevron_left_white")?.withRenderingMode(.alwaysOriginal)
        let doneItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.backAction));
        navItem.leftBarButtonItem = doneItem;
        navBar.setItems([navItem], animated: false);
     }

     @IBAction func backAction(_ sender: Any) {
        print("back working")
   // TO POP
      self.navigationController?.popViewController(animated: true)
   // TO DISMISS
   dismiss(animated: true, completion: nil)
     }

Perform any based on your need.

You also don't need to embed navigationController as root if you don't want to perform push.


问:
Javascript Caesars Cipher algorithm code break down needed?
I am a freecodecamp camper. And I need a help to understand how does the below code works which is an advanced solution.

function rot13(str) { // LBH QVQ VG!
  str.replace(/[A-Z]/g, L => String.fromCharCode((L.charCodeAt(0) % 26) + 65));
}

// Change the inputs below to test
console.log(rot13("AAA !"));```

I do have a little idea on why we are using modulus 26 and then adding 65. but I dont understand what L=> is actually doing. I also understand a bit of regular expression. Please break down this code.

答:
L => declares an arrow function, which is a shorthand syntax for:

```<code>function(L) {
    return String.fromCharCode((L.charCodeAt(0) % 26) + 65));
}
</code>```

When you use a function as the replacement argument in String.prototype.replace(), it gets called on each match of the regular expression, and the return value is used as the replacement.

So the regular expression matches each uppercase letter in str. It calls that function, which calculates the new character code using modulus and addition, converts it back to a character, and that returned character becomes the replacement.

However, the function won't work as written -- it needs to return the result of str.replace().

function rot13(str) { // LBH QVQ VG!
  return str.replace(/[A-Z]/g, L => String.fromCharCode((L.charCodeAt(0) % 26) + 65));
}

// Change the inputs below to test
console.log(rot13("ABMNTZ !"));```

Body:
I am a freecodecamp camper. And I need a help to understand how does the below code works which is an advanced solution.

function rot13(str) { // LBH QVQ VG!
  str.replace(/[A-Z]/g, L => String.fromCharCode((L.charCodeAt(0) % 26) + 65));
}

// Change the inputs below to test
console.log(rot13("AAA !"));

I do have a little idea on why we are using modulus 26 and then adding 65. but I dont understand what L=> is actually doing. I also understand a bit of regular expression. Please break down this code.

Body:
L => declares an arrow function, which is a shorthand syntax for:

function(L) {
    return String.fromCharCode((L.charCodeAt(0) % 26) + 65));
}

When you use a function as the replacement argument in String.prototype.replace(), it gets called on each match of the regular expression, and the return value is used as the replacement.

So the regular expression matches each uppercase letter in str. It calls that function, which calculates the new character code using modulus and addition, converts it back to a character, and that returned character becomes the replacement.

However, the function won't work as written -- it needs to return the result of str.replace().

function rot13(str) { // LBH QVQ VG!
  return str.replace(/[A-Z]/g, L => String.fromCharCode((L.charCodeAt(0) % 26) + 65));
}

// Change the inputs below to test
console.log(rot13("ABMNTZ !"));


问:
To change the value of an empty variable
I have a loop like this:

```<code>[centers, radii]=imfindcircles() %find circles in the image
if isnan(centers)==1 %if centres is empty
    centers='NA'; % assign centres a NA
else
    centers=centers;
end
</code>```

What I want to do is:

when no circles found and centers=[], I want to assign centres a value (could be 'NA' or 0).

if some circles found, then centres remains the same array.

The goal of this loop is to assign centres some value so that I can save it into a .xls file even if there is no circles found.

But my problem is after this loop, even if centers=[], centres will not change its value. This means this loop doesn't work at all. So could somebody check for me where is wrong?

答:
You can do:

```<code>function [ x ] = empty2nan( x, Size )
   if isempty(x), x=nan(1,Size); end
end
</code>```

And

```<code>centers=empty2nan(centers,2)
</code>```

Body:
I have a loop like this:

[centers, radii]=imfindcircles() %find circles in the image
if isnan(centers)==1 %if centres is empty
    centers='NA'; % assign centres a NA
else
    centers=centers;
end

What I want to do is:

when no circles found and centers=[], I want to assign centres a value (could be 'NA' or 0).

if some circles found, then centres remains the same array.

The goal of this loop is to assign centres some value so that I can save it into a .xls file even if there is no circles found.

But my problem is after this loop, even if centers=[], centres will not change its value. This means this loop doesn't work at all. So could somebody check for me where is wrong?

Body:
You can do:

function [ x ] = empty2nan( x, Size )
   if isempty(x), x=nan(1,Size); end
end

And

centers=empty2nan(centers,2)


问:
Materialize footer not going to bottom of page
Is there a way to keep the footer at the bottom of the page, even if there isn't a lot of content? I followed the instructions on the Materialize page and have all my HTML between , , and  tags. I haven't applied any of my own CSS to the footer at all.

Any help would be appreciated.

Here is my HTML:

```<code><body>
  <header>
    <nav role="navigation">
      <div class="nav-wrapper container"><a id="logo-container" href="/" class="brand-logo">Some Title <i class="material-icons left hide-on-med-and-down">apps</i></a>
        <ul id="dropdown" class="dropdown-content">
          <li><a href="">Register</a></li>
          <li class="divider"></li>
          <li><a href="">Sign In</a></li>
        </ul>
        <ul class="right hide-on-med-and-down">
          <li id="timer-tab"><a href="">Tab 1</a></li>
          <li id="stats-tab"><a href="">Tab 2</a></li>
          <li id="graphs-tab"><a href="">Tab 3</a></li>
          <li><a href="" data-activates="dropdown" class="dropdown-button">Tab 4<i class="material-icons right">arrow_drop_down</i></a></li>
        </ul>
      </div>
    </nav>
  </header>

  <main>
    <div class="container">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
  </main>

  <footer class="page-footer">
    <div class="container">
      <div class="row">
        <div class="col l6 s12">
          <h5 class="white-text">Some Title</h5>
          <p class="grey-text text-lighten-4">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
        </div>
        <div class="col l2 offset-l2 s6">
          <h6>About</h6>
          <ul>
            <li><a href="" class="grey-text text-lighten-3">Help</a></li>
            <li><a href="" class="grey-text text-lighten-3">Contact</a></li>
            <li><a href="" class="grey-text text-lighten-3">Suggestions</a></li>
          </ul>
        </div>
        <div class="col l2 s6">
          <h6>Developer</h6>
          <ul>
            <li><a href="" class="grey-text text-lighten-3">Source</a></li>
            <li><a href="" class="grey-text text-lighten-3">Contribute</a></li>
            <li><a href="" class="grey-text text-lighten-3">API Docs</a></li>
          </ul>
        </div>
      </div>
    </div>
    <div class="footer-copyright">
      <div class="container">Made by <a href="">Me </a></div>
    </div>
  </footer>

  <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
  <script src="/js/materialize.min.js"></script>
  <script src="/js/bundle.js"></script>
</body>
</code>```

答:
Just add this style: position:fixed;bottom:0;left:0;width:100%; at the footer element.

For example:

```<code><footer class="page-footer" style="position:fixed;bottom:0;left:0;width:100%;">
    ...
</footer>
</code>```

Body:
Is there a way to keep the footer at the bottom of the page, even if there isn't a lot of content? I followed the instructions on the Materialize page and have all my HTML between , , and  tags. I haven't applied any of my own CSS to the footer at all.

Any help would be appreciated.

Here is my HTML:

Some Title apps

Register

Sign In

Tab 1

Tab 2

Tab 3

Tab 4arrow_drop_down

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Some Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

About

Help

Contact

Suggestions

Developer

Source

Contribute

API Docs

Made by Me

Body:
Just add this style: position:fixed;bottom:0;left:0;width:100%; at the footer element.

For example:

<footer class="page-footer" style="position:fixed;bottom:0;left:0;width:100%;">
    ...
</footer>


问:
Routing algorithm for multiple vehicles with multiple drops
I'm looking to find/create a routing algorithm that can be used to manage multiple vans performing deliveries as well as the loads of each of those vans.

Here's a rough specification of what I'm looking for..

The routes should be calculated in a fast and efficient manner

100+ vans / 1000+ packages / 1000+ dropoff points could be processed in one go

Each van could be a different size and have different weight restrictions

Each package could be a different size and weight

The packages should be organised onto the vans in a fair and economical manner, taking into account the routes, weight and size restrictions

The routes the vans should take should be economical and as short as possible (or a configurable balance between the two)

Vans could be limited to certain roads (low bridges, width, height and weight restrictions)

Some packages may be given timeslots for delivery

Has anyone seen this sort of thing before, and if so, any ideas as to what algorithm could be used to do this, or an example of how it could be done? I've seen a few university papers but they're quite old (probably fairly inefficient now) and don't handle the package management - they just presume all the vans and packages are the same size.

Any thoughts would be appreciated!

Rich

答:
Any algorithm this specific is going to be proprietary and you will probably need to buy something. However, this sounds suspiciously like a problem that could be solved with a genetic algorithm implimentation. Here is some research I found:

http://www.ijimt.org/papers/38-M415.pdf

http://www.springerlink.com/content/w3165x33n24v8610/ (A book that looks like its focused on your problem)

http://www.computer.org/portal/web/csdl/doi/10.1109/ICCIT.2008.407

Just because an algorithm is old, doesn't mean its not efficient.


问:
does not known my file inside raw folder
someone know why my commands.json file inside raw folder is not known ?

I got cannot resolve symbole 'commands '
I have a few flavours and inside raw folder of each flavor, I have overrode  my commands.json file.

答:
try this

```<code>InputStream ins = getResources().openRawResource(getResources().getIdentifier(         "commands",          "raw",  getPackageName()));
//                                                                             FILENAME_WITHOUT_EXTENSION          YOUR_PACKAGE_NAME
</code>```

instead of this

```<code>InputStream ins = cx.getResources().openRawResource(R.raw.commands);
</code>```

Body:
try this

InputStream ins = getResources().openRawResource(getResources().getIdentifier(         "commands",          "raw",  getPackageName()));
//                                                                             FILENAME_WITHOUT_EXTENSION          YOUR_PACKAGE_NAME

instead of this

InputStream ins = cx.getResources().openRawResource(R.raw.commands);


问:
How to combine multiple arrays with same amount of items in php
Is there a way to combine multiple arrays with same amount of items? See below the 4 arrays with 5 items inside:

```<code>$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');
</code>```

Expected Results:

```<code>[0] => Array
    (
        [0] => Type 1
        [1] => Description 1
        [2] => Brand 1
        [3] => Model 1
    )

[1] => Array
    (
        [0] => Type 2
        [1] => Description 2
        [2] => Brand 2
        [3] => Model 2
    )

[2] => Array
    (
        [0] => Type 3
        [1] => Description 3
        [2] => Brand 3
        [3] => Model 3
    )

[3] => Array
    (
        [0] => Type 4
        [1] => Description 4
        [2] => Brand 4
        [3] => Model 4
    )

[4] => Array
    (
        [0] => Type 5
        [1] => Description 5
        [2] => Brand 5
        [3] => Model 5
    )
</code>```

I'm not PHP expert please help me :)

Thank you.

答:
array_map is really all you need here.

```<code>$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');

$res = array_map(function(...$val) {return $val;}, $type, $desc, $brand, $model);
print_r($res);
</code>```

See it in Action

Body:
Is there a way to combine multiple arrays with same amount of items? See below the 4 arrays with 5 items inside:

$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');

Expected Results:

[0] => Array
    (
        [0] => Type 1
        [1] => Description 1
        [2] => Brand 1
        [3] => Model 1
    )

[1] => Array
    (
        [0] => Type 2
        [1] => Description 2
        [2] => Brand 2
        [3] => Model 2
    )

[2] => Array
    (
        [0] => Type 3
        [1] => Description 3
        [2] => Brand 3
        [3] => Model 3
    )

[3] => Array
    (
        [0] => Type 4
        [1] => Description 4
        [2] => Brand 4
        [3] => Model 4
    )

[4] => Array
    (
        [0] => Type 5
        [1] => Description 5
        [2] => Brand 5
        [3] => Model 5
    )

I'm not PHP expert please help me :)

Thank you.

Body:
array_map is really all you need here.

$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');

$res = array_map(function(...$val) {return $val;}, $type, $desc, $brand, $model);
print_r($res);

See it in Action


问:
Is there any way we can get video duration before upload?
I want to limit the user to upload only videos with duration up to 30 sec.Is there any Way?</p>

答:
Try this

<form action="#" method="post" enctype="multipart/form-data">
  File: <input type="file" name="fup" id="fup" />

  Duration: <input type="text" name="f_du" id="f_du" size="5" /> seconds

  <input type="submit" value="Upload" />
</form>
<audio id="audio"></audio>

```

Body:
Try this

<form action="#" method="post" enctype="multipart/form-data">
  File: <input type="file" name="fup" id="fup" /><br>
  Duration: <input type="text" name="f_du" id="f_du" size="5" /> seconds<br>
  <input type="submit" value="Upload" />
</form>
<audio id="audio"></audio>

<script>
// Code to get duration of audio /video file before upload - from: http://coursesweb.net/

//register canplaythrough event to #audio element to can get duration
var f_duration =0;  //store duration
document.getElementById('audio').addEventListener('canplaythrough', function(e){
  //add duration in the input field #f_du
  f_duration = Math.round(e.currentTarget.duration);
  document.getElementById('f_du').value = f_duration;
  URL.revokeObjectURL(obUrl);
});

//when select a file, create an ObjectURL with the file and add it in the #audio element
var obUrl;
document.getElementById('fup').addEventListener('change', function(e){
  var file = e.currentTarget.files[0];
  //check file extension for audio/video type
  if(file.name.match(/\.(avi|mp3|mp4|mpeg|ogg)$/i)){
    obUrl = URL.createObjectURL(file);
    document.getElementById('audio').setAttribute('src', obUrl);
  }
});
</script>


问:
getting current time in different time zone using moment.js
I am trying to figure out how to get current time in different time zones but below method does not return anything</p>

```<code>var timeUpdate = setInterval(function () {
    var currentTime = moment().format()
    var GMT_current_time = currentTime.tz("Europe/London").format("HH:mm DD MMM");
$("#GMT_display_time").text(GMT_current_time);
}, 1000);
</code>```

答:
Returns current time with format.</p>

```<code>moment.tz(moment(), 'Asia/Karachi').format('DD/MM/YYYY HH:mm')
</code>```

Body:
I am trying to figure out how to get current time in different time zones but below method does not return anything

var timeUpdate = setInterval(function () {
    var currentTime = moment().format()
    var GMT_current_time = currentTime.tz("Europe/London").format("HH:mm DD MMM");
$("#GMT_display_time").text(GMT_current_time);
}, 1000);

Body:
Returns current time with format.

moment.tz(moment(), 'Asia/Karachi').format('DD/MM/YYYY HH:mm')

ContentLicense: CC BY-SA 4.0


问:
Is there a JavaScript minifier with conditional directives?
I'm looking for a JavaScript minifier which will have some kind of support for something similar to conditional compilation directives.

So for example, the original JavaScript code could look like something similar to this:

```<code>//#if Dev
    showLoginScreen();
//#else
    login("DevUser", "qwerty1");
//#endif
</code>```

So the original code could contain a directive #define Dev but once it goes into production that #define Dev would be removed, and the minifier would exclude the line login("DevUser", "qwerty1"); from its output.

Do any minifiers support this kind of behavior?

答:
I looked at the C preprocessor and a few other contenders based on answers to similar questions. Then found what I think is the best answer by far - PHP. Consider:

1) PHP is indeed a preprocessor (it's in the acronym).

2) PHP is ready to go on most servers. All you have to do is either change your file extensions from ".js" to ".php" or ".js.php", or (my preference), make a simple edit to a config file (you can find the details elsewhere).

3) Many JavaScript developers are already familiar with, or expert at, PHP.

4) PHP is Turing-complete, unlike many other preprocessors.

5) You only need basic PHP knowledge to benefit a lot.

6) There is way more documentation/tutorials/forums for PHP than other preprocessors.

But mostly, it's so weird it's cool. Thanks to whoever gave me the idea - I can't find their post at the moment.

Body:
I'm looking for a JavaScript minifier which will have some kind of support for something similar to conditional compilation directives.

So for example, the original JavaScript code could look like something similar to this:

//#if Dev
    showLoginScreen();
//#else
    login("DevUser", "qwerty1");
//#endif

So the original code could contain a directive #define Dev but once it goes into production that #define Dev would be removed, and the minifier would exclude the line login("DevUser", "qwerty1"); from its output.

Do any minifiers support this kind of behavior?


问:
Speed up page load by deferring images
I am creating a page which will contain a lot of large sized images, so naturally I want to make sure the page loads without too much trouble. I read this article here http://24ways.org/2010/speed-up-your-site-with-delayed-content

The method of deferring is as follows (pulled from page, don't mind the URL)

```<code><div>
    <h4>
        <a href="http://allinthehead.com/" data-gravatar-hash="13734b0cb20708f79e730809c29c3c48">
            Drew McLellan
        </a>
    </h4>
</div>
</code>```

then later a snippet of js takes care of the image loading

```<code>$(window).load(function() {
    $('a[data-gravatar-hash]').prepend(function(index){
        var hash = $(this).attr('data-gravatar-hash')
        return '<img width="100" height="100" alt="" src="http://www.gravatar.com/avatar.php?size=100&gravatar_id=' + hash + '">'
    });
});
</code>```

I don't plan on doing this for every image but definitely for some image which I don't need it to show up at page load time.

Is this the best way to go or are there better ways to achieve faster page load by deferring images?

Thanks

答:
Here's a version showcasing .querySelectorAll:

```<code>function swapSrcAttributes(source) {
  return function(element) {
    element.setAttribute('src', element.getAttribute(source));
  }
}

function forEach(collection, partial) {
  for (var i = 0; i < collection.length; i++) {
     partial(collection[i]);
  }
}

function initDeferImages() {
  // for images
  var deferImages = document.querySelectorAll('img[data-src]');

  // or you could be less specific and remove the `img`
  deferImages = document.querySelectorAll('[data-src]');

  forEach(deferImages, swapSrcAttributes('data-src'));
}

window.onload = function() {
  initDeferImages();
}
</code>```

Here is the compatibility table for .querySelector and .querySelectorAll via https://caniuse.com/#feat=queryselector

Title: Speed up page load by deferring images

Body:
I am creating a page which will contain a lot of large sized images, so naturally I want to make sure the page loads without too much trouble. I read this article here http://24ways.org/2010/speed-up-your-site-with-delayed-content

The method of deferring is as follows (pulled from page, don't mind the URL)

            Drew McLellan

then later a snippet of js takes care of the image loading

$(window).load(function() {
    $('a[data-gravatar-hash]').prepend(function(index){
        var hash = $(this).attr('data-gravatar-hash')
        return ''
    });
});

I don't plan on doing this for every image but definitely for some image which I don't need it to show up at page load time.

Is this the best way to go or are there better ways to achieve faster page load by deferring images?

Thanks

Body:
Here's a version showcasing .querySelectorAll:

function swapSrcAttributes(source) {
  return function(element) {
    element.setAttribute('src', element.getAttribute(source));
  }
}

function forEach(collection, partial) {
  for (var i = 0; i < collection.length; i++) {
     partial(collection[i]);
  }
}

function initDeferImages() {
  // for images
  var deferImages = document.querySelectorAll('img[data-src]');

  // or you could be less specific and remove the `img`
  deferImages = document.querySelectorAll('[data-src]');

  forEach(deferImages, swapSrcAttributes('data-src'));
}

window.onload = function() {
  initDeferImages();
}

Here is the compatibility table for .querySelector and .querySelectorAll via https://caniuse.com/#feat=queryselector


问:
javascript: switch statement
I'm trying to learn how to do a switch statement using javascript. Can you guys help me how to convert this one into switch statement?</p>

```<code>        if (x == ix && y == iy){//should be the default
            x.style.backgroundColor = 'white';
        }
        if(x < ix){
            x.style.backgroundColor = 'red';
        }
        else if(x > ix){
            x.style.backgroundColor = 'blue';
        }
        if(y < iy){
            x.style.backgroundColor = 'green';
        }
        else if(y > iy){
            x.style.backgroundColor = 'yellow';
        }
</code>```

答:
JavaScript does not support operations other than strict equality in switches. In other words, you cannot write that program as a switch.

In a switch, you can compare a variable to different values (or cases) and check if they are equal. If they are, you execute the code given under the case.

There is a drawback, however, and it is that you can convert this code into a switch easily:

```<code>if (a === 1) {
  console.log("one");
} else if (a === 2) {
  console.log("two");
} else {
  console.log("Out of range! :(");
}
</code>```

The above code in switch is

```<code>switch (a) {
  case 1:
    console.log("one");
    break;

  case 2:
    console.log("two");
    break;

  default:
    console.log("Out of range! :(");
    break;
}
</code>```

But you cannot do the same to a code that contains relational operations.

```<code>switch (a) {
  case > 1: // throws error
    doSomething();
    break;
}
</code>```

Title: javascript: switch statement

Body:
I'm trying to learn how to do a switch statement using javascript. Can you guys help me how to convert this one into switch statement?

        if (x == ix && y == iy){//should be the default
            x.style.backgroundColor = 'white';
        }
        if(x < ix){
            x.style.backgroundColor = 'red';
        }
        else if(x > ix){
            x.style.backgroundColor = 'blue';
        }
        if(y < iy){
            x.style.backgroundColor = 'green';
        }
        else if(y > iy){
            x.style.backgroundColor = 'yellow';
        }

Body:
JavaScript does not support operations other than strict equality in switches. In other words, you cannot write that program as a switch.

In a switch, you can compare a variable to different values (or cases) and check if they are equal. If they are, you execute the code given under the case.

There is a drawback, however, and it is that you can convert this code into a switch easily:

if (a === 1) {
  console.log("one");
} else if (a === 2) {
  console.log("two");
} else {
  console.log("Out of range! :(");
}

The above code in switch is

switch (a) {
  case 1:
    console.log("one");
    break;

  case 2:
    console.log("two");
    break;

  default:
    console.log("Out of range! :(");
    break;
}

But you cannot do the same to a code that contains relational operations.

switch (a) {
  case > 1: // throws error
    doSomething();
    break;
}


问:
Previewing an image after it has been submitted through AJAX (Rails solution)?
I'm trying to see what is the best way to implement a mechanism as in use here: https://sortfolio.com/signup . Essentially, one selects a picture to be uploaded. Picture uploads in the background and then it appears on the page with no refresh required.

So far I manage to do the POST of the image (I'm posting to an IFrame, using a jQuery plugin) and show the progress bat. I don't quite understand, when / how to pull the image back.

I'm using paperclip for processing.

Any thoughts ?

Thanks.

答: I did some time ago an example application for a similar problem. You can find it here. It renders the image on a modal window, but I'm quite sure you can find some ideas on how to solve your problem.</p>


问:
How to change a widget's font style without knowing the widget's font family/size?
Is there a way to change a Tkinter widget's font style without knowing the widget's font family and font size?

Use case: We create our UI using standard Tkinter widgets (Label, Entry, Text, etc). While our application runs we may want to dynamically change the font style of these widgets to bold and/or italics using the .config() method. Unfortunately there appears to be no way to specify a font spec without specifying the font's family and size.

The following are examples of what we'd like to do, but neither of these examples work:

```<code>widget.config(font='bold')
</code>```

or

```<code>widget.config(font=( None, None, 'bold' ))
</code>```

答:
Although it's been quite some time since this Q was asked, I recently had to implement a solution to this, which I thought worth sharing.  The function widget_font_config(...) runs on Python 2 and 3.

In essence, the "current value" of the widget's font is grabbed, modified, and then put back.  Named fonts are supported, and the default inplace_f value of True means that named fonts will be preserved and modified in place.  But the flag can also be set to False, which will cause a named font to be replaced with a different named font, in case the user does not wish for the changes in the font of the widget to percolate to all other widgets which use the named font.

```<code>def widget_font_config(widget, inplace_f=True, **kwargs):
    import sys
    if sys.version_info[0] == 2:
        import tkFont as tk_font
    else:
        import tkinter.font as tk_font
    inplace_f = kwargs.pop('inplace', inplace_f)
    font = None
    if widget and 'font' in widget.config():
        current_font = widget.cget('font') #grabs current value
        namedfont_f = False
        try:
            font = tk_font.nametofont(current_font)
            namedfont_f = True
        except:
            font = current_font
        if namedfont_f and inplace_f:
            font.config(**kwargs)
        else:
            font_d = tk_font.Font(font=font).actual()
            font_d.update(**kwargs)
            font = tk_font.Font(**font_d)
            widget.config(font=font)
        widget.update_idletasks()
    return font

if __name__ == '__main__':
    import sys
    pyVers = sys.version_info[0] # .major
    if pyVers == 2:
        import Tkinter as tk, tkFont as tk_font
    else:
        import tkinter as tk, tkinter.font as tk_font
    def go():
        print(widget_font_config(root.label,  slant='roman', underline=1).actual())
        print(widget_font_config(root.button, overstrike=1).actual())
    root = tk.Tk()
    font_s = 'Courier 20 italic'
    font_d = dict(family='Courier', size=10, weight='normal', slant='italic')
    font = tk_font.Font(**font_d)
    root.label = tk.Label(text='Label {}'.format(font_s), font=font_s)
    root.label.pack()
    root.button = tk.Button(text='Button {}'.format(font), font=font, command=go)
    root.button.pack()
    root.mainloop()
</code>```

Body:
Is there a way to change a Tkinter widget's font style without knowing the widget's font family and font size?

Use case: We create our UI using standard Tkinter widgets (Label, Entry, Text, etc). While our application runs we may want to dynamically change the font style of these widgets to bold and/or italics using the .config() method. Unfortunately there appears to be no way to specify a font spec without specifying the font's family and size.

The following are examples of what we'd like to do, but neither of these examples work:

widget.config(font='bold')

or

widget.config(font=( None, None, 'bold' ))

Body:
Although it's been quite some time since this Q was asked, I recently had to implement a solution to this, which I thought worth sharing.  The function widget_font_config(...) runs on Python 2 and 3.

In essence, the "current value" of the widget's font is grabbed, modified, and then put back.  Named fonts are supported, and the default inplace_f value of True means that named fonts will be preserved and modified in place.  But the flag can also be set to False, which will cause a named font to be replaced with a different named font, in case the user does not wish for the changes in the font of the widget to percolate to all other widgets which use the named font.

def widget_font_config(widget, inplace_f=True, **kwargs):
    import sys
    if sys.version_info[0] == 2:
        import tkFont as tk_font
    else:
        import tkinter.font as tk_font
    inplace_f = kwargs.pop('inplace', inplace_f)
    font = None
    if widget and 'font' in widget.config():
        current_font = widget.cget('font') #grabs current value
        namedfont_f = False
        try:
            font = tk_font.nametofont(current_font)
            namedfont_f = True
        except:
            font = current_font
        if namedfont_f and inplace_f:
            font.config(**kwargs)
        else:
            font_d = tk_font.Font(font=font).actual()
            font_d.update(**kwargs)
            font = tk_font.Font(**font_d)
            widget.config(font=font)
        widget.update_idletasks()
    return font

if __name__ == '__main__':
    import sys
    pyVers = sys.version_info[0] # .major
    if pyVers == 2:
        import Tkinter as tk, tkFont as tk_font
    else:
        import tkinter as tk, tkinter.font as tk_font
    def go():
        print(widget_font_config(root.label,  slant='roman', underline=1).actual())
        print(widget_font_config(root.button, overstrike=1).actual())
    root = tk.Tk()
    font_s = 'Courier 20 italic'
    font_d = dict(family='Courier', size=10, weight='normal', slant='italic')
    font = tk_font.Font(**font_d)
    root.label = tk.Label(text='Label {}'.format(font_s), font=font_s)
    root.label.pack()
    root.button = tk.Button(text='Button {}'.format(font), font=font, command=go)
    root.button.pack()
    root.mainloop()


问:
Android Studio Firebase Notification Device to Device with Topics
Sorry if this post was duplicated, but I could not find an answer in here, so I decided to post a new question.

Is there anyway I can do to easily send a notification from a device to other device in a specific topics with a single button ?

I know I successfully push a notification through firebase notification by its website in https://console.firebase.google.com/u/0/project/project/notification but I want to do it within my own device.

a full method would be very helpful for me.

```<code>mSendNotificationBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        sendNotificationToTopic("title","description","latestNews");
    }
});
</code>```

above is the example of my button.

UPDATE

After trying some codes, I decided to combine the notification manager with thread that listens to a firebase database, as follows

```<code>    DatabaseReference mDatabaseNotification = FirebaseDatabase.getInstance().getReference().child("Notification");
    String subscribedTopic = "news";

    Thread thread = new Thread(){
        @Override
        public void run() {
            mDatabaseNotification.child(subscribedTopic ).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    if(dataSnapshot != null) {
                        if(dataSnapshot.child("title").getValue(String.class) != null && dataSnapshot.child("desc").getValue(String.class) != null) {

                            NotificationCompat.Builder mBuilder =
                                new NotificationCompat.Builder(MainActivity.this)
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .setContentTitle(dataSnapshot.child("abc").child("title").getValue(String.class))
                                    .setContentText(dataSnapshot.child("abc").child("desc").getValue(String.class));
                            int mNotificationId = 001;
                            NotificationManager mNotifyMgr =
                                    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                            mNotifyMgr.notify(mNotificationId, mBuilder.build());

                        }
                    }
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {}
            });
        }
    };
    thread.start();
</code>```

and it works fine, I could subscribe the users by editing the subscribedTopic and listens to that database only even on background.

So, another question is, can this cause something bad later ?

UPDATE 2

I found a bug which the ValueEventListener triggered more than once even though the data changed...

UPDATE 3

Check my answer below

答:
First, the user has to generate
String token = FirebaseInstanceId.getInstance().getToken(); and then store it in firebase database with userId as key or you can subscribe the user to any topic by FirebaseMessaging.getInstance().subscribeToTopic("topic");

To send notification you have to hit this api https://fcm.googleapis.com/fcm/send with headers "Authorization" your FCM key and Content-Type as "application/json" the request body should be

```<code>{
 "to": "/topics or FCM id",
 "priority": "high",
 "notification": {
    "title": "Your Title",
    "text": "Your Text"
  }
 "data": {
     "customId": "02",
     "badge": 1,
     "sound": "",
    "alert": "Alert"
  }
}
</code>```

or you can Use okHttp which is not recommended method because your FCM key will be exposed and can be misused.

```<code>public class FcmNotifier {

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

public static void sendNotification(final String body, final String title) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                OkHttpClient client = new OkHttpClient();
                JSONObject json = new JSONObject();
                JSONObject dataJson = new JSONObject();
                dataJson.put("text", body);
                dataJson.put("title", title);
                dataJson.put("priority", "high");
                json.put("notification", dataJson);
                json.put("to", "/topics/topic");
                RequestBody body = RequestBody.create(JSON, json.toString());
                Request request = new Request.Builder()
                        .header("Authorization", "key=your FCM key")
                        .url("https://fcm.googleapis.com/fcm/send")
                        .post(body)
                        .build();
                Response response = client.newCall(request).execute();
                String finalResponse = response.body().string();
                Log.i("kunwar", finalResponse);
            } catch (Exception e) {

                Log.i("kunwar",e.getMessage());
            }
            return null;
        }
    }.execute();

}
}
</code>```

Body:
Sorry if this post was duplicated, but I could not find an answer in here, so I decided to post a new question.

Is there anyway I can do to easily send a notification from a device to other device in a specific topics with a single button ?

I know I successfully push a notification through firebase notification by its website in https://console.firebase.google.com/u/0/project/project/notification but I want to do it within my own device.

a full method would be very helpful for me.

mSendNotificationBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        sendNotificationToTopic("title","description","latestNews");
    }
});

above is the example of my button.

UPDATE

After trying some codes, I decided to combine the notification manager with thread that listens to a firebase database, as follows

    DatabaseReference mDatabaseNotification = FirebaseDatabase.getInstance().getReference().child("Notification");
    String subscribedTopic = "news";

    Thread thread = new Thread(){
        @Override
        public void run() {
            mDatabaseNotification.child(subscribedTopic ).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    if(dataSnapshot != null) {
                        if(dataSnapshot.child("title").getValue(String.class) != null && dataSnapshot.child("desc").getValue(String.class) != null) {

                            NotificationCompat.Builder mBuilder =
                                new NotificationCompat.Builder(MainActivity.this)
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .setContentTitle(dataSnapshot.child("abc").child("title").getValue(String.class))
                                    .setContentText(dataSnapshot.child("abc").child("desc").getValue(String.class));
                            int mNotificationId = 001;
                            NotificationManager mNotifyMgr =
                                    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                            mNotifyMgr.notify(mNotificationId, mBuilder.build());

                        }
                    }
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {}
            });
        }
    };
    thread.start();

and it works fine, I could subscribe the users by editing the subscribedTopic and listens to that database only even on background.

So, another question is, can this cause something bad later ?

UPDATE 2

I found a bug which the ValueEventListener triggered more than once even though the data changed...

UPDATE 3

Check my answer below

Body:
First, the user has to generate
String token = FirebaseInstanceId.getInstance().getToken(); and then store it in firebase database with userId as key or you can subscribe the user to any topic by FirebaseMessaging.getInstance().subscribeToTopic("topic");

To send notification you have to hit this api https://fcm.googleapis.com/fcm/send with headers "Authorization" your FCM key and Content-Type as "application/json" the request body should be

{
 "to": "/topics or FCM id",
 "priority": "high",
 "notification": {
    "title": "Your Title",
    "text": "Your Text"
  }
 "data": {
     "customId": "02",
     "badge": 1,
     "sound": "",
    "alert": "Alert"
  }
}

or you can Use okHttp which is not recommended method because your FCM key will be exposed and can be misused.

public class FcmNotifier {

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

public static void sendNotification(final String body, final String title) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                OkHttpClient client = new OkHttpClient();
                JSONObject json = new JSONObject();
                JSONObject dataJson = new JSONObject();
                dataJson.put("text", body);
                dataJson.put("title", title);
                dataJson.put("priority", "high");
                json.put("notification", dataJson);
                json.put("to", "/topics/topic");
                RequestBody body = RequestBody.create(JSON, json.toString());
                Request request = new Request.Builder()
                        .header("Authorization", "key=your FCM key")
                        .url("https://fcm.googleapis.com/fcm/send")
                        .post(body)
                        .build();
                Response response = client.newCall(request).execute();
                String finalResponse = response.body().string();
                Log.i("kunwar", finalResponse);
            } catch (Exception e) {

                Log.i("kunwar",e.getMessage());
            }
            return null;
        }
    }.execute();

}
}


问:
SVG Image xlink:href is not working with knockout
I am trying to render a svg image with knockout, but it is not showing image after I successfully bound the viewmodel.

Here is the SVG

```<code><svg width="500" height="500" style="border: solid 1px black">

<image id="img1" width="500" height="500"
        data-bind="attr:{'xlink:href': image}"></image>
</svg>
</code>```

Here is the knockout bindings,

```<code><script>
    var viewModel = function(data){
        var self = this;
        self.image = ko.observable(data.image)
    };

    var data = {image: "http://2.bp.blogspot.com/-cGeVTe2XeWU/VUEiQidIJKI/AAAAAAAACwU/UYzCrcNMMAk/s1600/comic.png"};

    var vm = new viewModel(data);
    ko.applyBindings(vm);
</script>
</code>```

Anyway I checked the page source after executing this code. So the SVG image element in page source is

```<code><image id="img1" width="500" height="500" data-bind="attr:{'xlink:href': image}" xlink:href="http://2.bp.blogspot.com/-cGeVTe2XeWU/VUEiQidIJKI/AAAAAAAACwU/UYzCrcNMMAk/s1600/comic.png"></image>
</code>```

As you can see here, it is setting xlink:href correctly, but it is not showing on svg.

Do I need to refresh DOM somehow?
Simply how can I render SVG image using knockout?

Any help will be appreciated

答:
xlink:href attribute needs to be there even with empty value to initialize the HTML svg image.

so image tag should be like Here is a demo and more info

```<code>  <image id="img1" width="500" height="500" xlink:href=""
        data-bind="attr:{'xlink:href': image}"></image>
</code>```

Body:
I am trying to render a svg image with knockout, but it is not showing image after I successfully bound the viewmodel.

Here is the SVG

<svg width="500" height="500" style="border: solid 1px black">

<image id="img1" width="500" height="500"
        data-bind="attr:{'xlink:href': image}"></image>
</svg>

Here is the knockout bindings,

Anyway I checked the page source after executing this code. So the SVG image element in page source is

<image id="img1" width="500" height="500" data-bind="attr:{'xlink:href': image}" xlink:href="http://2.bp.blogspot.com/-cGeVTe2XeWU/VUEiQidIJKI/AAAAAAAACwU/UYzCrcNMMAk/s1600/comic.png"></image>

As you can see here, it is setting xlink:href correctly, but it is not showing on svg.

Do I need to refresh DOM somehow?
Simply how can I render SVG image using knockout?

Any help will be appreciated

Body:
xlink:href attribute needs to be there even with empty value to initialize the HTML svg image.

so image tag should be like Here is a demo and more info

  <image id="img1" width="500" height="500" xlink:href=""
        data-bind="attr:{'xlink:href': image}"></image>


问:
Jquery Datepicker prev, next icon hiding on hover
I am using jquery date picker, on top of datepicker two icons is available(next, previous) when i hovering on those icons they are disappearing.

I have checked on hover two classes getting added in tag

classes - ui-state-hover ui-datepicker-next-hover

what can the problem be?

```<code> <a class="ui-datepicker-prev ui-corner-all" data-handler="prev" data-event="click" title="Prev">
 <span class="ui-icon ui-icon-circle-triangle-w">Prev</span>
 </a>
</code>```

On hover these two classes are getting added in anchor tag

```<code> ui-state-hover ui-datepicker-prev-hover
</code>```

Now I Want to remove above mentioned classes from anchor tag on hover/mouseover

ui-datepicker-prev ui-corner-all ui-state-hover ui-datepicker-prev-hover

答:
Please check this:

$(function() {
  $( "#datepicker" ).datepicker();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#ui-datepicker-div .ui-widget-header {
 background: #2D8CB9;
}
.ui-state-default, .ui-widget-content .ui-state-default{
  background: transparent!important;
}
.ui-state-highlight, .ui-widget-content .ui-state-highlight{
  background: #fffa90!important;
}
.ui-datepicker-calendar th {
 color: #2D8CB9;
}
.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active, a.ui-button:active, .ui-button:active, .ui-button.ui-state-active:hover{
  color:#333!important;
}</code>```

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Date: <input type="text" id="datepicker">
```

Body:
I am using jquery date picker, on top of datepicker two icons is available(next, previous) when i hovering on those icons they are disappearing.

I have checked on hover two classes getting added in tag

classes - ui-state-hover ui-datepicker-next-hover

what can the problem be?

 Prev

On hover these two classes are getting added in anchor tag

 ui-state-hover ui-datepicker-prev-hover

Now I Want to remove above mentioned classes from anchor tag on hover/mouseover

ui-datepicker-prev ui-corner-all ui-state-hover ui-datepicker-prev-hover

Body:
Please check this:

$(function() {
  $( "#datepicker" ).datepicker();
});

#ui-datepicker-div .ui-widget-header {
 background: #2D8CB9;
}
.ui-state-default, .ui-widget-content .ui-state-default{
  background: transparent!important;
}
.ui-state-highlight, .ui-widget-content .ui-state-highlight{
  background: #fffa90!important;
}
.ui-datepicker-calendar th {
 color: #2D8CB9;
}
.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active, a.ui-button:active, .ui-button:active, .ui-button.ui-state-active:hover{
  color:#333!important;
}

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<p>Date: <input type="text" id="datepicker"></p>


问:
Joining tables using more than one column in Linq To Entities
Every single example of joins in Linq to Entities involves only one column in the on clause. What is the syntax if I need 2 or more columns to make the join work? I would need an example for Linq to Entities Query Expressions and Method Based also, if possible. Below is the example of what I need. There isn't a relationship between Table1 and Table2.

```<code>CREATE TABLE dbo.Table1 (
  ID1Table1 INT NOT NULL,
  ID2Table1 SMALLDATETIME NOT NULL,
  Value1Table1 VARCHAR(50) NOT NULL,
  CONSTRAINT PK_Table1 PRIMARY KEY (ID1Table1, ID2Table1));
CREATE TABLE dbo.Table2 (
  ID1Table2 INT NOT NULL,
  ID2Table2 SMALLDATETIME NOT NULL,
  ID3Table2 INT NOT NULL,
  Value1Table2 VARCHAR(50) NOT NULL,
  CONSTRAINT PK_Table2 PRIMARY KEY (ID1Table2, ID2Table2, ID3Table2));

SELECT a.ID1Table1, a.ID2Table1, a.Value1Table1, b.ID3Table2, b.Value1Table2
FROM dbo.Table1 a JOIN dbo.Table2 b
  ON a.ID1Table1 = b.ID1Table2
  AND a.ID2Table1 = b.ID2Table2
</code>```

答:
You can write it using two from expressions like below:

```<code>from a in Table1s
from b in Table2s
where a.ID1Table1 == b.ID1Table2 && a.ID2Table1 == b.ID2Table2
select new {a.ID1Table1, a.ID2Table1, a.Value1Table1, b.ID3Table2, b.Value1Table2}
</code>```

Using join:

```<code>from a in Table1s
join b in Table2s on new{PropertyName1 = a.ID1Table1, PropertyName2 = a.ID2Table1} equals new{PropertyName1 = b.ID1Table2, PropertyName2 = b.ID2Table2}
select new {a.ID1Table1, a.ID2Table1, a.Value1Table1, b.ID3Table2, b.Value1Table2}
</code>```

Body:
Every single example of joins in Linq to Entities involves only one column in the on clause. What is the syntax if I need 2 or more columns to make the join work? I would need an example for Linq to Entities Query Expressions and Method Based also, if possible. Below is the example of what I need. There isn't a relationship between Table1 and Table2.

CREATE TABLE dbo.Table1 (
  ID1Table1 INT NOT NULL,
  ID2Table1 SMALLDATETIME NOT NULL,
  Value1Table1 VARCHAR(50) NOT NULL,
  CONSTRAINT PK_Table1 PRIMARY KEY (ID1Table1, ID2Table1));
CREATE TABLE dbo.Table2 (
  ID1Table2 INT NOT NULL,
  ID2Table2 SMALLDATETIME NOT NULL,
  ID3Table2 INT NOT NULL,
  Value1Table2 VARCHAR(50) NOT NULL,
  CONSTRAINT PK_Table2 PRIMARY KEY (ID1Table2, ID2Table2, ID3Table2));

SELECT a.ID1Table1, a.ID2Table1, a.Value1Table1, b.ID3Table2, b.Value1Table2
FROM dbo.Table1 a JOIN dbo.Table2 b
  ON a.ID1Table1 = b.ID1Table2
  AND a.ID2Table1 = b.ID2Table2

Body:
You can write it using two from expressions like below:

from a in Table1s
from b in Table2s
where a.ID1Table1 == b.ID1Table2 && a.ID2Table1 == b.ID2Table2
select new {a.ID1Table1, a.ID2Table1, a.Value1Table1, b.ID3Table2, b.Value1Table2}

Using join:

from a in Table1s
join b in Table2s on new{PropertyName1 = a.ID1Table1, PropertyName2 = a.ID2Table1} equals new{PropertyName1 = b.ID1Table2, PropertyName2 = b.ID2Table2}
select new {a.ID1Table1, a.ID2Table1, a.Value1Table1, b.ID3Table2, b.Value1Table2}


问:
Not authorized to execute any sonarqube analysis with sonarqube scanner on Travis CI
I recently started using Travis CI and sonarqube in an open source project and have run into a problem with sonarqube-scanner.

My Travis CI page can be seen here: https://travis-ci.org/uglyoldbob/decompiler

My sonarqube page can be seen here: https://sonarqube.com/overview?id=uglyoldbob_decompiler

I'm running sonarqube-scanner on Travis CI it suddenly stopped working with the following error:

```<code>"ERROR: You're not authorized to execute any SonarQube analysis. Please contact your SonarQube administrator."
</code>```

I am using a token generated on sonarqube and have added it to the environment variables of Travis CI. I generated a new token when I noticed the problem and updated the environment variable with Travis but it did not change anything.

What can I do to fix this?

答:
with mvn I had to pass to sonarcloud.io the parameter -Dsonar.branch=master

all command goes something like this:

```<code>mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.organization={ORG_KEY} -Dsonar.login={GENERATED_KEY_ON_SONARCLOUD_SECURITY} -Dsonar.branch={BRANCH_NAME}
</code>```

this fixed the following error:

You're only authorized to execute a local (preview) SonarQube analysis without pushing the results to the SonarQube server. Please contact your SonarQube administrator.

remember adding the analysis permission on the sonarcloud admin console.

Body:
I recently started using Travis CI and sonarqube in an open source project and have run into a problem with sonarqube-scanner.

My Travis CI page can be seen here: https://travis-ci.org/uglyoldbob/decompiler

My sonarqube page can be seen here: https://sonarqube.com/overview?id=uglyoldbob_decompiler

I'm running sonarqube-scanner on Travis CI it suddenly stopped working with the following error:

"ERROR: You're not authorized to execute any SonarQube analysis. Please contact your SonarQube administrator."

I am using a token generated on sonarqube and have added it to the environment variables of Travis CI. I generated a new token when I noticed the problem and updated the environment variable with Travis but it did not change anything.

What can I do to fix this?

Body:
with mvn I had to pass to sonarcloud.io the parameter -Dsonar.branch=master

all command goes something like this:

mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.organization={ORG_KEY} -Dsonar.login={GENERATED_KEY_ON_SONARCLOUD_SECURITY} -Dsonar.branch={BRANCH_NAME}

this fixed the following error:

You're only authorized to execute a local (preview) SonarQube analysis without pushing the results to the SonarQube server. Please contact your SonarQube administrator.

remember adding the analysis permission on the sonarcloud admin console.


问:
Google Cloud Identity Aware Proxy (IAP) Force logout
I'm trying to work out how to logout a user which is using an application behind Google IAP

The end goal is to be able to bounce the user right back to the initial process they completed the first time they visited the site (i.e. they cannot access my application until they sign in again)

I've looked at the documentation and all I can see is the "Clearing user login" section of https://cloud.google.com/iap/docs/special-urls-howto

However, when the user is redirected to /_gcp_iap/clear_login_cookie this sets the GCP_IAAP_AUTH_TOKEN cookie to none and then redirects the user to the root of my application. The request to / then in turn redirects the user to https://accounts.google.com/o/oauth2/v2/auth (inc. many get params), which then in turn redirects the user to /_gcp_gatekeeper/authenticate, which then sets the GCP_IAAP_AUTH_TOKEN cookie again and finally delivers the user back to my application (now logged back in as if nothing happened)

Could the issue here be that the user is still logged into other google account applications? (e.g. google cloud console, gmail etc)

I wondered if I could perhaps send the GCP_IAAP_AUTH_TOKEN cookie value to https://accounts.google.com/o/oauth2/revoke?token=token, however this appears to be stripped by the IAP load balancer

Any and all assistance appreciated on this one.

答:
What you're seeing is that clear_login_cookie clears the IAP login cookie, but it isn't intended to do anything about the fact that the user is still logged into Google.

We do have a change rolling out soon that will force the user back to the account-select screen after clear_login_cookie. You can preview what this will look like by going to https://myaccount.google.com/permissions and clicking on your application in that list, selecting "Remove Access", and then visiting clear_login_cookie.

I'm not sure whether that's what you're looking for, though. Could you tell me more about what your goal is?

--Matthew, Google Cloud IAP


问:
Intellij Abnormal build process termination (Error connecting to 127.0.0.1)
I have installed IntelliJ IDEA CE and jdk 1.8.0_152 on my mac OS Sierra version10.12.6 and written a simple hello world program. When i try to build the project through the UI (CMD+F9), it gives me the following error:

```<code>Error:Abnormal build process termination:
Build process started. Classpath: /Applications/IntelliJ IDEA CE.app/Contents/lib/jps-launcher.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home/lib/tools.jar:/Applications/IntelliJ IDEA CE.app/Contents/lib/optimizedFileManager.jarSLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementationSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Error connecting to 127.0.0.1:50569; reason: nulljava.nio.channels.ClosedChannelException
    at io.netty.channel.AbstractChannel$AbstractUnsafe.ensureOpen(...)(Unknown Source)
Exiting.
</code>```

I have disabled the firewall. I am struggling to get a simple program to work with IntelliJ. I have tried re-installing IntelliJ and restarting my mac already.

```<code>IntelliJ configuration:
IntelliJ IDEA 2017.2.6
Build #IC-172.4574.11, built on November 13, 2017
JRE: 1.8.0_152-release-915-b12 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Mac OS X 10.12.6
</code>```

答: Try using a more recent JDK build for your project. jdk1.8.0_152 is quite old. The issue can be also caused by the antivirus/firewall killing the process or blocking the connections.</p>

Body:
I have installed IntelliJ IDEA CE and jdk 1.8.0_152 on my mac OS Sierra version10.12.6 and written a simple hello world program. When i try to build the project through the UI (CMD+F9), it gives me the following error:

Error:Abnormal build process termination:
Build process started. Classpath: /Applications/IntelliJ IDEA CE.app/Contents/lib/jps-launcher.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home/lib/tools.jar:/Applications/IntelliJ IDEA CE.app/Contents/lib/optimizedFileManager.jarSLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementationSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Error connecting to 127.0.0.1:50569; reason: nulljava.nio.channels.ClosedChannelException
    at io.netty.channel.AbstractChannel$AbstractUnsafe.ensureOpen(...)(Unknown Source)
Exiting.

I have disabled the firewall. I am struggling to get a simple program to work with IntelliJ. I have tried re-installing IntelliJ and restarting my mac already.

IntelliJ configuration:
IntelliJ IDEA 2017.2.6
Build #IC-172.4574.11, built on November 13, 2017
JRE: 1.8.0_152-release-915-b12 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Mac OS X 10.12.6