text:
Q: How can I delete everything before and afrer match pattern from pdb file? I'm beginner in bash scripts, but I try to delete everything in my pdb file (test.pdb) before REMARK time 20.00 and from REMARK time 30.00 to the end of this file. I'm using to this sed command, which is such as:
sed 's/^.*\(REMARK time 20.00.*REMARK time 30.00\).*$/\1/' test.pdb > end.pdb

Unfortunately, above command generate end.pdb file, which is totally empty. Can you help me with solve this problem ?
My test.pdb file is as follows:
REMARK time   10.00                                       ENERGY     1.95686E+03
HELIX    1 H1  GLU    131  SER    146  1                                      15
HELIX    2 H2  GLU    278  SER    293  1                                      15
HELIX    3 H3  GLU    426  SER    441  1                                      15
HELIX    4 H4  GLU    574  SER    589  1                                      15
SHEET    1 B1  2 ALA    32  VAL    34  0
SHEET    2 B1  2 LYS    48  GLU    50 -1  N  GLU    50   O  ALA    32
SHEET    1 B2  2 ALA    32  LEU    35  0
SHEET    2 B2  2 TRP   123  ASP   126 -1  N  ASP   126   O  ALA    32
SHEET    1 B3  2 LEU    47  PRO    51  0
SHEET    2 B3  2 VAL    62  PHE    66 -1  N  PHE    66   O  LEU    47
SHEET    1 B4  2 ASN    58  ASN    68  0
SHEET    2 B4  2 ASP    71  LEU    81 -1  N  LEU    81   O  ASN    58
SHEET    1 B5  2 TRP    77  ASP    82  0
SHEET    2 B5  2 LYS    85  LEU    90 -1  N  LEU    90   O  TRP    77
SHEET    1 B6  2 ALA    84  LEU    90  0
SHEET    2 B6  2 LEU    93  VAL    99 -1  N  VAL    99   O  ALA    84
SHEET    1 B7  2 ASN    96  VAL    99  0
SHEET    2 B7  2 ASP   111  GLU   114 -1  N  GLU   114   O  ASN    96
SHEET    1 B8  2 HIS   107  VAL   113  0
SHEET    2 B8  2 ASP   119  LEU   125 -1  N  LEU   125   O  HIS   107
SHEET    1 B9  2 ALA   179  VAL   181  0
SHEET    2 B9  2 LYS   195  GLU   197 -1  N  GLU   197   O  ALA   179
SHEET    1 B*  2 ALA   179  LEU   182  0
........
ENDMDL
REMARK time   20.00                                       ENERGY     1.96641E+03
HELIX    1 H1  GLU    131  SER    146  1                                      15
HELIX    2 H2  GLU    278  SER    293  1                                      15
HELIX    3 H3  GLU    426  SER    441  1                                      15
HELIX    4 H4  GLU    574  SER    589  1                                      15
SHEET    1 B1  2 ALA    32  VAL    34  0
SHEET    2 B1  2 LYS    48  GLU    50 -1  N  GLU    50   O  ALA    32
SHEET    1 B2  2 ALA    32  LEU    35  0
SHEET    2 B2  2 TRP   123  ASP   126 -1  N  ASP   126   O  ALA    32
SHEET    1 B3  2 LEU    47  PRO    51  0
SHEET    2 B3  2 VAL    62  PHE    66 -1  N  PHE    66   O  LEU    47
SHEET    1 B4  2 ASN    58  ASN    68  0
SHEET    2 B4  2 ASP    71  LEU    81 -1  N  LEU    81   O  ASN    58
SHEET    1 B5  2 TRP    77  ASP    82  0
SHEET    2 B5  2 LYS    85  LEU    90 -1  N  LEU    90   O  TRP    77
SHEET    1 B6  2 ALA    84  LEU    90  0
SHEET    2 B6  2 LEU    93  VAL    99 -1  N  VAL    99   O  ALA    84
SHEET    1 B7  2 ASN    96  VAL    99  0
SHEET    2 B7  2 ASP   111  GLU   114 -1  N  GLU   114   O  ASN    96
SHEET    1 B8  2 HIS   107  VAL   113  0
SHEET    2 B8  2 ASP   119  LEU   125 -1  N  LEU   125   O  HIS   107
SHEET    1 B9  2 ALA   179  VAL   181  0
SHEET    2 B9  2 LYS   195  GLU   197 -1  N  GLU   197   O  ALA   179
SHEET    1 B*  2 ALA   179  LEU   182  0
SHEET    2 B*  2 TRP   270  ASP   273 -1  N  ASP   273   O  ALA   179
SHEET    1 B*  2 LEU   194  GLY   196  0
SHEET    2 B*  2 MET   211  PHE   213 -1  N  PHE   213   O  LEU   194
SHEET    1 B*  2 ASN   205  ASN   215  0
SHEET    2 B*  2 ASP   218  LEU   228 -1  N  LEU   228   O  ASN   205
SHEET    1 B*  2 TRP   224  ASP   229  0
....................
ENDMDL
REMARK time  100.00                                       ENERGY     1.95395E+03
HELIX    1 H1  GLU    131  SER    146  1                                      15
HELIX    2 H2  GLU    278  SER    293  1                                      15
HELIX    3 H3  GLU    426  SER    441  1                                      15
HELIX    4 H4  GLU    574  SER    589  1                                      15
SHEET    1 B1  2 ALA    32  VAL    34  0
SHEET    2 B1  2 LYS    48  GLU    50 -1  N  GLU    50   O  ALA    32
SHEET    1 B2  2 ALA    32  LEU    35  0
SHEET    2 B2  2 TRP   123  ASP   126 -1  N  ASP   126   O  ALA    32
SHEET    1 B3  2 LEU    47  PRO    51  0
SHEET    2 B3  2 VAL    62  PHE    66 -1  N  PHE    66   O  LEU    47
SHEET    1 B4  2 ASN    58  ASN    68  0
SHEET    2 B4  2 ASP    71  LEU    81 -1  N  LEU    81   O  ASN    58
SHEET    1 B5  2 TRP    77  ASP    82  0
SHEET    2 B5  2 LYS    85  LEU    90 -1  N  LEU    90   O  TRP    77
SHEET    1 B6  2 ALA    84  LEU    90  0
.......

CONECT   1131   1133   1132
CONECT   1133   1135   1134
CONECT   1135   1137   1136
CONECT   1137   1139   1138
CONECT   1139   1141   1140
CONECT   1141   1143   1142
CONECT   1143   1145   1144
CONECT   1145   1146
ENDMDL

Finally I want pull out information about only REMARK time 20.00 such as:
REMARK time   20.00                                       ENERGY     1.96641E+03

HELIX    1 H1  GLU    131  SER    146  1                                      15
HELIX    2 H2  GLU    278  SER    293  1                                      15
HELIX    3 H3  GLU    426  SER    441  1                                      15
HELIX    4 H4  GLU    574  SER    589  1                                      15
SHEET    1 B1  2 ALA    32  VAL    34  0
SHEET    2 B1  2 LYS    48  GLU    50 -1  N  GLU    50   O  ALA    32
SHEET    1 B2  2 ALA    32  LEU    35  0
SHEET    2 B2  2 TRP   123  ASP   126 -1  N  ASP   126   O  ALA    32
SHEET    1 B3  2 LEU    47  PRO    51  0
SHEET    2 B3  2 VAL    62  PHE    66 -1  N  PHE    66   O  LEU    47
SHEET    1 B4  2 ASN    58  ASN    68  0
SHEET    2 B4  2 ASP    71  LEU    81 -1  N  LEU    81   O  ASN    58
SHEET    1 B5  2 TRP    77  ASP    82  0
SHEET    2 B5  2 LYS    85  LEU    90 -1  N  LEU    90   O  TRP    77
SHEET    1 B6  2 ALA    84  LEU    90  0
SHEET    2 B6  2 LEU    93  VAL    99 -1  N  VAL    99   O  ALA    84
SHEET    1 B7  2 ASN    96  VAL    99  0
SHEET    2 B7  2 ASP   111  GLU   114 -1  N  GLU   114   O  ASN    96
SHEET    1 B8  2 HIS   107  VAL   113  0
SHEET    2 B8  2 ASP   119  LEU   125 -1  N  LEU   125   O  HIS   107
SHEET    1 B9  2 ALA   179  VAL   181  0
SHEET    2 B9  2 LYS   195  GLU   197 -1  N  GLU   197   O  ALA   179
SHEET    1 B*  2 ALA   179  LEU   182  0
SHEET    2 B*  2 TRP   270  ASP   273 -1  N  ASP   273   O  ALA   179
SHEET    1 B*  2 LEU   194  GLY   196  0
SHEET    2 B*  2 MET   211  PHE   213 -1  N  PHE   213   O  LEU   194
SHEET    1 B*  2 ASN   205  ASN   215  0
SHEET    2 B*  2 ASP   218  LEU   228 -1  N  LEU   228   O  ASN   205
SHEET    1 B*  2 TRP   224  ASP   229  0
SHEET    2 B*  2 LYS   232  LEU   237 -1  N  LEU   237   O  TRP   224
......
CONECT   1141   1143   1142
CONECT   1143   1145   1144
CONECT   1145   1146
ENDMDL

A: The command you use is for editing inside a line. To extract a range of lines, you can use range addressing /start_pattern/,/end pattern/:
sed -n '/REMARK time *20\.00/,/ENDMDL/p' test.pdb

So, you suppress default output with option -n, then print everything from REMARK time *20.00 to the next ENDMDL (this seems to be what you want instead of including the next REMARK time – address ranges are not greedy, so you can do it this way).
If your REMARK lines use tabs instead of spaces, you may use /REMARK time[[:space:]]*20\.00/. Finally, you need to escape the . with \. because otherwise . would match any character.

A: Philippos already gave you a fine sed answer, but here's a different approach. You can use awk and set the input and output record separator variables (RS and ORS respectively; this is normally a \n character, it is what defines a "line", and what is appended to every print call) to ENDMDL. That way, the entire block of lines between each ENDMDL will be treated as a single "line", so you can then tell awk to print any line containing the pattern you are looking for:
awk 'BEGIN{ RS=ORS="ENDMDL\n"}/REMARK\s*time\s*20\.00/' foo.pdb

Running it on your file gives:
$ awk 'BEGIN{ RS=ORS="ENDMDL\n"}/REMARK\s*time\s*20\.00/' foo.pdb
REMARK time   20.00                                       ENERGY     1.96641E+03
HELIX    1 H1  GLU    131  SER    146  1                                      15
HELIX    2 H2  GLU    278  SER    293  1                                      15
HELIX    3 H3  GLU    426  SER    441  1                                      15
HELIX    4 H4  GLU    574  SER    589  1                                      15
SHEET    1 B1  2 ALA    32  VAL    34  0
SHEET    2 B1  2 LYS    48  GLU    50 -1  N  GLU    50   O  ALA    32
SHEET    1 B2  2 ALA    32  LEU    35  0
SHEET    2 B2  2 TRP   123  ASP   126 -1  N  ASP   126   O  ALA    32
SHEET    1 B3  2 LEU    47  PRO    51  0
SHEET    2 B3  2 VAL    62  PHE    66 -1  N  PHE    66   O  LEU    47
SHEET    1 B4  2 ASN    58  ASN    68  0
SHEET    2 B4  2 ASP    71  LEU    81 -1  N  LEU    81   O  ASN    58
SHEET    1 B5  2 TRP    77  ASP    82  0
SHEET    2 B5  2 LYS    85  LEU    90 -1  N  LEU    90   O  TRP    77
SHEET    1 B6  2 ALA    84  LEU    90  0
SHEET    2 B6  2 LEU    93  VAL    99 -1  N  VAL    99   O  ALA    84
SHEET    1 B7  2 ASN    96  VAL    99  0
SHEET    2 B7  2 ASP   111  GLU   114 -1  N  GLU   114   O  ASN    96
SHEET    1 B8  2 HIS   107  VAL   113  0
SHEET    2 B8  2 ASP   119  LEU   125 -1  N  LEU   125   O  HIS   107
SHEET    1 B9  2 ALA   179  VAL   181  0
SHEET    2 B9  2 LYS   195  GLU   197 -1  N  GLU   197   O  ALA   179
SHEET    1 B*  2 ALA   179  LEU   182  0
SHEET    2 B*  2 TRP   270  ASP   273 -1  N  ASP   273   O  ALA   179
SHEET    1 B*  2 LEU   194  GLY   196  0
SHEET    2 B*  2 MET   211  PHE   213 -1  N  PHE   213   O  LEU   194
SHEET    1 B*  2 ASN   205  ASN   215  0
SHEET    2 B*  2 ASP   218  LEU   228 -1  N  LEU   228   O  ASN   205
SHEET    1 B*  2 TRP   224  ASP   229  0
....................
ENDMDL

Note that some awk versions might not like the \s, so you could try this instead:
awk 'BEGIN{ RS=ORS="ENDMDL\n"} $1=="REMARK" && $2=="time" && $3=="20.00"' foo.pdb


text:
Q: software for connection monitoring anyone know a simple software that can monitoring a connection between two computers?
my problem is the internet connection on ships, i want to know when they are offline, and the time of it.
a simple program that i can check the connection from a computer to the servers/computers exist on board of the ships. in teamviewer i can see when they are offline. but i dont know how many hours ou minutes are offline.
best regards
dont know any software capable to do this task

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I fix this cors error with cors module I installed cors module and coded like below.
var express = require('express'),
    favicon = require('serve-favicon'),
    cors = require('cors');
var app = express();

if (app.get('env') === 'development') {
    app.locals.pretty = true;
}

app.set('view engine', 'pug');
app.set('views', './views');

app.use(express.static(__dirname + '/public'));
app.use(favicon(__dirname + '/public/img/logo.ico'));
app.use(cors());

app.get('/', (req, res) => {
    res.render('view');
});

app.listen(80, () => {
    console.log('Server started on port 80');
});

After this I turned on server and tried to access files on server by this code.
$.getJSON('https://server.domain/global.json', data => {
    console.log(data);
});

But It makes error.
I can access to js files but not json file.

What's the problem?
[+Edit]
I can get js files by
$.getScript('~/js/file.js');

But not by
$.get('~/js/file.js');

A: Server in express don't allow you to access files directly.
if you want it to enable access files directly . you have  to do it like this
app.use(express.static('public'))

now you can access files in public folder directly like
if there is file data.json in public, you can access it by localhost:3000/data.json.
Hope this is answer of your question

A: do you get the error after trying this:
app.get('/', cors(), (req, res) => {
    res.render('view');
});

and
$.getJSON('https://server.domain/global.json', cors(), data => {
    console.log(data);
});

A: put the cors module as the first module that you load (use)

A: I finally solved this problem with code below.
app.all('/*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    next();
});


text:
Q: If attribute returns empty / null then automatically set it as "N/A" value without if - then condition Originally, I directly set my attribute value in the getter setter model without testing whether the attribute is empty or null.
String urlLDAP = "ldap://localhost:389/";
NamingEnumeration results = null;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, urlLDAP);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=admin,ou=sa,o=system");
env.put(Context.SECURITY_CREDENTIALS, "XXX");
DirContext context = new InitialDirContext(env);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
results = context.search(recipientDN, "(objectclass=person)", controls);
while (results.hasMore()) {
    SearchResult searchResult = (SearchResult) results.next();
    Attributes attribute = searchResult.getAttributes();
    try{
        Info info = new Info();
        for (user : userList){

            info.setUserName(attribute.get("fullName").toString());
            info.setdivision(attribute.get("division").toString());
            info.setAttr3(attribute.get("attribute3").toString());
            .
            .
            .
            .
            info.setAttr3(attribute.get("attribute16").toString());

        }
    }catch (NullPointerException ex) {
        Logger.getLogger(robotb.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Then, I add in if-else condition for each attribute because I realised not all users contain the same attribute as other users.
For example, User A does not has attribute 4 and 5 but User B has those two attributes.
for (user : userList){

        if(attribute.get("fullName").toString() != null)
            info.setUserName(attribute.get("fullName").toString())
        else
            info.setUserName("N/A");

        if(attribute.get("division").toString() != null)
            info.setdivision(attribute.get("division").toString())
        else
            info.setdivision("N/A");

        if (attribute3 != null)
        .
        .
        .

        if (attribute4 != null)
        .
        .
        .
        .
        .

        if (attribute16 ! null)
        .
        .
        .

    }

However, this causes my code to be very lengthy.
Is there other ways to make it simpler? Sorry for asking silly question such as this
Appreciates your advice
--EDIT
I added if-else condition to avoid hitting the exception such as this
Exception in thread "main" java.lang.NullPointerException

When I hit such exception, the looping stop and I cannot read other attributes

A: The easiest way of doing so is to create a method to check the values.
private String fixValue(Object input){
    return input != null ? input.toString() : "N/A";
}

Then you can use it on your setters:
info.setUserName(fixValue(attribute.get("fullName")))

If you also want to check empty strings you can overload the fixValue() method with this second one, so it checks also if the atribute is empty when it is an String:
private String fixValue(String input){
    Object inputValue = input == null || input.isEmpty() ? null : input;
    return fixValue(inputValue);
}

EDIT:
you can just declare a single method like this:
private String fixValue(Object input){
    return input == null || input.toString().isEmpty() ? "N/A" : input.toString();
}

A: Use can use ? operator of JAVA like this:
info.setdivision((attribute.get("division")==null)?"N/A":attribute.get("division").toString());

For more info read about ? operator:
http://www.cafeaulait.org/course/week2/43.html

A: Using org.apache.commons.lang.StringUtils
info.setUserName(StringUtils.defaultIfEmpty(attribute.get("fullName"), "N/A"));

Or you could make a private method handling it to reduce the code even more


text:
Q: KendoUI Switch control with AngularJS I am trying to use kendo UI's switch control (http://demos.telerik.com/kendo-ui/web/mobile/switch.html) with angularjs. I am having problem that the value is not being bound with model. I am using it like this:
<input type="checkbox" id="locked" kendo-mobile-switch on-label="Yes" off-label="No" ng-model="Model.IsLocked" checked="{{Model.IsLocked}}" data-role="switch">

Basically the variable in model keep the value received from db irrespective of the state on UI.
Second problem I am having is with on and off labels that it keeps on displaying default On and Off.

A: I opened an issue on the github site and a fix was applied. See this link:
"I pushed a fix, it should work now if you use k-ng-model. The plain ng-model is still broken."
https://github.com/kendo-labs/angular-kendo/issues/333

A: The second problem (the on/off labels) is because it should be:
k-on-label="'Yes'" k-off-label="'No'"

Note the string literals, otherwise it is interpreted as a variable.


text:
Q: Vue js populate second select dynamically on first select changed Im using Laravel blade and Vue js 2. Im trying to perform a simple task: populate secondary select once first select being changed. With axios call of course. Here is HTML part:
<div class="content" id="app">
    <select v-model="selected" @change="onChange">
        <option value="" disabled selected>Please Select the Attraction</option>
    @foreach($pkgs as $pkg)
        <option value="{{$pkg->id}}">{{$pkg->name}}</option>
    @endforeach
    </select>
    <select v-model="selected2">
        <option v-for="subpackage in subpackages" v-bind:value="subpackage.id">@{{ subpackage.name }}</option>
    </select>
</div>

Here is the js part:
new Vue({
    el: '#app',
    data: {
        selected: '',
        selected2: '',
        subpackages: [
            {id:'', name:'Please select an attraction first'}
        ]
    },
    methods: {
        onChange:function(){
            axios.get("{{route('pos.ajaxGetPkg')}}", {
                params:{
                    pkg_id: this.selected
                }
              })
            .then(function(response){
                this.subpackages = [];
                this.subpackages = response.data.variants;
                console.log(this.subpackages);
            })
            .catch(e => {
              //...
            })
        }
    }
});

In the console I can see received object dumped like
0:{id: 14, name: "Adult", price: "45.00"}
However select2 reminds unchanged


text:
Q: C#: Real-time combobox updating I have been trying to load a text file into a combobox, and then making a button to save any changes I make in the combobox back to the text file.
The problem is, when I type something in my combobox, the selected 'item' doesn't get updated. I can change the sentence, but as soon as I click the 'save' button, which also updates the combobox, it goes back to before I edited it.
Also, when I edit the combobox and click the dropdown-arrow, it shows the content of the text file, once again without my edited sentence.
I've been searching for a while now, but nobody seems to know how to do it so far. :P
private void cbBanken_SelectedValueChanged(object sender, EventArgs e)
{
    this.cbBanken.Update();
}

I thought something like that might work, but it doesn't do anything. I did manage to ádd a new item to the list after changing it, but that's not what I want. I want to be able to edit the items, not add a new one.
I hope this is detailed enough. Thank you for your time!
Edit: Alright, just one more thing: "It will only update the first character I change. So if I use backspace anywhere, it updates, and then I have to restart before it will update again. Also, it will go to the far left of the combobox line, which can be pretty annoying.. If anyone knows how to fix that too, I'd be really gratefull."
I am currently using this code:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
    if(comboBox1.SelectedIndex>=0)
    {
        int index = comboBox1.SelectedIndex;
        comboBox1.Items[index] = comboBox1.Text;
    }

}

A: ComboBox.Update method just redraws the combobox area.
As I understood, you want to change the combobox selected item in runtime. In that case you might want to use TextUpdate event. Combobox selected index is automatically stops the editing. So there is another way. Tracking of the value changing. Here is a code snippet:
    private int editedIndex = -1;
    private String editString = "";
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (editedIndex == comboBox1.SelectedIndex) return;
        if(editedIndex>0) comboBox1.Items[editedIndex] = editString; //Change the previous item
        if(comboBox1.SelectedIndex>=0)         //get new item parameters
        {
            editedIndex = comboBox1.SelectedIndex;
            editString = comboBox1.Items[editedIndex].ToString();
        }
    }

    private void comboBox1_Leave(object sender, EventArgs e)
    {
        if(editedIndex>=0)
            comboBox1.Items[editedIndex] = editString;
    }

    private void comboBox1_TextUpdate(object sender, EventArgs e)
    {
        if (editedIndex >= 0)
        {
            editString = comboBox1.Text;
        }
    }

    private void comboBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if(e.KeyData==Keys.Enter&&editedIndex>=0)
            comboBox1.Items[editedIndex] = editString;
    }

A: What if you create a property in code-behind and bind to that property?
First win is better debuggability, second win is that you can decide what to do when getting / setting the data.

A: I just had a similar problem: I had Winforms Combo box, VB.Net, Style= DropDown, and I wanted changes in the edit box to change the actual list item.
I also had multiple combo boxes that I wanted to have the same behavior.
Here's how I adapted the approach above:
Public Class frmDocEntry
    ...
    Private lastIdx As Integer = -1
    ...
    Private Sub cbAnyMV_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbRGBStringMV.Enter, cbRGBIntegerMV.Enter, cbRGBFloatMV.Enter, cbRGBDateMV.Enter
        ' comboBox.SelectedIndex will get *reset* to -1 by text edit
        lastIdx = sender.SelectedIndex
    End Sub

    Private Sub cbAnyMV_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbRGBStringMV.Leave, cbRGBIntegerMV.Leave, cbRGBFloatMV.Leave, cbRGBDateMV.Leave
        If lastIdx >= 0 Then
            sender.Items(lastIdx) = sender.Text
        End If
        lastIdx = -1
    End Sub

    Private Sub cbAnyMV_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbRGBStringMV.SelectedIndexChanged, cbRGBIntegerMV.SelectedIndexChanged, cbRGBFloatMV.SelectedIndexChanged, cbRGBDateMV.SelectedIndexChanged
        lastIdx = sender.SelectedIndex
    End Sub


text:
Q: How to make filename of file uploaded with getClientOriginalName make safe? In https://laravel.com/docs/9.x/filesystem#file-uploads I read as file custom file uploading :
However, keep in mind that the getClientOriginalName and getClientOriginalExtension methods are considered unsafe,
as the file name and extension may be tampered with by a malicious user. For this reason, you should typically prefer the
hashName and extension methods to get a name and an extension for the given file upload:

I do not like using of hashName I would prefer original name, making it safe.
I wonder what how file name can be unsafe ? I know that say login/username can be used to bypass login procedure.
But File name ? If it can be unsafe, how to modify ot to make safe ?
Thanks in advance!

A: A few things i had to implement to kinda avoid this security hole since nothing is safe nowadays.
1- Use a custom approach to name files, you can add a GUID for instance to the client file name.
2-Add  right after <form method="POST "enctype="multipart/form-data"
3-for the validation you can add
'image' =>  'file|mimes:jpg,jpeg,png,gif|max:1024',


text:
Q: Definir el valor del contador Tengo la siguiente función que definí para saber cuantas veces aparece el carácter "3" dentro de un string, pero también quiero que si este aparece 0 veces, tiene que devolver "@" en lugar de "0". Intente definir que si cant == 0 entonces cant="@". Pero me sigue retornando "0". Me pueden ayudar? les dejo el código acá abajo.
 `def cantAparicionesTres (histClin):
 cantidad=0
 for pos in range (len(histClin)):
   if histClin[pos]=="3":
        cantidad+=1
   if cantidad==0:
    cantidad=="@"
   return cantidad`

A: En lugar de asignar una @, estás comparando contra @
 if cantidad == 0:
    cantidad == "@"

La forma correcta es:
 if cantidad == 0:
    cantidad = "@"


text:
Q: using the .htaccess file I have written the following line of code in the .htaccess file..
Options +FollowSymLinks
RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)/$ $1.php [L]

RewriteRule ^honeymoon$ honeymoon.php [L]

to redirect http://localhost/site1/honeymoon.php to http://localhost/site1/honeymoon/
but am getting the error message from my browser..
Object not found!

The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

If you think this is a server error, please contact the webmaster.
Error 404
localhost
Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.16

What is the problem. Please some one help me.


text:
Q: Laravel - login for auth with Eloquent My Laravel is a fresh install.
routes.php
Route::get('/', 'MainController@idle');

Route::get('login', 'MainController@login');

Route::get('call', 'MainController@call')->before('auth');

MainController.php
class MainController extends Controller {

   public function idle() {
      return Response::json('idle');
   }

   public function login() {
      $user = array(
         'username' => Input::get('username'),
         'password' => Input::get('password')
      );

      if (Auth::attempt($user)) {
         return Redirect::intended();
      } else {
         return Redirect::route('login');
      }
   }

   public function call() {
      $users = User::all();
      return $users;
   }

}

filters.php
Route::filter('auth', function()
{
    if (Auth::guest()) return Redirect::guest('login');
});

Requesting:
http://l0calhost/survey/public/login
    InvalidArgumentException
Route [login] not defined.

Why does it say it is not defined?

A: Yes, since you added an AUTH filter
Route::get('call', array('before' => 'auth', 'uses' => 'MainController@call'));

Laravel will assume you have a route
Route::get('login', ...);

You will find something like this in your filters.php file and you can change it to whatever is best to you:
Route::filter('auth', function()
{
    if (Auth::guest()) return Redirect::guest('login');
});

You'll have to name your route too:
Route::get('login', array('as' = 'login', 'use' => 'MainController@login'));


text:
Q: Check null and execute one or another one line I have this code:
    $red = "value";
    $resp = (($red && get("aaa")) ?: getb("aaa"));

    print $resp;

    function get($aaa)
    {
        return "aaa";
    }

    function getb($aaa)
    {
        return $aaa . "bbb";
    }

But in this case $red && get("aaa") code is assigning to $resp, but instead, I want that if $red is not null, execute get("aaa") and if get("aaa") returns false it executes getb("aaa").
The code is doing fine when $red is null or get("aaa") is false, but when in this case is return true.
Is there anyway to do this in one line of code like this? Or I have to use ifs?


text:
Q: js oop style working in chrome but not in firefox I have this script and it runs fine in chrome (and in JS online validators) but firefox throws me this error:
screen.initialize is not a function
Is this syntax somehow not in accordance with standards?
$(document).ready(function() {

    screen = new Screen('t543f3r','user1','screen4',5);
    screen.initialize();

}

Here is the Screen class:
//Our screen object
function Screen(hashKey,username,screenName,layout) {

    this.hashKey = hashKey;
    this.username = username;
    this.screenName = screenName;
    this.layout = layout;

    //this.cacheRefreshInterval = 1000*60*5;
    this.checkLayoutInterval = 1000*60*5; //check for new cache every 5 minutes

}

    Screen.prototype.initialize = function() {

        var self = this;
        console.log('initializing screen '+this.screenName+' (layout is ['+this.layout+']) on player '+this.username+' using key '+this.hashKey);

        var time = self.checkLayoutInterval;
        setTimeout(function(){self.getValidLayout();}, time);
        console.log('getValidLayout() set for '+time);

    }

    Screen.prototype.getValidLayout = function() {

        var self = this;
        var url = self.findBaseUrl(true) + 'getValidLayout/'+self.hashKey;

        jQuery.ajax({
            async: true,
            url: url,
            success: function(result) {
                console.log('successfully fetched the valid screen layout: ['+result+']');
                if (result != self.layout) {
                    window.location.reload();
                }
            },
            error: function(result) {
                console.log('there was an error fetching the screen layout');
            },
            complete: function() {

                //setup next check
                var time = self.checkLayoutInterval;
                setTimeout(function(){self.getValidLayout();}, time);
                console.log('next getValidLayout() set for '+time);

            }
        });
    }

A: window.screen is a readonly property.  When you assign to it (because you didn't declare your screen as a var), the assignment gets ignored.


text:
Q: Minipage-Enumerate combination problems I have been trying to split the page to save space to make it look more appealing.
This is the code I came up with:
\subsection*{Services:}
\begin{enumerate}
    \begin{minipage}{0.45\textwidth}
    \item Bows
    \begin{itemize}
        \item Packaging for bows
        \item Bows for bottles
        \item Cosmetic bows
        \item Panettone-grind
    \end{itemize}
    \end{minipage}%
   \hfill
    \begin{minipage}{0.45\textwidth}
    \item Ribbons
    \begin{itemize}
        \item Plain ribbons
        \item Motiv ribbons
        \item Individualized ribbons
    \end{itemize}
\end{minipage}
\end{enumerate}

and this is how it looked:

For the most part it is what I wanted it but I wanted the numbers to be at the same level not have that weird offset.
I have also tried to make a line in between the minipages. this is how I thought I can do it:
\subsection*{Services:}
\begin{enumerate}
    \begin{minipage}{0.45\textwidth}
    \item Bows
    \begin{itemize}
        \item Packaging for bows
        \item Bows for bottles
        \item Cosmetic bows
        \item Panettone-grind
    \end{itemize}
    \end{minipage}%
  % \hfill
    \begin{minipage}{0.45\textwidth}
    \begin{tabular}{|p{\textwidth}}
    \item Ribbons
    \begin{itemize}
        \item Plain ribbons
        \item Motiv ribbons
        \item Individualized ribbons
    \end{itemize}
    \end{tabular}
\end{minipage}
\end{enumerate}

And this is how it turned out :

btw I don't know what to do, I thought I can probably do it by manipulating margins for any of these components but I'm fairly new and don't know what to do.
Thank you very much

A: Using multicols may be a good solution, I think: simple and it works.
\documentclass{article}
\usepackage{multicol}
\setlength\columnseprule{0.4pt}

\begin{document}
\subsection*{Services:}

\begin{multicols}{2}
  \begin{enumerate}
    \item Bows
    \begin{itemize}
        \item Packaging for bows
        \item Bows for bottles
        \item Cosmetic bows
        \item Panettone-grind
    \end{itemize}
\columnbreak
    \item Ribbons
    \begin{itemize}
        \item Plain ribbons
        \item Motiv ribbons
        \item Individualized ribbons
    \end{itemize}
\end{enumerate}
\vspace*{\fill}
\end{multicols}

\end{document}

A: It is quite simple to obtain this layout with the tasks package and its eponymous environment:
\documentclass{article}
\usepackage{tasks}

\begin{document}

\subsection*{Services:}
\begin{tasks}[label=\arabic*. ](2)
    \task Bows
    \begin{itemize}
        \item Packaging for bows
        \item Bows for bottles
        \item Cosmetic bows
        \item Panettone-grind
    \end{itemize}
%
    \task Ribbons
    \begin{itemize}
        \item Plain ribbons
        \item Motiv ribbons
        \item Individualized ribbons
    \end{itemize}
\end{tasks}%

\end{document}

A: (too long for a comment, hence posted as an answer)
If I (a) make your code snippet minimally compilable by prefixing it with \documentclass{article} \begin{document} and affixing \end{document} to it and (b) replace both instances of \begin{minipage}{0.45\textwidth} with \begin{minipage}[t]{0.45\textwidth}, i.e., if I insert the [t] placement specifier in two places, I get the following result:

If you get something vastly different, do please tell us which document class you employ and which list-related packages (such as enumitem and enumerate) are loaded by your document.


text:
Q: Обработка некорректного пользовательского ввода Есть функция для консольного приложения. Она должна возвращать 's' или 'h', если таковые символы были введены. Если же ввод не соответствует одному из них, то цикл повторяется. Проблема в том, что если было введено больше одного символа и первый символ это 's' или'h', то функция возвращает значение. Как изменить ее так, чтобы при количестве символов больше одного, значение В ЛЮБОМ СЛУЧАЕ не возвращалось?
char getChoice()
{
    char choice;

    while(choice != 'h' && choice != 's')
    {
        std::cout << "Hit or Stand?(h/s)...";
        std::cin >> choice;
        if (std::cin.fail())
        {
            std::cin.clear();
            std::cin.ignore(32767,'\n');
        }
        std::cin.ignore(32767,'\n');

    }
    return choice;
}

A: Возвращать из функции символ в любом случаи нужно. Другое дело, если вы хотите продолжить цикл пока символ не будет одиночным. Если да, то так:
char getChoice()
{
    char choice;
    std::cout << "Hit or Stand?(h/s)...";
    while ((std::cin >> choice  && choice != 'h' && choice != 's')
        || std::cin.peek() != '\n')
    {
        std::cout << "Hit or Stand?(h/s)...";
        if (std::cin.fail() )
        {
            std::cin.clear();
            std::cin.ignore(32767, '\n');
        }
        std::cin.ignore(32767, '\n');
    }
    return choice;
}

std::cin.peek() выдает следующий символ буффера, но не считывает


text:
Q: Finilize and GC.Collect I try to understand, why there is different behavior.
Code 1 different from Code 2 just with comment line Console.WriteLine(h.ToString());.
But in this case Console.Beep(); in Code 1 executes before static void Main(string[] args) finished.
In Code 2 Console.Beep(); executes only when static void Main(string[] args) finished (process terminated?).
Can you please explain me, why is it so?
I tried to call codes with [+/-] Optimization setting- looks like it doesn't depend on it.
Right now i dont have WinDbg,- mb the answer in decompiled code.
Code 1:
class Program
{
    static void Main(string[] args) {
        var h = new Haha();

        // Console.WriteLine(h.ToString());

        GC.Collect();
        GC.WaitForPendingFinalizers();

        /* Console.Beep() calls here */

        Console.ReadKey();
    }
}

public class Haha
{
    ~Haha() {
        Console.Beep();
    }
}

Code 2:
class Program
{
    static void Main(string[] args) {
        var h = new Haha();

        Console.WriteLine(h.ToString());

        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.ReadKey();

        /* Console.Beep() calls here */
    }
}

public class Haha
{
    ~Haha() {
        Console.Beep();
    }
}

A: In the first example:
var h = new Haha()

the variable isn't referenced anywhere, so it is removed. In this way the Haha() isn't referenced anywhere just after being created and so can be GC at any time.
In the second example the variable h is referenced, so it has a "maximum" lifetime of the block in which it is referenced (so the whole main). The compiler and the GC could detect the "last" use of h and consider it to be unreferenced just after the Console.WriteLine (the last use of h) (shortening its lifetime), but clearly don't do so.
Note that if you run your program in Release mode + Run without Debugger, the Code 2 will give (at least it gives to me) the same result as Code 1. The debugger, to make it easier to debug, guarantee that all the references are valid until the end of the block where they are declared (see https://stackoverflow.com/a/7165380/613130) Running the program in Release mode + Run without Debugger we solve this.
Done some tests: to have the shorter lifetime you need to have (at the same time): Debug Info (Properties->Build->Advanced->Debug Info) at none or pdb-only, plus run the program without debugger (Ctrl+F5). If you set the Debug Info at Full, then a DebuggableAttribute is injected in the assembly, and the CLR won't try to shorten the lifetime of the variables. The same if you run with a debugger. If you compile by command line, setting the option /debug is equivalent to /debug:full (see https://msdn.microsoft.com/en-us/library/8cw0bt21.aspx)


text:
Q: Getting all info on a Javascript variable I'm not a JavaScript Wizard by a long shot. But I am a web-developer and so I need to know my way around it at least a bit.
Something I'll often do is simply alert a variable to see what it is.
However, the problem is that I'll often get a result like: "object HTMLInputElement". To me this means little to nothing. Sure I can look it up, but I need to alert children() of children() of children(), etc...
I've tried walking through the JavaScript with Firebug, but for some reason this is very slow. Firefox hangs when I start a debug session, for every single debug session and I don't know why.
So, I want to inform if there is a way to get detailed info on variables some other way. Or a system I can use to work with to make things easier.

A: I find the developer tools in Chrome work quite well, giving a good amount of detail on demand (usually just hovering the mouse over the variable in the script tab; if that variable is a structured object, a little tree control appears and you can drill down). But then, I don't have your Firebug issue either (or at least, not often anymore).
Debugging with alert is very time-wasteful and, as you've found, frustrating; if at all possible I'd look at using a real debugger (like Chrome's Dev Tools; I've also heard good things about Opera's).

A: This should help:
http://www.openjs.com/scripts/others/dump_function_php_print_r.php

A: The easiest way to inspect a javascript variable is with a debugger. If Firebug is not working out for you try using Google Chrome, it has an inspector built in.
Btw - not sure what you mean by "start a debug session". If you have firebug installed, you should simply be able to click on the firebug icon on the bottom right of your browser. Go to the script tab, and select from the drop down whatever js file you want, stick in a break point (just left-click on the margin) and refresh the page. I've never had a problem with Firebug, it's always worked extremely well. I strongly advise figuring out whatever your issue with it is, it will make your life a million times easier.

A: Using any of the browser dev tools, including IE9, you can use console.log to get the variable output on the console. What information this gives you will vary by browser, but with Firebug it allows you to explore the variable in the DOM inspector tab, with full access to all properties and functions (you can even copy the content of a function to paste elsewhere).
For instance:
var foo = {};

// Do lots of stuff with foo

if (typeof(console) !== "undefined" && console.log) { // prevent errors when console not open, ideally all console calls should be removed before going into production
    console.log(foo);
}

This has the advantage that it doesn't require any break points, so no slow step-debugging. It won't solve everything though, you'll often still need the debugger.


text:
Q: Preseed Ubuntu / Debian - Partitioning: prevent "Partition 1 does not start on physical sector boundary." Preseeding of Ubuntu / Debian works correct - system is bootable.
But fdisk -l is resulting following:
Disk /dev/sda: 50 GiB, 53687091200 bytes, 104857600 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: dos
Disk identifier: 0x000e157a

Device     Boot    Start       End  Sectors   Size Id Type
/dev/sda1             63    192779   192717  94.1M 83 Linux
/dev/sda2  *      192780   1172744   979965 478.5M 83 Linux
/dev/sda3        1172745  96470324 95297580  45.5G 83 Linux
/dev/sda4       96470325 104856254  8385930     4G 82 Linux swap / Solaris

Partition 1 does not start on physical sector boundary.
Partition 2 does not start on physical sector boundary.
Partition 3 does not start on physical sector boundary.
Partition 4 does not start on physical sector boundary.

My current partitioning parameters in the preseed are:
d-i partman-lvm/device_remove_lvm                   boolean true
d-i partman-auto/purge_lvm_from_device              boolean true
d-i partman-md/device_remove_md                     boolean true
d-i partman-lvm/confirm                             boolean true
d-i partman/alignment                               select cylinder
d-i partman/confirm                                 boolean true
d-i partman-basicfilesystems/no_swap                  boolean false
d-i partman-partitioning/confirm_write_new_label    boolean true
d-i partman/choose_partition                        select finish
d-i partman/confirm_nooverwrite                     boolean true
d-i grub-installer/only_debian                      boolean true
d-i grub-installer/bootdev                                      string /dev/sda
d-i partman-auto/disk                               string /dev/sda
d-i partman-auto/method                             string regular
d-i partman-auto/expert_recipe string                         \
      boot-root ::                                            \
              100 50 100 free                                 \
                          $gptonly{ }                         \
                          $primary{ }                         \
                          $bios_boot{ }                       \
                          method{ biosgrub }                  \
              .                                               \
              500 50 500 ext2                                 \
                      $primary{ } $bootable{ }                \
                      method{ format } format{ }              \
                      use_filesystem{ } filesystem{ ext2 }    \
                      mountpoint{ /boot }                     \
              .                                               \
              500 10000 1000000000 ext4                       \
                      $primary{ }                             \
                      method{ format } format{ }              \
                      use_filesystem{ } filesystem{ ext4 }    \
                      mountpoint{ / }                         \
              .                                               \
              200% 500 200% linux-swap                        \
                      $primary{ }                             \
                      method{ swap } format{ }                \
              .

How to avoid the Partition {n} does not start on physical sector boundary error. How to set the correct starting sector and sector size in partman while preseeding?

A: Change your d-i partman/alignment parameter to optimal instead of cylinder. This should fix the issue.


text:
Q: Complex MySQL join with dynamic where Here are my two tables that I'm trying to join...
    name: notifications
-------------------------------------------
content | position | member  | contentType
-------------------------------------------
test a  | manager  | testera | Email
test b  | manager  | testera | Email
test c  | manager  | testera | SMS
-------------------------------------------

    name: position
-----------------------------------------------
position  |  member  |  getsEmail  |  getsSMS
-----------------------------------------------
manager   |  testera |  1          |  0
employee  |  testerb |  0          |  1
-----------------------------------------------

I would like to return the rows from the "notifications" table where the member is "testera", and the contentType from the "position" table is equal to "1".  So for the above table data, I want to get the first two rows from "notifications" returned since the contentType of "Email" is allowed in the position table.
Is this possible to do with my table structure?

A: Try this one:
SELECT n.*
  FROM notifications n
  JOIN position p
    ON n.member = p.member
 WHERE (n.contentType = 'Email' AND p.getsEmail = 1)
    OR (n.contentType = 'SMS' AND p.getsSMS = 1)

Result:
╔═════════╦══════════╦═════════╦═════════════╗
║ CONTENT ║ POSITION ║ MEMBER  ║ CONTENTTYPE ║
╠═════════╬══════════╬═════════╬═════════════╣
║ test a  ║ manager  ║ testera ║ Email       ║
║ test b  ║ manager  ║ testera ║ Email       ║
╚═════════╩══════════╩═════════╩═════════════╝

See this SQLFiddle
SQLFiddle with more data

A: Try:
select n.*
from notifications n
join position p
  on n.member = p.member and
     case n.contentType when 'Email' then p.getsEmail
                        when 'SMS' then p.getsSMS end = 1
where n.member = 'testera'

SQLFiddle here.

A: Here you can define the contenttype is email or sms
$contenttype="Email";
$query="select * from notification,position where position.member='testera' and position.gets".$contenttype."='1' ";


text:
Q: UDF or standard IF function for date range? I am trying to create a range from numbers in a column, and create a range. For example,
column F:
1899
1912
1915
1918
1929
1934
1935
1936
...

So as soon as 1934, 1935, 1936 sequence starts, it would capture 1934 and iterate through until the difference isn't 1.
The result for this example would be:
1934 - 1936.

Once I create these date ranges, I would use text to columns by the "-" delimiter to create begin and end date columns.
The difficulty in this is comparing another column and making sure the dates are based on a particular title.
So: IF(Title 1 = Title 2, (IF date 2 - date 1 = 1, increment to check date 3 - date 2 = 1, otherwise = date 1)).
I could try to nest many IF statements, but that would get nasty, plus no idea how many dates to compare per title.
Iteration seems like it would be much easier by creating a sub or UDF in VBA, but I haven't found any examples on here (or elsewhere) that may be helpful.

A: Retrieving the start and stop of the first group of one-day-sequences is not too difficult with the AGGREGATE function. In H2:I2 as a standard formula,
'in H2
=INDEX(F$2:F$15,AGGREGATE(15,6,ROW($1:$14)/((F$3:F$16-$F$2:$F$15)=1), 1))
'in I2
=INDEX(INDEX(F:F, MATCH(H2,F:F, 0)):F$15,AGGREGATE(15,6,ROW($1:$14)/((INDEX(F:F, MATCH(H2,F:F, 0)+1):F$16-INDEX(F:F, MATCH(H2,F:F, 0)):$F$15)<>1), 1))

If you wanted to combine them then substitute all references to H2 in the second formula with the first formula.

A: I understand you need a way to get dates "ranges" while I still don't get the "comparing another column" thing
as for the first issue you may try this (commented) code:
Option Explicit

Sub main()
    Dim fictitiousRng As Range, area As Range
    Dim arr As Variant
    Dim iCell As Long

    With Worksheets("numbers") '<--| reference your worksheet (change "numbers" to your actual worksheet name)
        With Intersect(.UsedRange, .Columns("F")).SpecialCells(xlCellTypeConstants, xlNumbers) '<-- reference its column "F" non blank cells with numeric data only
            With .Offset(, .Parent.UsedRange.Columns.Count) '<--| reference referenced range offsetted 1 colum to the right
                .FormulaR1C1 = "=""A"" & RC6" '<--| fill its content with a "fictitiuous" range address by placing an "A" in front of corresponding number in column "F"
                Set fictitiousRng = Range("B1") ' set a initial range for 'fictitiousRng' not to bother for subsequent first call of 'Union()' method
                For Each area In .Areas '<--| loop through referenced range areas (i.e. cells "groups")
                    For iCell = 2 To area.Cells.Count '<--| loop through current area cells
                        Set fictitiousRng = Union(fictitiousRng, Range(area.Cells(iCell, 1).value)) '<--| update 'fictitiousRng' with the cell corresponding to the current fictitious range address
                    Next iCell
                Next area
                arr = Split(Replace(Replace(Intersect(fictitiousRng, Columns(1)).Address(False, False), "A", ""), ":", " - "), ",") '<--| get the fictitious range address, remove "A"s and substitute "." with "-" and then write final "numbers" into an array
                .ClearContents '<-- clear referenced range, i.e. cells with fictitious addresses
                .Cells(1, 1).Resize(UBound(arr) + 1).value = Application.Transpose(arr) '<--| write array content into referenced range cells starting from its first cell
            End With
        End With
    End With
End Sub

it writes the dates "ranges" in the first not used column of the same column "F" dates worksheet

A: If you don't mind having the formula broken out into several columns, here's an IF() statement example on how to extract the Begin & End Years:

=IF(B13>1,"",IF(B14<2,IF(C12="",A13,C12),IF(ISNUMBER(C12),C12&"-"&A14,A13&"-"&A14)))
Explanation
Column B - Find difference between years
Column C - Elegant nested IF() formula ;)
Column D - Left() 4 character if length is > 4
Column E - Right() 4 character if length is > 4

A: This will do the job, it will take cells in column F and print your output in column G. If there is a range of years (ex: 1934-1935-1936), it will put it in a single cell as a string.
Sub range_dates()
Dim cel As Range
Dim iRow As Long, n As Long
Dim title As String, nextTitle As String
iRow = 2
n = 0
For i = 2 To 15
    Set cel = Cells(i, "F")
    title = Cells(i, "E").Value
    nextTitle = Cells(i + 1, "E").Value
    diff = Cells(i + 1, "F").Value - cel.Value

    If diff = 1 And title = nextTitle Then
        firstDate = cel.Value - n
        n = n + 1
    Else
        Cells(iRow, "H").Value = cel.Value
        Cells(iRow, "G").Value = title
        If n > 0 Then
            Cells(iRow, "H") = "'" & firstDate & " - " & cel.Value
            n = 0
        End If
        iRow = iRow + 1
    End If
Next
End Sub

I do know this code is not the most optimized, but as of now it's the one i have to share. Feel free to improve it :)
EDIT: I added the title conditions and changed the output to prevent excel from changing the string to a date format


text:
Q: How to send the string array of values in one key word using post method to the server I am using this code but i am not able to send the string array:
httpclient = new DefaultHttpClient();
httppost = new HttpPost(Call_Server.UPLOAD_VIDEO);
MultipartEntity mpEntity = new MultipartEntity(
        HttpMultipartMode.STRICT);
mpEntity.addPart("FILE_UPLOAD", new FileBody(videofile));
mpEntity.addPart("from_email", new StringBody(
        Call_Server.useremail));
mpEntity.addPart("recipient_emails", new StringBody(
        AddressArray));

httppost.setEntity(mpEntity);

HttpResponse response = httpclient.execute(httppost);

HttpEntity resEntity = response.getEntity();

A: You can do something like this.
// Prepare Category Array
for (String mBusinessID : mSelectedCategoryArray) {
    reqEntity.addPart("CategoryCBG[]", new StringBody(mBusinessID));
}

Just add [] with you array tag and paas values in a loop in it.
Here CategoryCBG is the array tag. You can pass your values in this tag by using loop. it will post as an array on server.
Here is the complete code how I used it :
public String executeMultipartPost() throws Exception {
    try {

        ByteArrayOutputStream mByteOutputStream = new ByteArrayOutputStream();

        mSelectedImage.compress(CompressFormat.JPEG, 75, mByteOutputStream);

        byte[] mImageByteDate = mByteOutputStream.toByteArray();

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(CONSTANTS.MAIN_URL_GLOBAL + CONSTANTS.BUSINESS_REGISTRATION_TAG);

        ByteArrayBody mImageByteArray = new ByteArrayBody(mImageByteDate, Long.toString(System.currentTimeMillis()) + ".jpg");

        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        reqEntity.addPart("logo_img", mImageByteArray);

        reqEntity.addPart("name", new StringBody(txtBusinessName_business_registration.getText().toString()));
        reqEntity.addPart("email", new StringBody(txtBusinessEmail_business_registration.getText().toString()));
        reqEntity.addPart("contact_phone", new StringBody(txtBusinessPhone_business_registration.getText().toString()));
        reqEntity.addPart("link_url", new StringBody(txtBusinessWebsite_business_registration.getText().toString()));
        reqEntity.addPart("Address", new StringBody(txtStreetAddress_business_registration.getText().toString()));
        reqEntity.addPart("City", new StringBody(txtCity_business_registration.getText().toString()));
        reqEntity.addPart("State", new StringBody(txtState_business_registration.getText().toString()));
        reqEntity.addPart("Zip", new StringBody(txtZip_business_registration.getText().toString()));
        reqEntity.addPart("details", new StringBody(txtDetail_business_registration.getText().toString()));
        reqEntity.addPart("products", new StringBody(txtService_business_registration.getText().toString()));

        // Prepare Category Array
        for (String mBusinessID : mSelectedCategoryArray) {
            reqEntity.addPart("CategoryCBG[]", new StringBody(mBusinessID));
        }

        postRequest.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        mStringBuilder = new StringBuilder();

        while ((sResponse = reader.readLine()) != null) {
            mStringBuilder = mStringBuilder.append(sResponse);
        }

        return mStringBuilder.toString();

    } catch (Exception e) {
        e.printStackTrace();
        // handle exception here
        Log.e(e.getClass().getName(), e.getMessage());

        return "error";

  }
    }

Update
To cancel ongioing uploading you can use
httpClient.getConnectionManager().shutdown();


text:
Q: Why import assignment makes module declaration with a relative module name valid? This particular declaration will compile (and  actually works as expected, that is, providing Prop importable declaration):
import _ = require("./_core");

declare module "./_core" {
  export var Prop: number;
}

Without assigned import though one will get TS2436: Ambient module declaration cannot specify relative module name..
My question is: why this import makes this declaration valid and where in documentation it's covered, since I'm actually failing to find any relevant explanation.
Just to clarify - "./_core" is actually a _core.d.ts file lying alongside with this particular declaration file.


text:
Q: SQLCLR Assembly deployment failed because assembly failed verification In case someone else runs into this problem.

Error:  SQL72014: .Net SqlClient Data Provider: ... CREATE ASSEMBLY
  for assembly 'Assembly.Name' failed because assembly 'Assembly.Name'
  failed verification. Check if the referenced assemblies are up-to-date
  and trusted (for external_access or unsafe) to execute in the
  database. CLR Verifier error messages if any will follow this message
  [token  0x02000003] Type load failed.

The SQLCLR assembly builds successfully but couldn't be deployed. When the assembly is accessed by regular a .NET application (outside of SQL Server), it will give a TypeLoadException:

Could not load type 'Type.In.Assembly' from assembly
  'Assembly.Name, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null' because the format is invalid.

The problem is related to the User-Defined Type (UDT) within the assembly.

A: The culprit is

System.Runtime.InteropServices.StructLayoutAttribute

When we define a UDT using
[Microsoft.SqlServer.Server.SqlUserDefinedType(Format.Native)]
and the UDT is a class (instead of a struct) it is required to also define a
[StructLayout(LayoutKind.Sequential)] on the class.
The problem was my UDT class was inheriting from a base class. The StructLayout must be defined on the base class too.


text:
Q: Issue in PlayFramework 2.7.0, sbt-play-ebean 5.0.1 java.lang.ArrayIndexOutOfBoundsException: 65791 I'm using following plugins & Versions
scalaVersion := "2.11.6"
sbt.version=1.2.7
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.7.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "5.0.1")

I'm getting following stack trace:
java.lang.ArrayIndexOutOfBoundsException: 65791
[error]     at scala.tools.asm.ClassWriter.findItemByIndex(ClassWriter.java:1755)
[error]     at scala.tools.asm.MethodWriter.getSize(MethodWriter.java:2045)
[error]     at scala.tools.asm.ClassWriter.toByteArray(ClassWriter.java:827)
[error]     at scala.tools.nsc.backend.jvm.GenASM$JBuilder.writeIfNotTooBig(GenASM.scala:529)
[error]     at scala.tools.nsc.backend.jvm.GenASM$JPlainBuilder.genClass(GenASM.scala:1343)
[error]     at scala.tools.nsc.backend.jvm.GenASM$AsmPhase.emitFor$1(GenASM.scala:197)
[error]     at scala.tools.nsc.backend.jvm.GenASM$AsmPhase.run(GenASM.scala:203)
[error]     at scala.tools.nsc.Global$Run.compileUnitsInternal(Global.scala:1500)
[error]     at scala.tools.nsc.Global$Run.compileUnits(Global.scala:1487)
[error]     at scala.tools.nsc.Global$Run.compileSources(Global.scala:1482)
[error]     at scala.tools.nsc.Global$Run.compile(Global.scala:1580)
[error]     at xsbt.CachedCompiler0.run(CompilerInterface.scala:130)...

A: scalaVersion := "2.11.6"
sbt.version=1.2.7
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.7.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "5.0.1")

sbt-play-ebean 5.0.1 has Scala Version 2.13.0-M5,2.12, and 2.11 supported.
So maybe you can try to use Java 8 Version because java 9 and up has a lot of incompatibilities.
Hope it helps.


text:
Q: How do I project to a dictionary with a custom type using Linq to SQL? I am attempting to use Linq to project each row from a DB query into a dictionary that has a custom type as its value. I am unsure of the LINQ syntax to do this?
This is my current attempt (which doesn't compile, but should demonstrate what I am trying to do). I am having trouble with the 'select new...' part.
public class MyClass
{
   public Dictionary<int, CustomType> dict;
}

public class MyType{
   string Name;
   decimal Value;
}

var result = (from t in table
              select new {
                 t.Id,
                 new MyType(t.Name,t.Value)
              }).AsEnumerable().ToDictionary();

ANSWER:
Thanks Jason. I just used properties and automatic initialisers rather than a constructor. The working code resembles this (any improvements to this are welcome):
public class MyType {
    public string Name {get;set;}
    public decimal Value { get; set;}
}

Dictionary<int, CustomType> dict;

dict = (from t in table
        select new {
           id = av.Account.Id,
           mt = new MyType { Name = t.Name, Value = t.Value }
        }).ToDictionary(item => item.id, item => item.mt);

A: MyType doesn't have a constructor that takes two arguments.
Add the following to the definition of MyType:
public MyType(string name, decimal value) {
    Name = name;
    Value = value;
}

Further, you did not give the anonymous type member defined by
new MyType(t.Name, t.Value)

a name; try changing that line to:
MyType = new MyType(t.Name, t.Value)

The compiler will yell at you that it can not discern a name for this anonymous member.
Finally, there isn't an overload of ToDictionary that has no arguments. Assuming you named the above anonymous member to be MyType, change the call to ToDictionary to be
....ToDictionary(item => item.Id, item => item.MyType);


text:
Q: I want to know a similar function for Array_contains in BigQuery. I am trying to get results for multiple values present in Array of Struct field I have a Array of Struct field containing values like- field_name= [1,2,3,4]
I want to identify rows where field_name NOT contains values 2 OR 3 in BigQuery
Sample Data: Assume I have 4 rows of data:
row_id = 1 , field_name = [1,2,3,4]
row_id = 2 , field_name = [1,2]
row_id = 3 , field_name = [3,4]
row_id = 4 , field_name = [4]
What I want- Expected Result: row_id = 4 , field_name = [4]
I tried with UNNEST and EXISTS, UNNEST gives output as row_id = 1, row_id = 2, row_id = 3 & row_id = 4

A: Consider below approach
select * from your_table t
where not exists (
  select value
  from t.field_name as value
  where value in (2,3)
)

if applied to sample data in your question - output is

if you would use where value in (1,2) - output were


text:
Q: window.addEventListener not working but window.onhashchange working? window.addEventListener("hashchange",myFunction);
console.log(window.onhashchange); //This one prints NULL

window.onhashchange = myFunction;
console.log(window.onhashchange); // This one working fine.

function myFunction() {
    alert("The anchor part has changed!");
}

Why I am not able to attach event listener using the addEventListener method ? But window.onhashchange working fine
EDIT I am indeed using the 'hashchange' not 'onhashchange' it was a typo.

A: There is no onhashchange event. There is a hashchange event:
window.addEventListener('hashchange', myFunction, false);

Likewise, there is no onclick event, but there is a click event:
element.addEventListener('click', someFunction, false);

testing on* properties for bound events is not an appropriate way to verify that a callback is bound. For testing, you'll have to trigger the event in some manner and have a test within the callback:

window.onhashchange = function () {
  console.log('onhashchange property works');
};

window.addEventListener('hashchange', function () {
  console.log('addEventListener method works');
}, false);
Click this to test

Successfully bound callbacks will not be exposed via the property.


text:
Q: one button to stop all audio AVAudioPlayer please keep in mind that I am a newbie therefore not very experienced: I have several audio files playing triggered by a button, each time a button is pressed, all other sounds stop. Now I want to creadte a button which stops whatever is playing at the moment. Also, each time I press one of the button, the music doesn t start from the beginning, but from the point in time when it was interrupted. Thank you in advance, here is a snippet:
- (IBAction)playSound1 {
if ((self.sound2Player.playing) ||  (self.sound3Player.playing)|| (self.sound4Player.playing)||(self.sound5Player.playing)||(self.sound6Player.playing)||(self.sound7Player.playing))
    [self.sound2Player stop];
    [self.sound3Player stop];
    [self.sound4Player stop];
    [self.sound5Player stop];
    [self.sound6Player stop];
    [self.sound7Player stop];
    [self.sound2Player stop];

[self.sound1Player play];

A: Please use this
- (IBAction)stopSound
 {

    [self.sound1Player stop];
    [self.sound2Player stop];
    [self.sound3Player stop];
    [self.sound4Player stop];
    [self.sound5Player stop];
    [self.sound6Player stop];
    [self.sound7Player stop];
    [self.sound2Player stop];
}

If you again want to play where it stop so why you are stopping the player use [avPlayer pause] to work instead of [self.avPlayer stop]; then when you play again they will start from where you have stopped them.


text:
Q: Making a simple text log file I have a model and want to export the run parameters to a log file. The idea is to get the following example into a decent text export:
a = 1;
b = 2;
c = 3;

p = Style[Grid[{
    {"Parameter a ", a},
    {"Parameter b ", b},
    {"Parameter c ", c}
    }]
  , Bold, Blue]

Export["_log.txt", p];

The problem here is, that the output includes all the Grid commands, which I obviously don't want. Just a somewhat neatly arranged text file.
More precisely: the above code gives the following log file>

The log file I'd like to have should look like>

A: You have wrapped your data with UI specific calls that makes sense only the UI. And then wanted to export it to a text file, which is not a good way to go about things.
You should have your data separate from the UI specific wrappers, then you can export your data on its own, or use the wrappers on it for UI display. Look at InputForm[p] and you can see what you have now.

Instead you can do this
a = 1;
b = 2;
c = 3;
data = {{"Parameter a ", a}, {"Parameter b ", b}, {"Parameter c ", c}};
p = Style[Grid[data], Bold, Blue]

SetDirectory[NotebookDirectory[]]
Export["foo.txt", data]

And this is the text file


text:
Q: Spark Structured Streaming Protobuf ScalaPB 'java.lang.NoSuchMethodError" I am new to use Spark Structured Streaming 2.2.2 to decode protobuf messages.
I used ScalaPB standalone to generate the scala code from my .proto file. Now I want to parse from Kafaka messages.
This is my code.
import scalapb.spark.Implicits._
val pbDs = kafkaDs
      .map(row => row.getAs[Array[Byte]]("value"))
      .map(Person.parseFrom(_).entries.head)

and build.sbt. I add scalapb-runtime as dependancy because Person is generated by ScalaPB standalone compiler.(refer to https://scalapb.github.io/scalapbc.html)
lazy val myDep = Seq(
    "com.thesamet.scalapb" %% "sparksql-scalapb" % "0.9.0",
    "com.thesamet.scalapb" %% "scalapb-runtime" % "0.9.0")

But scalaPB gave error:
java.lang.NoSuchMethodError: org.apache.spark.sql.catalyst.expressions.objects.StaticInvoke$.apply$default$6()Z
    at frameless.TypedEncoder$$anon$1.toCatalyst(TypedEncoder.scala:51)
    at frameless.TypedExpressionEncoder$.apply(TypedExpressionEncoder.scala:29)
    at scalapb.spark.Implicits$class.typedEncoderToEncoder(TypedEncoders.scala:125)
    at scalapb.spark.Implicits$.typedEncoderToEncoder(TypedEncoders.scala:128)

I googled the error and say it's becos frameless is complied against Java 6. Is that true? How does everyone else do this?


text:
Q: Can I insert a file in my standalone python program to be downloaded by users as a template file I'm doing python coding self study and not a programmer.. this is my first entry here. Not sure if this is doable, (I have a very little knowledge about programming) but here it is.
Is it possible to insert a file, like a template, for the user to download in a standalone program? Tried searching online but have not been successful, maybe I just don't know how to term it.
Any suggestion is very welcome.. thanks in advance..
When user clicks 'Download template', they can download an Excel template
User can download the template that I inserted in a program, that is if inserting file in a standalone program is possible.

A: I think what you are asking is if you can embed a file into the .py itself (which is what I think you mean when you are saying standalone), to which the answer is no. It might be possible to compile the program into an exe using pyinstaller, but not sure how efficient or feasible that is.
If you really need this to be only one .py, I would suggest hosting it somewhere online for free and having python download the file from the url.
If I am being honest, the best way to go about doing this is to ditch the "standalone program" requirement and just shipping the template in a zip file with the .py file.
Edit: Creating the file on-demand
This slipped my mind as an idea (probably because it is the most involved and difficult way to do it), but you may be able to use something like XSLX writer to create the excel file on demand. Would require you to code a function that makes a brand new excel file from scratch, but this would not require downloads, zip files, or an executable, so it would be truly standalone (minus the added pip dependency).
Be warned though, I think python and XLSX can be finicky at times.


text:
Q: Script error in ArcGIS 10.2 I have a problem when using some geoprocessing tools in ArcGIS 10.2, such as "Merge". The message that appears is an error has occurred in the script on this page. I've seen this is a quite common error, but I've tried all the options I've seen on different blogs and StackExchange answer and nothing has worked.
Things I've tried so far:

*

*Establishing Internet Explorer as the default browser.

*Establishing Microsoft Edge as the default browser.

*Replacing the "Stylesheet" folder´s files as indicated on this link https://support.esri.com/en/technical-article/000011008

*Repairing ArcGIS through the Desinstallation Procedure, but at some point this message appears -see pictures- (and can´t find this file) so I can´t continue.

Any suggestions?

A: That error message you are getting during the install process needs the original installation disc. How was ArcMap installed on your machine? You need to contact your IT support to either download the 10.2.2 iso from myESRI or get them to give you the install DVD. That will allow the repair process to continue.


text:
Q: JSP, JSTL, Check NaN I have a JSP in which I am using <fmt:formatNumber>. The problem is that we don't know that the value coming to JSP will be a number or a String. If a string is coming it throws NumberFormatException.
I tried to look in JSTL, but no success, somewhere it was mentioned if I check value == value it returns false if String but no success. Please see the code below.
<fmt:formatNumber type="currency" currencySymbol="$" maxFractionDigits="2" minFractionDigits="2" >${primary.value}</fmt:formatNumber>

Any help would be appreciated.
Thanks in advance.

A: This might be a solution to your problem. You'll get an exception when you try to add a String to 0.
<c:catch var="catchString">
  <c:set value="${0 + primary.value}" />
</c:catch>
<c:choose>
<c:when test="${not empty catchString}">
  ${primary.value}
</c:when>
<c:otherwise>
  <fmt:formatNumber type="currency" currencySymbol="$" maxFractionDigits="2" minFractionDigits="2" >${primary.value}</fmt:formatNumber>
</c:otherwise>
</c:choose>

A: Another solution is to create a custom tag library to check wether you're dealing with a String or with a number, or even to manually format your number (your choice).
I don't have time to work out the example for you but I found this
Tutorial
where they explain step by step on how to implement everything.
Edit: More info @Oracle
I hope you get it to work, if not let me know and I'll try to help you out tomorrow.


text:
Q: Suggest a best algorithm to encrypt XML file in C#.NET? I have to encrypt XML file and send in network to place in a private server.
My other application will decrypt and import to SQL the file by giving the actual Public key.
Could you please suggest me best way for this.
File: XML Type
Possible size: Up to 250 MB
Technology: C#.NET 2008

A: Use XML encryption. It is supported directly in .NET through the EncryptedXml class.
There is an example on MSDN here: How to: Encrypt XML Elements with Asymmetric Keys.
Note that you should use the public key to encrypt and the private key to decrypt (and not the other way around as you wrote in the question).

A: Upload the file using SSL/TLS (e.g., with HTTPS or a Socket+SslStream) and let the server require the client to present an X.509 client certificate.

A: I would suggest using the RijndaelManaged class.  This is a good example of its use.
Here is more the AES Algorithm.


text: Q: Are all elements of groups Garside elements? Here in the definition of Garside Element, it seems that if the monoid here is a group, then all its elements are Garside elements simply because all elements are both left and right divisors of any group element and of course the set of all these elements generate the group itself. But is this true?


text:
Q: Uniquely Append to Array on Conflict PostgreSQL I've got two columns in PostgreSQL, hostname and ip. Hostname is the primary key and ip is an array of IPs.
I want to be able to insert IPs for a give hostname, on conflict I want to append to the array with the data I'm trying to insert and the output data should be unique.
e.g
hostname - ip
test.com   {1.1.1.1,2.2.2.2}
Input
I attempt to insert...
test.com {1.1.1.1, 3.3.3.3, 4.4.4.4}
Output
test.com {1.1.1.1, 2.2.2.2 ,3.3.3.3, 4.4.4.4}
insert into auto_scope_pre_proc (hostname,ip) values ('test.com', '{10.10.10.10, 10.10.10.22}'::inet[])
on conflict (hostname) do update
SET ip = array_append(auto_scope_pre_proc.ip,ip);

A: The function array_append does not filter duplicates entries.
Here is a possible solution:
drop table auto_scope_pre_proc;
DROP TABLE
create table auto_scope_pre_proc
(
  hostname varchar(20) primary key,
  ip inet[]
);
CREATE TABLE
insert into auto_scope_pre_proc (hostname,ip) values ('test.com', '{1.1.1.1, 2.2.2.2}'::inet[])
on conflict (hostname) do update
set ip = array( select distinct unnest(auto_scope_pre_proc.ip || excluded.ip));
INSERT 0 1
select * from auto_scope_pre_proc;
 hostname |        ip
----------+-------------------
 test.com | {1.1.1.1,2.2.2.2}
(1 row)

insert into auto_scope_pre_proc (hostname,ip) values ('test.com', '{1.1.1.1, 3.3.3.3, 4.4.4.4}'::inet[])
on conflict (hostname) do update
set ip = array (select distinct unnest(auto_scope_pre_proc.ip || excluded.ip));
INSERT 0 1
select * from auto_scope_pre_proc;
 hostname |                ip
----------+-----------------------------------
 test.com | {4.4.4.4,2.2.2.2,3.3.3.3,1.1.1.1}
(1 row)


text:
Q: Question about derivation of the Heisenberg Uncertainty Principle? I am looking at the derivation presented here.

*

*The first thing I am unsure about is where the form of $\psi_0=Ae^{\frac{-m\omega x^2}{2\hbar}}$ came from.

*Also, is this form for all $\psi$, or just for the ground state?

*Also, I can't figure out where this comes from:

To get $\langle x^2 \rangle$ and $\langle p^2 \rangle$, we use the following useful calculation. Note that $x$ acting on $\psi_0$ must give the same answer as $-\frac{p^2}{m\omega}$[...]

Any help will be much appreciated.

A: In the first part of the linked document are not giving a formal derivation of the uncertainty principle. It is giving a particular example to show the general idea. The gaussian wavefunction is chosen because it is a particularly simple and happens to exactly satisfy the lower bound $\sigma_x\sigma_p = \frac{1}{2}\hbar$. For the harmonic oscillator being considered, then only the ground state will be a gaussian. A more general derivation is given on the last page.
The relation $\frac{-i\hat{p}}{2m}\psi_0 = x \psi_0$ comes from the fact that the annihilation operator acting on the ground state gives $a_-\psi_0 = 0$ by the definition of the ground state.

A: After a quick go-through over your reference, it was simply using the ground state (Yes, $\psi_o$ is just the ground state.) of the harmonic oscillator as an example to demonstrate that $\Delta x$ and $\Delta p$ really do satisfy the uncertainty principle.
For your second question, equation (8) is obtained by taking the derivative of $\psi_0$ and then rearranging. try it yourself. ^^

A: The given wave function $\psi_0$ is indeed only the ground state wave function for the quantum harmonic oscillator. Wave functions of excited levels involve Hermite polynomials in general and are not that simple.


text:
Q: Generate async-only interface from wsdl? Is there any way to generate only the task based async methods with svcUtil?
The reason is I have given WSDLs which I need to implement as a service. The easiest way seems to be to just add them as a service reference and implement the generated interface as a service. This works great as long as you stay synchronous but for async it obviously generates two methods with the same OperationContract, which is invalid.
Other ways of fixing this dilemma are appreciated as well of course. My constraint is that I have to stick to the given WSDL files, so I can't generate the WSDL from the interface (yay -.-)
Regarding the duplicate claim: nope. This does not help at all. I played around with ConcurrencyMode and Task-based services now and there is a huge difference in performance between the two. For example: Shooting with 100 threads against either of these implementations,
public async Task<SomeObj> GetSomeObj(SomeReq request)
{
    await Task.Delay(1000);
    return SomeObj();
}

performs much better than
public SomeObj GetSomeObj(SomeReq request)
{
    Thread.Sleep(1000);
    return new SomeObj();
}

no matter what ConcurrencyMode is selected in the ServiceBehavior (which, funny enough, had only very little influence on the performance).
So the question still stands: how to generate a task-based service contract from a WSDL, because we can clearly show that they have superior performance (both when it comes to startup behaviour as well as predictability of runtime performance).


text:
Q: Create Alias for PostgreSQL Table I have a table called assignments. I would like to be able to read/write to all the columns in this table using either assignments.column or homework.column, how can I do this?
I know this is not something you would normally do. I need to be able to do this to provide backwards compatibility for a short period of time.
We have an iOS app that currently does direct postgresql queries against the DB. We're updating all of our apps to use an API. In the process of building the API the developer decided to change the name of the tables because we (foolishly) thought we didn't need backwards compatibility.
Now, V1.0 and the API both need to be able to write to this table so I don't have to do some voodoo later to transfer/combine data later...
We're using Ruby on Rails for the API.

A: In Postgres 9.3 or later, a simple VIEW is "updatable" automatically. The manual:

Simple views are automatically updatable: the system will allow
INSERT, UPDATE and DELETE statements to be used on the view in
the same way as on a regular table. A view is automatically updatable
if it satisfies all of the following conditions:

*

*The view must have exactly one entry in its FROM list, which must be a table or another updatable view.

*The view definition must not contain WITH, DISTINCT, GROUP BY, HAVING, LIMIT, or OFFSET clauses at the top level.

*The view definition must not contain set operations (UNION, INTERSECT or EXCEPT) at the top level.

*The view's select list must not contain any aggregates, window functions or set-returning functions.

If one of these conditions is not met (or for the now outdated Postgres 9.2 or older), a manual setup may do the job.
Building on your work in progress:
Trigger function
CREATE OR REPLACE FUNCTION trg_ia_insupdel()
  RETURNS trigger
  LANGUAGE plpgsql AS
$func$
DECLARE
   _tbl  CONSTANT regclass := 'iassignments_assignments';
   _cols text;
   _vals text;
BEGIN
   CASE TG_OP
   WHEN 'INSERT' THEN
      INSERT INTO iassignments_assignments
      VALUES (NEW.*);

      RETURN NEW;

   WHEN 'UPDATE' THEN
      SELECT INTO _cols, _vals
             string_agg(quote_ident(attname), ', ')   -- incl. pk col!
           , string_agg('n.' || quote_ident(attname), ', ')
      FROM   pg_attribute
      WHERE  attrelid = _tbl        -- _tbl converted to oid automatically
      AND    attnum > 0             -- no system columns
      AND    NOT attisdropped;      -- no dropped (dead) columns

      EXECUTE format('
         UPDATE %s t
         SET   (%s) = (%s)
         FROM  (SELECT ($1).*) n
         WHERE    t.published_assignment_id
             = ($2).published_assignment_id' -- match to OLD value of pk
       , _tbl, _cols, _vals)        -- _tbl converted to text automatically
      USING NEW, OLD;

      RETURN NEW;

   WHEN 'DELETE' THEN
      DELETE FROM iassignments_assignments
      WHERE  published_assignment_id = OLD.published_assignment_id;

      RETURN OLD;
   END CASE;

   RETURN NULL;  -- control should never reach this
END
$func$;

Trigger
CREATE TRIGGER insupbef
INSTEAD OF INSERT OR UPDATE OR DELETE ON assignments_published
FOR EACH ROW EXECUTE PROCEDURE trg_ia_insupdel();

Notes

*

*assignments_published must be a VIEW, an INSTEAD OF trigger is only allowed for views.

*Dynamic SQL (in the UPDATE section) is not strictly necessary, only to cover future changes to the table layout automatically. The names of table and PK are still hard coded.

*Simpler and probably cheaper without sub-block (like you had).

*Using (SELECT ($1).*) instead of the shorter VALUES ($1.*) to preserve column names.

*My naming convention: I prepend trg_ for trigger functions, followed by an abbreviation indicating the target table and finally one or more of the the tokens ins, up and del for INSERT, UPDATE and DELETE respectively. The name of the trigger is a copy of the function name, stripped of the first two parts. This is purely a matter of convention and taste but has proven useful for me since the names tell the purpose and are still short.

*More explanation in the related answer that has already been mentioned:

*Update multiple columns in a trigger function in plpgsql

A: With Postgres 9.3 the following should be enough:

CREATE VIEW homework AS SELECT * FROM assignments;

It works because simple views are automatically updatable (see docs).

A: This is where I am with the trigger functions so far, any feedback would be greatly appreciated. It's a combination of http://vibhorkumar.wordpress.com/2011/10/28/instead-of-trigger/ and Update multiple columns in a trigger function in plpgsql
Table: iassignments_assignments
Columns:
published_assignment_id
name
filepath
filename
link
teacher
due date
description
published
classrooms

View: assignments_published - SELECT * FROM iassignments_assignments
Trigger Function for assignments_published
CREATE OR REPLACE FUNCTION assignments_published_trigger_func()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $function$
   BEGIN
      IF TG_OP = 'INSERT' THEN
        EXECUTE format('INSERT INTO %s SELECT ($1).*', 'iassignments_assignments')
        USING NEW;
        RETURN NEW;
      ELSIF TG_OP = 'UPDATE' THEN
        DECLARE
          tbl = 'iassignments_assignments';
          cols text;
          vals text;
        BEGIN
          SELECT INTO cols, vals
           string_agg(quote_ident(attname), ', ')
           ,string_agg('x.' || quote_ident(attname), ', ')
          FROM   pg_attribute
          WHERE  attrelid = tbl
          AND    NOT attisdropped   -- no dropped (dead) columns
          AND    attnum > 0;        -- no system columns

          EXECUTE format('
          UPDATE %s t
          SET   (%s) = (%s)
          FROM  (SELECT ($1).*) x
          WHERE  t.published_assignment_id = ($2).published_assignment_id'
          , tbl, cols, vals)
          USING NEW, OLD;

          RETURN NEW;
        END
      ELSIF TG_OP = 'DELETE' THEN
       DELETE FROM iassignments_assignments WHERE published_assignment_id=OLD.published_assignment_id;
       RETURN NULL;
      END IF;
      RETURN NEW;
    END;
$function$;

Trigger
CREATE TRIGGER assignments_published_trigger
INSTEAD OF INSERT OR UPDATE OR DELETE ON
assignments_published FOR EACH ROW EXECUTE PROCEDURE assignments_published_trigger_func();

Table: iassignments_classes
Columns:
class_assignment_id
guid
assignment_published_id

View: assignments_class - SELECT * FROM assignments_classes
Trigger Function for assignments_class
**I'll create this function once I have received feedback on the other and know it's create, so I (hopefully) need very little changes to this function.
Trigger
CREATE TRIGGER assignments_class_trigger
INSTEAD OF INSERT OR UPDATE OR DELETE ON
assignments_class FOR EACH ROW EXECUTE PROCEDURE assignments_class_trigger_func();


text:
Q: Nested fields mapping not working in Orika Mapper Find below entity classes :
@Entity
@Table(name="rooms")
public class RoomEntity {

    @Column(name="mr_code", length=50, nullable=false)
    private String code;

    @Column(name="mr_roomtype", nullable=false, length=50)
    private String type;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "mr__hotelId", nullable = false)
    private HotelEntity hotel;

    //getters and setters
}

 @Entity
 @Table(name="hotels")
 public class HotelEntity{

    @Column(name="mh_name", nullable=false)
    private String name;

    @Column(name="mh_description")
    private String description;

    @OneToMany(mappedBy = "hotel", fetch=FetchType.EAGER)
    private Set<RoomEntity> rooms = new HashSet<>(0);

    //getters and setters
 }

Find below DTO class
 public class RoomDTO{

    private String hotelName;
    private String code;
    private String type;

    //getters and setters
}

I written the below mapper code to copy data from RoomEntity to RoomDTO
public class BeanMapper {

    private static MapperFactory mapperFactory = new   DefaultMapperFactory.Builder().build();

        public static RoomDTO toRoomDTO(RoomEntity roomEntity) {
        mapperFactory.classMap(RoomEntity.class, RoomDTO.class).field("hotel.name","hotelName").byDefault().register();
        MapperFacade mapper = mapperFactory.getMapperFacade();
        return mapper.map(roomEntity,RoomDTO.class);
    }
}

The properties - code and type values are getting copied from RoomEntity to RoomDTO.
But the nested properties values(hotel.name -> hotelName) are not getting copied.
Please help to resolve this issue.


text:
Q: gdal_merge.py cannot import gdal in Windows 7 Anaconda GDAL Installation I have an installation of GDAL through Anaconda that is mostly working, but it throws an ImportError whenever I run gdal_merge.py:
Traceback (most recent call last):
  File "C:\Users\xxx\AppData\Local\Continuum\Anaconda2\Scripts\gdal_merge.py", line 37, in <module>
    from osgeo import gdal
ImportError: No module named osgeo

I can import GDAL without error from my own scripts and commands, even within the above folder. Most of what I have read about similar issues is that they are usually related to the PATH environment variable, but as far as I can tell mine is pointing to all the right places:
C:\Users\xxx\AppData\Local\Continuum\Anaconda2;C:\Users\xxx\AppData\Local\Continuum\Anaconda2\Scripts;C:\Users\xxx\AppData\Local\Continuum\Anaconda2\Library\bin;

I have 64-bit Anaconda for Python 2.7 installed on a Windows 7 system. My version of GDAL is 2.1.0, which I installed with the conda install utility. I set and tested my GDAL_DATA environment variable, and believe it to be correct:
C:\Users\xxx\AppData\Local\Continuum\Anaconda2\Library\share\gdal

I have replaced my user name with xxx throughout.

A: Try changing the line to simply:
import gdal

I've had similar issues, that worked, no idea why.


text:
Q: famo.us physics set magnitude of particle velocity independently of x-y components In the famo.us physics engine, is it possible to set the magnitude of a particle's velocity without changing the x/y components?  I want to be able to set the speed of a ball object independently of its interactions with other objects, in a manner akin to
ball.particle.setVelocity([1,1,0]);

but affecting magnitude of the velocity only.
I guess a more general version of the question is, can vectors be manipulated in terms of magnitude and angle, rather than in terms of x and y coordinates?

A: The angle and magnitude of a vector is calculated from the x and y and z coordinates in Famo.us.
Understanding Magnitude will help you here. Magnitude is a measure derivative of the vector calculated by using the coordinates. Magnitude is the length of the vector.  You can learn about magnitude in Kahn academy.  There is no way to know a vector values based just on knowing the Magnitude.
Back to what you want to accomplish using Famo.us.
Basic Explanations of Particle
A particle in Famo.us is based on it's velocity, position and force. So, we have to know the vector of the angle to set a velocity of the particle in Famo.us.  There currently is not a method to be able to pass the angle and have the velocity set.
Creating an example of having a constant Magnitude in Famo.us
Working Example Code on jsBin
Setup up the original Vector
  var impulse = 0.01;
  var vector = new Vector(1,1,0);
  // Setup our maximum Magnitude to the magnitude of our vector
  var maxMagnitude = vector.norm();

Set the force to be an impulse on the particle to keep it in motion. Set our velocity to the maximum magnitude to control our constant speed.
Note: Magnitude in a Particle in Famo.us is particle.norm(). Not sure why they did not call it magnitude.
  function setForce() {
    // Apply an impulse to the current vector keep it in motion
    this.applyImpulse(this.velocity.cap(impulse));
    // set the velocity speed to be a max in units
    this.setVelocity(this.velocity.cap(maxMagnitude));
    // Return the particles transform value
    return this.getTransform();
  }

Transform from the Particle Transform
var physicsEngine = new PhysicsEngine();

var particle = new Particle({
  mass: 1,
  position: [100, 100, 0]
});

var modifier = new Modifier();
modifier.transformFrom(setForce.bind(particle));

var surface = new new ImageSurface({
  content: 'http://code.famo.us/assets/famous_logo.svg',
  size: [radius * 2, radius * 2],
  properties: {
    borderRadius: (radius * 2) + 'px'
  }
});

physicsEngine.addBody(particle);

context.add(modifier).add(surface);

//Start the particle in motion
particle.setVelocity([vector.x, vector.y, 0]);

A: This will allow an arbitrary setting of magnitude & direction (in degrees with standard orientation).
function setMagAndDir(particle, magnitude, angle) {
  angle = angle * (Math.PI / 180);
  var xComp = magnitude * Math.cos(angle);
  var yComp = -1 * magnitude * Math.sin(angle);
  particle.setVelocity([xComp,yComp,0]);
};

The only drawback is that both have to be set at the same time.  To set individually, pass one of the getters below.
function readMagnitude(particle) {
  return Math.sqrt( ((particle.getVelocity()[0]) * (particle.getVelocity()[0])) + ((particle.getVelocity()[1]) * (particle.getVelocity()[1])) );
};

function readDirection(particle) {
  var direction = Math.atan2((-1 * particle.getVelocity()[1]),particle.getVelocity()[0]);
  direction = direction * (180 / Math.PI);
  if (particle.getVelocity()[1] > 0) {
    direction = direction + 360;
  }
  return direction;
};


text:
Q: How can I get an ItemsSource as an ObservableCollection<>? I'm trying to modify a property of a grid depending on whether or not there are any items in the ObservableCollection<> the ItemsSource is bound to. I currently have an event for OnItemsSourceChanged on the grid, but the problem is that ItemsSource is an object, and without casting it, I don't have access to the CollectionChanged event of the ObservableCollection<>.  The generic type of ObservableCollection<> is undetermined until runtime and can be many things.
I've tried casting it with ItemsSource as ObservableCollection<object>, but that returns null.  No luck with ItemsSource as ObservableCollection<dynamic>, either. Doing ItemsSource as IEnumerable<object> works surprisingly enough, but that still does not allow me to access the CollectionChanged event.
How can I cast my object to the underlying ObservableCollection<>? I'd prefer to avoid using reflection, but I'm not going to be picky here.

A: What about casting it to INotifyCollectionChanged?
EDIT:
What you probably should be doing is something like this:
<TextBlock Visibility="{Binding MyObservableCollection.Count, Converter={StaticResource NonZeroToVisibleConverter}}">

Where NonZeroToVisibleConverter is something like:
public class ColorConverter : IValueConverter
{
  public object Convert(object value, Type targetType,
      object parameter, CultureInfo culture)
  {
    return (int)value > 0 ? Visibility.Visible : Visibility.Collapsed
  }

  public object ConvertBack(object value, Type targetType,
      object parameter, CultureInfo culture)
  {
    throw new NotImplmentedException();
  }
}

OR probably even better
<Grid Name="MyGrid" ItemsSource="{Binding MyObservableCollection" />

<TextBlock Visibility="{Binding HasItems, ElementName=MyGrid, Converter={StaticResource BoolToVisibilityConverter}}" />

Last Resort For Future Reference
Your last resort would of been better to expose a property ShouldBe/IsVisible in you ViewModel and and bind to that in your View.

A: Consider the following code:
// where
ObservableCollection<Foo> foo = new();
element.ItemsSource = foo;
// then negotiate to non-generic types
var bar = element.ItemsSource as INotifyCollectionChanged;
bar.CollectionChanged += (NotifyCollectionChangedEventHandler)(delegate(object sender, NotifyCollectionChangedEventArgs e)
{
  var collection = bar as ICollection;
  // TODO: handle based on collection.Count
});

This way you are able to handle the event regardless of the generic types applied to ObservableCollection<T>.


text:
Q: Unable to access static property / field (C#) I am getting a compile time exception that states:
Actor.TimeScale.get' cannot be accessed with an instance reference;
qualify it with a type name instead.

This is the code, which has been cleaned up to just the relevant lines:
class Actor
{
    static float _timeScale = 1.0f;

    public static float TimeScale
    {
        get { return _timeScale; }
        set { _timeScale = value; }
    }
}
class Game1
{
    private void BeginLevel()
    {
        Actor.TimeScale = 0.3f;
    }
}

Now, I know something is amiss with static, but I don't understand what.

A: A child class of actor had:
this.TimeScale;

which of course doesnt work so well with static.


text:
Q: Element UI with Electron did anybody try to use it with Electron? I'm not able to run it.
Instead of <el-button type="primary" @click.native="test">Primary Button</el-button> I see just Primary Button text.
Probably some loader...
Here is my content: webpack.config.js
var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './app/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'build.js'
  },
  module: {
    loaders: [
    {
      test: /\.vue$/,
      loader: 'vue'
    },
    {
      test: /\.js$/,
      loader: 'babel',
      exclude: /node_modules/
    },
    {
      test: /\.css$/,
      loaders: ['style-loader', 'css-loader', 'postcss-loader']
    },
    {
      test: /\.(png|jpg|jpeg|gif|eot|ttf|woff|woff2|svg|svgz)(\?.+)?$/,
      loader: 'file'
    }]
  },
  babel: {
    "presets": ["es2015"],
    "plugins": ["transform-runtime"]
  },
  plugins: [
    new webpack.ExternalsPlugin('commonjs', [
      'electron'
    ])
  ]
}

Main.js is easy:
import Vue from 'vue'
import { Button } from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import App from './App.vue'

Vue.use(Button)

new Vue({
  el: 'body',
  components: { App }
})

And here is my list of dev-dependencies:

*

*"autoprefixer": "^7.1.1"

*"babel-core": "^6.7.4"

*"babel-loader": "^6.2.4"

*"babel-plugin-transform-runtime": "^6.6.0"

*"babel-preset-es2015": "^6.6.0"

*"babel-runtime": "^5.8.38"

*"css-loader": "^0.23.1"

*"electron-prebuilt": "^0.37.2"

*"file-loader": "^0.11.2"

*"postcss-loader": "^2.0.6"

*"style-loader": "^0.18.2"

*"url-loader": "^0.5.8"

*"vue-hot-reload-api": "^1.3.2"

*"vue-html-loader": "^1.2.0"

*"vue-loader": "^8.2.2"

*"vue-style-loader": "^1.0.0"

*"webpack": "^1.12.14"

*"webpack-dev-server": "^1.14.1"

And dependencies:

*

*"element-ui": "^1.3.7"

*"jquery": "^2.2.2"

*"vue": "^1.0.19"

Thanks