text:
Q: C# Newtonsoft cant modify array in JSON file I have a JSON file from this schema.
This has an array called accounts.
{
  "UplayExecutable": "C:\\Program Files (x86)\\Ubisoft\\Ubisoft Game Launcher\\UbisoftConnect.exe",
  "foo": "barr",
  "OpeningTime": 8,
  "accounts": [
    "abc@a.com , testpass",
    "rumirad@gmail.com , password2",
    "rumirad@outlook.com , password3",
    "rumirad@test.com , password3"
  ]
}

I am using .NET framework.I also use the newtonsoft library. I want to replace that array with a C # String array.
The string array is hard-coded because I want to test it here.
This has no compile errors. There is  a runtime error.
private void button1_Click(object sender, EventArgs e)
        {
            string json = File.ReadAllText("data.json");
            dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

            string[] accs = { "hi@hi.com , testpass", "hey@hey.com , abcd123", "hello@hello.com , hi123" };

            jsonObj["accounts"] = accs;
            string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);

            File.WriteAllText("data.json", output);
        }

I want to know how to write a string array to a file as a json array
This is the error .I read the newtonsoft documentation but i could not find any solution

A: your type casting is wrong. Beast way is to use c# object like below.
Create one class for json data
public class jsonData
    {
        public string UplayExecutable { get; set; }

        public string foo { get; set; }
        public int OpeningTime { get; set; }

        public string[] accounts { get; set; }
    }

Now, write code for reading json file, update accounts value and write back to file.
            string json = File.ReadAllText("data.json");
            var jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject<jsonData>(json);

            string[] accs = { "hi@hi.com , testpass", "hey@hey.com , abcd123", "hello@hello.com , hi123" };

            jsonObj.accounts = accs;

            var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
            File.WriteAllText("data.json", jsonString);

A: Yes you cannot implicitly cast string[] to a JContainer the way you fix it is by assigning a JArray with string[] values inside., here is a fix to your code
string json = File.ReadAllText("data.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

string[] accs = { "hi@hi.com , testpass", "hey@hey.com , abcd123", "hello@hello.com , hi123" };

jsonObj["accounts"] = new JArray(accs);
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);

File.WriteAllText("data.json", output);

However we dont need to use dynamic typing here, we can just parse the JSON, replace the array then get the json back. like so
string json = File.ReadAllText("data.json");
var jObject = JObject.Parse(json);
string[] accs = { "hi@hi.com , testpass", "hey@hey.com , abcd123", "hello@hello.com , hi123" };
jObject["accounts"] = new JArray(accs);

File.WriteAllText("data.json", jObject.ToString(Newtonsoft.Json.Formatting.Indented) );


text:
Q: How to SET the last YEARWEEK to 53 in Amazon Redshift 2015-12-27 is week 53 of 2015, but is also part of week 1 2016.
When I run DATE_PART('W', '2015-12-27' + interval '1 day') it returns 1, since 2016-01-01 is on Friday of that same week.
I have added the + interval '1 day', because I want the week to run from Sunday to Monday.
I am not sure how to set the final week of each year to 53, rather than 1 as is the case when the final week of a year shares days with the first week of the new year.  For example, I need 2015-12-27 to 2015-12-31 to be week 53 and 2016-01-01 to 2016-01-02 to be week 1.

A: See the simmilar answer How to set 1/1 to Week 1 and 12/31 to Week 53
Create a custom function with this case statement or use it in your SQL statements:
CASE WHEN DATE_PART('DOY', ReturnDate) >= 358 AND DATE_PART('W', ReturnDate + interval '1 day') = 1
    THEN 53
    ELSE DATE_PART('W', ReturnDate + interval '1 day')
END AS Week_Num

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can retrieve a specific valued of a UDF field in Candidate Entity For istance, if I have a UDF field with name "test_name" in the Candidate UDF's, I would like to get the value of the UDF with the name "test_name"

A: I was looking at this this morning, in my case I'm using a C# client generated from the WSDL. I found that there was a property available for all entities called flexValuesField.
This contains an array of UDF values which you can search with your key.


text:
Q: p-Group satisfying the minimal condition on abelian subgroups Are there examples of $p$-groups satisfying the minimal condition on abelian subgroups but do not satisfying the minimal condition on subgroups?
Obviously such a group cannot be locally finite.
I've already asked it on stackexchange but no answer in a few days.
https://math.stackexchange.com/questions/1981177/p-group-satisfying-the-minimal-condition-on-abelian-subgroups

A: The free Burnside group $B(2,n)$, of rank $2$ and exponent $n$, where $n$ is a sufficiently large power of an odd prime, satisfies both conditions:

*

*all of its abelian subgroups are cyclic (S. I. Adian, "The Burnside Problem and Identities in Groups," Nauka, Moscow, 1975;
English transl.: Springer-Verlag, New York, 1979), which implies the minimality condition on abelian subgroups;

*it contains a copy of the free Burnside group $B(\infty,n)$, of infinite countable rank (V. L. Shirvanyan, "Embedding the group $B(\infty,n)$ in the group $B(2,n)$", Mathematics of the USSR-Izvestiya, 1976, 10:1, 181–199), hence it does not have the minimality condition on all subgroups.


text:
Q: Cast by member value I've got a problem with casting an object instance by the value of its member.
The test case:
class base {
  public:
      virtual int type() const = 0;
};
class derived : public base {
  public:
      virtual int type() const { return 1; }
      virtual void derivedspecific() {}
};

int main() {
    base* test = new derived;
    (test->type()==1?((derived*)test):NULL)->derivedspecific();
}

Imagine, that we have hundreds of child classes and hundreds of cases in the ternary operator all written in a macro. How should I solve this problem? If i put more cases in the ternary operator i got error 'conditional expression between distinct pointer types'. And yeah, the test variable needs to be a base class pointer. It's just a short example.

A: First of all, your derivedspecific doesn't need to be virual as it looks like you don't call it by a pointer to base class. I assume that the name will always be different in derived classes.
Otherwise, if derivedspecific is always the same name and signature, you don't actually need type():
class base
{
public:
    virtual int doWork() const = 0;
};
class derived : public base
{
public:
    virtual void doWork() { /* do your work here*/ }
};
int main()
{
    base* test = new derived;
    test->doWork();
}

A: *

*NULL->derivedspecific() won't compile

*((derived*)NULL)->derivedspecific() is undefined behaviour (segmentation fault on most platforms

there is a mechanism which is specifically designed to support this kind of behaviour, i.e. dynamic_cast which goes like:
#include <typeinfo>

class base
{
    public:
        virtual ~base(){};
};
class derived1 : public base
{
    public:
        void derived1specific() const {}
};
class derived2 : public base
{
    public:
        void derived2specific() const {}
};
int main()
{
    // use pointers
    base* test = new derived1;
    derived2* d2 = dynamic_cast<derived2*>(test);
    if(d2)
        d2->derived2specific();
    derived1* d1 = dynamic_cast<derived1*>(test);
    if(d1)
        d1->derived1specific();

    // or simply
    if(derived1* d1 = dynamic_cast<derived1*>(test) )
        d1->derived1specific();
    else if(derived2* d2 = dynamic_cast<derived2*>(test))
        d2->derived2specific();

    // use references
    const base& testr = derived1();
    try{
        const derived1& d1 = dynamic_cast<const derived1&>(testr);
        d1.derived1specific();
    }
    catch(std::bad_cast&){}
    try{
        const derived2& d2 = dynamic_cast<const derived2&>(testr);
        d2.derived2specific();
    }
    catch(std::bad_cast&){}
}

What you wanted to do, which I would not recommend you, is something like:
auto doNothing = [](){return;};
(test->type()==1?(((derived1*)test)->derived1specific()):doNothing());

You can try the full code here.
As for your comment: you can substitute the macro with a free-function (which is advisable anyway)
void derived1specific(base* b){
    if(derived1* d1 = dynamic_cast<derived1*>(b))
        d1->derived1specific();
}

which does exactly what your code wants to do: execute the derived specific function if and only if it is appropriate; you simply call it like:
derived1specific(test);

A: For that, use a switch:
Base * test = //something returning a Base *
switch(test)
{
   case 0 :
      static_cast<Derived0*>(test)/*[...]*/;
      break;
   case 1 :
      static_cast<Derived1*>(test)/*[...]*/;
      break;
//...
}

If There is only one class wich return the same type(), so, you can use static_cast, because you are sure.


text:
Q: spacy custom tokenizer doesn't group words Using spacy,  I'm trying to merge three different tokens into one token.
for example two different tokens "bell" "peper" into one token "bell pepper" by the code below.(I don't think my code is a right approach though)
text='extra-virgin olive oil bell pepper Parmesan Cheese onion red bell pepper carrots cloves, beans fennel bulb parsnips vegetable broth broccoli florets macaroni Parmesan cheese'

import spacy
nlp = spacy.load('en_core_web_sm')
nlp.tokenizer.add_special_case('connection',
    [
        {   'pos': 'NOUN',
            'F': '-',
            'F': 'oil'},
        {
            'F':'bell',
            'F':'pepper'
        },
        {
            'F':'olive',
            'F':'oil'
        },
        {
            'F':'Parmesan',
            'F':'Cheese'
        }
    ])

doc= nlp(text)

doc[0]

extra

How do I achieve this?
Thank you

A: So it looks like what you want to do is merge some phrases, like "olive oil" or "bell pepper", into single tokens. This is usually not something you'd do with the tokenizer exceptions - those are generally more useful for splitting words or dealing with idiosyncratic punctuation. For example, you might want to tokenize "gimme" as "gim me" (so that "me" can be recognized) or to have "2km" and "2 km" both be two tokens.
In this case I would make a list of all the phrases you want to make into a single token and use the EntityRuler to assign an entity label to them. This assumes you have a list of the things you want to merge.
If you don't have a list of things you want to make into phrases, given your example text, this is going to be hard because there's no general principle like part of speech patterns behind the merges you're making. spaCy models are trained on natural language text, while you seem to just have an unpunctuated list of ingredients, so the part of speech tagger isn't always going to work very well. For example, consider these sentences:

I went to the store and bought olive oil bell peppers and cake mix.

This is not properly punctuated, but it's obviously a list. If it were properly punctuated, spaCy's noun_chunks would give you what you want.
The issue is that this is also a valid sentence:

I made olive oil bell pepper pasta for dinner.

This is somewhat awkward but properly punctuated, and in this case "olive oil bell pepper" is a modifier of "pasta" and not a list of separate items, so it would correctly be a single noun chunk.


text:
Q: Tabs: Unexplained view behind inflated tabs I have a custom tab activity that I've put together using a lot of help from SO.  I am running into a couple problems however, that I can't find an answer to here.
Firstly, all the tabs states are coming from android apk tab resources of which I've adjusted the colors. The unselected tab nine-patch image is showing underneath each tab and I can't get it to go away, any suggestions?
Secondly, when I first go to the tab activity, the text of the focused tab does not change, but when I press the tab, or move to another tab and come back, the text changes.  How do I get the initial focus text to show as the focused text shows after a press?
Here are images to show what I mean; initial load on left, pressed on right, and both images show the unselected tab image showing behind the tabs:
I tried to post images of how the tabs look but my rep isn't high enough yet.  Sorry!
Here is the tab layout xml that I'm inflating:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="75dp"
    android:layout_weight="1"
    android:background="@drawable/custom_tab_selector"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/ivTabIicon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true" />

    <TextView
        android:id="@+id/tvTabTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Here is my selector XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Active tab -->
    <item
        android:drawable="@drawable/tab_selected"
        android:state_focused="false"
        android:state_pressed="false"
        android:state_selected="true"/>

    <!-- Inactive tab -->
    <item
        android:drawable="@drawable/tab_unselected"
        android:state_focused="false"
        android:state_pressed="false"
        android:state_selected="false"/>

    <!-- Pressed tab -->
    <item
        android:drawable="@drawable/tab_press"
        android:state_pressed="true"/>

    <!-- Selected tab (using d-pad) -->
    <item
        android:drawable="@drawable/tab_focus"
        android:state_focused="true"
        android:state_pressed="false"
        android:state_selected="true"/>

</selector>

And here is my activity java portion that inflates and displays each tab
// Initialize a TabSpec for each tab and add it to the TabHost
// Team tab
View tabTeamIndicator = LayoutInflater.from(this).inflate(R.layout.tab_team_layout, getTabWidget(), false);
spec = tabHost.newTabSpec("teamTab");
title = (TextView) tabTeamIndicator.findViewById(R.id.tvTabTitle);
title.setText("Team Manager");
icon = (ImageView) tabTeamIndicator.findViewById(R.id.ivTabIicon);
icon.setImageResource(R.drawable.custom_teamtab_icon);

spec.setIndicator(tabTeamIndicator);
spec.setContent(intentTeam);
tabHost.addTab(spec);

Thanks so much in advance for any help!  By the way, the colors look much better on the phones that I'm trying them on than they do in the emulator!!!
EDIT: Changed thread title

A: Silly mistake here.  The xml layout that holds the tab widget had the
android:background="@drawable/custom_tab_selector"

attribute in it which was causing the background of the tabs to be drawn a second time in the background.


text:
Q: vba check for negative value I wrote a simple VBA code to check if the value of a cell is negative and if it is negative, highlight it red. For some reason, I keep getting "run-time mismatch". My code is
For x = 2 To 100

Set val3 = Worksheets("Summary").Cells(x, 9)
If val3.Value < 0 Then
Worksheets("Summary").Cells(x, 9).FontColorIndex = 3

End If
Next x

Column 9 (the column I am checking) is filled with dollar values. Thank you in advance for your help.

A: In your code, you're simply missing a dot.

FontColorIndex = 3

should be:

Font.ColorIndex = 3

A: Public Sub test()
   For x = 2 To 100
      Set val3 = Worksheets("Sheet1").Cells(x, 9)
      If val3.Value < 0 Then
         Worksheets("Sheet1").Cells(x, 9).Font.Color = RGB(99, 179, 73)
      End If
   Next x
End Sub

Code above works in excel 2007

A: Thanks for your post, I needed to change the negative numbers to zeros after a certain process - BUT I want to check them before I use them so changing the font color is useful, so this code works well for the whole sheet range until (245,50)
Sub negnumbers()
    For x = 1 To 245
        For y = 1 To 50
        Set val3 = Worksheets("target sheet").Cells(x, y)
        If val3.Value < 0 Then
        Worksheets("target sheet").Cells(x, y).Font.ColorIndex = 3
        Worksheets("target sheet").Cells(x, y) = 0
        End If
        Next y
    Next x
End Sub


text:
Q: How do i design this menu in Android? I've seen this kind of menu in many android apps including the Evernote app i like it, but i have no clue where to start? Any ideas how i can lay it out.

A: You're probably talking about the DashboardLayout. Use this as layout and fill it with Buttons or other elements you like.


text:
Q: R parallel code for two arrays I'm trying to process two 3d arrays using parallel computing in R. I have a function that takes two vectors as input, so I need to loop through the rows and columns of my arrays. Doing this in serial code is simply too slow and R gets stuck as the arrays are large.
I've not found a solution for doing this with parallel functions and would appreciate any suggestions. I've tried parApply but do not know how to incorporate a second input, and mcmapply but it is hard to use over rows/cols. Ideally the output should also be an array of the same dimension.
Below is a reproducible example of what I'm trying to do in serial code. Any help on how this could be written in parallel code would be much appreciated!
fun <- function(a,b)
{
  a*b
}

input1 <- array(data=1:1000, dim=c(10,10,10))
input2 <- array(data=2:1001, dim=c(10,10,10))

result <- array(data=NA, dim=c(10,10,10))

for(i in 1:nrow(mat1))
{ for(j in 1:ncol(mat1)) {
    result[,i,j] <- fun(input1[,i,j], input2[,i,j])
}}

A: Here's one way to do it with the foreach package:
library(doSNOW)
library(abind)
cl <- makeSOCKcluster(parallel::detectCores())
registerDoSNOW(cl)

fun <- function(a,b) a*b
input1 <- array(rnorm(60), dim=c(4,5,3))
input2 <- array(rnorm(60), dim=c(4,5,3))
rdim <- dim(input1)[1:2]
comb <- function(...) abind(..., along=3)
result <-
  foreach(i1=iapply(input1, 3), i2=iapply(input2, 3),
          .multicombine=TRUE, .combine='comb') %dopar% {
    r <- array(data=NA, dim=rdim)
    for (i in 1:ncol(i1)) {
      r[,i] <- fun(i1[,i], i2[,i])
    }
    r
  }

The "iapply" function from the iterators package is used to split the 3D input arrays into 2D matrices. The result matrices are combined into a 3D array using the "abind" function from the abind package.
Note that I'm specifically using the "doSNOW" parallel backend because it sends data from the two "iapply" iterators to the workers and processes the results on-the-fly. This reduces the memory needed by the master process. The "doParallel" backend can't work on-the-fly because the "parallel" package doesn't export the necessary functions.


text:
Q: AWS Lambda gives class not found exception for jdbc and org.json JARS I'm trying to run an AWS Lambda function with the help of eclipse and Maven using AWS tool kit. When I run the project as a Maven test, it successfully runs. But when I export the project as a .jar and upload the jar to AWS Lambda, it gives me the following error trace:
Input: ToRupeeDatabase error: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Done inserting the data in RDS

The code says it runs successfully and the data has been inserted in the RDS, but it is being caught as an exception and the code is crashing.
Code:
package com.amazonaws.torupee.demo;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;

import java.util.logging.Level;
import java.util.logging.Logger;

public class RemoteDataCRON implements RequestHandler<Object, String> {

 @Override
    public String handleRequest(Object input, Context context) {
        context.getLogger().log("Input: " + input);

        try {
            // Exception in the following line when uploaded on AWS Lambda!
            Class.forName("com.mysql.jdbc.Driver");
            String endPoint = "pathtodatabase?useSSL=false";
            String username = "foor";
            String password = "bar";
            PreparedStatement stmt = null;
            try {
                Connection dbConnection = DriverManager.getConnection(endPoint, username, password);
            } catch (SQLException ex) {
                Logger.getLogger(RemoteDataCRON.class.getName()).log(Level.SEVERE, null, ex);
            }
            // Some processing here and org.json exception here!
        } catch (Exception ex) {
            System.err.println("Database error: " + ex);
        }
        System.out.println("Done inserting the data in RDS");

        // TODO: implement your handler
        return "Hello from Lambda!";
    }

}

.pom file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.amazonaws.torupee</groupId>
  <artifactId>demo</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.6.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
          <forceJavacCompilerUse>true</forceJavacCompilerUse>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.0.0</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-bom</artifactId>
        <version>1.11.256</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-lambda-java-events</artifactId>
      <version>1.3.0</version>
    </dependency>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-lambda-java-core</artifactId>
      <version>1.1.0</version>
    </dependency>
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180130</version>
</dependency>
  </dependencies>
</project>

Here is a list of solutions that I tried:

*

*I tried adding external JARS for mysql and org.json but that gave me the same errors

*I tried zipping the project instead of exporting it as a JAR but that gave me ClassNotFoundException on the handler itself

*I then added the dependencies in the pom file itself as I thought that external JARS were not bundled when making a .jar file

*I then changed the driver path from "com.mysql.jdbc.Driver" to "com.mysql.cj.jdbc.Driver" but that still gave me the exception on the console

Am I doing something wrong or building the Jar incorrectly, is it why Lambda gives me the error when I'm on the management console?

A: So I solved this by completely ditching the maven approach and did it using a simple java class. You can follow the solution for creating a simple AWS Lambda function in java step by step with this video tutorial I created.
https://www.youtube.com/watch?v=-Pm22SJibpQ&t=40s


text: Q: Does c2dm still work? I'm working with some legacy code not used for a while. There's Android Push based on c2dm and it's not working - conection is refused while authenticating. Can it be because of discontinuation of c2dm?


text:
Q: Backbone.js Sub-View Template Not Rendering Although Render Function Does Run Unfortunately, I have written a sub-view for my project. While it had previously rendered perfectly well and exactly how I wanted it to, I learned that my app was not structured properly. I am in the process of restructuring, and everything else works like a charm, but with my new setup it doesn't seem to render in its el. The el renders perfectly fine, but nothing is inserted. I put a console.log() in that printed the template that was supposed to render, and it is flawless. However, the that.$.el.html() line doesn't render the template at all. I am not sure what is going on. The file is below. My noobish-ness is killing me!
contactlist.js (View):
define([
  'jquery',
  'underscore',
  'backbone',
  'text!templates/contactlist.html',
  'collections/contacts'
], function($, _, Backbone, contactListTemplate, Contacts){

  var ContactListView = Backbone.View.extend({
    initialize: function () {
        var that = this;
        this.options = {
            idclicked: null,
            query: null,
            scrolled: 0
        };
        this.options.get = function (property) {
            return that.options[property];
        };
        this.options.set = function (properties) {
            for (property in properties) {
                that.options[property] = properties[property];
            }
        };
    },
    el: '.contact-list',
    render: function() {
        var that = this;
        var contacts = new Contacts();
        contacts.fetch({
            success: function(contacts) {
                var results = contacts.models;
                if (that.options.query || that.options.query === '') {
                    var query = that.options.query.toUpperCase();
                    var results = contacts.toArray();
                        results = contacts.filter(function(contact){
                            return _.any(['firstname', 'lastname', 'email', 'phonenumber'], function(attr){
                                return contact.get(attr).toString().toUpperCase().indexOf(query) !== -1;
                            });
                        });
                        that.options.set({idclicked: null});
                }
                if (!that.options.idclicked && results[0]) {
                    that.options.idclicked = results[0].get('id');
                    Backbone.history.navigate('/contacts/' + results[0].get('id'), {trigger: true});
                }
                var template = _.template(contactListTemplate, {contacts: results, idclicked: that.options.idclicked});
                that.$el.html(template);
                $(document).ready(function() {
                    $('.contact-list').scrollTop(that.options.scrolled);
                });
            }
        });
    },
    events: {
        'click .contact': 'clickContact'
    },
    clickContact: function (ev) {
        $('.contact-clicked').removeClass('contact-clicked').addClass('contact');
        $(ev.currentTarget).addClass('contact-clicked').removeClass('contact');
        window.location.replace($(ev.currentTarget).children('a').attr('href'));
    }
  });

  return ContactListView;

});

UPDATE:
tried one thing that worked, but not sure about whether it is a good practice or not. The code below is the parent view:
allcontacts.js (View):
define([
  'jquery',
  'underscore',
  'backbone',
  'text!templates/allcontacts.html',
  'views/contactlist',
  'collections/contacts'
], function($, _, Backbone, allContactsTemplate, ContactListView, Contacts) {
  var AllContactsView = Backbone.View.extend({
    initialize: function () {
        var that = this;
        this.options = {
            idclicked: null,
            pageloaded: false,
            renderlist: true,
            scrolled: null
        };
        this.options.get = function (property) {
            return that.options[property];
        };
        this.options.set = function (properties) {
            for (property in properties) {
                that.options[property] = properties[property];
            }
        };

        that.contactListView = new ContactListView();
    },
        el: '.allcontacts',
        render: function() {
            var that = this;
            if (!that.options.pageloaded) {
                var template = _.template(allContactsTemplate, {});
                that.$el.html(template)
        }
        if (that.options.renderlist) {
                this.contactListView.options.set({idclicked: that.options.idclicked, scrolled: that.options.scrolled});
                this.contactListView.setElement('.contact-list').render();
            }
        },
        events: {
        'keyup .search': 'search',
        'submit .search-contacts-form': 'cancelSubmit'
        },
        search: function (ev) {
            this.contactListView.options.set({idclicked: this.options.idclicked, query: $(ev.currentTarget).val(), scrolled: this.options.scrolled});
            this.contactListView.setElement('.contact-list').render();
        },
        cancelSubmit: function (ev) {
            return false;
        }
    });

  return AllContactsView;

});

A: Check if your el element is available when you bind it. Seems like it's not rendered yet.


text:
Q: How to properly display JSON data in Vue.js? I am recently new to Vue and I am trying to show JSON data in the page I am currently working on.
I've managed to have the whole JSON show and now I am trying to properly show it without brackets or the object keys on it and where each data occupies one line on the page.
Would anyone please assist me on this?
Here is the code:
<template>

    <v-card class="guidelines">

test

This is a test for the new guidelines page card

      {{ info }}
    </v-card>

</template>

Part of the JSON data
{
  "San Francisco County": {
    "info": [
      {
        "header": "County Guidelines",
        "body": [
          {
            "h4": "Shelter in Place",
            "content": [
              {
                "p2": [
                  {
                    "p": "Residents should remain at home when possible as it is the safest choice. If you do leave your home, keep the following guidelines in mind."
                  }
                ],
                "bullets": [
                  {
                    "bullet": "Maintain 6ft distance between yourself and people who are not in your hosehold unit."
                  },
                  {
                    "bullet": "Wear a mask, scarf, bandana or other facial covering."
                  },
                  {
                    "bullet": "Limit face to face interactions with those vulnerable to the coronavirus such as those over 60 or those with underlying health conditions."
                  },
                  {
                    "bullet": "Wash hands frequently with soap and water for at least 20 seconds, or use hand sanitizer."
                  },
                  {
                    "bullet": "Cover coughs and sneezes with a tissue or fabric or, if not possible, use the sleeve of your shirt or elbow. Do not cough or sneeze into your hand."
                  },
                  {
                    "bullet": "Use antibactiral wipes to clean any surface that you have to touch."
                  }
                ],
                "link": "https://sf.gov/stay-home-except-essential-needs"
              }
            ]
          },


text:
Q: Google maps not behaving the same in different machines after committing my code to SVN I am working with google maps javascript api v3. I have coded and tested the page in my machine and it works perfectly fine. But when I have committed my code to SVN and other team members downloaded my page, it's not behaving as expected. When my teammates are running it on their machines it is throwing all the markers into random locations on the map. Could anyone please let me know if they have encountered it before? Has it got anything to do with API key?
Please find my code below:
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
            <script src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=true&key=#{MY_API_KEY}" type="text/javascript"></script>
            <script type="text/javascript">
            var geocoder;
            var map;
            var i;
            function initialize() {

              geocoder = new google.maps.Geocoder();
              var address = document.getElementById('address').value;
              var jString = JSON.parse(address);
              var contentStr;
              var latlng = new google.maps.LatLng(40.3, 73.2);
              var mapOptions = {
                zoom: 11,
                center: latlng
              }
              map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

              for (var key in jString) {
                  contentStr = JSON.stringify(jString[key]);
                  if (jString.hasOwnProperty(key)) {
                      geocodeAddress(map, key, contentStr);//end of geocode
                  }//end of if
              }//end of for

            }//end of initialize

            function geocodeAddress(map, key, contentStr) {
                   geocoder.geocode({
                     'address': key,
                   },function(results, status){
                      if(status == google.maps.GeocoderStatus.OK) {
                    var marker = createMarker(results[0].geometry.location, contentStr);
                      }else {
                          alert('Geocode was not successful for the following reason: ' + status);
                        }
                   });
                }

            function createMarker(latlang, contentStr) {
                    var marker = new google.maps.Marker({
                        map: map,
                        position: latlang,
                        title: contentStr
                    });
                    //alert(contentStr)
                    var info = new google.maps.InfoWindow({
                        content: contentStr+" cases"
                    });
                        info.open(map, marker);
                   return marker;
            }

            google.maps.event.addDomListener(window, 'load', initialize);

            </script>


text:
Q: Pipe character URL encoding issue I am using URL encoding for my links in a Django template smoothly for all sorts of characters in the link so far. However, today I faced a problem with encoding of the pipe (|) character.
When a pipe character was encoded, I saw the URL appeared with "%7C" (it is correct).
This part of the encoding was for parameter passing through HTTP GET, which I display as part of a title. However, the title rendered is ",".
Here's the full cycle:

*

*A = "|x|"

*Passed {{A|urlencode}} will give the URL phrase as "%7Cx%7C"

*"%7Cx%7C" decoded to the title as ",x,".

What is the reason?


text:
Q: get a value from firebase document collection I don't know how to convert these type of data or if my code will works well by this way.
this my function

I'm trying to get a value from the doc by it's id
this doc has a fields one of them is..
image : 'url'
I want to get 'url' field as String.
another problem:
is this code right?

and how I can use it in a condition?
================================================================
Edit:

image 2

A: chnage snapshot['image']
to snapshot.get("image")
or use this way :
getPhotoUrl(String documentId)async{
await yourCollection
.doc(documentId)
.get()
.then((doc) async {
if (doc.exists) {
return doc.get("image");
        }
  });
}


text:
Q: Locking a website to a individual system Recently i tried to visit a website to vote for a competition. After voting for first time , visiting the same page after 2 days it was not allowing to vote. It detected I already visited page. It didn't collect any details for voting.
How is this possible . Can anyone explain ?

A: The simplest solution website wise would be IP detection. Try to vote trough Tor, a VPN or Proxy connection. If that works, it might be the case.
Some providers change the IP relatively seldom, even if you don't have a fixed IP. Making it possible to identify you or at least the connection for a quite long period.
Although it isn't too smart, since the worst case would be that many people can no longer participate (e.g. company internet) – it is possible.
Combining the IP with all the client information the website can easily gather (like OS, browser version, language setting, connection speed, local time, resolution) leads to very good detectability of a single client.
So try to vary one/or multiple of these informations to find out what the website really used to detect you. The website https://panopticlick.eff.org offers a test to demonstrate how trackable your browser is.
Also, as Roald van Doorn, pointed out in his comment. It could be a simple Cookie. But since this is very, very easy to bypass my experience is that these polls and competitions at least try to make a simple client detection.


text:
Q: Filter Data By Chaining Ng-Select(s) I have a list of states (U.S. State) and counties that I need to filter and display the values.  For simplicity's sake, I thought to chain ng-selects would be the simplest UI.  However, I'm having trouble loading the selected state's respective counties in the second ng-select.  Where am I going off track?  Thanks in advance..
template:

State {{selectedState}}

        <ng-select
           [items]="states"
           bindLabel="state"
           bindValue="state"
           [(ngModel)]="selectedState">
        </ng-select>

County {{selectedCounty}}

        <ng-select
           [items]="selectedState.counties"
           bindLabel="selectedState.counties.name"
           bindValue="selectedStatecounties.name"
           [(ngModel)]="selectedCounty">
        </ng-select>

Lists:
states = [
        {
            state: "Alabama",
            counties:  [{
                name: "Alabama1"
              },
              {
                name: "Alabama2"
                          }]
          },
        {
          state: "Alaska",

          counties:  [{
                name: "Alaska1"
              },
              {
                name: "Alaska2"
                          }]
        },

A: Stackblitz: https://stackblitz.com/edit/ng-select-ymus3e
Try the below:
app.component.ts:
import {Component, NgModule, ViewChild} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormControl, FormGroup, ReactiveFormsModule, FormsModule} from '@angular/forms';
import {NgSelectModule, NgOption} from '@ng-select/ng-select';

@Component({
    selector: 'my-app',
    template: `

State {{selectedState}}

        <ng-select
           [items]="states"
           bindLabel="state"
           bindValue="state"
           (change)="stateChanged($event)"
           [(ngModel)]="selectedState">
        </ng-select>

County {{selectedCounty}}

        <ng-select
           [items]="availableCounties"
           bindLabel="name"
           bindValue="name"
           [(ngModel)]="selectedCounty">
        </ng-select>

`
})
export class AppComponent {

    states = [
        {
            state: "Alabama",
            counties:  [{
                name: "Alabama1"
              },
              {
                name: "Alabama2"
                          }]
          },
        {
          state: "Alaska",

          counties:  [{
                name: "Alaska1"
              },
              {
                name: "Alaska2"
                          }]
        }
    ]

    selectedState: any;
    availableCounties: any;
    selectedCounty: any;

    constructor() {

    }

    stateChanged(event) {
      this.selectedCounty = undefined;
      this.availableCounties = event.counties;
    }
}

A: Here is the modified version of your code which works.

State {{selectedState.state}}

        <ng-select
           [items]="states"
           bindLabel="state"
           [(ngModel)]="selectedState">
        </ng-select>

County {{selectedCounty}}

        <ng-select
           [items]="selectedState.counties"
           bindLabel="name"
           bindValue="name"
           [(ngModel)]="selectedCounty">
        </ng-select>


text:
Q: Why does 'new line' offset the all the characters byte position in a .txt file +1? When I use fstream::tellg, after reading in the first character with fstream::get (char) the result is: 1
I then insert a 'new line' after the first character
I fstream::seekg to the beginning: 0
When I use fstream::tellg, after reading in the first character this time
the result is: 2
If I insert: "abc", into a .txt file:

*

*after reading "a" tellg will give: 1

*after "b" 2

*and after "c" 3.

But if I insert: "abc\n" or "abc" << endl;:

*

*after reading "a" tellg will give 2

*after "b" 3

*after "c" 4

*lastly 5 after the new line.

What is the reason for this?
I understand that 'newline' is characters too. What I do not understand is the offsetting of the tellg result after reading a character. With each use of  'newline' this offset is incremented by one.
Update

*

*Conclusion:
There was a problem with my IDE setup! I have been using Code::Blocks. I tried building the program in Microsoft Visual Studio IDE and it ran with no trace of the problem. This does not mean that Code::Blocks is broken. It might have been an issue in my Code::Blocks settings. I have no recollection of changing anything. Even if that was the case; I, in my humble opinion, do not think it is right that you can change this sort of thing by accident. I am disappointed in Code::Blocks.

*mySolution: Change IDE

A: My guess is you're writing code on a Microsoft OS.
In text files, Microsoft OSes (and associated software) expect the end of a line to be marked with a \r\n sequence, so when you write a new-line to a (text) file, it gets translated from \n to \r\n. So, even though you only inserted one character into the stream, that resulted in two characters being written to the external file.
If you're concerned with ensuring that the content of the external file exactly match what you inserted into the stream, that may indicate that you want what the C++ standard library would consider a binary file, which you'd get by specifying std::ios::binary when you open the file.
Now, it is true that when you deal with a text file, tellg doesn't produce a very meaningful number. What we have is something like this:

The upper side is the data as you see it. The lower side is the data as it's stored in the file. When you call tellg, it's telling you the position along the lower side-that is, the position relative to the start of the file. But, depending on how many \r\n pairs there are before that in the file, that may result in a different number of characters in the upper row, which is what you'll see when you read the data from the file.
What this means it that the result from tellg can only be used in a few fairly specific ways--mostly, when you get a number from tellg, you can give that number back to seekg, and start reading from the same place.
As far as your code goes, I guess I don't see what I understand your question to be saying. I rewrote the code a bit to show the results together:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

std::string show(char x) {
    if (x > 32)
        return std::string(1, x);
    else switch (x) {
    case '\r': return "<\\r>";
    case '\n': return "<\\n>";
    case '\t': return "<\\t>";
    default: return "<BAD>";
    }
}

void display_txt_file(fstream& file)
{
    file.seekg(0, ios_base::beg);
    char x;
    cout << "tellg: " << file.tellg() << "| ";
    while (file.get(x))
    {
        cout << "'" << show(x) << "' tellg: " << file.tellg() << "| ";
    }
    file.clear();
    file.seekg(0, ios_base::end);
    std::cout << "\n";
//    cout << "\n> " << file.tellg() << "\n" << endl;
}

int main(int argc, char* argv[])
{
    ofstream new_file;
    new_file.open("test.txt");
    new_file.close();

    fstream file("test.txt", ios::in | ios::out);
    if (!file.is_open())
    {
        cout << "error file not opened" << endl;
        return 0;
    }

    file << "ABCD";
    display_txt_file(file);

    file.seekp(0);

    file << "ABCD\nE";
    display_txt_file(file);

    return 0;
}

When I run this on Windows, I get the following output:
tellg: 0| 'A' tellg: 1| 'B' tellg: 2| 'C' tellg: 3| 'D' tellg: 4|
tellg: 0| 'A' tellg: 1| 'B' tellg: 2| 'C' tellg: 3| 'D' tellg: 4| '<\n>' tellg: 6| 'E' tellg: 7|

So, everything up to the new-line matches, exactly as we'd expect. Then the new-line gets expanded to two characters, followed by the E. But, after we read the 'A', tellg has returned 1, not 2, as was claimed in the question.

A: Update

*

*Conclusion: There was a problem with my IDE setup! I have been using Code::Blocks. I tried building the program in Microsoft Visual
Studio IDE and it ran with no trace of the problem. This does
not mean that Code::Blocks is broken. It might have been an issue in
my Code::Blocks settings. I have no recollection of changing
anything. Even if that was the case; I, in my humble opinion, do not
think it is right that you can change this sort of thing by accident.
I am disappointed in Code::Blocks.

*my Solution: Change IDE

A: It is hard to tell what or why you'd be working around anything without an explanation of your expectations and a full code listing.
However, it is important that you understand character encoding when reading and writing to a file.
The newline character takes up a byte. It's value is 0x0A if we are using the ASCII character set. There are other character encodings aside from ASCII. There is also UTF-8 or UTF-16 encodings, for example. Every character encoding might have a different byte, or multibyte, representation for a readable text character, as well as the unreadable text characters, such as the newline.
On Windows, there is a convention to use carriage return followed by line feed, instead of just a line feed. Those two byes would look like 0x0D, 0x0A, in ASCII. On *nix systems there is no such convention.
Therefore, when you are counting bytes in your fstream, you will need to account for the newline character taking up a byte, or two bytes if you are expecting '\r\n', That is , if you are using ASCII encoding.
As far as I know, fstream assumes it's content is ASCII. This might have changed with C++17. I think there were plans to support various character encodings in streams. Those on the cutting edge might be able to comment.
Your operating system has a default character encoding set somewhere in its configuration. I know older Windows machines used Windows-1252. I am not sure what Windows 10 uses. I think most *nix systems use UTF-8. At any rate, you will want to consult your operating system's configuration.
C++ streams are going to want to transform from one to the other when you read and write to file. The transformation of text to it's byte representation are a big part of what streams are trying to do for you.
If you don't want the byte representation that the stream is going to provide, then you can feel free to write bytes yourself, however you wish, in binary mode. However, be mindful of how that effects other readers of the file and what encoding they are expecting.
So, keep in mind who created the file, what it looks like as text, what it's binary representation is, in file, and in memory, and code for it appropriately.
Lucky for us, some encodings also contain the entire ASCII character set, and simply expand on it. UTF-8 is one such encoding that does this.
You can refer to What's the difference between \n and \r\n? for a discussion on that topic.
You can also refer to Difference between files written in binary and text mode
"Standard C++ IOStreams and Locales: Advanced Programmer's Guide and Reference
Book by Angelika Langer and Klaus Kreft" is a good book if you want to really get to know your streams inside and out.


text:
Q: Using 2 equal fields in 2 different databases databases PHP I'm gonna try to explain this as well as I possibly can. I'm creating a translation function and it is based on every text having a code value. For an example: a title for a certain page has a code and a value associated with the code.
I have 2 tables: translations: where all the codes and values are kept and a table where there is just the code itself and it goes through a function that takes it through the translation table:
public function T($code) {
      $value = $code;
      $db_value = $this->db->getRow("SELECT value FROM translations WHERE code = '".$code."'");
      if($db_value) {
        $value = $db_value['value'];
      }
            return $value;
        }

GetRow is a custom function that select a single column from a table:
function getRow() {
    $func_num_args = func_num_args();
    $func_get_args = func_get_args();
    if ($func_num_args == 0) {
        return null;
    } else if ($func_num_args == 1) {
        $this->query($func_get_args[0]);
    } else {
        $args = array();
        $query = $func_get_args[0];
        unset($func_get_args[0]);
        foreach ($func_get_args as $arg) {
            if (is_string($arg) && !is_numeric($arg)) {
                $args[] = mysqli_real_escape_string($this->conn, $arg);
            } else {
                $args[] = $arg;
            }
        }
        $this->query(vsprintf($query, $args));
    }
    return ($this->rows() ? $this->fetch() : null);
}

Now making the admin page for the site I ran into a problem, I want the code of the texts to be hidden and display the text that the code represents. My current elect looks a little likee this: it doesnt work however, it only selects the columns but doesnt find any rows:
  SELECT vc.*,
       t.code,
       t.value
  FROM vakances_card AS vc
  JOIN translations AS t
  ON vc.title = t.code
  AND vc.descr = t.code

A: I am not sure what exactly you want to achieve. You may change your query to
SELECT vc.*,
   t.code,
   t.value
FROM vakances_card AS vc
JOIN translations AS t
ON vc.title = t.code
AND vc.descr = t.code

To the following query
SELECT vc.*,
   t.code,
   t.value
FROM vakances_card AS vc
LEFT JOIN translations AS t
ON vc.title = t.code
AND vc.descr = t.code

Or may change to
SELECT vc.*,
   t.code,
   t.value
FROM vakances_card AS vc
RIGHT JOIN translations AS t
ON vc.title = t.code
AND vc.descr = t.code


text:
Q: Pass variables to another pipeline Jenkins my goal is to get variables from, let's say pipeA to pipeB.
After pipeA finishes it creates new app version and upload it to AWS S3.
In pipeB I want to get all the app versions that was uploaded to S3, so I need to pass appNames to some place.
Then when I build pipeB with params I want to get all appNames as params before build, but I can't figure out how.
Jenkins ver: 2.141

Example pre build step

A: Massive edit workflow is

*

*Ask S3 for variables

*Put this var as choice parameters

*Select on Jenkins UI some parameter

*Execute pipeline

In this case Active Choices Reactive Parameter, inside use groovy script with return. For example:
//S3 file request
response = ["curl", "-k",
"-H", "Host: ${bucket}.s3.amazonaws.com",
"-H", "Date: ${dateValue}",
"-H", "Authorization: AWS ${s3Key}:${signature}",
"https://${bucket}.s3.amazonaws.com/${file}"].execute().text

def choices = []
response.eachLine {
    if (it.contains("Not Found")) {choices.push("There is no file")}
    //here parse your file, in my example is flat custom text
    else {
        if (!it.contains("  ")) {
            param= it.replace(":", "")
            choices.push(param)
        }
    }
}
def clean = choices.findAll { item -> !item.isEmpty() }
return clean.sort()

In this way You need insert some param, of course the simplest method is define it in groovy script in plain text:
def bucket = '13dfvcqe'
def dateValue = '123'
def s3Key = '1452234F'
def signature = '2133'
def file  = 'vars'

This is easy and dangerous :) Better option is fill this confidential value as Jenkins password parameter before that param and use Referenced parameters option.


text:
Q: How to make list including certain multi-bit letters by using Python? I am trying to list up certain words by using Python.
Here's the text file(input file): (the 'random_text' are random texts that exist in text file)
random_text

reg A1_M0;
reg A1_M1;
reg A1_M10;
reg A1_M11;
reg A1_M2;

reg [3:0] B1_M0;
reg [3:0] B1_M1;
reg [3:0] B1_M10;
reg [3:0] B1_M11;
reg [3:0] B1_M2;

random_text

I want to make below two lists by extracting the lines and spliting the data.
list1 = [A1_M0, A1_M1, A1_M10, A1_M11, A1_M2]

list2 = [B1_M0[3], B1_M0[2], B1_M0[1], B1_M0[0], B1_M1[3], B1_M1[2], ... , B1_M2[1], B1_M2[0]]

I thought about 3 steps:

*

*Extract target data (by using '.findall') -> A1_M0, A1_M1, A1_M10, A1_M11, A1_M2, B1_M0[3:0], B1_M1[3:0], B1_M10[3:0], B1_M11[3:0], B1_M2[3:0]

*In case of 4-bit-data, split all of those into 1-bit data.

*Make these into 2 types of lists (list1, list2)
I've tried '.readlines' method, but It's hard for me to achieve. How can I deal with this?

A: I made some assumptions that I hope were correct.

*

*I group all bits together by their prefix, as that seems to be the commonality between the bits in list1 and list2

*The difference between your random text and meaningful data was the presence of the prefix "reg "

*There are only 2 types of "reg " prefixed lines, and the difference is the presence of the "[" character, you can modify the conditions if there is a more nuanced definition than this.

def get_reg_lines(f):
    for line in f.readlines():
        if "reg " in line:
            yield line.removeprefix('reg ').removesuffix(';\n')

def handle_single(d, line):
    k, _ = line.split("_", 1)
    d.setdefault(k, []).append(line)

def handle_multi(d, line):
    r, b = line.split(" ", 1)
    k, _ = b.split("_", 1)

    start, end = [int(v) for v in r[1:-1].split(":")]
    d.setdefault(k, []).extend([f'{b}[{i}]' for i in range(start, end - 1, -1)])

def main():
    d = {}
    with open('input.txt', 'r') as f:
        for line in get_reg_lines(f):
            if "[" in line:
                handle_multi(d, line)
            else:
                handle_single(d, line)
    print(d)

if __name__ == '__main__':
    main()

I put them in a dict d keyed with the prefixes A1 and B1. You can unpack these into whatever lists you need if that is your preferred way to interact with the data.
Also note: I used removeprefix and removesuffix which requires Python3.9 or newer, replace with slice notation for prior versions.
yield line[4:-2]

*Code was tested on input.txt with the following contents:
random_text

reg A1_M0;
reg A1_M1;
reg A1_M10;
reg A1_M11;
reg A1_M2;

reg [3:0] B1_M0;
reg [3:0] B1_M1;
reg [3:0] B1_M10;
reg [3:0] B1_M11;
reg [3:0] B1_M2;

random_text


text:
Q: How to return (a varying number of) objects with their original name in a function in Python I'm very new to Python. I'm looking to return a varying number of objects (will eventually be lists or pandas), ideally with their original name.
So far I'm looking at something like this:
def function(*Args):
    Args = list(Args)
    for i in range(len(Args)):
        Args[i] += 1
        print Args[i]
    return *all variables with original name, in this case a, b, c, d *

a=1
b=2
c=3
d=4

a, b, c, d = function(a, b, c, d)

Any help, ideas or comments would be very appreciated. Thanks.

A: Are you just looking to return the tuple?
def function(*Args):
    Args = list(Args)
    for i in range(len(Args)):
        Args[i] += 1
        print Args[i]
    return Args

 a, b, c, d = function(a, b, c, d)

A: In the meantime I tried it as @Xavier C. suggested and it seems to work. the lists/input arguments i would name after the industry and would therefore like to preseve. Is there any way to achieve that?
def BBGLiveRequest(*args):
    data = []

    for i in range(len(args)):
        print args[i]
        result = BLPTS(args[i], ['PX_Last'])
        result.get()
        print result.output
        data.append(result.output)

    return data


text:
Q: How can you turn off alternate screen in OSX's Terminal.app? altscreen is evil. If you don't know what I'm talking about, see this page
for visual demonstration.
Problem is, there doesn't seem to be a way to stop it with Terminal.app (under OSX), when you're not using  screen. Yes, you can edit terminfo definition, but that's rather blunt hammer. Plus that solution might break if Apple decides to update relevant term's definition in some patch. Is there some clean way to convince Terminal.app to block altscreen usage?

A: Yes.
Terminal -> Preferences -> Settings -> Advanced
Change "Declare terminal as:" from xterm-color to xterm (or experiment with the other options...)
(worked for me with man, didn't try some of the others.)


text:
Q: If and Else Statements Always Output If I was messing around with a previously existing snippet and ran into an issue.
Whenever I try to enter an input that doesn't apply the to If statement it always gives me the If output. Also I was looking to, instead of saying approved, have you sent to a URL, like Google for example, and I'm not sure about a solution for either of the two.

function myFunction() {
  var a = document.getElementById("text_a").value;

  if (a == "02035", "02048", "02067") {
    document.getElementById("answer").innerHTML = "Approved";
  } else {
    document.getElementById("answer").innerHTML = "Our service currently isn't available in your area! Try again soon!";
  }
}

Enter Zip Code

<input id="text_a" type="text" />

<button onclick="myFunction()">Check</button>

A: May be you need to change the condition in if statement:
if (a == "02035" || a == "02048" || a == "02067"){
  document.getElementById("answer").innerHTML="Approved";
}
else{
  document.getElementById("answer").innerHTML="Our service currently isn't available in your area! Try again soon!";
}

A: if (a=="02035","02048","02067")

You can't do like this.
There are many ways to check it. You could do like this
function myFunction() {
  var a = document.getElementById("text_a").value;
  var list = ["02035", "02048", "02067"];
  console.log(a)
  if ((list.indexOf(a) > -1)) {
    document.getElementById("answer").innerHTML = "Approved";
  } else {
    document.getElementById("answer").innerHTML =
      "Our service currently isn't available in your area! Try again soon!";
  }
}

I made a sample:  https://codepen.io/anon/pen/bWBvMj?editors=1011


text:
Q: Common directive ng-click guidance needed I have a directive which consists of a form text element and a continue button along with the associated controller etc.  This directive is going to be used in about 5 different pages, but on each page it is used the continue button will do something different.
My question is where can/should I put the code for the continue button if it does different things for each page?
Since its a directive I cant simply pass a different function into ng-click depending on what page im on (ie, if i simply replicated the code on each page it is used I could simply change the function called on ng-click and have that function in each of the page controllers.
Hopefully Im not being too vague with my question and you can make sense of what im asking.  If not just say so and ill try to explain in more detail.
I would really appreciate some guidance on this matter.
Thanks.

A: There are two ways that you can do it. If you are creating your directive as a true component you can use isolated scope with & binding that binds to an expression.
Assume your directive looks like

and the generated html

   <input ...>
   <button ng-click="doAction()"><button>

The directive scope will be defined
scope:{
   onClick:'&'
}

In your directive controller or link function you need to implement the button doAction, which in turns evaluates the onClick action
scope.doAction=function() {
   scope.onClick({//if params are required});
}

Now you have linked the parent through the direct onClick reference. One thing to remember here is that this creates a directive with isolated scope.
In case you do not want isolated scope created you need to use
scope.$eval(attr.onClick); // this evaluates the expression on the current scope.
Hope this helps.

A: Ideally you should not create directives which are not re-usable.
In your case, you may do it like following -

*

*create an isolated scope in the directive

*add a function to be called and pass the page/ page id as parameter

*call functions in controller based on parameter

Directive

myApp.directive('someDirecive', function () {
    return {
        // restrict options are EACM. we want to use it like an attribute
        restrict: 'A',
        // template : <inline template string>
        // templateUrl = path to directive template.
        // templateUrl: '',
        scope: {
            onButtonClick : '&'
        },
        controller: function ($scope, $element, $attrs, $transclude) {

   $scope.onButtonClick = function(pageId) {
    if (pageId == 1) {
     // do something
    }
    else if (pageId == 2) {
     // do something
    }
   }

        },

        //link: function (scope, iElement, iAttrs) {
        //}

    };
});

HTML


text:
Q: display row data as column title in a CTE in SQL Server 2014 i have  table that contain student absence information, i make a CTE from that table to display StudentName,CName as column title and the absence hours for each student in each course.
this is my CTE code:
DECLARE @SummaryTable TABLE
(
  SName nvarchar(50),-- Student Name
  CName nvarchar(50) -- Course Name
 )
    INSERT INTO @SummaryTable(SName, CName)
    SELECT Student_tbl.SName,Sum_Abs from Absence_Summary_tbl
    inner join Student_tbl on Student_tbl.S_ID = Absence_Summary_tbl.S_ID
    inner join Stages_tbl on Stages_tbl.Stage_ID = Student_tbl.Stage_ID
    where Stages_tbl.Stage_ID = 1;
WITH CTE AS (
SELECT SName, CName,
       ROW_NUMBER() OVER(PARTITION BY SName ORDER BY CName) AS rn FROM @SummaryTable )
SELECT SName,
       MAX(CASE WHEN rn=1 THEN CName ELSE 0 END) AS CName1,
       MAX(CASE WHEN rn=2 THEN CName ELSE 0 END) AS CName2,
       MAX(CASE WHEN rn=3 THEN CName ELSE 0 END) AS CName3
FROM CTE
GROUP BY SName;

The result of CTE is display like image below:

in the result it display Course names as CName1,CName2,CName3 as column titles, is there any way to display real course names except the aliases as column titles for course names. in my real table 'Absence_Summary_tbl' i have a Course Name in a column called CName.

A: In @SummaryTable you are inserting the sum_Abs instead of CourseName,
@SummaryTable should have 3 columns SName, CName, Sum_Abs(to store the absent count per student per course)
there is no need of CTE to achieve this
Use Pivot instead:-
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(CName)
                    from Absence_Summary_tbl
                    group by CName
                    order by CName
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT SName,' + @cols + ' from
             (
                select SName, CName, Sum_Abs
                from @SummaryTable
            ) x
            pivot
            (
                sum(Sum_Abs)
                for CName in (' + @cols + ')
            ) p '

execute(@query);


text:
Q: Raspberry PI powering a peripheral device while accessing it via USB causing PI brownout/short-circuit My current project utilises a Raspberry PI (3B+ or 4B) to communicate and control an external peripheral device.
The Raspberry PI also has a UPS (PiJuice) attached, including a Li-Ion battery (and therefore ~3.7v).
Background
This peripheral device, was not designed or made by me, and is current limited in the device's circuitry preventing the device to be wholly powered via the USB cable.  It was never designed to be used the way I am using it.  It is instead, meant to be powered via a stand alone power source (AA batteries). USB was only meant to program the device, then be disconnected.
The device which requires ~4.2v-5v and pulling around 40mA to correctly operate within tolerances, contains a microcontroller (3.3V) and microSD card.  When the voltage drops (AA batteries), other components on the device stop working, due to their own (less forgiving) tolerances.  As mentioned above, when the device is connected solely via USB, the same component circuitry also stops working, as it doesn't receive sufficient power.
The device has my custom firmware, enabling access to the microSD filesystem via a MSD protocol.
The PI gpio is used to control the device's CLK, RST and another interrupt pin, externally signalled via jumpers, which switch the device between its normal mode, to MSD mode.
So in summary, the PI is connected to the device via both GPIO pins and a USB cable to access the USB MSD and interact with the USB HID, when the mode permits.
Side Note 1: Until I've come up with a working solution, I added a simple arduino style 5v relay, to disconnect the AA battery when not in use and conserve power, but this needs to go also.
Side Note 2 The device is highly sensitive to noise, as it records ultrasonic audio.  The PI USB has been found to introduce noise in the ultrasonic recordings, so I added python code on the PI to control the USB hub power, which disconnects the USB power when the device is recording (not in MSD mode).  This removes much of the the noise in recordings.
So far all this works, but it isn't nearly pretty or a long term workable solution.
Problem
I'm trying to remove the need for the additional power source for the peripheral device, as it causes big headaches when the AA batteries go flat.  I have a battery right there, already in the PiJuice.
Connecting the 5V pin on the Pi to the VCC of the peripheral device causes the PI to turn off every time, whenever the USB port is also connected.
I can successfully power the device (no AA batteries), via the 5V pin on the PI whenever the USB is not connected.
Any suggestions how to power my peripheral device, and get rid of those pesky AA batteries?
tl-dr
Generally, when a peripheral device needs supplementary power and a USB connection as well, how should a PI connect to it?

A: Since RPi schematics are not released, this is a vague guess but might be worth a try.
It is possible (I'd even say likely) that the power delivered to the USB ports is coming from a power switch, sort of isolating the 5V pin of the RPi and the Bus voltage on the USB port. Personally I don't know if and how backpowering (see official documentation here) is possible in this case, but what I am proposing won't harm your devices in either case.
What I think is happening: Power is delivered from the 5V side to the output side of the power switch.
Simple fix: Add a diode to prevent current flow from your device to the USB cable (coming from the 5V pin).


text:
Q: ActionScript 2.0 Import package into Timeline script All,
I have been trying to import some sample actionscript package into my flash project.
The sample code is defined in the org.red5.flash.bwcheck package.
In my flash project's (flash 8 and actionscript 2.0) actions frame:
I added these lines at the beginning:
import org.red5.flash.bwcheck.app.*;
import org.red5.flash.bwcheck.events.*;
import org.red5.flash.bwcheck.*;

and add the call to this package in my code
function start()
{
    serverURL = settingsManager.getIP();
    serverApplication = "live";
    clientServerService = "checkBandwidthUp";
    serverClientService = "checkBandwidth";
    trace("calling connect()");
    connect();
}

The connect() is a function defined org.red5.flash.bwcheck.app.BandwidthDetectionApp.
Nothing happens when I test the movie.
I added these paths to both action script 2.0's settings and project preferences:
./org/red5/flash/bwcheck
./org/red5/flash/bwcheck/app
./org/red5/flash/bwcheck/events
when I test or debug movie, the connect() does not seem to be called.
If I called the connect with the full path name:
Then I got a lot of syntax errors about the sample code which should not have errors.
My question is how do I import package and use it in my Actions Frame?
Thanks,
Peter


text: Q: Uncaught TypeError: cannot set property 'inject' of undefined I am having some unwanted error after I build mine react project. It's working fine but some time due to network connectivity site keep loading my chunks and gives me that error but when I reload again it starts working.


text:
Q: how to return to fragment in android fragmentTabHost I have paint this  problem:

Do anyone know solution?

A: Start ActivityB from ActivityA using startActivityForResult.
int REQUEST_CODE = 99; // random number here
startActivityForResult(activityAIntent, REQUEST_CODE);

1) In ActivityB call:
  setResult(RESULT_OK);
  finish();

2) In ActivityA catch RESULT_OK from ActivityB:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == REQUEST_CODE) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
           // finish ActivityA and navigate back to FragmentA
           setResult(RESULT_OK);
           finish();
        }
    }
}

Other solution if you don't need ActivityA after you start ActivityB, then call finish() in ActivityA where you start ActivityB. Having that you can simply call finish() in ActivityB and user will be navigated back to FragmentA as expected.


text:
Q: F# inferred types in If/Then If I have the following function:
let myFunc x y =
  if y = 0 then 1
  x

I get the error:
Program.fs(58,17): error FS0001: This expression was expected to have type
    unit
but here has type
    int

Why does the compiler expect 'unit' instead of int ?

A: It might worth adding that this is not just a property of if. F# is an expression-based language meaning that pretty much every piece of code (aside from type declarations and a few exceptions) is an expression that evaluates to some result. In fact, F# does not call if the if statement, but an if expression.
This means that you can use if in unexpected places. For example, this might be useful:
x/2 + (if x%2=0 then 0 else 1)

As already explained by Garry, if you omit else, then the expression still needs to return something - if the result was to be an int, then it would not really make sense (which number should the compiler pick?), so it requires that the result is of type unit, which is a special type representing "no result".
The unit type is also the result of all imperative functions (e.g. printf) or of all expressions that do not logically return any value (assignment or e.g. loop). This means that if you write:
if x > 0 then printfn "Big!"

... then the expression is well-typed, because printfn "Big!" has a return type unit and the implicitly added else branch also returns unit. You can create a value of type unit directly by hand (the type has exactly one value), so the above actually corresponds to:
if x > 0 then printfn "Big!" else ()

From the C# perspective, it makes more sense to read if .. then .. else as the conditional operator:
x/2 + (x%2 == 0 ? 0 : 1)

A: In F# when using an if statement when there is no else branch then it implicitly returns unit. If your then branch returns a type other than unit you must have an explicit else branch for it to work correctly. In your example you could write:
let myFunc x y = if y = 0 then 1 else x

MSDN - http://msdn.microsoft.com/en-us/library/dd233231.aspx


text:
Q: Ebizmarts Mailchimp Can We Use Storewise In Magento2 I want to use Ebizmarts_Mailchimp store wise to know that which language site the subscription came from.
Also How to link the signup form in footer to Mailchimp and link checkout to record revenue.
I configure all API key in admin.
But I am confused that How it work.

A: I work in Ebizmarts and I will be happy to help you out on this one.
There are a couple ways to be able to know where the subscription came from.

*

*Create one list per language. This is usually what we recommend because it has the best compatibility with the full e-commerce synchronization.

*Add interest groups and then force the subscription to a certain group when subscribing from each store view.

If you are not sure on how to do this please contact our support at mailchimp@ebizmarts-desk.zendesk.com.

A: But we can select ONLY 1 list per new store, that is the problem.
How can we assign two or more  different lists and use it for each language?


text:
Q: Access vnode of tag element without ref My component:
{
    updated()
    {
         var forms = document.getElementsByTagName('form');
         forms.forEach(form =>
         {
            var myProp = form.__vnode.props.onDoSubmit;
         });
    }
}

This code works on dev, but on production __vnode is undefined. How I can access vnode of any form inside my component?


text:
Q: Error morris.js Estoy intentando crear un grafico con morris.js, pero me da un error:
Uncaught Error: Graph container element not found
    at d [as constructor] (morris.min.js:6)
    at d.c [as constructor] (morris.min.js:6)
    at new d (morris.min.js:6)
    at Object.d [as Area] (morris.min.js:6)
    at HTMLDocument.<anonymous> (morris-data.js:6)
    at j (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at Function.ready (jquery.js:2)
    at HTMLDocument.J (jquery.js:2)
He mirado soluciones, y una de ellas es poner los script al final, depues del div, pero no me soluciona nada. El div en cuestion, donde quiero que aparezca el grafico es el siguiente:
<%@page import="Clases.Usuario"%>
<%@page import="java.util.ArrayList"%>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <link rel="icon" type="image/png" href="img/logo_ur.png" />

    <title>UR Apuestas - Perfil</title>

    <link href="CSS/bootstrap.min.css" rel="stylesheet">

    <link href="CSS/sb-admin.css" rel="stylesheet">

    <link href="CSS/morris.css" rel="stylesheet">

    <link rel="stylesheet" href="CSS/estilos.css">

    <link href="CSS/font-awesome.min.css" rel="stylesheet" type="text/css">

                      <%=(String) session.getAttribute("puntos")%>

                             Canjear

                             Recargar

                             Comprar

John Smith

 Yesterday at 4:32 PM

Lorem ipsum dolor sit amet, consectetur...

John Smith

 Yesterday at 4:32 PM

Lorem ipsum dolor sit amet, consectetur...

John Smith

 Yesterday at 4:32 PM

Lorem ipsum dolor sit amet, consectetur...

                            Read All New Messages

                      <%=(String) session.getAttribute("user")%>

                             Perfil

                             Ajustes

                            <form action="ControladorUsuario" method="POST">
                                <input type="hidden" name=""
                                 Salir
                            </form>

                    <form action="ControladorUsuario" method="POST">
                         Salir
                    </form>

 <%=(String) session.getAttribute("nombre")%> <%=(String) session.getAttribute("apellidos")%>

                                <div class="progress-bar progress-bar-info progress-bar-striped " role="progressbar" aria-valuenow="<%=(String) session.getAttribute("exp")%>" aria-valuemin="0" aria-valuemax="100" style="min-width: 2em;width: <%=(String) session.getAttribute("exp")%>%">
                                    <%=(String) session.getAttribute("exp")%>%

                         Deportes

                                Futbol

                                Baloncesto

                                Tenis

                         Mis Apuestas

                         Premios

                         Ranking

                         Contacto

Imanol Urrutia Diaz

Cambiar imagen

Imanol Urrutia Diaz

urrutia

urrus88@gmail.com

605025198

Castro urdiales

<%=(String) session.getAttribute("puntos")%>

URCoins

 Donut Chart

                                    View Details

 Social

Cambiar Datos

Cambia los datos de tu cuenta!

                                                Modernizate tio!

Mis apuestas

Consulta tus apuestas!

                                                Habras ganado? o perdido?

Mensajes

Consulta los ultimos mensajes!

                                                Rapido ti@!Que no tenemos todo el dia!

 Tu perfil

Mi Perfil

Cambia los datos de tu perfil!

                                                Actualizate!

Ajustes

Configura los ajustes de la web!

                                                Configurate!

Contacto

Contacta con nosotros!

                                                Vamos!Que nos aburrimos...!

>

function Donut(options) {
  this.resizeHandler = __bind(this.resizeHandler, this);
  this.select = __bind(this.select, this);
  this.click = __bind(this.click, this);
  var _this = this;
  if (!(this instanceof Morris.Donut)) {
    return new Morris.Donut(options);
  }
  this.options = $.extend({}, this.defaults, options);
  if (typeof options.element === 'string') {
    this.el = $(document.getElementById(options.element));
  } else {
    this.el = $(options.element);
  }
  if (this.el === null || this.el.length === 0) {
    throw new Error("Graph placeholder not found.");
  }
  if (options.data === void 0 || options.data.length === 0) {
    return;
  }
  this.raphael = new Raphael(this.el[0]);
  if (this.options.resize) {
    $(window).bind('resize', function(evt) {
      if (_this.timeoutId != null) {
        window.clearTimeout(_this.timeoutId);
      }
      return _this.timeoutId = window.setTimeout(_this.resizeHandler, 100);
    });
  }
  this.setData(options.data);
}

Donut.prototype.redraw = function() {
  var C, cx, cy, i, idx, last, max_value, min, next, seg, total, value, w, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _results;
  this.raphael.clear();
  cx = this.el.width() / 2;
  cy = this.el.height() / 2;
  w = (Math.min(cx, cy) - 10) / 3;
  total = 0;
  _ref = this.values;
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    value = _ref[_i];
    total += value;
  }
  min = 5 / (2 * w);
  C = 1.9999 * Math.PI - min * this.data.length;
  last = 0;
  idx = 0;
  this.segments = [];
  _ref1 = this.values;
  for (i = _j = 0, _len1 = _ref1.length; _j < _len1; i = ++_j) {
    value = _ref1[i];
    next = last + min + C * (value / total);
    seg = new Morris.DonutSegment(cx, cy, w * 2, w, last, next, this.data[i].color || this.options.colors[idx % this.options.colors.length], this.options.backgroundColor, idx, this.raphael);
    seg.render();
    this.segments.push(seg);
    seg.on('hover', this.select);
    seg.on('click', this.click);
    last = next;
    idx += 1;
  }
  this.text1 = this.drawEmptyDonutLabel(cx, cy - 10, this.options.labelColor, 15, 800);
  this.text2 = this.drawEmptyDonutLabel(cx, cy + 10, this.options.labelColor, 14);
  max_value = Math.max.apply(Math, this.values);
  idx = 0;
  _ref2 = this.values;
  _results = [];
  for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
    value = _ref2[_k];
    if (value === max_value) {
      this.select(idx);
      break;
    }
    _results.push(idx += 1);
  }
  return _results;
};

Donut.prototype.setData = function(data) {
  var row;
  this.data = data;
  this.values = (function() {
    var _i, _len, _ref, _results;
    _ref = this.data;
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      row = _ref[_i];
      _results.push(parseFloat(row.value));
    }
    return _results;
  }).call(this);
  return this.redraw();
};

Donut.prototype.click = function(idx) {
  return this.fire('click', idx, this.data[idx]);
};

Donut.prototype.select = function(idx) {
  var row, s, segment, _i, _len, _ref;
  _ref = this.segments;
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    s = _ref[_i];
    s.deselect();
  }
  segment = this.segments[idx];
  segment.select();
  row = this.data[idx];
  return this.setLabels(row.label, this.options.formatter(row.value, row));
};

A: Sería indispensable que nos facilitaras el HTML completo y, sobre todo, si en la consola de depuración de red aparecen recursos que no han podido ser cargados (archivo no encontrado o similares) ya que he intentado reproducir tu problema y me ha funcionado correctamente.
He usado el mismo orden de carga de javascripts que tú, pero no me queda claro si intentas hacer uso de jQuery (la función $( ... )) antes de haberla cargado en el HTML. Si es así sube todas las etiquetas

Usando window.onload

<link  rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css"/><link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css"/>

 Donut Chart

      View Details

Fíjate que pongas donde pongas tu código sólo se ejecutará cuando todos los recursos definidos en la página hayan sido cargados.


text:
Q: Increase the size for mobile menu by dragging I have a mobile menu for which I would like to increase the size of the menu by dragging it. Currently what I am doing is fixing it to a size of 50% of the screen. Below is how the menu looks.

The CSS, which I used to drag, doesn't work in this case.
.cbp-spmenu-bottom.cbp-spmenu-open {
    bottom: 8%;
    width: 100%;
  /*   height: 55%; */
    background: black;
    opacity: 1;
      overflow-y: auto;
    position: fixed;
    resize: vertical;
}

What could I do, so that I could touch the top bar, and resize the menu?

A: Just make sure you dont set the position of the css to be fixed otherwise,you wont be able to drag.
position:fixed

Or you can set the position of the but what you can do is set it fixed after you resize and drag it as shown in this thread

Fiddle

A: Here is a website which might help you. If this is unable to help you, you could check this website which has information on everything you can ever know about coding.
EDIT:
You could try this sample code- <button onclick="myFunction(width:200%;height:200%)">Increase Size Of Menu</button>
I hope I helped you enough so you can be able to do what you want to do!

A: The problem with the resize property is that it is not supported by most mobile browsers. You can find more details here and here.
If you want mobile support a javascript solution would be your only choice.
You can try a library like interact.js which seems to work fine on mobile devices.


text:
Q: Why initialValue of ThreadLocal doesn't increment my variables? I am learning about multithreading; and I have the following ThreadID class:
public class ThreadID {

    private static volatile int nextID=0;

    private static class ThreadLocalID extends ThreadLocal<Integer>{
        protected synchronized Integer initialValue(){
            return nextID ++;
        }
    }

    private static ThreadLocalID threadID =new ThreadLocalID();

    public static int get(){
        return threadID.get();
    }

    public static void set (int index){
        threadID.set(index);
    }
}

and the following Thread class:
class MyThread1 extends Thread {
    int x;
    public ThreadID tID;
    public int myid;

    public MyThread1(String name) {
        tID = new ThreadID();
        myid = tID.get();
    }

    public void run() {
        System.out.println("la thread =" + tID.get() + " myid= " + myid);
        try {
            this.sleep(10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("la thread =" + tID.get() + "   apres le sommeil ");
    }
}

and my main Class:
public static void main(String[] args) {
    MyThread1 TH[] = new MyThread1[10];
    for (int i = 0; i < 10; i++)
        TH[i] = new MyThread1("nom" + i);
    try {
        for (int i = 0; i < 10; i++) TH[i].start();
        for (int i = 0; i < 10; i++) TH[i].join();
    } catch (InterruptedException e) {
    }
}

Question:
What I want is to give each Thread an ID; I found that when I init the id in the thread constructor the value is always 0 (normally the initialValue should increment the nextID)
la thread =1 myid= 0
la thread =3 myid= 0
la thread =2 myid= 0

but when I init the id inside the Run function it works !
la thread =1 myid= 1
la thread =3 myid= 3
la thread =2 myid= 2

Can any one explain why this happens?

A:
What I want is to give each Thread an ID I found that when I init the
id in the thread constructor the value is always 0 (normally the
initialValue should increment the  nextID)

So in the MyThread1 class constructor you do:
public MyThread1(String name) {
    tID = new ThreadID();
    myid = tID.get();
}

In this case, the thread actually calling tID.get(); is the main thread, i.e., the thread that is calling those constructors, from the main class:
MyThread1 TH[] = new MyThread1[10];
for (int i = 0; i < 10; i++)
    TH[i] = new MyThread1("nom" + i);

The first call to tID.get() will generate a new ID as 0, since it is the first time that any thread is calling tID.get(). The next calls from the same thread (i.e., main thread) will not generate a new ID, but instead, it always returns the same ID, in this case, return 0 for the main thread.

but when I init the id inside the Run function it works!

Inside the run method:
public void run() {
    System.out.println("la thread =" + tID.get() + " myid= " + myid);
    try {
        this.sleep(10);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("la thread =" + tID.get() + "   apres le sommeil ");
}

the  tID.get() will be called by different threads, and that is why you get new IDs. One new ID per thread calling for the first time tID.get().


text:
Q: How do you properly change a model in sequelize? I have the below two models, and am trying to change the userId property on the Report model to not have to be unique. When I change unique to false, or delete the property altogether, I am still getting the unique validation error when trying to create a Report with an existing userId (using models.Report.create({ userId: 1 }) when 1 is an existing user's id). I've also tried making a migration and running that to no avail.
Am I missing something here? Been stuck on this for a while, so any input is massively appreciated. Thank you.
Report.js

module.exports = (sequelize, DataTypes) => {
  const Report = sequelize.define(
    'Report',
      userId: {
        allowNull: false,
        type: Sequelize.INTEGER,
        unique: true,
      },
  );

  Report.associate = function(models) {
    Report.belongsTo(models.UserInfo, { foreignKey: 'userId' });
  };
  return Report;
};

UserInfo.js
module.exports = (sequelize, DataTypes) => {
  const UserInfo = sequelize.define(
    'UserInfo',
    {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
  );

  UserInfo.associate = function associate(models) {
    ApplicantInfo.hasMany(models.Report, { foreignKey: 'applicantId' });
  };

  return ApplicantInfo;
};


text:
Q: Load Image From URL into ListView How to load image in imageView for List item from an URL.

A: Simply you can use this library
which uses the concept of lazy loading.

A: I used this in getView() in ListView adapter.
Webview kWebview = new Webview(context);
kWebview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
kWebview.setFocusable(false);
kWebview.setClickable(false);
kWebview.setLongClickable(false);
kWebview.setFocusableInTouchMode(false);
kWebview.setInitialScale(100);
kWebview.setBackgroundColor(Color.BLACK);

WebSettings kSet = kWebview.getSettings();
kSet.setLoadWithOverviewMode(false);
kSet.setLoadsImagesAutomatically(true);
kSet.setAppCacheEnabled(true);
kSet.setAppCachePath(_context.getCacheDir().toString());
kSet.setCacheMode(WebSettings.LOAD_DEFAULT);
kSet.setAllowFileAccess(true);
kSet.setDomStorageEnabled(true);

kWebview.loadUrl("http://image_url");

Webview is more smoothly load than ImageView

A: Try this code:
string path = item.ImgPath;
URL url = new URL(path);
URI uri = new URI(url.Protocol, url.UserInfo, url.Host, url.Port, url.Path, url.Query, url.Ref);
url = uri.ToURL();

//convert it into bitmap
var bitmap = Android.Graphics.BitmapFactory.DecodeStream(url.OpenStream());

//set bitmap drawable
System.IO.Stream stream = url.OpenStream();
Img.SetImageBitmap(bitmap);

A: Try Below code :
try
{
     URL img_value = null;
     img_value = new URL("ImageUrl");
     Bitmap mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
     Image.setImageBitmap(mIcon1);
}
catch(Exception e)
{
}


text:
Q: IBM API Connect health check Would like to know in API Connect, is there a built-in way to check health of an API in Prod? (Like Springboot actuator/health)
If not, best way recommended to implement health check for each of our APIs that we are about to develop in API Connect
Regards,
Martand

A: API Connect v2018 portals do not have an inbuilt health check, they removed it in v5. There is a RFE to request this functionality.
For the gateway component the best way is to use a tcp_half_open health check on the IP/Port that your gateway is listening on. Note it has to be tcp_half_open otherwise your appliance will be spammed with TLS handshake errors.
This will confirm that the gateway is up and running and serving requests. You should also check the management port is running, as your gateway might not be synchronizing with the APIM and it's possible that it is serving up an old API.
Health checks on an individual API are a little more difficult, and would need to be added as a separate operation in your spec.


text:
Q: BigDecimal HALF_UP rounding issue I am trying to round 0.14049 using scale=3 and HALF_UP rounding mode and hoping to see rounded value = 0.141 but getting 0.140 instead.
As per my understanding the last decimal digit 9 should round up the 4 to 5 and that should in-turn round up 0 to 1 when using scale 3 and i should see 0.141.
Is that a bug in BigDecimal setScale method or my expectation of Rounding is wrong. How can I get rounded values similar to 0.141 and not 0.140?
BigDecimal bd=new BigDecimal("0.14049");
BigDecimal normalizedField = field.setScale(3, RoundingMode.HALF_UP);
System.out.println(normalizedField);
// Output = 0.140

A:
As per my understanding the last decimal digit 9 should round up the 4 to 5 and that should in-turn round up 0 to 1 when using scale 3 and i should see 0.141.

This understanding is incorrect. Rounding is not an iterative process. Only the first digit after the scale position is considered, not the whole chain of digits. In your case, the digit is 4, so it gets converted down to zero.

A: Depending on your business domain, the "4999998" case will happen always on the same position. I had a similar situation, were the scale was 2. So I added and extra step to the rounding. In your case:
BigDecimal bd=new BigDecimal("0.14049");
BigDecimal normalizedField = bd.setScale(4, RoundingMode.HALF_UP).setScale(3, RoundingMode.HALF_UP);
System.out.println(normalizedField);


text:
Q: Transcendental equation solution by numerical method I want to solve one transcendental equation numerically. I have used the function 'solve' for the solution but my results are varied as compared to graphical solution. My code is written below and I am sending the graphical solution results.
clear all;
n1=1.77;
n2=1.45;
d=1e-6;
lambda = 1e-6;
ko = 2*pi/lambda;
A=(ko*n1)^2;
B=(ko*n2)^2;
r=(ko*d)*sqrt(n1^2-n2^2);
syms h;
s=((h*d)-m*pi) == 2*atan(sqrt(r^2/(h^2*d^2)-1));
solve (s)
prop=sqrt(A-ans^2);
neff=(prop*lambda)/(2*3.14)

where m will be varries from 0 to 2.0 with interval of 0.5. Graphical results are: m=0 neff is 1.7299 but graphical solution is 1.75 m=0.5 neff is 1.678 but graphical solution is 1.71 m=1.0 neff is 1.608 but graphical solution is 1.65 m=1.5 neff is 1.523 but graphical solution is 1.55 m=2.0 neff is 1.451 but graphical solution is 1.452
Can anyone please help me out and tell me the fault ? Also is there any other function can be used instead of 'solve'.
Thanks.

A: In principle, you need to do something like
fun = @(hd) ((hd)-m*pi)-2*atan(sqrt(r^2/(hd^2)-1));
fsolve(fun, 1.)

where I solved for the combined value hd=h*d, to avoid truncation errors in the terms h*d-m*pi and sqrt(r^2/(hd^2)-1).


text:
Q: Finding the nearest distances between a vector of points and a polygon in R I have a data frame of lat/long coordinates and a polygon, which represents a coastline. I am trying to find the distance between each point and the nearest coastline feature.  I would like to end up with an output data frame that includes columns for my original lat/long values and a new distance column.
I have attempted to use the gDistance function after reading answers to similar questions online, but I think that I am missing a few steps and am having trouble figuring it out. At present, I only end up with a single distance value. I am quite new to R and would really appreciate any help that anyone might be able to give.
Thanks!
#Load data
     Locs = structure(list(id = 1:5, Lat = c(29.59679167, 29.43586667, 29.37642222,29.52786111, 30.10603611), Long = c(-81.02547778, -80.92573889,
-80.97714167, -81.08721667, -80.94368611)), .Names = c("id","Lat", "Long"), class = "data.frame", row.names = c(NA, -5L))

#Extract lat/long coordinates
   xy = Locs[,c("Lat","Long")]
#Create SpatialPointsDataFrame from xy data and change projection to metres
   spdf = SpatialPointsDataFrame(coords=xy, data=xy, proj4string = CRS("+proj=aea +zone=17 ellps=WGS84"))

#Read in shapefile as a spatialdataframe object
  coast = readOGR(dsn="land data", layer="coast")
#Transform to AEA (m) projection to match projection of points
   land_poly = spTransform(coast, CRS("+proj=aea +zone=17 ellps=WGS84"))

#OR load map from map package (but unfortunately map objects do not work in gDistance)
   library(maps)
   library(mapdata)
   coast2 = map('usa', col = "grey90", fill=TRUE)

#Calculate distance between each point and the nearest land feature
  for(i in 1:dim(spdf)[1]){
  g = gDistance(spdf[i,],land_poly)
  }

EDIT: Using AEF's code alterations below (for the for loop step), I am able to get gDistance values for each row, however the output distances are not correct (see below). According to arcGIS they should be between 4-37km, not >500km. Any thoughts on what I am doing wrong here? My land polygon and points are both in the same projection.
gDistance output
  id      Lat      Long dist_gDist
1  1 29.59679 -81.02548  516299.0
2  2 29.43587 -80.92574  516298.8
3  3 29.37642 -80.97714  516298.9
4  4 29.52786 -81.08722  516299.0
5  5 30.10604 -80.94369  516299.0

The correct distances (calculated in GIS)
  id      Lat      Long dist_arc
1  1 29.59679 -81.02548  13.630
2  2 29.43587 -80.92574  15.039
3  3 29.37642 -80.97714  8.111
4  4 29.52786 -81.08722  4.784
5  5 30.10604 -80.94369  36.855

A: I think you get only one distance value because you overwrite g in every iteration of your for-loop. I do however not not know if this is the only problem because I cannot reproduce your issue without suitable data.
Try changing the last loop to this:
g = rep(NA, dim(spdf)[1])
for(i in 1:dim(spdf)[1]){
  g[i] = gDistance(spdf[i,],land_poly)
}


text:
Q: Add address at end of line in hosts file using sed I have a specific line in the hosts file that is used for my local Wordpress Multisite install, which looks like this:
127.0.0.1       localhost domain.dev site1.domain.dev site2.domain.dev

I'm writing a Shell script that I can run to create a new individual site on my Multisite install straight from Terminal. I need to be able to add a new record to my /etc/hosts file whenever I run this command. In the Shell file, I'm using $site_addr as my variable for the site name. You then need to add .domain.dev to the end of this. An example I've done (which didn't work) using sed:
sed -i'.bak' '7i7 $site_addr.domain.dev' /etc/hosts

Yhe line from my hosts file (above) that I need to edit is line 7, hence the 7i7 in the sed command. I want to add the new record at the end of the line. I also want to create a backup hosts file in case anything goes wrong.
Thanks for any help guys, hope i've explained it well enough :)

A: if this is the line 7
sed -i '.bak' "7 s/$/ ${site_addr}.domain.dev/" /etc/hosts

but you can use the pattern matching (a bit safer) with
sed -i '.bak' "/127\.0\.0\.1/ s/$/ ${site_addr}.domain.dev/" /etc/hosts

i recommend to also first check if the domain is not already in