text:
Q: How to calculate distance between two location by road? I want to calculate distance between two locations by road/like driving mode.
Here is my code but error is coming at "response = client.execute(httppost);" this line.Please help me.
private double getDistance(double latFrom, double lngFrom,double latTo,double lngTo) {
    StringBuilder stringBuilder = new StringBuilder();
    String apikey="API KEY";
    Double dist = 0.0;
    try {

        String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + latFrom + "," + lngFrom + "&destination=" + latTo + "," + lngTo + "&mode=driving&sensor=false"+"&key="+apikey;

        HttpPost httppost = new HttpPost(url);

        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();

        response = client.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {

        jsonObject = new JSONObject(stringBuilder.toString());
        JSONArray array = jsonObject.getJSONArray("routes");
        JSONObject routes = array.getJSONObject(0);
        JSONArray legs = routes.getJSONArray("legs");
        JSONObject steps = legs.getJSONObject(0);
        JSONObject distance = steps.getJSONObject("distance");
        Log.i("Distance", distance.toString());
        dist = Double.parseDouble(distance.getString("text").replaceAll("[^\\.0123456789]","") );

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return dist;
}

A: The solution to your error would be to perform all network operations on a background thread. For example, using AsyncTask or Runnable on a separate thread from the main.
To elaborate more on my answer, your network call would be performed in the doInBackground() method of your AsyncTask.
NEVER perform network operations on the main thread because network calls are blocking operations and would severely hinder your UI responsiveness.


text:
Q: How to tween/animate fog three.js So i am trying to change the fog density by tweening it is this possible because it doesn't seem to change here's my defaults:
var camera, densityFog, colorFog2;
                    colorFog2 = 0xfee2ed;
                    densityFog = 0.25;
                    scene.fog = new THREE.FogExp2(colorFog2, densityFog);

and here is what I've tried using the libs GSAP and tweenjs:
tween = new TWEEN.Tween(scene.fog)
                .to({densityFog: 0.02}, 1000 )
                .easing(TWEEN.Easing.Exponential.InOut)
                .onComplete(function() { }).start();

                gsap.to(scene.fog, {
                        duration: 2,
                        densityFog: 0.02,
                        onUpdate: function () {
                            controls.update();
                            isZoomed = 0;
                            controls.enabled = false;

                        },
                    });

can anyone point me in the right direction?

A: This answer uses gsap
Use an object eg. myfog = { value: .5 } and tween its value property to what you desire.
Then in onUpdate, set scene.fog to a new THREE.FogExp2 with the current myfog.value as a parameter.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
camera.position.y = 2;

// Init the object and fog here
var myfog = { value: .5 }
scene.fog = new THREE.FogExp2(0x00ff00, myfog.value);

var geometry = new THREE.BoxGeometry(1, 1, 5);
var mat = new THREE.MeshBasicMaterial({
  color: 0xff0000
});
var mesh = new THREE.Mesh(geometry, mat);

scene.add(mesh);

var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x00ff00);
document.body.appendChild(renderer.domElement);

function render() {
  renderer.render(scene, camera);
}

function animate() {
  requestAnimationFrame(animate);
  render();
}

animate();

// This animates the fog
gsap.to(myfog, {
  duration: 2,
  value: 0.002, // The end value
  onUpdate: function() {
    // New fog with current myfog value
    scene.fog = new THREE.FogExp2(0x00ff00, myfog.value);
  },
  // These just infinitely repeat the animation
  yoyo: true,
  repeat: -1,
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.1/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r127/three.min.js"></script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Treat dictionary key with multiple characters as "one character"? I'm trying to create a simple "translator" to be able to encrypt/decrypt between binary and "leetspeak" using dictionarys to map keys to values and "translate" between them. It works just fine to "encrypt" one letter to x number of characters (and of course also to decrypt it, as long as the key arent longer than one character) but I noted that stuff breaks when trying to decrypt multiple characters to one and started to thinking about if it's possible in a fairly simple way to treat one key as a single character or something like that.
The only suggestions I've had so far is basically to write something similar to unicode myself and that seems overkill enough since i'm new at this and just learning and that's not something I want to even try to do, at least not at the moment, so basically my question is if it's another way to accomplish the same thing? Even if i have to rewrite the whole thing, using a completely different method than this dict-idea i came up with, it would really be of help.
binary_encrypt = {
    "A": "01000001", "B": "01000010", "C": "01000011", "D": "01000100", "E": "01000101",
    "F": "01000110", "G": "01000111", "H": "01001000", "I": "01001001", "J": "01001010",
    "K": "01001011", "L": "01001100", "M": "01001101", "N": "01001110", "O": "01001111",
    "P": "01010000", "Q": "01010001", "R": "01010010", "S": "01010011", "T": "01010100",
     "U": "01010101", "V": "01010110", "W": "01010111", "X": "01011000", "Y": "01011001",
    "Z": "01011010", "Å": "11000101", "Ä": "11000100", "Ö": "11010110",

    "a": "01100001", "b": "01100010", "c": "01100011", "d": "01100100", "e": "01100101",
    "f": "01100110", "g": "01100111", "h": "01101000", "i": "01101001", "j": "01101010",
    "k": "01101011", "l": "01101100", "m": "01101101", "n": "01101110", "o": "01101111",
    "p": "01110000", "q": "01110001", "r": "01110010", "s": "01110011", "t": "01110100",
    "u": "01110101", "v": "01110110", "w": "01110111", "x": "01111000", "y": "01111001",
    "z": "01111010", "å": "11100101", "ä": "11100100", "ö": "11110110",

    "0": "00110000", "1": "00110001", "2": "00110010", "3": "00110011", "4": "00110100",
    "5": "00110101", "6": "00110110", "7": "00110111", "8": "00111000", "9": "00111001",
    " ": "00100000", # Whitespace-character

    "!": "00100001", "\"": "00100010", "#": "00100011", "¤": "10100100", "%": "00100101",
    "&": "00100110", "/": "00101111", "(": "00101000", ")": "00101001", "=": "00111101",
    "?": "00111111", "§": "10100111", ",": "00101100", ".": "00101110", "-": "00101101",
    ";": "00111011", ":": "00111010", "_": "01011111", "<": "00111100", ">": "00111110",
    "|": "01111100", "´": "10110100", "`": "01100000", "@": "01000000", "£": "10100011",
    "$": "00100100", "€": "10101100", "{": "01111011", "[": "01011011", "]": "01011101",
    "}": "01111101", "\\": "01011100"
}

binary_decrypt = dict([(value, key) for key, value in binary_encrypt.items()])

leetspeak_encrypt = {
    "A": "4", "B": "13", "C": "(", "D": "[)", "E": "3",
    "F": "|=", "G": "6", "H": "|-|", "I": "|", "J": ".]",
    "K": "|<", "L": "1", "M": "|Y|", "N": "/\/", "O": "0",
    "P": "|>", "Q": "0,", "R": "|2", "S": "5", "T": "7",
   "U": "[_]", "V": "\/", "W": "\v/", "X": "}{", "Y": "`/",
    "Z": "2", "Å": "A.", "Ä": "A..", "Ö": "0.."
}

leetspeak_decrypt = dict([(value, key) for key, value in leetspeak_encrypt.items()])

language = input("Language? Binary/Leetspeak: ")
mode = input("Mode? Encrypt/Decrypt: ")
string = input("Enter your string you want to en/decrypt: ")

if language == "binary":
    if mode == "encrypt":
        translated_msg = []
        for letter in string:
            translated_msg.append(binary_encrypt.get(letter, letter) + " ")
        translated_msg = "".join(translated_msg)
        print("Done! Here is your encrypted message [EN]CRYPT -> BINARY:")
        print(translated_msg)
    elif mode == "decrypt":
        translated_msg = []
        for letter in string:
            translated_msg.append(binary_decrypt.get(letter, letter) + " ")
        translated_msg = "".join(translated_msg)
        print("Done! Here is your decrypted message [DE]CRYPT <- BINARY:")
        print(translated_msg)
elif language == "leetspeak":
    if mode == "encrypt":
        string = string.upper()
        translated_msg = []
        for letter in string:
            translated_msg.append(leetspeak_encrypt.get(letter, letter))
        translated_msg = "".join(translated_msg)
        print("Done! Here is your encrypted message [EN]CRYPT -> LEETSPEAK:")
        print(translated_msg)
    elif mode == "decrypt":
        translated_msg = []
        for letter in string:
            translated_msg.append(leetspeak_decrypt.get(letter, letter))
        translated_msg = "".join(translated_msg)
        print("Done! Here is your decrypted message [DE]CRYPT <- LEETSPEAK:")
        print(translated_msg)

Output as expected (example trying to decrypt the key for the value of letter M in leetspeak):
> python .\testchiffer.py
Language? Binary/Leetspeak: leetspeak
Mode? Encrypt/Decrypt: decrypt
Enter your string you want to en/decrypt: |Y|
Done! Here is your decrypted message [DE]CRYPT <- LEETSPEAK:
IYI

Thanks on beforehand!

A: I might not have understood exactly what you want here, but can't you just have either another dictionary or directly use binary number notation like instead of storing them as strings use 0b0011001... ?
You could use a table with only binary numbers or maybe two with string/binary.
Because a string of 0s and 1s is only encoding the 0 and 1 character not storing binary values.
Since well, a string of characters can't be treated as "one character".
You could also maybe do a custom class or something like that
Lemme know if I misunderstood your question


text:
Q: PHP show query different of sql execute config.php
@$mysqli= mysqli_connect($servername, $username_bd, $password_bd, $dbname);
if($mysqli->connect_error)
    return false;

insert.php
include 'config.php';
$DateDefault = '2015-07-30 00:00:00
2015-08-30 00:00:00';

 $sql = "INSERT INTO users (date) VALUES ('$DateDefault')";
   if($query = $mysqli->query($sql)===true)
       echo "Date add successfully";
   else
       echo "Error into date";

show.php
include 'config.php';

$sql = "SELECT date FROM users WHERE username='$username'";
$query = $mysqli->query($sql);
if (@$query->num_rows > 0){
    while ($dados = $query->fetch_assoc()) {
        echo substr($dados['date'], 21, 19);
    }
}

Result:
"2015-08-30 00:00:00"
Now, when I changed the date in the phpmyadmin, for
"2015-07-30 00:00:00
2015-09-30 00:00:00"

Shows this:
"015-09-30 00:00:00 "

In localhost, using wampserver, this bug don't happen

A: Your issue is likely to do with how different operating systems treat line endings. In a nutshell, on Windows, line endings take up two characters (carriage return and newline, \r\n), and on most other operating systems, they occupy only one (newline, \n). By using specific character offsets, you're introducing the possibility of the off-by-one error you're seeing.
A simple fix would be to separate your dates by using a single space (or another character) instead of a line break. If you still want to use a line break, you can split the string by whitespace:
$dates = preg_split('/\s+/', $dados['date']); // Split dates by whitespace
echo $dates[1]; // Print the second date


text:
Q: Mask for EditText in Android I want to limit input in the EditText of all symbols except figures, "?" And "*". How I am able to do it?

A: If you also have a maximum strict length of your string, you can use a mask. I'm not sure that it's the right solution, but it's the easiest one. An easy way use a mask in your Android programs in Android Studio is to use MaskedEditText library (GitHub link).
I can not understand what does mean: figures, "?" And "", so I suppose just "?" and "". So the code is:
In your build.gradle:
compile 'ru.egslava:MaskedEditText:1.0.5'

And in your layout:
<br.com.sapereaude.maskedEditText.MaskedEditText
    android:id="@+id/phone_input"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="phone"
    android:typeface="monospace"
    mask:allowed_chars="?*"
    mask:mask="##########"
    app:keep_hint="true"
    />

This code creates an EditText that can contain ONLY "?" and "*" and max length is 10. Feel free to ask your questions :-)

A: You could add a TextWatch via addTextChangedListener. afterTextChanged allows you to modify the text after it was modified.
(Keep in mind that there are many ways to modify a text field - entering text, auto-complete through IME, copy and paste). Handle those properly in the TextWatch.

A: By this, we can restrict the user to not type ? and *
<EditText
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:textSize="@dimen/register_text_size"
   android:layout_weight="1"
   android:id="@+id/first_name"
   android:padding="14dp"
   android:digits="@#$%^&()_-+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12"
   android:singleLine="true"
   android:hint="@string/first_name"/>

A: you can check your input from edittext.addTextChangeListener method.
etAdjustmentInput.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
             //checking the length of input
            if (etAdjustmentInput.getText().toString().trim().length()<=0){
                 // if length less then or equals 0 show warning or make button not clickable
                tvAdjustmentInfoOk.setClickable(false);
                tvAdjustmentInfoOk.setTextColor(getResources().getColor(R.color.time_color));
            }
            else {

                 // input length greater then 0 now check the input type according to your requirement
                tvAdjustmentInfoOk.setClickable(true);
                tvAdjustmentInfoOk.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                if(s.equals("?")){
                 //do your task
                  }
                else{ // whatever you want to tell the user
                  }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

Inside onTextChanged method you can restrict the user to maximum length and also you can check the input type according to your requirement

A: Try this
From this code you can enter 0 to 9 digits and only two special character ? and *.
<EditText
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:id="@+id/first_name"
   android:digits="?*1234567890"
   android:singleLine="true"
   />

A: public class MainActivity extends Activity {

private EditText editText;
private String blockCharacterSet = "?*";

private InputFilter filter = new InputFilter() {

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

        if (source != null && !blockCharacterSet.contains(("" + source))) {
            return "";
        }
        return null;
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText = (EditText) findViewById(R.id.editText);
    editText.setFilters(new InputFilter[] { filter });
}

}


text:
Q: Transform tree from graphql format to json format in javascript I'm trying to transform my data on client side from this format:
[{
    "id": 1,
    "name": "dad",
    "parent": [],
    "children": [{
            "group": {
                "id": 2,
                "name": "child1",
                "parent": [{
                    "parent": 1
                }]
            }
        },
        {
            "group": {
                "id": 3,
                "name": "child2",
                "parent": [{
                    "parent": 1
                }]
            }
        },
        {
            "group": {
                "id": 8,
                "name": "child3",
                "parent": [{
                    "parent": 1
                }]
            }
        }
    ]
}]

to this format:
[{
    id: 1,
    name: "parent",
    parent: null,
    children: [{
            id: 2,
            name: "child1",
            parent: {
                id: 1
            },
            children: []
        },
        {
            id: 3,
            name: "child2",
            parent: {
                id: 1
            },
            children: []
        }
    ]
}]

key points:

*

*All keys should not be in a string type

*The 'parent' should just include the id of the parent

*'group' object should be removed - and its contents should just
replace him

I can't find a transformation library in npm to use and i need the data to be in that exact format to use in 'react-vertical-tree' component (didn't find any other good looking vertical tree component in react).

A: You could map new objects with converted parts.

const convert = o => {
    var children;
    if ('group' in o) o = o.group;
    if ('children' in o) children = o.children.map(convert);
    return Object.assign({}, o, { parent: o.parent.length ? { id: o.parent[0].parent } : null }, children && { children });
};

var data = [{ id: 1, name: "dad", parent: [], children: [{ group: { id: 2, name: "child1", parent: [{ parent: 1 }] } }, { group: { id: 3, name: "child2", parent: [{ parent: 1 }] } }, { group: { id: 8, name: "child3", parent: [{ parent: 1 }] } }] }],
    result = data.map(convert);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Get notifications for socket events in kernel I need to find for local tcp-connections/Unix-domain-connections the client process that starts the connection in the most effective way possible.
I currently have a solution for this implemented in a driver, that intercept both accept and connect syscalls, match them, and finds out the client process.
Now I try to achieve the same without my own driver.
Different approaches I tried:

*

*Linux auditing system plugin that intercept the appropriate syscalls and resolve the client in a similar manner. This method has 3 problems:

*

*Each intercepted event flows from the kernel to the auditd process to some other intermediate process and only than to my plugin.

*The audit rules are applies for all the plugins and audit-log - I can't define my own set of filtering rules. - which may cause on machines that uses the audit system for extreme inefficiency.

*It requires that audit to be installed on the machine (which is not default for many Linux distributions).

*Imitate netstat/lsof - In order to find the process that holds a connection, they iterate the entire procfs mount - this makes sense, because after connection establishment, each connection could belongs to more than one process.
This approach is extremely not effective if I want to do so for each connection establishment.

*I thought to try one of the LSM (Linux security modules) solutions - but I am currently unfamiliar with it - Is their a LSM that can pass the kernel events for a running application for a "decision"?

I will be happy to hear suggestions and other comments that could lead me to a reasonable solution for my original goal.

A: Found an option that suits my needs for Unix-domain-sockets only - if runnning code in the server side is a possability (as in my case) one can use getsockopt in the following manner:
getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len)

More details in http://welz.org.za/notes/on-peer-cred.html


text:
Q: Why finally block does not execute? When I run this code, finally block does not execute. If I change System.out to System.err in try block, it works. Or when I change out to err in finally block it works. What is the reason?
Thanks in advance for answer!
    String fn = "data.txt";

try (var w = new BufferedWriter(new FileWriter(fn)); var s = System.out) {

    w.write("Hi, there!");

    w.flush();

    w.write('!');

    System.out.print("1");

} catch (IOException e) {

    System.out.print("2");

} finally {

    System.out.print("3");

}


text:
Q: Using Leibniz integral rule when minimizing Expected Absolute Loss Consider choosing $\theta^*$ that minimizes the expected absolute loss:
\begin{align} \tag{1}
\int_{\Theta}|\theta-\theta^*|\pi(\theta|\mathbf{x})d\theta= \int_{-\infty}^{\theta^*}(\theta^*-\theta)\pi( \theta|\mathbf{x})d\theta+\int_{\theta^*}^{\infty}(\theta-\theta^*)\pi(\theta|\mathbf{x})d\theta
\end{align}
Differentiating with respect to $\theta^*$ and equating to zero yields:
\begin{align} \tag{2}
\int_{-\infty}^{\widehat{\theta^*}}\pi(\theta|\mathbf{x})d\theta = \int_{\widehat{\theta^*}}^{\infty}\pi(\theta|\mathbf{x})d\theta
\end{align}
EDITED:
I'm confused about the step taken from (1) to (2), which can be found on p. 12 (94) in online notes (Note: I replaced $\delta(\mathbf{x})$ by $\theta^*$) . A more detailed insight will be highly appreciated. My understanding is that it makes use of Leibniz rule. Here $\widehat{\theta^*}$ is the Bayes estimate (which turns out to be the median of $\pi(\theta|\mathbf{x})$), an argument that minimizes (1).


text:
Q: WPF Designer load failure using IoC I have a fairly simple and standard MVVM WPF app.  I am using TinyIoC as a containter to provide the underlying data and cache providers for the ViewModels.  I am using TinyIoC because I want to also share this code with MonoTouch and Monodroid projects.
Every user control who's ViewModels are not dependent on resolving a data provider from TinyIoC are working fine when added to the XAML of the MainWindow.
The user controls who's ViewModels ARE using TinyIoC to resolve the data provider used get their data, cannot be instantiated in the designer view when added to the MainWindow.
Important note: everything works fine when I run the app, just the designers are broken - a big impediment.
Here is the basic code:
    // From App.xaml.cs
    private void HandleAppStartupEvent(object sender, StartupEventArgs e) {
        IDataStoreProvider store = new XmlDataStoreProvider();
        ICacheProvider cache = new DictionaryCacheProvider();

        TinyIoCContainer.Current.Register(store);
        TinyIoCContainer.Current.Register(cache);
    }

View / ViewModel / XAML binding standard implementation - nothing an issue here.
In the depths of the data layer, the IoC container is used to resolve which provider to use - the one that was set in the above code.
public static class Gateway
{
    private static IDataStoreProvider store;
    private static ICacheProvider cache;

    static Gateway() {
        store = TinyIoCContainer.Current.Resolve<IDataStoreProvider>();
        cache = TinyIoCContainer.Current.Resolve<ICacheProvider>();
    }

    // use the store and cache here...

}

Here is the exact error I get from the designer.

Unable to resolve type: Sample.Core.Data.IDataStoreProvider
     at TinyIoC.TinyIoCContainer.ResolveInternal(TypeRegistration registration, NamedParameterOverloads parameters, ResolveOptions options) in C:_dev\Sample\SampleSolution\Sample.Core\Utility\TinyIoC.cs:line 3281
     at TinyIoC.TinyIoCContainer.Resolve(Type resolveType) in C:_dev\Sample\SampleSolution\Sample.Core\Utility\TinyIoC.cs:line 1314
     at TinyIoC.TinyIoCContainer.ResolveResolveType in C:_dev\Sample\SampleSolution\Sample.Core\Utility\TinyIoC.cs:line 1433
     at Sample.Core.Data.Gateway..cctor() in C:_dev\Sample\SampleSolution\Sample.Core\Data\Gateway.cs:line 14

I think I understand why I get this error - the App startup event is not fired to load the IoC before the designer loads and executes the user control inside the MainWindow.
Again important to note, the app works fine - IoC and everything.  I would like to stop the designer loading error by either (in order of preference):

*

*Understanding how to fix the code to properly work with the designer

*Stub out the existing control data with mock data for the designer

*Disabling this designer feature

A: Are you trying to load data in the event handler for your Windows/container loaded event? Doing so has caused this type of problem for me in the past.

A: Here a solution to the second bullet (Stub out the existing control data with mock data for the designer)
Added the following code to the ViewModel constructor:
    public AdminViewModel(UserControl view) {
        this.view = view;

        var designMode = DesignerProperties.GetIsInDesignMode(view);

        if (designMode) {
            Items = new ObservableCollection<ItemModel>
                      {new ItemModel {Name = "Item1"},
                       new ItemModel {Name = "Item2"}};
        }
        else {
            Items= new ObservableCollection<ItemModel>(Gateway.GetItems());
        }
    }

Although works, I have a couple concerns:

*

*Pollutes the code with non-app logic

*Forces me to pass a reference of the View to the ViewModel

I would prefer to make this more "Blend-able" and designer friendly in cleaner ways - any other thoughts?


text:
Q: Dots for Children in div. A jQuery headache - PART 2 So this is part 2 of my previous question (was advised to start a new question for this one).Just for reference here is my previous post: Dots for Children in div. A jQuery headache
My question now is:  How does one go about adding an "active" class/id to the "imgdots" div for styling purposes?For example:Say I'm on image 4 then I want the 4th "imgdots" div to be another colour.Again, any help would be much appreciated!  EDITI have set up a fiddle containing what I have thus far. The initial image slider was from a tutorial I followed and kinda pieced it all together from there.  Here is the link: jsfiddle.net/Reinhardt/cgt5M/8/

A: Have you seen nth child css?
http://www.w3schools.com/cssref/sel_nth-child.asp
#showContainer:nth-child(4)
{
background:#ff0000;
}

A: Try
/* The jQuery plugin */
(function ($) {
    $.fn.simpleShow = function (settings) {
        var config = {
            'tranTimer': 5000,
            'tranSpeed': 'normal'
        };
        if (settings) $.extend(config, settings);
        this.each(function () {
            var $wrapper = $(this),
                $ct = $wrapper.find('.showContainer'),
                $views = $ct.children();
            var viewCount = $views.length;

            var $imgdotholder = $('

').appendTo('.wrapper');
            for (var i = 0; i < viewCount; i++) {
                $('

').appendTo($imgdotholder);
            }
            var $imgdots = $imgdotholder.children();

            var timer, current = 0;

            function loop() {
                timer = setInterval(next, config.tranTimer);
            }

            function next(idx) {
                $views.eq(current).hide();

                current = idx == undefined ? current + 1 : idx;
                if (isNaN(current) || current < 0 || current >= viewCount) {
                    current = 0;
                }

                $views.eq(current).fadeIn(config.tranSpeed);
                $imgdots.removeClass('current').eq(current).addClass('current');
            }

            $imgdots.click(function(){
                clearInterval(timer);
                next($(this).index());
            })

            $wrapper.find('.btn_nxt').click(function(){
                clearInterval(timer);
                next();
            });
            $ct.hover(function(){
                clearInterval(timer);
            }, loop);

            $views.slice(1).hide();
            $imgdots.eq(0).addClass('current');
            loop();
        });
        return this;
    };
})(jQuery);

/* Calling The jQuery plugin */
$(document).ready(function () {
    /**/
    $(".wrapper").simpleShow({
        'tranTimer': 3000,
        'tranSpeed': 800
    });
});

Demo: Fiddle


text:
Q: Use Xcode UIAutomation to record user interactions on ios apps when connected to Mac system I have gone across Appium and recorded the user interactions in iOS Apps with the help of Appium . My aim is to replicate the same feature of recording user interaction and saving the recorded actions into some specific directory in Mac system and later utilize the same whenever required . Is there any way to do that if so can anyone guide me ? . I will be using iOS app signed with developer profile .

A: This might be too obvious but, have you looked at Apple's documentation? You can definitely record user interactions on UIA and then save the script for later use.
https://developer.apple.com/library/ios/documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/UsingtheAutomationInstrument/UsingtheAutomationInstrument.html


text:
Q: Is such a polynomial coefficient possible? Suppose we have a polynomial $(x+y)^2$. What I noticed is that if you subtract $4xy,$ the result changes to $(x-y)^2$.
$(x+y)^2 - 4xy = x^2 + 2xy+ y^2 - 4xy = x^2-2xy+y^2 = (x-y)^2.$
This has me thinking about the flexibility of changing that sum just by adding or subtraction coefficients of $xy.$
So, my question is, does there exist nonzero coefficients $b, c, d \in \mathbb{C}$ such that
$$b(x+y)^2 + cxy = d(x+y)^2?$$
I don't know why, but for some reason I have this mental roadblock about analyzing multivariate polynomials. The answer seems like "no" by equating coefficients and deriving a contradiction, but on the other hand there's numbers like the golden ratio that satisfy $1 + \frac{1}{\phi} = \phi$ and so maybe there's two specific non-zero numbers where such a postulation is possible.

A: The answer is no by the method of equating coefficients as discussed in the comments.
Upon expanding both sides, we obtain
$bx^2 + 2bxy + by^2 + cxy = dx^2 + 2dxy + dy^2.$
$bx^2 + (2b+c)xy+by^2 = dx^2 + 2dxy + dy^2.$
Equating coefficients, one may first find $b=d,$ then $2b+c = 2d \implies c=0.$


text:
Q: Application.displayalerts = false not stopping popup window I'm trying to use VBA in Excel to find and replace multiple values.  The field that is being updated has HTML text so I'm getting a window popup that says I'll lose formatting changes and when it's published back out to TFS it'll be stored as plain text.  Using Application.displayalerts = false isn't stopping that window from appearing.
Is there a way I can use code to make this go away?

A: Addinng the below line will solve the problem.
Application.EnableEvents = False

If you're interested, I like to use this function when I start a long process:
Sub SetEvents(ByVal State As Boolean)
    With Excel.Application
        .DisplayAlerts = State
        .ScreenUpdating = State
        .EnableEvents = State
        If State = True Then .Calculation = xlCalculationAutomatic Else .Calculation = xlCalculationManual
    End With
End Sub

By adding this you can turn off calcs, events, screen and alerts like this in your main sub:
Sub CallEvents()
    SetEvents False
    'Do some stuff
    SetEvents True
End Sub


text:
Q: ElasticSearch dynamic bucket aggregations Currently I have the following mapping:
    array(
        'index' => 'my_index',
        'body'  => array(
            'mappings' => array(
                'products' => array(
                    '_source'    => array('enabled' => false),
                    'properties' => array(
                        'id'     => array('type' => 'integer'),
                        'active' => array('type' => 'boolean'),
                        'specs'  => array(
                            'type'       => 'nested',
                            'properties' => array(
                                'id'      => array('type' => 'integer'),
                                'value'   => array('type' => 'text'),
                                'visible' => array('type' => 'boolean')
                            )
                        )
                    )
                )
            )
        )
    );

I would like to query the products.
And have ElasticSearch return the specifications aggregated. But for each specs.id a bucket with all the values.
And only if visible is true.
  "aggregations": {
      "specs_2": {
        "buckets": [
          {
            "key": "Yes",
            "doc_count": 90
          },
          {
            "key": "No",
            "doc_count": 80
          },
        ]
      },
      "specs_4": {
        "buckets": [
          {
            "key": "Yes",
            "doc_count": 190
          },
          {
            "key": "No",
            "doc_count": 180
          },
        ]
      }
  }

Without knowing the specification ids that are in the data set.
Is this possible?

A: Have you tried doing a nested term aggregation on path specs and field properties.id ? This should create buckets with different ids and specs docs having same id will fall in same buckets. Doing a filter aggregation on visibility will filter out all docs with visibility false. Now you can do a term aggregation on value as sub-aggregation of filter aggregation to get the desired output.


text:
Q: The local variable driver may not have been initialized selenium I'm trying to create a new function and I'm unable to use a driver within the function
I'm getting this message "The local variable driver may not have been initialized "
In the main I have no problem using the driver
    {
        WebDriver driver;
    WebElement check = driver.findElement(By.id("conditions_agree"));
    boolean selected_value = check.isSelected();
    if(!selected_value)
    check.click();
    }```

A: Your code is java, not javascript.
For local variable (variable that is declared in a method), java requires user to initialize before using, so you can modify like this:
WebDriver driver = new ChromeDriver();

A: I think you've created a driver instance in the main method as you stated and next, you are using a non-static block where you again tried to use WebDriver driver instead of it use the previously created instance
public class AutmationTesting {
 static WebDriver driver;

public static void main(String[] args){
{
    System.setProperty("webdriver.chrome.driver", "Path to driver");
    driver = new ChromeDriver();
}

{
  //try to directly access the methods and not by writing the WebDriver driver; otherwise, it'll show an initialization error

    driver.findElement(By.xpath("element_xpath"));
    WebElement check = driver.findElement(By.id("conditions_agree"));
    boolean selected_value = check.isSelected();
    if(!selected_value)
    check.click();
}
}
}


text:
Q: Symfony 3 DateTimeType Incorrect records Form Builder:
->add('createdAt', DateTimeType::class, array(
    'label' => 'admin.accountEdit.formCreatedAt',
    'format' => 'yyyy-MM-dd HH:mm',
    'html5' => false,
    'widget' => 'single_text'
))

I enter the record : 2017-01-01 23:00
But it looks as follows in the database : 2017-01-01 21:00
'Format' parameter is not a problem when the default : 'yyyy-MM-dd'T'HH:mm:ssZZZZZ'

A: Try this instead:
'format' => 'Y-m-d H:i'

It follows the PHP format:
http://php.net/manual/en/class.datetime.php

A: It is due to the timezone settings.
'model_timezone' => 'Europe/Istanbul',
'view_timezone' => 'Europa/Istanbul',


text:
Q: How do you bind a combobox to a Database and show values from an enum, or is this the right approach? I have some comboboxes on a WinForm that have been populated by an enum:
enum valueGenTypes
    {
        None = 0, Prefix = 1, All = 2, Abbreviation = 3, Number = 4
    }

I have one combobox that is Bound to a field in the database that is a value of 0-4.
I've wired up the combobox datasource to the enum:
valGenTypeID.Properties.DataSource = Enum.GetValues(typeof(valueGenTypes));

I get a drop down of the values, however, they don't save or reflect what is in the database.
Forgive me if this sounds dumb, but so far it looks like I can only have the drop down linked to the enum or the DB individually(with predefined values in the combobox).
Is there a way to bridge the relationship between:
DBField = 0
ComboBox displays = "None"
Should I be using an enum, or is this even the right approach?
Thanks,

A: You can set the values that you want to select to the enum values, but you will want to bind the EditValue of the Combobox to the Database field that you are wanting to manipulate.

A: With this:
valGenTypeID.DataSource = Enum.GetValues(typeof(valueGenTypes));

then you have to add the databinding to the combobox:
valGenTypeID.DataBindings.Add("SelectedItem", ClassWithValGen, "ValGenField", false, DataSourceUpdateMode.OnPropertyChanged);

A: I figured out my problem. We are using CSLA with an OR mapper. I had to define and populate the enum on the OR object, then reference the OR object (table name) in the datasource.
Basically, the enum had to be at the object level, rather than the UI (form level).
Thanks for your replies!


text:
Q: cuda fortran speed-up I am trying to evaluate the speed-up of a simple cuda fortran code: increment of an array.
CPU version:
module simpleOps_m
contains
subroutine increment (a, b)
implicit none
integer , intent ( inout ) :: a(:)
integer , intent (in) :: b
integer :: i, n

n = size (a)
do i = 1, n
a(i) = a(i)+b
enddo

end subroutine increment
end module simpleOps_m

program incrementTest
use simpleOps_m
implicit none
integer , parameter :: n = 1024*1024*100
integer :: a(n), b

a = 1
b = 3

call increment (a, b)

if ( any(a /= 4)) then
write (* ,*) '**** Program Failed **** '
else
write (* ,*) 'Program Passed '
endif
end program incrementTest

GPU version:
module simpleOps_m
contains
attributes ( global ) subroutine increment (a, b)
implicit none
integer , intent ( inout ) :: a(:)
integer , value :: b
integer :: i, n

n = size (a)

do i=blockDim %x*( blockIdx %x -1) + threadIdx %x ,n, BlockDim %x* GridDim %x
    a(i) = a(i)+b
end do

end subroutine increment
end module simpleOps_m

program incrementTest
use cudafor
use simpleOps_m
implicit none
integer , parameter :: n = 1024*1024*100
integer :: a(n), b
integer , device :: a_d(n)
integer :: tPB = 256

a = 1
b = 3

a_d = a
call increment <<< 128,tPB >>>(a_d , b)
a = a_d

if ( any(a /= 4)) then
write (* ,*) '**** Program Failed **** '
else
write (* ,*) 'Program Passed '
endif
end program incrementTest

So I compile both versions with pgf90
http://www.pgroup.com/resources/cudafortran.htm
Using "time" command to evaluate execution time, I obtain:

for CPU version
$ time (cpu executable)
real    0m0.715s
user    0m0.410s
sys 0m0.300s

for GPU version
$ time (gpu executable)
real    0m1.057s
user    0m0.710s
sys    0m0.340s

So the speed-up=(CPU exec.time)/(GPU exec.time) is < 1
Are there some reason why the speed-up is not > 1 as one should attain?
Thanks in advance

A: The problem here is that in this rather contrived example, the cost of initialising the large array on the host (a=1) is almost the same as the cost of loop to increment the array contents, which is the part of the code being parallelised on the GPU. Because the total amount of parallel work is about the same as the total amount of serial work, Amdahl's Law is heavily stacked against achieving any sort of significant speed up by parallelising some of the code on the GPU.
A more significant speed up could probably be achieved by fusing the initialisation and increment operations into a single parallel operation on the GPU.
[This answer has been assembled from comments and added as a community wiki entry to get this question off the unanswered list for the CUDA tag]


text:
Q: Python Script Engine not created in MSScriptControl I am trying to use Python from Excel 2003 by means of MSScriptControl.  I followed all the steps required, as indicated on various topics here and elsewhere, such as:

*

*Installing ActivePython

*Adding Reference "MSScriptControl 1.0" to VBA in Excel

*Registering Python by launching the script C:\Python27\Lib\site-packages\win32comext\axscript\client\pyscript.py
but I cannot get my code to work on one PC (whilst working on another, where I followed the same steps as above).
Here's the code in VBA:
Global sc As New MSScriptControl.ScriptControl

Public Function calibrate()

 sc.Language = "python"

 sc.ExecuteStatement ("import SABRSolver")

End Function

when I execute the function, it stops at sc.Language telling me that "A script Engine for the specified language can not be created (Error 380)"
This is really driving me mad, since as said, it is working on other machines with the same setup.
Am I missing something else?


text:
Q: Kill specific process in vb.net I'm writing a program for my school, which is supposed to terminate some processes opened by user, like for example taskmgr, or regedit etc. How to do it? I know files names, and I'm not sure how to get their PIDs.
For example, nasty student want to bypass security program which is blocking "adult" sites, or chans etc. And now I have to block executing files - only two of them - I mean taskmgr and regedit.

A: You don't need to get the PID, it doesn't really get any easier than this ...
For Each proc As Process In Process.GetProcessesByName("taskmgr")
    proc.Kill()
Next


text:
Q: Is it possible to apply a directive to a component inside another component template? I have a ComponentA:
@Component({
    selector: 'component-a',
    template: `<span>{{sampleText}}</span>`,
    styles: []
})
export class ComponentA implements OnInit {

    sampleText: string = 'ComponentA';

    constructor() {}

    ngOnInit() {
    }
}

and a directive for ComponentA:
@Directive({
  selector: '[DirectiveForA]'
})
export class DirectiveForA implements OnInit {

    @Input('customText') customText: string;

    constructor(private componentA: ComponentA) {
    }

    ngOnInit() {
        this.componentA.sampleText = this.customText;
    }
}

I could apply my directive for it:
<component-a>
    <ng-template DirectiveForA customText="injectedText"></ng-template>
</component-a>

But then, I have another ComponentB, which have an ComponentA inside:
@Component({
    selector: 'component-b',
    template: `<component-a></component-a>`,
    styles: []
})
export class ComponentB implements OnInit {

    @ViewChild(ComponentA, { static: false }) componentA: ComponentA;

    constructor() {}

    ngOnInit() {
    }
}

I want to apply the directive to the ComponentA inside it, when using ComponentB like this:
<component-b>
    <ng-template DirectiveForA customText="injectedText!"></ng-template>
</component-b>

Angular is complaining:
ERROR NullInjectorError: StaticInjectorError(AppModule)[DirectiveForA -> ComponentA]:
    StaticInjectorError(Platform: core)[DirectiveForA -> ComponentA]:
    NullInjectorError: No provider for ComponentA!

Question: Is there a way for me to make it works? If there isn't, what is the better practice for this?
(In my case, ComponentA is actually a grid, and DirectiveA is template for a certain grid column. ComponentB is actually the grid with an input form. ComponentB is used very frequently but I want to customize a column inside ComponentA.)

A: I found a way using optional injection at last.
@Directive({
  selector: '[DirectiveForA]'
})
export class DirectiveForA implements OnInit {

    @Input('customText') customText: string;
    private target: ComponentA;

    constructor(@Host() @Optional() public componentA: ComponentA, @Host() @Optional() public componentB: ComponentB) {
        if(componentA){
            this.target = componentA;
        }
        else if(componentB){
            this.target = componentB.componentA;
        }
    }

    ngOnInit() {
        if(this.target){
            this.target.sampleText = this.customText;
        }
    }
}


text:
Q: When I try to add new account for google analytic it doesn't take my project from firebase for iOS When I try to create account with google analytic it shows me error like this: "This Firebase project is already connected to an Analytics account. In order to connect it to this account, you must first disconnect it from its current Analytics account."
 I already delete it by following these steps.
1.Click Admin.
2.In the ACCOUNT column, use the menu to select the account you want to delete.
3.In the ACCOUNT column, click Account Settings.
But shows same error.
Here is the screenshot for the same.


text:
Q: Добавление, построение данных на страницы post в Wordpress Как лучше/правильнее реализовать динамическое добавление полей с формы в запись.
С возможностью в дальнейшем редактировать информацию с админ панели.
Правильно ли так делать:
foreach( $_POST['amount'] as $key => $n ) {
  $key++;
  update_post_meta($post_id, 'key_'.$key, sanitize_text_field( $n ));
}


text:
Q: How to configure antisamy in cq 5.5? I have cq 5.5 project.
I want to Prevent XSS attacks.
According this link cq provides integration with AntiSamy project.
Please provide concrete steps for integration with AntiSamy because I really cannot find it.
update
Should I write code like this somewhere?
import org.owasp.validator.html.*;

Policy policy = Policy.getInstance(POLICY_FILE_LOCATION);

AntiSamy as = new AntiSamy();
CleanResults cr = as.scan(dirtyInput, policy);

MyUserDAO.storeUserProfile(cr.getCleanHTML()); // some custom function

A: The XSS protection mechanism offered by CQ is already based on the AntiSamy Project. You only need to provide your custom antisamy configuration, in case the default configuration doesn't suit your needs.
The default antisamy configuration is present at /libs/cq/xssprotection/config.xml, which can be overlaid with your custom config within /apps.
You can make use of the XSS Protection API available in CQ, to protect your website from security attacks. The XSSAPI and the XSSFilter classes provide various methods to validate the given values.
The xssAPI is available as an implicit object on inclusion of /libs/foundation/global.jsp, whereas the XSSFilter can be obtained and used as shown below.
XSSFilter xssFilter = sling.getService(XSSFilter.class);
String filteredString = xssFilter.filter(ProtectionContext.HTML_HTML_CONTENT,
                            dirtyInput, POLICY_FILE_LOCATION);

You can find some predefined policy files and steps to create a new configuration here.
UPDATE:
In case you do not want to use the XSS API, then you need to have the owasp esapi bundle installed in your instance, and then you can use the code mentioned in the question.


text:
Q: How to get Last Active Cell in Excel 2007 I am working with C++ unmanaged and Excel 2007. I am using a call to the Excel4 API to get the range of cells selected by the user.
When the user selects what I call a "common" range, this call returns a range like this "R1C1:R4C3", which is exactly the format that I need for doing other operations in my application.
However, when the user decides to select whole columns then this API call returns a range only with columns, something like this "C1:C3", which of course is a valid excel range, but it means to me that I have to modify it so it looks like the the range above; in other words I have to manually add it the rows range.
So I take this range "C1C3" and change it to be "R1C1:R65534C3".
Perhaps at this point you already noticed my problem, as you can see I'm hard coding the rows range to be the max numbers of rows supported by Excel 2003 (the application also works with this version of excel).
This of course is not what I'm looking for, because once I get the selected range, I read the info in that range and use that info to make a query to the server, so imagine that the user only entered data until row 534 and still my query will have 65000 rows with nothing.
So my question is how can I get the last cell in which the user entered data, I think it is called the last active cell, so I can delimit my range until that row and please remember that I'm working with unmanaged code.

A: The Excel 4 API? Really?
There's a command xlcSelectEnd which you can use to jump to the last cell with text entered in it in any direction from a given cell.

A: Try casting range.selection to a Range object.

A: region Get Last Used Row
     Excel.ApplicationClass app = new Excel.ApplicationClass();
        Excel.Workbook workBook = app.Workbooks.Open(_PathFile,
                 System.Reflection.Missing.Value,
                 System.Reflection.Missing.Value,
                 System.Reflection.Missing.Value,
                 System.Reflection.Missing.Value,
                 System.Reflection.Missing.Value,
                 System.Reflection.Missing.Value,
                 System.Reflection.Missing.Value,
                 System.Reflection.Missing.Value,
                 System.Reflection.Missing.Value,
                 System.Reflection.Missing.Value,
                 System.Reflection.Missing.Value,
                 System.Reflection.Missing.Value,
                 System.Reflection.Missing.Value,
                 System.Reflection.Missing.Value);
        // Get the active worksheet using sheet name or active sheet
        Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;
        // Find the last real row
        int _InLastRow = workSheet.Cells.Find("*",System.Reflection.Missing.Value,
            System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSearchOrder.xlByRows,Excel.XlSearchDirection.xlPrevious, false,System.Reflection.Missing.Value,System.Reflection.Missing.Value).Row;
#endregion


text:
Q: Flutter cannot call setState to rebuild widget I am very new to flutter and the millions of answers I have read online made me even more confusion. This is my page:
class SecondDegreePage extends StatefulWidget {
  const SecondDegreePage({Key key}) : super(key: key);

  @override
  SecondDegreePageState createState() => SecondDegreePageState();
}

class SecondDegreePageState extends State<SecondDegreePage> {

  final GlobalKey<FormState> _formKey = new GlobalKey();

  final controllerParamA = TextEditingController();
  final controllerParamB = TextEditingController();
  final controllerParamC = TextEditingController();

  Quadratic _solver = Quadratic([
    (Random().nextInt(10) + 1) * 1.0,
    (Random().nextInt(10) + 1) * 1.0,
    (Random().nextInt(10) + 1) * 1.0
  ]);

  void updateData() {
    setState(() {
      _solver = Quadratic([
        (Random().nextInt(10) + 1) * 1.0,
        (Random().nextInt(10) + 1) * 1.0,
        (Random().nextInt(10) + 1) * 1.0
      ]);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalization.of(context).title),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[

          // Input form
          Form(
            key: _formKey,
            child: Padding(
              padding: EdgeInsets.all(20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  EquationInputField(
                    controller: controllerParamA,
                    textHint: 'a',
                    width: 70,
                  ),
                  EquationInputField(
                    controller: controllerParamB,
                    textHint: 'b',
                    width: 70,
                  ),
                  EquationInputField(
                    controller: controllerParamC,
                    textHint: 'c',
                    width: 70,
                  ),
                ],
              ),
            ),
          ),

          // Submit button
          Padding(
            padding: EdgeInsets.fromLTRB(0, 30, 0, 30),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                RaisedButton(
                  onPressed: () => updateData(),
                  color: Colors.blue,
                  elevation: 6,
                  child: Text(
                    AppLocalization.of(context).solve,
                    style: TextStyle(
                        color: Colors.white
                    ),
                  ),
                )
              ],
            ),
          ),

          //Solutions
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(bottom: 10),
              child: AlgebraicSolutions(
                solver: _solver
                ),
              ),
            ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    controllerParamA.dispose();
    controllerParamB.dispose();
    controllerParamC.dispose();

    super.dispose();
  }
}

The type Quadratic is simply a class that does some math, nothing important. The problem is in this line:
RaisedButton(
  onPressed: () => updateData()
}

Why nothing happens? I have read thet the call to setState calld the build method and the widget is re-built. For this reason I expect that
child: AlgebraicSolutions(
  solver: _solver
),

here the _solver reference gets updated. AlgebraicSolutions is the following:
class AlgebraicSolutions extends StatefulWidget {

  final Algebraic solver;

  const AlgebraicSolutions({Key key, @required this.solver}) : super(key: key);

  @override
  AlgebraicSolutionsState createState() => AlgebraicSolutionsState();
}

class AlgebraicSolutionsState extends State<AlgebraicSolutions> {

  //'Quadratic' is a subtype of Algebraic
  Algebraic _solver;

  @override
  void initState() {
    _solver = widget.solver;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var solutions = _solver.solve();

    return ListView.builder(
      itemCount: solutions.length,
      itemBuilder: (context, index) {
        //...
      }
    );
  }

}

Is that because I am using initState in AlgebraicSolutionsState  that breaks something?
Please note that Quadratic type is subclass of Algebraic type.

A: Yep, saving the initial value in initState is what's giving you trouble. That lifecycle method is only called on first build but since the widget reconciles to the compatible type the same state is used. i.e. the properties change (widget instance is different) but the state is the same object. build gets called again but initState does not.
In this situation I would use a getter to give you the same convenience but always use the _solver from the current widget. Then you can discard the initState.
Algebraic get _solver => widget.solver;

The other option being didUpdateWidget but it really not necessary here for something so straightforward otherwise.


text:
Q: How to read a big file in cloud storage with beam TextIO in Dataflow I have a bucket in which I daily insert enormous text files (about 300 millions lines), in GZIP format. Every time a new file is added in this bucket, I need to read every line of it and process it in a Dataflow pipeline. To do this, I implemented a streaming pipeline in Java, with the following piece of code
 p.apply("Read new file", TextIO.read()
            .from("gs://my_bucket/*")
            .withCompression(Compression.GZIP)
            .watchForNewFiles(Duration.standardMinutes(1), Watch.Growth.never()))

My text files are stored in Google Cloud Storage with the following metadata :

*

*Content-Type: text/plain

*ContentEncoding: gzip

The problem is the following: when a new document is added, an infinite amount of lines are read from this file by TextIO, as we can see on the following picture (I stopped the process after 500M lines have been sent by TextIO):

My questions are: why is this happening ? Where is the mistake in my piece of code ?


text:
Q: Solving $x$, $y$ and $z$ If I have $22x = 23y = 24z$ and $x+y+z = 3865$ how to obtain the values of $x$,$y$ and $z$ ?

A: First, try to express $y$ and $z$ by $x:$
$$22x = 23y\Leftrightarrow y = \frac{22}{23}x$$
$$22x = 24z\Leftrightarrow z = \frac{11}{12}x$$
Then put this into your term to find the value of $x\colon$
$$x+y+z=3865\Leftrightarrow x+\frac{22}{23}x+\frac{11}{12}x=3865$$
Now you have the value of $x.$ To figure out $y$ and $z$ is left as an exercise to you.

A: use $ y = \frac{22}{23}x$ and $z = \frac{22}{24}x$ in last equation.

A: Rewrite $ 22x = 23y = 24z $ as three separate equations:
$$ 22x=23y $$ $$ 22x=24z $$ $$ 23y = 24z $$
Then choose one of the three options below:
Option 1
Solve for $y$ and $z$ in terms of $x$.
$$ y = \frac{22}{23}x$$
$$ z = \frac{22}{24}x$$
The equation $x + y + z = 3865$ can be rewritten as $$ x + \frac{22}{23}x + \frac{22}{24}x = 3865 $$ Combine like terms to solve for $x$, then use that solution of $x$ to solve for both $y$ and $z$.
Option 2
Solve for $x$ and $z$ in terms of $y$.
$$ x = \frac{23}{22}y$$
$$ z = \frac{23}{24}y$$
The equation $x + y + z = 3865$ can be rewritten as $$ \frac{23}{22}y + y + \frac{23}{24}y = 3865 $$ Combine like terms to solve for $y$, then use that solution of $y$ to solve for both $x$ and $z$.
Option 3
Solve for $x$ and $y$ in terms of $z$.
$$ x = \frac{24}{22}z$$
$$ y = \frac{24}{23}z$$
The equation $x + y + z = 3865$ can be rewritten as $$ \frac{24}{22}z + \frac{24}{23}z + z = 3865 $$ Combine like terms to solve for $z$, then use that solution of $z$ to solve for both $x$ and $y$.


text:
Q: Cordova 2.1.0 magtek idynamo sdk We upgraded our cordova from 1.6.1 to 2.1.0 and also to iOS6. Now we are experiencing duplicate symbol error. here is the link of my question iOS6: duplicate symbol error in xcode 4.5
I tried downgrading cordova. On 2.0.0 still have the same problem but when I downgraded to 1.9.0 it works fine. Based on my initial research I found out that the problem might be caused by the new Xcode project template of cordova. Since 1.6.1 to 1.9.0, creating a new project must be done from the xcode application but with 2.0.0 to 2.1.0 the project is created via command line. Can anybody help me shed some light with this? Thank you


text:
Q: Converting long value(epoch) to Date format using gremlin query I have vertex created date in long format (epoch). I want to convert the long value into particular date format (YYYY-MM or YYYY-MM-DD) using gremlin query. .map or .transform is not working. Can someone please help.

A: The Gremlin language doesn't have built in features to convert dates. You would have to use a lambda if you want to do it within Gremlin - for Groovy it would look like:
gremlin> g = TinkerGraph.open().traversal()
==>graphtraversalsource[tinkergraph[vertices:0 edges:0], standard]
gremlin> g.addV('person').property('dob',Date.parse('yyyy-MM-dd','2018-10-01').getTime())
==>v[0]
gremlin> g.V().valueMap()
==>[dob:[1538366400000]]
gremlin> g.V().values('dob').map{new Date(it.get()).format('yyyy-MM-dd')}
==>2018-10-01

You could write the same in Java by skipping the shorthand Groovy provides and just using SimpleDateTime in the lambda. Of course, TinkerPop advises against lambdas and in this case, I think that the better solution is to simply return your result as a Long and then transform it on the client as needed once in hand.


text:
Q: UFT ObjectSpy unable to identify objects in chrome I was trying to make ObjectSpy work with Chrome browser but its unable to identify objects.
Whenever trying to identify getting this: WinObject("Chrome Legacy Window").
I tried reinstalling UFT and chrome and Microfocus extension for chrome but it didn't help.
I have downloaded extension from internet and its shows the version as Micro Focus UFT Agent
2022.0.1.25. My UFT version is 14.53. I am not sure if its compatibility issue.
Please help.

A: UFT 14.53 is pretty old as far as supported browsers are concerned (July 2019), if possible I would suggest upgrading to the latest version (upgrades are included in the license).
Failing that you can try to remove the extension from Chrome and install the one that comes with your version of UFT (in <UFT installation dir>/Installations) although I'm not sure it will work with current versions of Chrome.


text:
Q: Observable BehaviorSubject Service - Singleton and providers I have a simple component progressBar in order to display (or not) the progress bar.
And a simple observable service.
Here is the service :

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class ProgressBarService {
  subject = new BehaviorSubject<any>(false);
  changes = this.subject
              .asObservable()
              .do(changes => console.log('new state', changes));

  constructor(private http: Http) {
  }
  show() {
    this.subject.next(true);
  }
  hide() {
    this.subject.next(false);
  }
}

Nothing fancy here, just a BehaviorSubject which is set by default with false, hide/show is used to change the value with .next().
The component looks like this :

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { ProgressBarService } from './progressbar.service';

@Component({
  selector: 'app-progressbar',
  templateUrl: './progressbar.component.html',
  styleUrls: ['./progressbar.component.scss'],
  providers:[ProgressBarService]
})

export class ProgressbarComponent implements OnInit {

  isDisplay : boolean;

  constructor(private $progressbar : ProgressBarService) { }

  ngOnInit() {
    this.$progressbar
      .changes
      .subscribe((display : boolean) => this.isDisplay = display);
  }

  showProgress(){
    (this.isDisplay)
      ? this.$progressbar.hide()
      : this.$progressbar.show();
  }
}

During the init, the component subscribe to the subject in order to get the default value and set it to isDisplay.
showProgress is only used to try it in my template.
<md-progress-bar mode="indeterminate" color="accent" *ngIf="isDisplay"></md-progress-bar>

<button type="submit" md-raised-button color="primary" (click)="showProgress()">Show/hide progressBar</button>

And it works just fine when the service is used inside the component.
But, when I try to call this service inside another component, it doesn't work.
Example : My other component called profilesComponent
import { ProgressBarService } from ../progressbar/progressbar.service';

@Component({
  selector: 'profiles',
  templateUrl: 'profiles.component.html',
  providers: [ProgressBarService]
})

export class ProfilesComponent implements OnInit {

  toto :boolean = false;

  constructor(private $progressbar : ProgressBarService) {}

  ngOnInit() {}

  showProgress() {
    if(this.toto) {
      this.$progressbar.hide();
      this.toto = false;
    } else {
      this.$progressbar.show();
      this.toto = true;
    }
  }
}

I think it's because the two component does not share the same instance of the service but i can't find a way to do so. (Maybe providers in @NgModule?)

A: Thanks to @micronyks, Here is the solution.
For each component, I add the service in the provider's component. In result, the components create a new instance of the service.
In order to resolve the issue, i removed the service from the providers of each component then provide it to the main module.
import { ProgressBarService } from './progressbar/progressbar.service';

@NgModule({
  imports: [
    CommonModule,
    BrowserModule,
    HttpModule,
    AppRoutingModule,
    HomeModule,
    MaterialModule.forRoot()
  ],
  declarations: [AppComponent, ProgressbarComponent],
  providers: [ProgressBarService],
  bootstrap: [AppComponent],
})
export class AppModule { }

The components now share the same instance and the progress bar is well displayed.


text:
Q: Tool Tip is not showing properly when Zoom in & Zoom out on the browser is performed I am using EXT JS 3.4.
The code of my Column Model goes like this : -
My Ext.grid.Column for Column Model is getting configured from the database like this.
Ext.QuickTips.init();
cm = new Ext.grid.ColumnModel( {
            columns : cols // the cols is getting generated from the database
        });

The json data for the cols mentioned in above code is generated as follows:
{
  header: "Title Alias",
  type: "STRING",
  dataIndex: "order#title_alias",
  width: 80,
  tooltip: "Title Alias",
  sortable: "true",
  filter: {
    test: "/^{0}/i"
  }
}

QUERY :  The tool tip is shown in two lines. i want the tool tip to adjust its width
according to text the tool tip text should be shown in single line only.
BOUNDATION : cannot modify "cols".
APPROACH : can we override or apply some kind of configuration to the quick tips. IS it possible.

A: You should be able to set the css for the tooltip and define:
.x-tip .x-tip-body {
    white-space: nowrap;
}

to prevent it from wrapping.


text:
Q: Cannot set property 'background' of undefined When I run the code below, I get the following error:

Uncaught TypeError: Cannot set property 'background' of undefined

What am I doing wrong?

for(var n = 0; n < 5; n++) {
    var heads='head'+n;
    var image="images/"+heads+".jpg";
    console.log(heads);
    document.getElementsByClassName('horse2').style.background="url("+image+")";
}
#results .horse1 { background-image: url(images/head1.png); }
#results .horse2 { background-image: url(images/head2.png); }
#results .horse3 { background-image: url(images/head3.png); }
#results .horse4 { background-image: url(images/head4.png); }

        1st

        1st

        1st

A: The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object. The nodes can be accessed by index numbers.
You should use
document.getElementsByClassName('horse2')[0].style.background="url("+image+")";

A: document.getElementsByClassName('horse2') this will return an array of elements. You should use
document.getElementsByClassName('horse2')[0].style.background="url('img-url')";

A: You should aware that getElementsByClassName selector returns an array so you need to supply the index for it , change your code to this :
var el = document.getElementsByClassName('horse2')[0];
el.style.background = "url("+image+")";

A:
Document.getElementsByClassName returns an array-like object of all child elements which have all of the given class names.

It is important to note two things:

*

*An array-like object is a regular object with a length property, and  properties with sequential numerical names starting at 0. Other than that, it has none of the other methods of a normal array, though it has a couple of its own.

*The array-like object returned by Document.getElementsByClassName is a "live HTMLCollection", which means that as elements are added and removed from the DOM, so too will they be added to or removed from the collection.

Document.getElementsByClassName will never return a single element by itself, it will always return a live HTMLCollection.
You have a few options (minor variations may not be mentioned):

*

*Iterate the collection (unnecessary if there will only ever be one element of each class):
var collection = document.getElementsByClassName('horse2');
for(var i = 0; i < collection.length; ++i) {
    collection[i].style.background = "url("+image+")";
}

*If there will only ever be one element, the recommended way would be to use an id instead of a class then use document.getElementById, which returns a reference to a single element with the supplied ID.
document.getElementById('horse1').style.background = "url("+image+")";

*If there will only ever be one element and you need to use classes, but you don't need to use Document.getElementsByClassName specifically, you can instead use Document.querySelector, which returns the first Element within the document that matches the specified selector, or group of selectors.
document.querySelectorAll('.horse1').style.background = "url("+image+")";

*If there will only ever be one element and you must use Document.getElementsByClassName, you can use bracket notation to select the first element in the collection
document.getElementsByClassName('horse1')[0].style.background = "url("+image+")";

However, if there ever happens to be no elements in the collection, there will be no first element to select, and you will get the same error all over again.


text:
Q: How to check for internet connection throughout the app I want to implement a functionality in the appdelegate which checks for internet connection whenever the app is running and show alerts accordingly.I wouldnt want to code in each and every class checking for internet connectivity. Is this possible? Iam using Alamofire and SwiftyJson too in the project.

A: Add this class in ur project:
import SystemConfiguration

open class Reachability {
class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }

    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        return false
    }

    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
}
}

Use it where ever you want as follows :
if (Reachability.isConnectedToNetwork() == true){
       // Do what you want...
    }
    else{
        //Show alert
    }

A: You could make use of the SystemConfiguration framework (Determine the reachability of the device) to do so. Then make a swift file like the example below to keep things clean. This will handle all the cases. This will check for no internet, cellular and wifi.
Connection.swift
import SystemConfiguration

protocol Utilities {
}

extension NSObject:Utilities{

    enum ReachabilityStatus {
        case notReachable
        case reachableViaWWAN
        case reachableViaWiFi
    }

    var currentReachabilityStatus: ReachabilityStatus {

        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
        zeroAddress.sin_family = sa_family_t(AF_INET)

        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                SCNetworkReachabilityCreateWithAddress(nil, $0)
            }
        }) else {
            return .notReachable
        }

        var flags: SCNetworkReachabilityFlags = []
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
            return .notReachable
        }

        if flags.contains(.reachable) == false {
            // The target host is not reachable.
            return .notReachable
        }
        else if flags.contains(.isWWAN) == true {
            // WWAN connections are OK if the calling application is using the CFNetwork APIs.
            return .reachableViaWWAN
        }
        else if flags.contains(.connectionRequired) == false {
            // If the target host is reachable and no connection is required then we'll assume that you're on Wi-Fi...
            return .reachableViaWiFi
        }
        else if (flags.contains(.connectionOnDemand) == true || flags.contains(.connectionOnTraffic) == true) && flags.contains(.interventionRequired) == false {
            // The connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs and no [user] intervention is needed
            return .reachableViaWiFi
        }
        else {
            return .notReachable
        }
    }

}

Then you can use it however you like: Here is a sample to check if no internet.
if currentReachabilityStatus == .notReachable {
        // Internet is offline
        // show alert or do something.
    }


text:
Q: Ubuntu 18.04.1 freezes after loging in I recently installed Ubuntu 18.04.1 (Dual boot with win.10), and ever since the first login, it'd freeze after i logged in (typed pass & enter). The cursor would get stuck, and nothing would happen.
My current work-around/fix is booting through recovery mode/dpkg, and then resume normal boot.
Now after doing some googling, i found that it might be related to graphics driver (Nvidia), so i followed this solotion. I have HP with Nvidia 1050, & am not sure if it's the right driver.
I'm also relatively new to the linux environement, so i don't know how to trouble shooot. So thanks in advance for help!

A: Update:
Ok so I continued to do some googling, and since I have a clean install I didn't mind the risk of experimenting. Therefore, first went on Software Update/Settings/Additional Drivers, and chose Nvidia 396 (instead of 390), which led me to a login loop.
Thereafter I followed the FIRST instruction here, but no fix.
Finally, I booted through FailsafeX, and chose X.org X server driver instead. I restarted a couple of times, even started windows just to be sure, and it now seems to work.
PS: I don't know exactly what happened, and I'm almost certain that it will reverse soon enough, so if someone knows a solid fix, pls let me know! and if this is a fix, hope it helps :)


text:
Q: Why would ISC dhcpd ignore vendor options? I'm trying to use an existing dhcpd to autoconfigure Raritan networked PDUs. This works roughly like PXE booting: there are additional DHCP options that direct the device to fetch a config file via TFTP. However, it uses vendor DHCP options to do this.
I have defined the option space, and a new class for the PDUs. I can see that my class is being matched (I set the DNS and domain-name differently inside the class, and those options are sent). However, the vendor-specific options are not sent (checked with dhcpdump). The server has no problem with the config though (that it logs anyway).
What can cause it to not send vendor options?
set vendor-string = option vendor-class-identifier;

option space RARITAN code width 1 length width 1 hash size 3;
option RARITAN.pdu-tftp-server code 1 = ip-address;
option RARITAN.pdu-update-control-file code 2 = text;
option RARITAN.pdu-update-magic code 3 = text;

class "PDUs" {
    match if option vendor-class-identifier = "Raritan PDU 1.0";
    vendor-option-space RARITAN;
    option vendor-class-identifier "Raritan PDU 1.0";
    option domain-name-servers 1.1.1.1;
    option domain-name "pdu.net";
    option RARITAN.pdu-tftp-server 10.251.0.9;
    option RARITAN.pdu-update-control-file "raritan-update.cfg";
    option RARITAN.pdu-update-magic "20180822-0005";
}

Nothing in any of the existing scopes uses vendor-option-space, so I don't think there are any conflicts there.


text:
Q: Validating logistic regression - formulas needed for simulation This is related to a data classification problem having a Boolean output variable.
Summary: Once I perform the ML task using Logistic regression, I get the required coefficients. I use the multivariate model $\theta_0 + \theta_1X_1 + .. = Y$. Having obtained the $\theta$'s, am looking for some straightforward formulas that I can use to get the following:

*

*For the coefficients:

*

*Standard Error: I think it is $(X^TX)^{-1} * (X^TY)$. Please correct me if wrong

*Wald Stats: Is it square of $\text{Coefficient} / \text{StdError}$?

*95 %CI: Is it $(\text{lower, upper}) = (\text{coefficient}_i - 1.96 SE_i,~  \text{coefficient}_i + 1.96 SE_i)$?

*p-value and significance

*For the whole model

*

*Null model -2 Log likelihood

*Full model -2 Log Likelihood

*Chi-squared

*DF

*Significance level

*ROC Curve

*

*Area under the curve (AUC)

I am new to ML and trying out C# based simulation, so any vector-based formulas would be highly appreciated.


text:
Q: Dynamic relationship class loading with sqlalchemy I have a library via which I dynamically load classes.  It's exposed as
mylib.registry.<className>

registry is an instance of a class that contains a dictionary of class name (strings) to module names, and a getattr call that dynamically loads a class if it is requested.  A user can thus refer to any class without having to deal with the module locations (there is a global namespace for class names, but not module names).
For example, the entries:
{'X', 'mylib.sublib.x',
 'Y', 'mylib.sublib.y'}

could then be used like:
import mylib

x = mylib.registry.X()
y = mylib.registry.Y()

That's the background. On top of this, these objects are sqlalchemy ORM classes which have relationships to one another.  Let's assume here that X has a one-to-many with Y.
Assume thus this definition.
class X(Base):
    y_id = Column(Integer, ForeignKey('y.id'))
    y = relationship('Y')

class Y(Base):
    xs = relationship('X')

These are in separate files, and each imports the top-level registry.
So here's the issue -- how do I actually get this to resolve without loading every class up front?
The example above doesn't work, because if I import only X via the registry, then Y isn't in sqlalchemy class registry, and thus the relatiobship breaks.
If I import the registry itself and then refer to the classes directly, then the modules don't load because of interdependencies.
I tried using a lambda to defer loading, but this too fails with an error about a missing 'strategy'.
What approaches have others used here?   If I'm missing something obvious, let me know.  It's been a long day.
Thanks.

A: You should never use relationships on two sides that don't know about each other. Normally, this is avoided by using backref but in your case this creates problems, because you want each side to be aware of its relationship by itself. The trick here is the back_populates keyword, offered by relationship:
y = relationship("Y", back_populates="xs")

and
xs = relationship("X", back_populates="y")

Applying these will make them aware of each other. However, it will not solve your importing problem. Normally, you could now just from x import X on the Y side. But the other way around won't work because it will create a circular import.
The trick is simple: Put the import after the class you want to import. Because the strings in relationship are evaluated lazily, you can import the class after the relationship was defined. So for X do this:
class X(Base):
    __tablename__ = 'x'
    id = Column(Integer, primary_key=True)
    y_id = Column(ForeignKey('y.id'))
    y = relationship("Y", back_populates="xs")

from y import Y

And the other way around for the Y as well (this is not required, but creates more symmetry). I'd also put a comment there to explain this to avoid someone putting it to the top, breaking the program.


text:
Q: How to get local time from UST in flutter I am making an app using flutter, dart.
I am using some api to get sunrise time using longitude and latitude.
But the data I get is in UST time zone.
I want to convert it to local time zone.
In short I have location and I want to convert time to local time.
eg. I have time "3:02:32 PM" which is in UST and I have location (say India which is +5:30) so I want to get time which will be in this case "8:32:32 PM"

A: In flutter, the standard date time format should come in the local DateTime unless otherwise specified. If you already have the data and you didn't create it then you can parse the time that you get to a DateTime object using:
DateFormat format = new DateFormat("HH:mm:ss");
DateTime time = format.parse("3:02:32 PM");
time.toLocal();

Then to get it back to a string again you can simply go:
time.toString();

The Dart documentation states that

A DateTime object is anchored either in the UTC time zone or in the local time zone of the current computer when the object is created.

And that,

Use the methods toLocal and toUtc to get the equivalent date/time value specified in the other time zone.

This is the documentation for reference.


text:
Q: SQL Server table with different case in PowerShell SMO vs SSMS I'm quite confused and not sure where to start looking. I have a tablename that appears in different case sys.object and in the SSMS GUI, as opposed retrieving it via SMO
e.g. in SSMS I see "TABLENAME" but in Smo I see "TableName." This is causing issues with an IBM application and I'm struggling to figure out why this is.
$table = $SmoServer.Databases.Item("MyDb").Tables.Item("TABLENAME","dbo")
Write-Output $table

Output given is "TableName."
Running a sql query though:
select [name] from sys.objects where name = 'TABLENAME'

Output given is "TABLENAME."
Not that it should matter but collation is case insensitive.
Does anyone have any thoughts?
Thanks.

A: This seems to be a quirk of using the Item method to retrieve the table from the SMO Tables object. The first time you retrieve the table, it seems to return the table with the casing provided in the method argument. If I run the Item method again with different casing, it still outputs the casing the first call.
e.g.:
1st run:
$SmoServer.Databases.Item("MyDb").Tables.Item("TableName","dbo")

Will output "TableName" as was provided in the above parameter, even if the table is actually "TABLENAME."
2nd Run:
$SmoServer.Databases.Item("MyDb").Tables.Item("TableNAME","dbo")

Will still output "TableName" even though I changed the casing. It will only output the new casing of "TableNAME" if I recreate the smoServer object.
Interesting behaviour. I think I'll use Where-Object instead.


text:
Q: [Perforce]p4 files command parse arguments wrong when there are unicodes in arguments You can just try

p4 files //Root//哈哈.txt

The supposed result is

//Root//哈哈.txt - no such file(s).

Instead, you will see

Usage: files [-a -A -e -m max] [-U] files...
      Missing/wrong number of arguments.

Apparently, p4 files command could not parse the unicode argument "//Root//哈哈.txt" and discard it.

A: Your shell might not support the character set you're trying to use.  Note that the p4 command line client lets you set a separate charset to decode command line args, to let you work around this:
https://www.perforce.com/perforce/doc.current/manuals/cmdref/Content/CmdRef/P4COMMANDCHARSET.html


text:
Q: whats yardoc syntax for linking to models that are in a namespace? I couldn't find it anywhere on their website.
Here is what I have:
# {Page::Section}

but when i run the yardoc generation, I get this error:
[warn]: In file `app/controllers/pages_controller.rb':2: Cannot resolve link to Page::Section from text:
[warn]: ...{Page::Section}...

and when I go to the api page where my documentation above is written, it just shows plain text, and not a link to that object's page.
I suspect though, that the above error is because it never found this class:
class Page::Section < ActiveRecord::Base

(but If I change it to PageSection, the docs render just fine).
Maybe it has something to do with the version of yard-rest-plugin i'm using?
I'm not sure

A: I had this problem with namespaced controllers. I was frustrated but it ended up being user error.
Assuming class Inherited::ResourceController < InheritedController
{Inherited::ResourceController#show} will work, but {InheritedController::ResourceController#show} will not. (See, I told you it was user error)


text:
Q: Include a JavaScript library in a JSP file I'm trying to use JavaScript functions from the a JavaScript library in my JSP file to display the result on a web-browser page, but it seems like the inclusion didn't work.
I actually put the .js file corresponding to the library in the WEB-INF folder and added the following line in the JSP file to include it in it :

    <script type="text/javascript" src="./jsgl.min.js"></script>

I successfully managed to use the library in a simple HTML file, that's why I don't understand why this doesn't work.
EDIT :

A: TLDR
Put the JS file in a folder under web content (but not WEB-INF) like [WebContent]/js/jsgl.min.js, and use the following in the JSP:
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jsgl.min.js"></script>

Explanation
JSP files are compiled by the server, then processed to send data (typically HTML) back to the web browser.  A <script> tag is a HTML tag that gets interpreted by the browser, not by the servlet container. So the browser sees that in the HTML then makes a new request to the server for the JavaScript file in the src attribute.
The src attribute is relative to the URL that the browser asked for, not to the path of the JSP on the server.
So as an example, let's say:

*

*The browser asks for a page at http://example.com/SomeWebApp/some-resource

*The servlet container internally forwards the request to a JSP at /WEB-INF/jsp/somepage.jsp

*The response sent to the browser contains the script tag <script type="text/javascript" src="./jsgl.min.js"></script> (as in your question)

*The browser sees the URL ./jsgl.min.js and resolves it relative to the URL it has asked the server for (which in this case was http://example.com/SomeWebApp/some-resource - note there is no trailing '/') so the browser will request the JS file from http://example.com/SomeWebApp/jsgl.min.js*.  This is because the relative URL in the script tag's src attribute starts with a '.'.

Another answer suggested putting the JS file in a 'js' folder and changing the script tag to <script type="text/javascript" src="/js/jsgl.min.js"></script>.  Using the same original page URL as in the example above, the browser would translate this src URL to http://example.com/js/jsgl.min.js.  Note that this is missing the "/SomeWebApp" context path.
The best solution therefore is indeed to put the JS file in a static folder like /js/jsgl.min.js, but to use the following in the JSP script tag:
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jsgl.min.js"></script>

The JSP will translate the ${pageContext.request.contextPath} bit into the current context path, making the code portable (if you redeploy the webapp with a different context path, it will still work).  So the HTML response received by the browser will be (again, sticking with our example above):
<script type="text/javascript" src="/SomeWebApp/js/jsgl.min.js"></script>

The browser will now resolve that relative URL to the correct target.
__
*If the original URL had a trailing slash = i.e., was http://example.com/SomeWebApp/some-resource/, the JS URL would be http://example.com/SomeWebApp/some-resource/jsgl.min.js

A: Static resources should be put outside the WEB-INF folder (as you would typically not allow web access to its content).
You could put the file under webapp/js/, then change your script import to:
<script type="text/javascript" src="/js/jsgl.min.js"></script>

In addition to being good practice, this is good as it is not relative to the location of the JSP file.

A: Files in WEB-INF are inaccessible.

You may put them under webapp and try accessing as mentioned above.


text:
Q: How to test Here Map Android SDK Navigation Using HERE Mobile SDK for Android, we tried to test the navigation and created a GPS Feeder for mock locations. We get different results using position manager vs navigation
Using the position manager, we tracked the location as in this image
(click here)
Using the position listener from the navigation manager
(click here)
We also tried with HERE WeGo Android App from Android Play Store, and we had the same issues.
But using Google Navigation, this issue didn't happen.
Do you know any other solution for Navigation testing?

A: Best for testing your navigation is to use navigationManager.simulate(navigationRoute, 60); Then you will be driving along the route, however, you cannot test how the route is being recalculated in case you don't follow the route.

A: If you want to real testing means when you are moving and navigation updates you then you have to use navigationManager.startNavigation(route) instead of navigationManager.simulate(navigationRoute, 50);


text:
Q: Convert number into hours and minutes wile reading CSV in Pandas I have CSV file where the second column indicates a time point with the format HHMMSS.
ID;TIME
A;110500
B;090000
C;130200

This situation indicates some questions for me.

*

*Does pandas have a data format to represent a time point with hour, minutes and seconds but without the day, month, ...?

*How can I convert that fields to such a format?
On Python I would iterate over the fields. But I am sure that Pandas have a more efficient way.
If there is no time of day format without date I could add a day-month-year date to that timepoint.
That is an MWE
import pandas
import io

csv = io.StringIO('ID;TIME\nA;110500\nB;090000\nC;130200')

df = pandas.read_csv(csv, sep=';')

print(df)

Results in
  ID    TIME
0  A  110500
1  B   90000
2  C  130200

But what I want to see is
  ID    TIME
0  A  11:05:00
1  B   9:00:00
2  C  13:02:00

Or much better cutting the seconds also
  ID    TIME
0  A  11:05
1  B   9:00
2  C  13:02

A: You could use the parameter date_parser in read_csv like and the time accesor
df = pandas.read_csv(csv, sep=';',
                     parse_dates=[1], # need to know the position of the TIME column
                     date_parser=lambda x: pandas.to_datetime(x, format='%H%M%S').time)

print(df)

  ID      TIME
0  A  11:05:00
1  B  09:00:00
2  C  13:02:00

But doing it after reading might be as good
df = (pandas.read_csv(csv, sep=';')
        .assign(TIME=lambda x: pandas.to_datetime(x['TIME'], format='%H%M%S').dt.time)
        #or lambda x: pandas.to_datetime(x['TIME'], format='%H%M%S').dt.strftime('%#H:%M')
     )


text:
Q: Rotate Camera in the Direction behind object in OpenGL I'm making a game in OpenGL, using freeglut.
I have a car, which I am able to move back and forward using keys and the camera follows it. Now, when I turn the car(glRotate in xz plane), I want the camera to change the Camera position(using gluLookAt) so it always points to the back of the car.
Any suggestions how do I do that?

A: For camera follow I use the object transform matrix

*

*get object transform matrix
camera=object

use glGetMatrix or whatever for that

*shift rotate the position so Z axis is directing where you want to look
I use object aligned to forward on Z axis, but not all mesh models are like this so rotate by (+/-)90 deg around x,y or z to match this:

*

*Z-axis is forward (or backward depends on your projection matrix and depth function)

*X-axis is Right

*Y-axis is Up

with respect to your camera/screen coordinate system (projection matrix). Then translate to behind position

*apply POV rotation (optional)
if you can slightly rotate camera view from forward direction (mouse look) then do it at this step
camera*=rotation_POV

*convert matrix to camera
camera matrix is usually inverse of the coordinate system matrix it represents so:
camera=Inverse(camera)

For more info look here understanding transform matrices the OpenGL inverse matrix computation in C++ is included there.


text:
Q: Analog of COM programming in Linux/UNIX The Component Object Model (COM) is (or was...) the way in Windows to provide language-neutral software components.
Is there any programming model in Linux/UNIX with the same philosophy of code reuse through binary components?

A: On Linux, DBus is currently in the process of becoming the de-facto higher-level standard.

A: The Evolution email client as part of GNOME uses CORBA. It uses ORBit which is a lightweight CORBA ORB.
http://projects.gnome.org/ORBit2/

A: Sun RPC was supposed to be that. Then there was CORBA. Then GNOME Bonobo and KDE DCOP. Now it looks like D-Bus is latest fashion.


text:
Q: EXC_ARITHMETIC Error in Xcode if (([gameplay1.text intValue] % [gameplay3.text intValue]) == 0)
{
    //Do something
}

Can someone please help me out with this?

A: You have provided almost no information, but it seems to me that
[gameplay3.text intValue]

returns 0. You can't divide by zero, hence the error.

A: There are a few things that can cause this, the most likely of which being that you are trying to divide by 0. What is the value of [gameplay3.text intValue] when this occurs?

A: it because you can't divide by zero
you can add some code like
if(![gameplay3.text intValue]){
    gameplay3.text = "1";
}

before your if judgement
it should be work and not affect your results :)


text:
Q: Using a counter to find multiple occurences on same day from ID & date I am trying find when a person has multiple occurences on the same day & when they do not.
My data looks something like this
data have;
input id date ;
datalines ;
1 nov10
1 nov15
2 nov11
2 nov11
2 nov14
3 nov12
4 nov17
4 nov19
4 nov19
etc...;

I want to create a new variable to show when an occurence happens on the same day or not. I want my end rseult to look like
data want;
input id date occ;
   1 nov10  1
   1 nov15  1
   2 nov11  2
   2 nov11  2
   2 nov14  1
   3 nov12  1
   4 nov17  1
   4 nov19  2
   4 nov19  2
   etc...;

THis is what I tried but it is not working for each date instead only doing it if the date repeats on the first. Here is my code
data want ;
set have ;
by id date;
if first.date then occ = 1;
else occ = 2;
run;

A: Your IF/THEN logic is just a complicated way to do
occ = 1 + not first.date;

Which is just a test of whether or not it is the first observation for this date.
Looks like you want to instead test whether or not there are multiple observations per date.
occ = 1 + not (first.date and last.date) ;


text:
Q: Android: Accessing a function within a thread and getting the result? In my android service, I'm starting a new thread like this
    thread = new Thread(new Runnable() {
        public void run() {
            new myClassName(getApplicationContext());
        }
    });
    thread.start();

The class is ran in a separate thread because it would otherwise block the service thread (causes timeout). That code is in the "onCreate" method, and is alive the whole time whilst the service is alive (unless it crashes, of course).
Now, I need to have a function in "myClassName" which returns a String. I've not actually created that function yet, but I'm trying to test it with a function which simply returns "hello", so let's call that function "helloFn".
    public String helloFn(String name) {
        return "hello "+name;
    }

How can I call "helloFn" which is inside the thread I just created, from my service? Thanks!

A: Create a new class which implements Runnable, and call helloFn(name) on the instance of that class.


text:
Q: How to remove some value of condition in scss? I have a condition in scss, but I want to remove my value, how can I remove that value in scss? I put some code in bellow and also with image too
$color-sp: color-sp;
$width: 100%;

@for $i from 1 through 12 {
   @for $j from 12 through 1 {
      .#{$color-sp}-#{$i} {
          width: $j;
      }
  }
}

I put some link to know my result :
https://www.sassmeister.com/gist/3d049565b0be28429f7d3803baf1bcb1

A: You can achieve that with an if statement
$color-sp: color-sp;
$width: 100%;
$max: 12;
$min: 1;
$j: $max;
@for $i from $min through $max {
    #{$color-sp}-#{$i} {
        width: $j;
    }
    $j : $j - 1;
}


text:
Q: Is that a good solution to handle multi language website? I already have a solution for multi language website, but I'm not sure whether is that a good solution.. and as much flexible as it could be.
First of, I'm developing a project using Visual webgui. Long story short, webgui is a web programming but very similar to WinForms.
So, Here it is:

*

*I've got an MDI application. It is a simple webpage with MainMenu on the top and ability to open many windows inside.

*First of all I create resx file in my main startup project. Let's say "myStrings.resx" for default language and "myStrings.de-DE.resx" for german translation.

*Every string which will be translated has to be in that two resources files.

*Now, my biggest concern. In every class (Form or no-Form) I must have method like this (in this example there is only one control to translate):
private void adjustCulture()
    {
        System.Resources.ResourceManager rm = new System.Resources.ResourceManager("MyApp.myStrings", typeof(testWindow).Assembly);
        label2.Text = rm.GetString("DefaultString", culture);
    }

And this bother me a lot, because I have to implement this function in every window separately. And not exactly for every control in that window (only that ones, which will be translated). So It is a little bit "not-flexible".
5.I also, cannot just initialize label in my designer, I have to do all initialization in constructor manually:
label2.Text = rm.GetString("DefaultString", culture);

(or in Designer partial class inside InitializeComponent method - but also, manually).

6.And finally, When Somebody changes language:
I have to call adjustCulture function in Load event in EVERY window, always! First of all, to initialize.. and secondly, when somebody (in MDI menu) changes Language to German and I have opened three windows in my MDI at that moment.. I have to translate everyone separately. So I have to store somewhere opened windows handlers, and call Load event of everyone.
Is that a good solution for multilanguage webgui appliacation ? Or is there any better solution? more flexible ?

A: One way you can do it is to have a xml file per each language with Key/Value pairs and use it as your translator for different languages. In this case, you can also implement the caching, rtl/ltr and other necessary attributes you want for each expression. You can have write a library for it and then you can easily add support for different languages and also automate the translation and other features.