text:
Q: initialization makes integer from pointer without a cast [enabled by default] i just started to learn how to program and i encountered this error that goes like this: "initialization makes integer from pointer without a cast [enabled by default]"
What is the problem?
 // This program pairs three kids with their favorite superhero
#include <stdio.h>
#include <string.h>
main()
{
char Kid1[12];
// Kid1 can hold an 11-character name
// Kid2 will be 7 characters (Maddie plus null 0)
char Kid2[] = "Maddie";
// Kid3 is also 7 characters, but specifically defined
char Kid3[7] = "Andrew";
// Hero1 will be 7 characters (adding null 0!)
char Hero1 = "Batman";
// Hero2 will have extra room just in case
char Hero2[34] = "Spiderman";
char Hero3[25];
Kid1[0] = 'K';  //Kid1 is being defined character-by-character
Kid1[1] = 'a';  //Not efficient, but it does work
Kid1[2] = 't';
Kid1[3] = 'i';
Kid1[4] = 'e';
Kid1[5] = '\0';  // Never forget the null 0 so C knows when the
// string ends
strcpy(Hero3, "The Incredible Hulk");

printf("%s\'s favorite hero is %s.\n", Kid1, Hero1);
printf("%s\'s favorite hero is %s.\n", Kid2, Hero2);
printf("%s\'s favorite hero is %s.\n", Kid3, Hero3);
return 0;
}

A: The problem is with char Hero1 = "Batman":

*

*When you use a double-quoted string of characters in your code, the compiler replaces it with a pointer to the beginning of the memory space in which the string will reside during runtime.

*So by char Hero1 = "Batman", you are actually attempting to assign a memory address (which typically consists of 32 or 64 bits of data, depending on your system) into a character variable (which typically stores 8 bits of data).

In order to fix the problem, you need to change it to either one of the following options:

*

*char  Hero1[] = "Batman"

*char* Hero1   = "Batman"

FYI, in both cases above, the string "Batman" will reside in a read-only memory section during runtime.
However, there is a notable difference between these two cases:

*

*Using char Hero1[], the "Batman" string will be copied into the stack every time the function is called. The Hero1 array will start at that address, and you will be able to change the contents of that array at a later point within the function.

*Using char* Hero1, the "Batman" string will not be copied into the stack every time the function is called. The Hero1 variable will be pointing to the original address of the string, hence you will not will be able to change the contents of that string at any point within the function.

When the executable image is generated from your code, the string is placed in the code-section, which is one of several memory-sections within the program. The compiler then replaces the so-called "string assignment" with a so-called "integer assignment".
For example, char* x = "abc" is changed into char* x = (char*)0x82004000 before being compiled into object code, where 0x82004000 is the (constant) address of the string in the program's memory space.
When you do sizeof("abc"), the executable image will not even contain the "abc" string, since there is no "runtime" operation performed on this string.
There is no object code generated for sizeof - the compiler computes this value during compilation, and immediately replaces it with a constant.
You can look into the (intermediate) map file that is usually generated, and see that the input string of that sizeof operation does not appear anywhere.

A: char Hero1 = "Batman";

should be
char Hero1[] = "Batman";

A: A couple times you have some issues:
#include <stdio.h>
#include <string.h>
main()
{
    char Kid1[12];
    // Kid1 can hold an 11-character name
    // Kid2 will be 7 characters (Maddie plus null 0)
    char Kid2[] = "Maddie";
    // Kid3 is also 7 characters, but specifically defined
    char Kid3[7] = "Andrew";
    // Hero1 will be 7 characters (adding null 0!)
    char *Hero1 = "Batman"; //needs to be a pointer
    // Hero2 will have extra room just in case
    char *Hero2 = "Spiderman"; //needs to be a pointer
    char Hero3[25]
    Kid1[0] = 'K';  //Kid1 is being defined character-by-character
    Kid1[1] = 'a';  //Not efficient, but it does work
    Kid1[2] = 't';
    Kid1[3] = 'i';
    Kid1[4] = 'e';
    Kid1[5] = '\0';  // Never forget the null 0 so C knows when the
                  // string ends
    strcpy(Hero3, "The Incredible Hulk");

    printf("%s\'s favorite hero is %s.\n", Kid1, Hero1);
    printf("%s\'s favorite hero is %s.\n", Kid2, Hero2);
    printf("%s\'s favorite hero is %s.\n", Kid3, Hero3);
    return 0;
}

You should define all of your vars at the top of the function, its a good C practice.
Other than that, I flagged the issues (and corrected them) with comments.

A: Solution:
This error you get because String data type is not in C
programming you can print string by using array or char pointer like
1.Array:
  #include<stdio.h>
   int main(){
   char  a[]={'a','b','c','d','f','\0'};
   printf("%s",a);
   return 0;
   }

Click here to check the output of solution array
2.char pointer:
    #include<stdio.h>
     int main(){
     char*  a="abcd";
     printf("%s",a);
     return 0;
     }

Click here to check the output of solution char pointer


text:
Q: Optional Parameters In Stored Procs - CASE vs. OR Is there any difference Performance wise between these filter methods?
Method 1: WHERE (@Col1 IS NULL OR t.column = @Col1)

Method 2: WHERE 1 = case when @col1 is null then 1 else case when col1 = @col1 then 1 else 0 end end

A: Why not use Coalesce?
Where Col1 = Coalesce(@Col1, Col1)

EDIT:  (thx to Joel's comment below) This works only if col1 does not allow Nulls, or if it does allow nulls and you want the null values excluded when @Col1 is null or absent.  SO, if it allows nulls and you want them included when @Col1 parameter is null or absent then modify as follows:
 Where Coalesce(@Col1, Col1) Is Null Or Col1 = Coalesce(@Col1, Col1)

A: If you know your Col1 column doesn't itself contain any null values, you can do this:
WHERE Col1 = COALESCE(@Col1, Col1)

Otherwise your CASE statement should typically do a little better than the OR. I add emphasis to "typically" because ever table is different.  You should always profile to know for sure.
Unfortunately, typically the fastest way is to use dynamic sql to exclude the condition from the query in the first place if the parameter is null.  But of course save that as an optimization of last resort.

A: Yes. CASE has a guaranteed execution order while OR does not. Many programmers rely on OR short-circuit and are surprised to learn that a set oriented declarative language like SQL does not guarantee boolean operator short-circuit.
That being said using OR and CASe in WHERE clauses is a bad practice. Separate the condition into a clear IF statement and have separate queries on each branch:
IF @col1 IS NOT NULL
  SELECT ... WHERE col1 = @col1;
ELSE
  SELECT ... WHERE <alternatecondition>;

Placing the condition inside the WHERE usually defeats the optimizer that cannot guess what @col1 will be and produces a bad plan involving a full scan.
Update
Since I got tired of explaining again and again that boolean short-circuit is not guaranteed in SQL, I decided to write a full blog column about it: SQL Server boolean operator short-circuit. There you'll find a simple counter example showing that boolean short-circuit is not only not guaranteed, but relying on it can actually be very dangerous as it can result in run time errors.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to start activity ComponentInfo (android) I am getting this error, please help me.
Unable to start activity ComponentInfo{com.example.newandrojenaproject/com.example.newandrojenaproject.MainActivity}: java.lang.NullPointerException
Here is my MainActivity.java
package com.example.newandrojenaproject;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import com.hp.hpl.jena.query.*;
public class MainActivity extends Activity {
    TextView t;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String str = extractUsingSparql("<http://dbpedia.org/resource/Babur>");
        t = (TextView) findViewById(R.id.textView1);
        if(!str.equalsIgnoreCase("null"))
        t.setText(str);
        else
            t.setText("Null Value Returned");
    }

     public static String extractUsingSparql(String url){

            String abstract1= "";
            String var = "abstract";
            String r="";

            String service = "http://dbpedia.org/sparql";
            String query = "SELECT ?abstract WHERE { { "+url+" <http://dbpedia.org/ontology/abstract> ?abstract. FILTER langMatches( lang(?abstract), 'en') } } ";
            //Abstract
            Query q = QueryFactory.create(query, Syntax.syntaxARQ);
            QueryExecution qe = QueryExecutionFactory.sparqlService(service, q);
            try{
            ResultSet resultSet = qe.execSelect();
            while (resultSet.hasNext()) {
                QuerySolution solution = resultSet.next();
                if (solution.get(var) == null) {

                      System.out.println("{null}");
                      r = "null";

                    } else if (solution.get(var).isLiteral()) {

                      System.out.println (solution.getLiteral(var).toString());
                     r= solution.getLiteral(var).toString();
                    } else {
                      System.out.println(solution.getResource(var).getURI());
                      r = solution.getResource(var).getURI();
                    }
            }
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
            }
            finally
            {
                qe.close();
            }
            return r;
     }

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

}

Here is the XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

I am not using any other activity. I am using androjena and ARQoid libraries for sparql queries. I don't know where actually the error is and how to solve it!
Here are the errors (LogCat output):
03-19 13:00:29.125: E/AndroidRuntime(832): FATAL EXCEPTION: main
03-19 13:00:29.125: E/AndroidRuntime(832): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newandrojenaproject/com.example.newandrojenaproject.MainActivity}: java.lang.NullPointerException
03-19 13:00:29.125: E/AndroidRuntime(832):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-19 13:00:29.125: E/AndroidRuntime(832):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-19 13:00:29.125: E/AndroidRuntime(832):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-19 13:00:29.125: E/AndroidRuntime(832):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-19 13:00:29.125: E/AndroidRuntime(832):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-19 13:00:29.125: E/AndroidRuntime(832):  at android.os.Looper.loop(Looper.java:137)
03-19 13:00:29.125: E/AndroidRuntime(832):  at android.app.ActivityThread.main(ActivityThread.java:5039)
03-19 13:00:29.125: E/AndroidRuntime(832):  at java.lang.reflect.Method.invokeNative(Native Method)
03-19 13:00:29.125: E/AndroidRuntime(832):  at java.lang.reflect.Method.invoke(Method.java:511)
03-19 13:00:29.125: E/AndroidRuntime(832):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-19 13:00:29.125: E/AndroidRuntime(832):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-19 13:00:29.125: E/AndroidRuntime(832):  at dalvik.system.NativeStart.main(Native Method)
03-19 13:00:29.125: E/AndroidRuntime(832): Caused by: java.lang.NullPointerException
03-19 13:00:29.125: E/AndroidRuntime(832):  at com.android.internal.os.LoggingPrintStream.println(LoggingPrintStream.java:298)
03-19 13:00:29.125: E/AndroidRuntime(832):  at com.example.newandrojenaproject.MainActivity.extractUsingSparql(MainActivity.java:56)
03-19 13:00:29.125: E/AndroidRuntime(832):  at com.example.newandrojenaproject.MainActivity.onCreate(MainActivity.java:16)
03-19 13:00:29.125: E/AndroidRuntime(832):  at android.app.Activity.performCreate(Activity.java:5104)
03-19 13:00:29.125: E/AndroidRuntime(832):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-19 13:00:29.125: E/AndroidRuntime(832):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-19 13:00:29.125: E/AndroidRuntime(832):  ... 11 more

A: As you may see from the log file, the error is located in the 16th row of the MainActivity.java.
It's caused because t(textView) is equal to null.
It may be caused by some kind of mess in references, so, try to clean and refresh your project.
Project -> Clean in eclipse.


text:
Q: Plot 2D in line graph for android using eclipse im looking for a working source code about plotting 2D to line graph using java.
So far I've been try AndroidPlot but I had so many error, for example "Unfortunately apps is stop" .
Im tired and sick with Eclipse because user must concern about its compatible version of everything.
So, I really need a complete tutorial for plotting 2D to line graph, which works.

A: I tried some Android plotting libraries and stopped at Android Plot. It is really good, but indeed a bit hard to understand how the sample code works.
Tutorials and docs of AndroidPlot are sufficient to be able to use it. However, I wasted 5 hours to create plotting engine for my app. I recommend you to study sample code in the docs and try to understand how it works. What is important is that when the plot is redrawn, you need to replace values in the set, but not add new values.
I used following strategy to deploy this library: I copied sample code to my project and replaced small pieces of code there and looked what happens.
UPDATE: Also take a look at this video in youtube. It explains very well what to do.


text:
Q: How to make HTML Form to open a new page everytime we submit new value I have a form which on submit refer to a PHP page, currently i am using the following code.
<form action="load.php" method="post" target="_blank" class="form">

the problem is, if i click submit on new values it will reload the same new page, How can i make it open a completely new windows everytime i submit the form.

A: I got it to work using:
<form action="load.php" method="post" target="_blank" enctype="multipart/form-data" class="form">

and
<input type="submit" onClick="window.open" value="Executar" id="but"/></p>

A: In load.php at the end you could do this
<?php
echo '<script type="text/javascript" language="javascript">
window.open("new url here");
</script>';
?>


text:
Q: System.JSONException when deserializing JSON to object note : this is a follow up to this question
I'm following the approach on this post, and have created a class to use to deserialize a json string as I know the structure of the response.
I am able to deserialize the json to a map<string,decimal> but I receive an error if I try to deserialize to a list of an inner class that consists of a string and a decimal:
public class CurrentRate {
    string IsoCode;
    decimal value;
}

here is the structure of my JSON class, with the portion that doesnt work commented out:
public class myJSONClass{
    public string disclaimer;
    public string license;
    public string timestamp;
    public string base;
    // public currentRate[] rates;
    public map<string,decimal> rates = new map<string,decimal>();
}

The JSON being parsed is structured as follows
{
    "disclaimer": "Usage subject to terms: https://openexchangerates.org/terms",
    "license": "https://openexchangerates.org/license",
    "timestamp": 1506733203,
    "base": "USD",
    "rates": {
        "AED": 3.672611,
        "AFN": 68.671,
        "ALL": 113.870562,
        "AMD": 478.245,
        "ANG": 1.779798
   }
}

The deserialization is happening here:
string responseText = res.getBody();
myJSONClass obj = (myJSONClass)JSON.deserialize(responseText, myJSONClass.class);

And the error is:

System.JSONException: Expected List but
  found { at [line:5, column:16]

And here is the full code in case its helpful.  I can work with the map, but it seems like I should be able to deserialize to a list and I want to know what I am doing wrong.
public class CurrencyUpdater {

    public class CurrentRate {
            string IsoCode;
            decimal value;
    }

    public class myJSONClass {
        public string disclaimer;
        public string license;
        public string timestamp;
        public string base;
        // does not work        public currentRate[] rates;
        public map<string,decimal> rates = new map<string,decimal>();
    }

    public list<CurrentRate> callEndpoint() {

          list<currentRate> OERRates = new list<currentRate>();

          HttpRequest req = new HttpRequest();
          req.setMethod('GET');
          req.setEndpoint('callout:OpenExchangeRates');
          Http http = new Http();

          try {
              HTTPResponse res = http.send(req);
              string responseText = res.getBody();
              system.debug('responseText = ' + responseText);

              myJSONClass obj = (myJSONClass)JSON.deserialize(responseText, myJSONClass.class);
              system.debug(obj.rates.keySet());

          } catch(System.CalloutException e) {

          }

         return OERRates;
    }
}

A: To deserialize it as a list, you'd have to change your JSON:
"rates": [
    { "IsoCode": "AED", "value": 3.672611 },
    { "IsoCode": "AFN", "value": 68.671 },
    { "IsoCode": "ALL", "value": 113.870562 },
    { "IsoCode": "AMD", "value": 478.245 },
    { "IsoCode": "ANG", "value": 1.779798 }
  ]

At this point the currentRate[] would be the correct data type. If you can't change the JSON, then Map<String, Decimal> is your best alternative, assuming you don't want to enumerate all the possible currency codes that you may receive.

A: Your approach to create a Class based on the structure of the JSON string is spot on, but it was just a simple mistake on the "shape" of that Class. There's not an Array of rates in that JSON String.
Something that I use to help me with that is a JSON editor/linter rather than trying to figure it out in my head. I use JSON Editor Online (which I am in no way affiliated with), but there are more than a few available.


text:
Q: What is the cable diameter of a single core of cat6 ? What is the cable diameter of a single core of cat6 ? I can find the diameter and AWG of a whole cat6 cable (eg, 8 cores + outer insulation) but couldn't find the cable diameter of a single core of cat6.

A: 1.14 mm per D-Link's specification, or one could simply measure a sample or two with a caliper


text:
Q: woocommerce failed to load resource add_action( 'admin_menu', array($this, 'admin_menu'), 100 );

public function admin_menu() {
    $page = add_submenu_page( 'edit.php?post_type=product', __( 'ajaxmain' ), __( 'ajaxmainagain' ), apply_filters( 'woocommerce_csv_product_role', 'manage_woocommerce' ), 'ajaxmain-product', array( $this, 'output' ) );
}

public function output() {
    include( 'ajaxmain.php' );
}

i have attached 2 screenshots. it goes and adds ajaxmainagain to the submenu. when i click on it, it loads ajaxmain.php. however it fails to load stylesheets, scripts. the scripts and stylesheets are in the same directory as ajaxmain.php. it is looking for scripts and stylesheets in wp-admin directory. thanks for the help. unable to find resource http://localhost/wordpress/wp-admin/ajax1.php?stateofmachine=xm234jq&q=2. the resource is in plugins directory.

A: You need to load your style/script like this.
wp_register_style('custom-style', plugins_url("/path/to/style.css"), '', true );
wp_enqueue_style('custom-style');

wp_register_script('custom-script', plugins_url("/path/to/script.js"), '', true );
wp_enqueue_script('custom-script');

and with this plugin_url you will get the path till your plugin directory like eg.
http://localhost/wordpress/wp-content/plugins/sample-plugin/


text:
Q: How can i calculate code coverage of a static library in XCode 5 using a project that links to this static library? I have an Xcode5 project that builds a static library as its product. While building this library i had turned on the Code coverage settings i.e. "Generate Test Coverage files" and " Instrument Program Flow".
As a result, when library was built, gcno files were created for all the files correspondingly in the same directory.
And in order to calculate its code coverage i have another project which links to this library and creates an executable. This project was also built with "Generate Test Coverage files" and " Instrument Program Flow" as YES.
Now, upon executing this product, only the gcda files for the files in the project of my test executable are generated.
How can i generate the gcda files for the static library that was linked into my project while building it.

A: You can do it now with Xcode 7.3.
Put the library project and the test project into the same workspace and configure the test project to link to the product of the library project. Turn on "Gather Code Coverage" in both the framework scheme in the library project and the test scheme in the test project. After that you'll be able to see the code coverage for the library in the coverage tab in Xcode.


text:
Q: Alternative to entering entity references in source code Google's HTML/CSS Style Guide advises against using entity references:

Do not use entity references.
There is no need to use entity references like —, ", or ☺, assuming the same encoding (UTF-8) is used for files and editors as well as among teams.

<!-- Not recommended -->
The currency symbol for the Euro is “&eur;”.
<!-- Recommended -->
The currency symbol for the Euro is "€".

I'm not sure I understand what it is that they are proposing. The only thing I can think of is that they are saying that you should be using your text editor's insert character command (e.g., in Atom, Ctrl-Shift-U, or in Emacs, C-x 8) to enter Unicode characters rather than typing in the literal entity references. Is that it?

A:
The only thing I can think of is that they are saying that you should be using your text editor's insert character command […] rather than typing in the literal entity references. Is that it?

Yes, that's precisely what they're saying.
You don't write A to insert the letter A, after all! There's no more reason to write ä for ä, or ♥ for ♥, when those characters can be represented directly in the HTML file.


text:
Q: Django template tag to recurse a nested dict This is a followup on Build directory tree from dropbox API
I've got my dictionary sorted out, and it's how I want it. But now I'd like to write a template tag that writes this nested structure out as html, something like:

        Dir/

                Dir2/
                ...

Inner File

File1

File2

All I've been able to come up with is a recursive generator that gets me the files and directories and I can put these in a flat list just fine, but I can't figure out how to get the nesting to work, and how to get the html in the right place.
def recurse(d):
    for key, value in d.items():
        if value['contents']:
            for inner_key, inner_value in recurse(value['contents']):
                yield inner_key, inner_value
        else:
            yield key, value

And the template tag:
@register.simple_tag()
def dropbox_files():
    files = function_from_other_question()

    s = '
'
    for key, value in recurse(files):
        s += '
{}
'.format(key)
    s += '
'
    return s

This gets me all the paths, but as I said, without any nested structure.

A: You might be able to do with a template include:
recurse_dict.html
{% if dict and dict.keys|length > 0 %}

    {% for key, value in dict.items %}

            {% if value and value.keys|length > 0 %}
               {{ key }} {% include "recurse_dict.html" with dict=value %}
            {% else %}
               {{ value }}
            {% endif %}

    {% endfor %}

{% endif %}


text:
Q: pre-allocation of array size in Matlab What is the efficient way of dynamically preallocating the size of an array variable which appears to change its size on every loop iteration in Matlab? It is possible to initialize it using the zeros() matrix but it sometimes is very tricky (for example: in determining the upper and lower limits).

A: This is the solution that I use for 2D arrays of dynamic size. Say the maximal limit of my array is 2000x2000, then I just preallocate zeros of the 1-D vector analogue (a 2000^2x1 vector) and after the code ends get rid of the zeros (or just ignore them in case the data is going to a histogram), and reshape once if needed after the code ends...
For example:
 for n=1:100;
     v=zeros(2000^2,1);
     v(1:numel(data))=data(:);
     % rest of the code here
 end


text:
Q: Problems splitting an array without creating array inside array I have a propertyArray and each property have one or more expense
I want to take the expense out of the propertyArray and put them all into the expenseArray
My problem is that it makes an array in an array.
How do I avoid that?
    for (var i=0; i<propertyArray.length; i++) {
        expenseArray[i] = propertyArray[i].expense;
        delete propertyArray[i].expense;
    }

And here is the propertyArray
propertyArray: [
    {
        "_id": "ANA-C202",
        "name": "Ananya",
        "expense": [
            {
                "_id": 2,
                "expenseCategory": "OFFICE",
                "dueDate": 1493719324,
                "amount": 8121,
                "account": "BANK01",
            }
        ]
    },
    {
        "_id": "PAP-720",
        "name": "Paradise Park",
        "expense": [
            {
                "_id": 1,
                "expenseCategory": "OFFICE",
                "dueDate": 1493719324,
                "amount": 100000,
                "account": "BANK01",
            },
            {
                "_id": 3,
                "expenseCategory": "CONDOBILL",
                "dueDate": 1493719324,
                "amount": 3123,
                "account": "BANK01",
            },
            {
                "_id": 5,
                "expenseCategory": "CONDOBILL",
                "dueDate": 1493719324,
                "amount": 925,
                "account": "BANK02",
            }
        ]
    }
}

propertyArray looks fine after it has been run, but expenseArray does not...
expenseArray: [
    [
        {
            "_id": 2,
            "expenseCategory": "OFFICE",
            "dueDate": 1493719324,
            "amount": 8121,
            "account": "BANK01",
        }
    ],
    [
        {
            "_id": 1,
            "expenseCategory": "OFFICE",
            "dueDate": 1493719324,
            "amount": 100000,
            "account": "BANK01",
        },
        {
            "_id": 3,
            "expenseCategory": "CONDOBILL",
            "dueDate": 1493719324,
            "amount": 3123,
            "account": "BANK01",
        },
        {
            "_id": 5,
            "expenseCategory": "CONDOBILL",
            "dueDate": 1493719324,
            "amount": 925,
            "account": "BANK02",
        }
    ]

A: Try using concat

var propertyArray = [{
    "_id": "ANA-C202",
    "name": "Ananya",
    "expense": [{
      "_id": 2,
      "expenseCategory": "OFFICE",
      "dueDate": 1493719324,
      "amount": 8121,
      "account": "BANK01",
    }]
  },
  {
    "_id": "PAP-720",
    "name": "Paradise Park",
    "expense": [{
        "_id": 1,
        "expenseCategory": "OFFICE",
        "dueDate": 1493719324,
        "amount": 100000,
        "account": "BANK01",
      },
      {
        "_id": 3,
        "expenseCategory": "CONDOBILL",
        "dueDate": 1493719324,
        "amount": 3123,
        "account": "BANK01",
      },
      {
        "_id": 5,
        "expenseCategory": "CONDOBILL",
        "dueDate": 1493719324,
        "amount": 925,
        "account": "BANK02",
      }
    ]
  }
];

var expensesArray = [];

// Use concat to get the desired result
propertyArray.forEach(function(property) {
  expensesArray = expensesArray.concat(property.expense);
  delete property.expense;
});

console.log(expensesArray);

A: Iterate each object inside the array and push that instead of pushing the whole array. See code below, or live example https://jsfiddle.net/b17moyvv/1/
var propertyArray = [
{
    "_id": "ANA-C202",
    "name": "Ananya",
    "expense": [{
        "_id": 2,
        "expenseCategory": "OFFICE",
        "dueDate": 1493719324,
        "amount": 8121,
        "account": "BANK01"
    }]
}, {
    "_id": "PAP-720",
    "name": "Paradise Park",
    "expense": [{
            "_id": 1,
            "expenseCategory": "OFFICE",
            "dueDate": 1493719324,
            "amount": 100000,
            "account": "BANK01"
        },
        {
            "_id": 3,
            "expenseCategory": "CONDOBILL",
            "dueDate": 1493719324,
            "amount": 3123,
            "account": "BANK01"
        },
        {
            "_id": 5,
            "expenseCategory": "CONDOBILL",
            "dueDate": 1493719324,
            "amount": 925,
            "account": "BANK02"
        }
    ]
}
];
console.log(propertyArray);

var expenseArray = [];
for (var i = 0; i < propertyArray.length; i++) {
    // iterate each object inside the array and push it instead of the whole array
    for (var j = 0; j < propertyArray[i].expense.length; j++){
        expenseArray.push(propertyArray[i].expense[j]);
    }
    delete propertyArray[i].expense;
}
console.log(expenseArray);


text:
Q: WARNING : "SDK Version Issue". xcode 10.1 when upload my app  with xcode 10.1 i'm getting the Warning

WARNING ITMS-90725: "SDK Version Issue. This app was built with the iOS 12.0 SDK. Starting March 2019, all iOS apps submitted to the App Store must be built with the iOS 12.1 SDK or later, included in Xcode 10.1 or later.

My project was developed in swift 4.2.1 and xcode 10.1

A: Also, if you're running a CI/CD pipeline/workflow (such as Bitrise), make sure you've updated the Xcode version in the tool's Stack as well.
In my case, my local version was correct but the Xcode version in my pipeline referenced 10.0 rather than 10.1

A: Make sure you have the latest version of Xcode.
If you do have Xcode 10.1 (or later) this is just a reminder that all of your apps need to comply with these terms.
Also regardless of Xcode version if your app did archive/build successfully you have nothing to worry about at the moment.
EDIT:
Now ALL APPS and GAMES submitted to the AppStore must have the 12.1 SDK or they will be rejected.
If your app is still rejected and you have Xcode 10.1 (or later), update Xcode or reinstall, as the SDK was not integrated correctly by the system.

A: This trick worked for me:
Download Xcode 10.2, extract and just copy(iPhoneOS12.2.sdk Folder):
or direct download zip : https://drive.google.com/file/d/1ZGANCBE90Ogt4FD_y_ACgcIFP0qQapSf/view?usp=sharing
Right click->Show Package Contents->Contents->Developer->Platforms->iPhoneOS.platform->Developer->SDKs->iPhoneOS12.2.sdk
and past it same directory on your Xcode.
after this close your Xcode, reopen Xcode , Archive and upload again.

A: I had to uninstall Xcode 10.1 and re-install it.


text:
Q: how can I submit the value of an unchecked checkbox I have a user edit page with a set of user permissions. Each permission is basically a checkbox. If checked the user has the permission if unchecked the user does not have the permission. So if I want to remove a permission I would uncheck the box and vice versa to add a permission.
I got everything to work using a hidden input, but the problem that I am having is that it is submitting both the hidden input and the checkbox value. For example even if I don't make a change and click the update button, I get a message that reads:
Removed access from 1 permission levels
Added access to 1 permission levels

I will show you my code below. Something to keep in mind is that each input calls a different function.
Here is the inputs:

<?php //List of permission levels user is apart of
foreach ($permissionData as $v1) {
    if(isset($userPermission[$v1['id']])){
?>

        <?php echo $v1['name']; ?>

            <input type="hidden" name="removePermission[<?php echo $v1['id'] ?>]" id="removePermission[<?php echo $v1['id'] ?>]" value="<?php echo $v1['id'] ?>" >
            <input type="checkbox" checked data-toggle="switch" name="addPermission[<?php echo $v1['id'] ?>]" id="addPermission[<?php echo $v1['id'] ?>]" value="<?php echo $v1['id'] ?>" >

<?php
    }
}
?>
<?php //List of permission levels user is not apart of
foreach ($permissionData as $v1) {
    if(!isset($userPermission[$v1['id']])){
?>

        <?php echo $v1['name']; ?>

            <input type="checkbox" data-toggle="switch" name="addPermission[<?php echo $v1['id'] ?>]" id="addPermission[<?php echo $v1['id'] ?>]" value="<?php echo $v1['id'] ?>" >

<?php
    }
}
?>

Here is the PHP:
//Remove permission level
    if(!empty($_POST['removePermission'])) {
        $remove = $_POST['removePermission'];
        if ($deletion_count = removePermission($remove, $userId)) {
            $successes[] = lang("ACCOUNT_PERMISSION_REMOVED", array ($deletion_count));
        } else {
            $errors[] = lang("SQL_ERROR");
        }
    }
    // Add permission level
    if(!empty($_POST['addPermission'])) {
        $add = $_POST['addPermission'];
        if ($addition_count = addPermission($add, $userId)) {
            $successes[] = lang("ACCOUNT_PERMISSION_ADDED", array ($addition_count));
        } else {
            $errors[] = lang("SQL_ERROR");
        }
    }

Even if I add the hidden input underneath the checkbox input I receive the same message. I know it has something to do with using different functions so can anyone guide me in the right direction? Should I use some JS code to find if it is checked or not?

A: If you want to use that trick... you must to name the same both arrays!
<input type="hidden" name="Permission[<?php echo $v1['id'] ?>]" id="removePermission[<?php echo $v1['id'] ?>]" value="0" >
<input type="checkbox" <?php echo ($v1['id']=='YES')?'checked':'' ?> data-toggle="switch" name="Permission[<?php echo $v1['id'] ?>]" id="AddPermission[<?php echo $v1['id'] ?>]" value="1" >

Take a look at "$v1['id']=='YES'" and use the correct comparison. Remember, name must be the same and a value of 0 will be disabled and 1 enabled.
Good luck.

A: //EDIT:
This is the code I would use for this problem. Just overwrite all rules for the user in the DB. Only thing you have to know is the amount of rules (represented by the constant).

<?PHP

define("NUMBEROFINPUTS",5);

if(isset($_GET["permissions"])){
    $dbperms = array();
    foreach($_GET["permissions"] as $permission) {
        $dbperms[$permission] = 1;
    }
    //$dbperms: 0->Input is not set; 1-> Input is set
    for($i=0;$i<NUMBEROFINPUTS;$i++){
        if(isset($dbperms[$i])) {
            echo "Input ".$i." is set
";
        }
        else{
            echo "Input ".$i." is not set
";
        }
    }
}
else {
    echo '<form>';
    for($i = 0;$i<NUMBEROFINPUTS;$i++){
        echo 'Permission '.$i.': <input type="checkbox" name="permissions[]" value="'.$i.'" checked />
';
    }
    echo '<input type="submit" /></form>';
}
?>

I hope I could help.

A: Both the hidden input and the checkbox values are submitted because they're of different input types.
You don't need to hardcode checked explicitly. Write a php if loop to check if the user has permission and echo "checked" accordingly.

A: use this in jQuery
$("input[type=checkbox]:not(:checked)").attr("value");

well for get and do some with all unchecked checkbox you can collect it into array... and send it on submit to server
var aUnchecked = new Array();
$("input[type=checkbox]:not(:checked)").each(fucntoin(){
    aUnchecked.push($(this).attr("name"));
}


text:
Q: how to shutdown my ubuntu-server 16.04.2 When I use sudo init 0 to shutdown the system ,it always staying at

[ok] Stopped LVM2 metadata daemon

What can I do?

A: The proper way to shutdown, is to use the shutdown command.
e.g.:
sudo shutdown -P now

info about shutdown

*

*shutdown man

*nix Craft

shutdown [OPTION]... TIME [MESSAGE]
-h Requests that the system be either halted or powered off after it has been brought down, with the choice as to which left up to the system.
-H Requests that the system be halted after it has been brought down.
-P Requests that the system be powered off after it has been brought down.


text:
Q: Why I can only train some NetModel with GPU I can train NetModel's models with CPU.
I'm on Windows 10 with Mathematica 11.2 GPU is GTX1080 with 8G memory.
My datasets is 1000 pictures with 224*224.
I can train some NetModel like Inception V1 Trained on ImageNet Competition Data with TargetDevice->"GPU"
But I cannot train some NetModel like ResNet-152 Trained on ImageNet Competition Data with TargetDevice->"GPU"
NetTrain::interr: An internal error occurred. Please contact Wolfram Research.

Since I can train some model with GPU, I think my graphics card driver is OK.
Since I can train them with CPU, I think Mathematica implement their layers.
I can use ImageRestyle with TargetDevice->"GPU", if I encounter with the problem An internal error occurred in training NetModel, then ImageRestyle also gives the same error information unless I Quit or Restart Mathematica.

I can train with GPU:
"Inception V1 Trained on ImageNet Competition Data"
"Wolfram ImageIdentify Net for WL 11.1"
"Yahoo Open NSFW Model V1"
"SqueezeNet V1.1 Trained on ImageNet Competition Data" crashes my kernel like Quit.

Well, some net can be trained with 20/30 pictures, but some can be trained by 1000 pictures....I'm not sure whether this is normal?
Even I use File object, the Out of Core training, it also gives the error information, and has limit number of training set.

A: The cause is the GPU running out of memory, and Mathematica not correctly reporting the failure (ResNet 152 is very memory hungry!).
This can be seen by running Internal`$LastInternalFailure, which will include a line "cudaMalloc failed: out of memory". I have reported this incorrect reporting as a bug.
Try a smaller BatchSize in NetTrain to reduce your memory usage in order to train a large net like this.


text:
Q: URL to my module with adminhtml controller I added a form to customer page from backend. How do I create the URL for action attribute to a certain function ( public function editAction(){...} )?
Function that is founded in app/code/local/company/module/controllers/Adminhtml/IndexController.php
Ideeas?
The form is used to set a custom customer attribute created in that module. The form only contains the input and a button for submit. In that particular action I setCustomAttribute and send an email. But every time I submit I get that 404.
This is the layout for my template:
<layout version="0.1.0">
    <adminhtml_customer_edit>
        <reference name="customer_edit_tab_view">
            <action method="setTemplate">
                <template>customcustomerfields/customer/tab/view.phtml</template>
            </action>
        </reference>
    </adminhtml_customer_edit>
</layout>


text:
Q: How do you get centered content using Twitter Bootstrap? I'm trying to follow a very basic example.  Using the starter page and the grid system, I was hoping the following:

Bootstrap starter template

Example text.

...would produce centered text.
However, it still appears on the far left. What am I doing wrong?

A: If you use Bootstrap 3, it also has built-in CSS class named .text-center. That's what you want.

    left

    center

    right

Please see the example in jsfiddle. http://jsfiddle.net/ucheng/Q4Fue/

A: Bootstrap 2.3 has a text-center class.

Left aligned text.

Center aligned text.

Right aligned text.

A: This is for Text Centering (which is what the question was about)
For other types of content, see Flavien's answer.
Update: Bootstrap 2.3.0+ Answer
The original answer was for an early version of bootstrap. As of bootstrap 2.3.0, you can simply give the div the class .text-center.

Original Answer (pre 2.3.0)
You need to define one of the two classes, row or span12 with a text-align: center. See http://jsfiddle.net/xKSUH/ or http://jsfiddle.net/xKSUH/1/

A: Bootstrap 5 (update 2021)
Bootstrap 5 still uses flexbox grid layout, so centering works the same way.

*

*text-center to center display:inline elements (ie: span, img)

*mx-auto for centering inside flex elements

*offset-* or mx-auto can be used to center columns (.col-)

*justify-content-center to center columns (col-*) inside row
Bootstrap 4
"Centered content" can mean many different things, and Bootstrap centering has changed a lot since the original post.
Horizontal Center
Bootstrap 3

*

*text-center is used for display:inline elements

*center-block to center display:block elements

*col-*offset-* to center grid columns

*see this answer to center the navbar

Demo Bootstrap 3 Horizontal Centering
Bootstrap 4

*

*text-center is still used for display:inline elements

*mx-auto replaces center-block to center display:block elements

*offset-* or mx-auto can be used to center grid columns

*justify-content-center in row can also be used to center col-*
mx-auto (auto x-axis margins) will center display:block or display:flex elements that have a defined width, (%, vw, px, etc..). Flexbox is used by default on grid columns, so there are also various flexbox centering methods.
Demo Bootstrap 4 Horizontal Centering

**Vertical Center**
--
Now that Bootstrap 4 is flexbox by default there are many different approaches to vertical alignment using: auto-margins, flexbox utils, or the display utils along with vertical align utils. At first "vertical align utils" seems obvious but these only work with inline and table display elements. Here are some Bootstrap 4 vertical centering options..

1 - Vertical Center Using Auto Margins:
Another way to vertically center is to use my-auto. This will center the element within it's container. For example, h-100 makes the row full height, and my-auto will vertically center the col-sm-12 column.

Card

Vertical Center Using Auto Margins Demo
my-auto represents margins on the vertical y-axis and is equivalent to:
margin-top: auto;
margin-bottom: auto;

2 - Vertical Center with Flexbox:

Since Bootstrap 4 .row is now display:flex you can simply use align-self-center on any column to vertically center it...

                 Center

                    Taller

or, use align-items-center on the entire .row to vertically center align all col-* in the row...

                 Center

                    Taller

Vertical Center Different Height Columns Demo

3 - Vertical Center Using Display Utils:
Bootstrap 4 has display utils that can be used for display:table, display:table-cell, display:inline, etc.. These can be used with the vertical alignment utils to align inline, inline-block or table cell elements.

            I am centered vertically

Vertical Center Using Display Utils Demo

A: On my side I define new CSS styles ready to use and easy to remember:
.center { text-align: center;}
.left { text-align: left;}
.right { text-align: right;}
.justify { text-align: justify;}
.fleft { float: left;} /*-> similar to .pull-left already existing in bootstrap*/
.fright { float: right;}  /*-> similar to .pull-right already existing in bootstrap*/
.vab { vertical-align: bottom;}
.bold { font-weight: bold;}
.italic { font-style: italic;}

Is it a good idea?
Is there any good practice for this?

A: If you are using Bootstrap 2.0+
This can make the div centered to the page.

        //your content here gets centered of the page

A: Bootstrap 3.1.1 has a .center-block class for centering divs. See: http://getbootstrap.com/css/#helper-classes-center.

Center content blocks Set an element to display: block and center via margin. Available as a mixin and class.

...

Or, as others have already said, use the .text-center class to centre text.

A: Any text-align utility class would do the trick. Bootstrap has been using .text-center class for centering text for a long time now.
.text-center { text-align: center !important; }

Or you can create your own utilities. Some variations I've seen over the years:
.u-text-center { text-align: center !important; }
.ta-center { text-align: center !important; }
.ta\:c { text-align: center !important; }

A: You need to adjust with the .span.
Example:

Sign In

        <form>

            <input class="span6" type="text" placeholder="Email address">

            <input class="span6" type="password" placeholder="Password">

        </form>

A: The best way to do this is define a css style:
.centered-text {
    text-align:center
}

Then where ever you need centered text you add it like so:

Bootstrap starter template

Use this document as a way to quick start any new project.
 All you get is this message and a barebones HTML document.

or if you just want the p tag centered:

Bootstrap starter template

Use this document as a way to quick start any new project.
 All you get is this message and a barebones HTML document.

The less inline css you use the better.

A: NOTE: this was removed in Bootstrap 3.

Pre-Bootstrap 3, you could use the CSS class pagination-centered like this:

    Centered content.

Class pagination-centered is already in bootstrap.css (or bootstrap.min.css) and has the only one rule:
.pagination-centered{text-align:center;}

With Bootstrap 2.3.0. just use class text-center

A: My preferred method for centering blocks of information while maintaining responsiveness (mobile compatibility) is to place two empty span1 divs before and after the content you wish to center.

Reading Resources

Read here...

A: For Bootstrap version 3.1.1 and above, the best class for centering the content is the .center-block helper class.

A: I guess most of the people here are actually searching for the way to center the whole div and not only the text content (which is trivial…).
The second way (instead of using text-align:center) to center things in HTML is to have an element with a fixed width and auto margin (left and right). With Bootstrap, the style defining auto margins is the "container" class.

        "Centered stuff there"

Take a look here for a fiddle: http://jsfiddle.net/D2RLR/7788/

A: The class .show-grid is applying center aligned text in the example in the link.
You can always add style="text-align:center" to your row div or some other class I would think.

A: As of February 2013, in some cases, I add a "centred" class to the "span" div:

      This div will be centred.

and to CSS:
[class*="span"].centred {
  margin-left: auto;
  margin-right: auto;
  float: none;
}

The reason for this is because the span* div's get floated to the left, and the "auto margin" centering technique works only if the div is not floated.
Demo (on JSFiddle): http://jsfiddle.net/5RpSh/8/embedded/result/
JSFiddle: http://jsfiddle.net/5RpSh/8/

A:

           label

Do not use container-fluid in the main.

A: Center-block is also an option not referred in above answers

...

All the class center-block does is to tell the element to have a margin of 0 auto, the auto being the left/right margins. However, unless the class text-center or css text-align:center; is set on the parent, the element does not know the point to work out this auto calculation from, so it will not center itself as anticipated.
So text-center is a better option.

A: You can use any one of the below types

*

*Use the Bootstrap existing class text-center.

*Adding a custom style, style = "text-align:center".

*Use a column offset:
Example:

A: I created this class to keep the  centered regardless of screen size while maintaining responsive features:
.container {
    alignment-adjust: central;
}

A: Simply use a class, text-center, for the div or tag which you want. I think it may work fine. It is a Bootstrap class for text align center.
Here are some text alignment Bootstrap classes:
text-left, text-right, text-justify, etc.

Bootstrap starter template

Example text.

A: I tried two ways, and it worked fine to center the div. Both the ways will align the divs on all screens.
Way 1: Using Push:

Grievance form

Way 2: Using Offset:

Grievance form

Result:

Explanation
Bootstrap will designate to the left, the first column of the specified screen-occupancy. If we use offset or push it will shift the 'this' column by 'those' many columns. Though I faced some issues in responsiveness of offset, push was awesome.

A: Update 2018:
In Bootstrap 4.1.3, content can be centered using class mx-auto.

  Centered element

Reference: https://getbootstrap.com/docs/4.1/utilities/spacing/#horizontal-centering

A: Adding an answer. Hope it helps someone

      <img
        className='img-fluid'
        src="<url>"
          />


text:
Q: Disable IntelliJ Method Path Toolbar I am not sure which tool bar this is:

The "SymanJunitXo | RECOMMENDED_CANDIDATES_ITEMS" tells me what path my cursor is currently on. I want to disable it and can't figure out which it this is.


text:
Q: Mongoose-auth and connect-assetmanager not playing nice together I'm using connect-assetmanager to consolidate js and css files, and mongoose-auth to authenticate users. Both features work independently, but don't seem to work together.
In this order, mongoose-auth works, but my minified js & css routes are broken:
app.use(
    mongooseAuth.middleware()
  , assetManager(assetManagerGroups)
);

In this order, the minified routes work, but req.user is not set by mongoose-auth:
app.use(
    assetManager(assetManagerGroups)
  , mongooseAuth.middleware()
);

Any ideas? Please let me know if you need more code. I've definitely isolated it to these two lines, though, and check that I'm not using a wildcard route with assetmanager or anything. Thanks!


text:
Q: How to customize datatables row? How can I customize the row of my jquery datatables?
I wanted to put a color to the row if it meets the condition isEvent == 1.
I followed this code from datatables community thread/example but the == is not working.
  searchResultsTable = $('#searchResultsTable').DataTable({
        bFilter: false,
        bLengthChange: false,
        searching: false,
        orderable: true,
        autoWidth: true,

        columns: [
            { data: null, render: 'department', title: 'Department', orderable: false, className: 'dt-center' },
            { data: null, render: 'employeeName', title: 'Employee Name', orderable: false, className: 'dt-center' },
            { data: null, render: 'recordDate', title: 'Date', orderable: false },
            { data: null, render: 'timeIn', title: 'Time In', orderable: false, className: 'dt-center' },
            { data: null, render: 'timeOut', title: 'Time Out', orderable: false, className: 'dt-center' },
            { data: null, render: 'day', title: 'Day', orderable: false, className: 'dt-center' },
            { data: null, render: 'eventTime', title: 'OT-UT-Errand', width: '50px',orderable: false, className: 'dt-center' },
            { data: null, render: 'eventName', title: 'Event', orderable: false, className: 'dt-center' },
            { data: null, render: 'total', title: 'No. of Hours Worked', orderable: false, className: 'dt-center' },
             { data: null, render: 'isEvent', title: 'isEvent?', orderable: false,visible:true, className: 'dt-center' }

        ],
        createdRow: function (row, data, index) {
            if (data[9]==1) {

                /*   $(row).addClass('blue');   //add class to row*/
                $('td', row).eq(2).css('font-weight', 'bold');
                $(row).css('background-color', 'yellow');   //add class to row
            }
            //add style to cell in third column
        }
    });

I already tried data[9] > 0 ,data[9] != 0 ,data[9] === 1 but when I use the data[9] = 1
it applies to all the rows, and I had it consol.log(data[9]) it returns all 1. But on my rendered table and actual data object i have multiple 0 and 1 also tried set the column's visible:true option still not working.

A: Just accessed data directly. Like data._isEvent


text:
Q: JavaScript editor for embedding into C# program Into a .NET application which I am developing, I would like to embed an editor (text box) in which the user can enter and edit JavaScript code. Syntax highlighting would be great. Does anyone have an idea how to achieve this? Thanks for any hint.

A: Assuming you are looking for something to use with WinForms, take a look at ScintillaNet, the .Net bindings for the great Scintilla editing component. Its open source and very reliable.


text:
Q: Can I convert an app configured in AOSP to an app using gradle in Android Studio? I have my legacy version System App which consists of mk files from AOSP.
However, debugging or modifying this app is time-consuming and tedious because you have to port it after building the entire platform.
I just want to modify this app and add features within android studio like the apps I've developed in the past.
Most of the dependencies written in the existing mk file could be configured using gradle script, but androidstudio fails to build because of the part that uses system api or the part where the framework itself is customized.
is there a way for me?

A: I would split it into two major parts:
For dependencies on Android Application component based Java code:
Try to make a list of all the dependencies you have there and add
them via imports if they're a part of the public Android SDK, and /
or add them to your app via the dependencies block in the module's
build.gradle as an implementation. Make sure to add google() and
mavenCentral() in the repositories. (Plenty of guides on how to add
a dependency of a third party library). And then gradle sync.
For customized framework dependency:
I think the best way to add any custom framework dependency is to add it as a compileOnly file / or implementation / api in the build.gradle of whatever module you have in the app source code on your project as an AAR or a JAR file. To generate this custom framework AAR / JAR (like a CustomServiceManager.java), build that specific module in AOSP environment if it can be built independently or via make framework / make services.
Ref: https://medium.com/@chauyan/import-aosp-framework-jar-file-f0c2ac979a8a


text:
Q: Не стираются все ключи в LocalStorage Нужно, чтобы стирались все два ключа при работе цикла
localStorage.setItem('2', 'lalala');
localStorage.setItem('3', 'lalala');

for (var i = 0; i < localStorage.length; i++) {
    if (localStorage.key(i) > 1) {
        alert(localStorage.key(i)); // показывается два ключа
        localStorage.removeItem(localStorage.key(i)); // удаляется не два, а один
    }
}

A: Можно очистить так:
localStorage.clear()

A: Код отрабатывает правильно. Вы добавили ключи "2" и "3" а длина localStorage = 2, так там всего 2 поля. Поэтому цикл будет идти до 2, а не до 3 и не дойдет до ключа 3.

A: Проблема сродни проблеме с функцией splice.
После удаления элемента, все остальные сдвинулись, и пропускается один элемент, так как счетчик все равно увеличился.
Для избежания этого можно обходить коллекцию с конца
localStorage.setItem('2', 'lalala');
localStorage.setItem('3', 'lalala');

for (var i = localStorage.length - 1; i >= 0; i--) {
  if (localStorage.key(i) > 1) {
    console.log(localStorage.key(i)) //показывается два ключа
    localStorage.removeItem(localStorage.key(i)) //удаляется не два, а один
  }
}

Либо сначала выбрать все нужные ключи, и лишь затем пройтись по ним и удалить
localStorage.setItem('2', 'lalala');
localStorage.setItem('3', 'lalala');
Object.keys(localStorage).filter(key=>key>1).forEach(key=>localStorage.removeItem(key))

Кроме того стоит обратить внимание, что ключи и значения в localStorage - всегда только строки. Поэтому если ожидаются переменные какого-то другого типа - лучше привести к нему явно, во избежание неожиданного поведения.


text:
Q: How to use style in selector? I want to increase textSize of button when selector state_pressed and bring it normal size for other state.
Please help to know how to use style for state_pressed? I did not find any option in selector.
For now I am just changing background color with selector, let me know if we can use style in selector that way can change textSize through style.
    // fragment's xml
    <Button
        android:id="@+id/btn_level3"
        android:text="@string/level3"
        android:textColor="#99CC00"
        style="@style/ButtonNormal"
        android:background="@drawable/button_custom"/>

-----------------------------------------------------------

    // styles.xml
    <style name="ButtonPressed">
        <item name="android:textSize">@dimen/button_pressed</item>
    </style>

-----------------------------------------------------------

    // buttom_custom.xml
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true" android:drawable="@drawable/color_highlight" />
        <item android:state_focused="true" android:drawable="@android:color/transparent" />
        <item android:drawable="@android:color/transparent" />
    </selector>

A: You can set button width and height using the setOnTouchListener method on your Button. Refer this Problem changing button size when pressed in Android.

A:
ya mahdi aj
  -- create btn.xml in drawable then paste:

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="false">
            <shape android:shape="oval">
                <solid android:color="@color/formbtn"/>
                <stroke android:width="10dp" android:color="@color/transparent" />

            </shape>
        </item>
        <item android:state_pressed="true">
            <shape android:shape="oval">
                <solid android:color="@color/formbtnborder"/>
                <stroke android:width="10dp" android:color="@color/transparent" />
            </shape>
        </item>
    </selector>


text:
Q: How can I solve the Type Error issue in my python code? def prepare_data(df, config, data_dir):
    X = np.empty(shape=(df.shape[0], config.dim[0], config.dim[1], 1))
    input_length = config.audio_length
    for i, fname in enumerate(df.index):
        file_path = data_dir + fname
        data, _ = librosa.core.load(file_path, sr=config.sampling_rate, res_type="kaiser_fast")

        # Random offset / Padding
        if len(data) > input_length:
            max_offset = len(data) - input_length
            offset = np.random.randint(max_offset)
            data = data[offset:(input_length+offset)]
        else:
            if input_length > len(data):
                max_offset = input_length - len(data)
                offset = np.random.randint(max_offset)
            else:
                offset = 0
            data = np.pad(data, (offset, input_length - len(data) - offset), "constant")

        data = librosa.feature.mfcc(data, sr=config.sampling_rate, n_mfcc=config.n_mfcc)
        data = np.expand_dims(data, axis=-1)
        X[i,] = data
    return X

I have a an audio datasets in my root directory and When I am executing the following code I am getting the Type Error but I don't know how to resolve it. The above code is used to prepare the data from my datasets. Type Error is accuring when I am executing the code below:
X_train = prepare_data(train, config, 'datasets/train_curated/')

The following error is describe below:
TypeError                                 Traceback (most recent call last)
<ipython-input-38-3c6c017b85c7> in <module>
      1 get_ipython().run_line_magic('time', '')
----> 2 X_train = prepare_data(train, config, 'datasets/train_curated/')
      3 X_test = prepare_data(test, config, 'datasets/test/')
      4 y_train = to_categorical(train.label_idx.astype('str'), num_classes=config.n_classes)

<ipython-input-36-0cb95e99049e> in prepare_data(df, config, data_dir)
      4     for i, fname in enumerate(df.index):
      5 #       print(fname)
----> 6         file_path = data_dir + fname + '.wav'
      7         data, _ = librosa.core.load(file_path, sr=config.sampling_rate, res_type="kaiser_fast")
      8

TypeError: can only concatenate str (not "int") to str

A: Yes because you're trying to concat strings and integers as file_path = data_dir + fname + '.wav' but fname will be an integer value so typecast it with string.
for i, fname in enumerate(df.index):
    #print(fname)
    file_path = data_dir + str(fname) + '.wav'
    data, _ = librosa.core.load(file_path, sr=config.sampling_rate, res_type="kaiser_fast")

A: file_path = str(data_dir) + str(fname) + '.wav'


text: Q: For Delta-Wye transformers, with neither side grounded, can one get electrocuted by standing on earth and touching one of the Delta side wires? It seems to me that there is no path to ground in this case. So, the voltage on the Delta-side of the transformer cannot drive a current through the ground (ie, through the one touching the wire), even with very high voltages. Is this a flawed understanding?


text:
Q: I am learning Excel, can someone tell me what's wrong with this please =IF(AND(A4=">30",B4=">30"),"Good","Bad")

What do I need to do to return if both columns are greater than 30?

A: There is nothing inherently wrong with the formula you have provided. However, there are a few things to consider:
The formula uses the logical operator AND to check if both conditions are true. In order for the formula to return "Good", both conditions must be true. If either condition is false, the formula will return "Bad".
The formula compares the values in cells A4 and B4 to the string ">30". This will not produce the intended result, as the comparison is being made between a cell value and a string rather than between two numbers.
In order to compare the values in cells A4 and B4 to a numerical value, you should use a numerical value rather than a string. For example, you could use =IF(AND(A4>30,B4>30),"Good","Bad") to compare the values to the number 30.
If the values in cells A4 and B4 are not numeric, the formula will return an error. You may want to consider using the ISNUMBER function to check if the cells contain numeric values before performing the comparison. For example, you could use =IF(AND(ISNUMBER(A4),ISNUMBER(B4),A4>30,B4>30),"Good","Bad") to check if the values are numeric and then compare them to 30.


text:
Q: "uninstal" option missing from "Programs and Features" window? - windows vista I'm using windows vista, trying to clean out the laptop (not really mine) and so I'm trying to uninstall all the crap. But when i go to the programs and features window, the uninstall option is missing. If i right click on anything in the list nothing happens. left clicking, double clicking, nothing happens. Can't figure out what to do here.. any help?

A: By the looks of the screenshot, most programs that are listed are not installed, but only their entries remain. This usually happens by removing the programs from the harddrive without properly uninstalling them, or by using an uninstall tool that doesn't work right.
There's a program to clean up this list.

A: Causes
This could be happening because of several causes. The most probable cause is that you installed the programs and they were either removed manually from program files folder, or they weren't installed properly. There are several other reasons as well, such as viruses, malware, and adware on your computer that edited the registries that disable uninstalltion of programs.
Experiment
First of all I would like you to confirm that the software directory itself exits. For uTorrent, the default location of the latest version is C:\Users\Shahrukh\AppData\Roaming\uTorrent. If the software does exist on the computer you can proceed to opening regedit.exe (Type it in run or search bar). Once open navigate to this path:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall\uTorrent

If that path exists and you see the UninstallString name, with the value of,
"C:\Users\Shahrukh\AppData\Roaming\uTorrent\uTorrent.exe" /UNINSTALL

you should be able to technically see the uninstall button. If you don't find the string than the program's registry was edited and the uninstall string doesn't exists. This could be caused by malicious content or as a result of program not being installed properly. IT could also be that you're not logged into to the admin account or the account that installed those applications. Most of the icons for the programs are not shown so my best guess would be that they have been uninstalled improperly.
Solution
You can either find each program's msi, exe and uninstall it using the proper switch but this option will take lots of time and research for each program that you would like to uninstall. For example to uninstall uTorrent, you would either create a batch file or open up a command prompt screen and paste this line:
"C:\Users\Shahrukh\AppData\Roaming\uTorrent\uTorrent.exe" /UNINSTALL

Basically the first part of the line points to the exe (either the uninstaller or the program itself - depending on the program itself) or the msi file. then uses the switch /uninstall. This is where the research comes in since the every program has a different format syntax and switch.
The easiest and by far the fastest way would be if you install Revo Uninstaller. This is a  great free software that helps removing all traces of any and all programs installed on your computer. It works much better than the built-in windows programs and feature and it keeps tracks of all files that a program installs so you have the piece of mind when removing software.


text:
Q: Sql Total Sum using no of row counts in a table i am trying to find the total marks for each student based on StudentId and MarksTypeId row count.
i have 3 tables
MarksType

----------------------------------
MarksTypeId |  MarkType    | Marks
----------------------------------
1           |    Writing   | 10
2           |    Drawing   | 30
3           |    Singing   | 20
----------------------------------

Students

--------------------------------
StudentId |  Name    | Address
--------------------------------
1         |    John  | USA
2         |    Raja  | India
3         |    Paul  | AUS
--------------------------------

MarksDetails      --  Has two foreign keys

-------------------------------------------------------
MarksDetailsId |  MarksTypeId    |  StudentId | Date
-------------------------------------------------------
1              |    3            | 1          | 18 jan
2              |    3            | 1          | 18 jan
3              |    1            | 3          | 19 jan
-------------------------------------------------------

This is my Desired Result :
------------------------------------
StudentId |  Name     | Total Marks
------------------------------------
1         |    John   | 40
2         |    Raja   | 0
3         |    Paul   | 10
------------------------------------

i mean if John sang two times a day, so using StudentId and MarksTypeId, i need his total Marks as result.
so far i did the following:
select  Sum(MarksType.Marks)  from MarksType inner join MarksDetails    on   MarksType.MarksTypeId=1

but the sum returns wrong total,
UPDATED OTHER ATTEMPTS:

*

*this results total row count for each studentid
select MarksDetails.StudentId , COUNT(MarksDetails.StudentId ) as     count   from MarksDetails
group by MarksDetails.StudentId

*this results Marks, with studentid and markstypeid
select  MarksType.Marks, MarksType.MarksTypeId , MarksDetails.StudentId   from MarksType inner join MarksDetails  on   MarksType.MarksTypeId =    MarksDetails.StudentId

may i know what i am doing wrong.
Any help would be Great.

A: finally with kind guidance from sql developers and after making some research, here is the query with desired result, maybe useful for someone, enjoy !
SELECT Student.StudentId, Student.Name, sum(MarksType.Marks) as TotalMarks
FROM
 MarksType
INNER JOIN
 MarksDetails on MarksType.MarksTypeId = MarksDetails.MarksTypeId
INNER  JOIN
 Student on Student.StudentId =  MarksDetails.StudentId

 group by Student.Name,Student.StudentId


text:
Q: How can I populate a table using ajax and php and add buttons in table rows? I'm trying to read information from a database and put them in a table and also to include buttons on the last column of each row. Besides adding the buttons, I'm having trouble getting it to work.
This is my retrieve.php
 <?php

require_once 'connect.php';

 $output = array('data' => array());
 $sql = "SELECT * FROM student_acc";
$query = $connect->query($sql);

$x = 1;
while ($row = $query->fetch_assoc()) {

    $actionButton = '' +
'' +
''
 ; // buttions I'd like to include

    $output['data'][] = array(
        $x,
        $row['address'],
        $row['single_unit'],
        $row['single_rent'],
        $row['sharing_unit'],
        $row['sharing_rent'],
        $row['date'],
        $actionButton; //I'm not sure how to include this
    );

    $x++;
}
$connect->close();

echo json_encode($output);

My ajax.js
    $(document).ready(function(){
            $.ajax({
            type: "POST",
            dataType: "json",
            url: "tableretrieve/retrievestudent.php",
            data: {action: "load"},
            success: function (response){
                console.log(response);
                $.each(response, function(index, obj) {
                var row = $('
');
                row.append('' + obj.address + '	');
                row.append('' + obj.single_unit + '	');
                row.append('' + obj.single_rent + '	');
                row.append('' + obj.sharing_unit + '	');
                row.append('' + obj.sharing_rent + '	');
                row.append('' + obj.date + '	');
                row.append('' + *Code to include buttions here* + '	');

                $('table').append(row)
                });
                }
            });

    });

I did some test with the code below and it appended fine:
    $(document).ready(function(){

        var ActionButions ='' +
                '' +
                '';

                 var row = $('
');
                row.append('' + "Vanderbijlpark, Bowker str, CE4, 12" + '	');
                row.append('' + "3" + '	');
                row.append('' + "1500" + '	');
                row.append('' + "1" + '	');
                row.append('' + "2500" + '	');
                row.append('' + "2019/08/14" + '	');
                row.append('' + ActionButions + '	');

                $('table').append(row);

});

I'm trying to replicate the code above by reading values from a database.

A: *

*The string should be concatenated with . (dot), not + (plus) in the PHP script.
What is [ad_id] here? If it's an id column of DB table, use  .$row['ad_id']..
$actionButton = ''
.
''
.
'
'
;

*You can try an associative array with key and value like this:
$output['data'][] = array(
    $x,
    $row['address'],
    $row['single_unit'],
    $row['single_rent'],
    $row['sharing_unit'],
    $row['sharing_rent'],
    $row['date'],
    'buttons' => $actionButton // no colon here
);

*And try row.append('' + obj.buttons + '	');
Use a code editor that helps you to fix the syntax errors. Also, use browser developer tools (F12 on Windows and cmd+option+i on Mac) to find your JavaScript errors.

A: I've managed to fix my problem I had to include a datatable javascript in my index.php

My retrieve.php
include 'connect.php'

 $sql = "SELECT * FROM student_acc";
$query = $connect->query($sql);

$x = 1;
while ($row = $query->fetch_assoc()) {
  $actionButton = '
  
  ';

  $data['data'][] = array(
        $row['address'],
        $row['single_unit'],
        $row['single_rent'],
        $row['sharing_unit'],
        $row['sharing_rent'],
        $row['date'],
        $actionButton);
}

echo json_encode($data);

And back to my index.php page, where my table is, I had to add this script
 $(document).ready(function(){

        Table = $("#studentAccomodationTable").DataTable({
            "ajax": "tableretrieve/retrieve.php"
        });

And that was it.
Thanks to https://datatables.net


text:
Q: How do I put infowindow contents into a separate `div`? I'm new to CartoJS. When a user clicks a dot on my CartoDB map, I want the content of the infowindow to appear in a separate div on the web page.
How do I do this with CartoDB/JS?

A: you could use what we call an Infobox. Check this example to see how it works:
http://bl.ocks.org/ernesmb/b53eaf7427427d3fd974


text:
Q: catch error from reject method of promise I have the following code which returns an 'uncaught (in promise) object' error in the console when the ajax call fails.
const customCall = (requestType, submitUrl, values) =>
  new Promise((resolve, reject) => {
    $.ajax({
      type: requestType,
      url: submitUrl,
      dataType: 'json',
      data: values,
      success: response => resolve(response),
      error: err => reject(err),
    });
  }).catch((err) => {
    const errorObject = { _error: "fail" };
    throw errorObject;
  }).then((result)=> { //do whatever }) ;

why can't i catch this error ?


text:
Q: How should Azure DevOps and App Center be connected for git push hooks? Our App Center 'Build on every push' is not working.  When I merge a PR in Azure DevOps and refresh App Center it shows the new commit but never triggers a build even though the build is configured to do so.  This issue reports the same issue, but doesn't offer any resolution.
In Azure DevOps I see two service hooks configured for App Center (both created by an ex-employee).  When I try to test those hooks, both return a 404 error from App Center.  I can find no documentation on how service hooks between Azure DevOps and App Center should be set up.
Is there some way I can disconnect the service hooks and re-create them?

A:
Is there some way I can disconnect the service hooks and re-create them?

The answer is yes.
You could go to the Project Settings->Service hook, select the service hook for App Center. You could delete it, then create a new service hook:

If you could not delete it, please check if you have permission to delete the  service hook.
Update:
Since you want to create a service hook, you could configure it as follows stpes:

*

*Select Azure devops as service on the Build tab:

*Sign in with your Azure devops account and select the project you want to build.

*Make sure the option Build this branch on every push is select:

Then, we could submit any change in that project in azure devops repo, the build in app center will be triggered. We could also check the service hook:

Hope this helps.

A: I contacted App Center support using the chat button in the lower corner. They did a soft reset on the projects on their back end and the existing service hooks started working.
Not sure could I have fixed the issue without support, as I didn't try recreating the service hooks myself.


text:
Q: How to Invoke anonymous javascript function on object in 1 line? I am learning about javascript anonymous functions and scope and am trying to understand something but have become a bit stuck.
I have the following three functions:
var funcA = function (value) {
    test = value;
};

var funcB = function (value) {
    this.test = value;
};

var funcC = function (func,value) {
    var item = {};
    //single line invocation
}

I am trying to write a single line of javascript (where it says //single line invocation) such that the result of the two following calls will differ, instead of having the same effect:
funcC(funcA, "set");
funcC(funcB, "set");

Since funcB is referencing this.test instead, it makes sense that it will be changing a local (instance) value so we can make use of the "item" object in funcC. I tried doing some anonymous function "stuff" like:
item.(function(func,value){func(value)})(func, value);

However I have not had any luck in terms of the statements resulting in different outcomes. (i.e. when I run my code using node(.js) the test and this.test values both change).
Any help on understanding this better would be great.
Thanks in advance,
ParagonRG

A: You have to use call to tell it the instance to work on.
funcB.call(item, value);

A: You can't use an anonymus function as a object property. You want to do
var item = {"f": func};
item.f(value);
// item.test == value now

right? The way JavaScript does this is the .call() function:
func.call(item, value);
// with the difference that item has no "f" property here

You can also use call with anonymous function expressions:
(function(val){ this.test = val; }).call(item, value);
// yet this equivalent looks much cleaner:
item.test = value;


text:
Q: How to fix Accessibility level A and AA errors Most of the sites are aiming for accessibility compliance these days. I installed google chrome Wave tool to check Level A and AA errors on my site. I see some errors like below for which I do not seem to have exact solution to fix.
1.Structural Elements | An unordered (bulleted) list ( element) is present.
2.Contrast Errors | Very low contrast between foreground and background colors.
3.Features | Alternative text is present for an image that is within a link.
4.ARIA | An aria-label or aria-labelledby attribute is present.
5.Structural Elements | A  element or navigation landmark is present.
6.Structural Elements | A  element or main landmark is present.
If I try to replace ul with ol, it gives me error like 'An ordered (bulleted) list ( element) is present.'
Rendering your navigation as plain links does not provide any semantic meaning; it would suggest that your navigation is a sentence to be read. By providing your links in a list, you supply a hint as to how we are to interpret this series of hypertext-linked words.(Reference link: Unordered lists and accessibility)
Then how do we fix such errors?
UPDATE
Currently my code looks like

Create Account

Log in

If you look at the left sidebar of the screenshot, you see level A error.


text:
Q: Email notifications after 'git archive'? Custom requirement: How to notify specific people, using email as soon as a git archive command is run to download a single file?
Couldn't find a hook which can do so.

A:
Couldn't find a hook which can do so.

That is because there isn't one associated to the git archive command.
One possible workaround would be to make a global git alias to archive, in order to call a wrapper script which would:

*

*check who is running that command

*execute the actual git archive command

*send an email appropriately

But all that is on the client side, which means this is valid for an environment shared among several clients.


text:
Q: How to get memory address from file path without opening file I have a file. I know its file path, and I want to know its memory address. My problem is that I can't actually open the file (fopen can't be used because the OS thinks the file is in use) to get its memory address.
Ex.
fopen("C:/example/file", "r") returns null
From why I understand the OS returns the memory address after it confirms the file isn't in use. So is it even possible to bystep the OS?

A: @Alter by finding the Process ID of the process that has locks on the file, you could get somewhere...  You might be able to track your files contents in memory as part of the memory space allocated to the Process.
However, just because a file is locked does not at all mean that the file is in memory.  Sometimes just a part of a file is used, like the functions within a DLL - where only the 'used' and necessary chunks of the file would be in memory.  Other times, the entire document (file) will be present very nicely and contiguously in memory (consider a text file open in Notepad) .  It is also possible that the file is locked purely like a placeholder, where the lock is all that matters and none of the file is actually loaded.  You really need to know alot about the Process that has locks on the file.
Now if you simply want to copy the file to another file, then launch the copy before the 'Process' locks the file.  You could try a batch file that runs at Windows Startup - and see if that is early enough to copy the file before a lock is placed on it.


text:
Q: Get facebook acces token without redirect This is how I retrieve the user acces token
$code = $_REQUEST["code"];
 //auth user
 if(empty($code)) {
     $dialog_url = 'https://www.facebook.com/dialog/oauth?client_id=myclientid&redirect_uri=' . urlencode('http://myweb.com/facebook.php') ;
    echo("<script>top.location.href='" . $dialog_url . "'</script>");
  }
  //get user access_token
  $token_url = 'https://graph.facebook.com/oauth/access_token?client_id=myclientid&redirect_uri=' . urlencode('http://myweb.com/facebook.php')
    . '&client_secret=mybigsecret&code=' . $code;
  $access_token = file_get_contents($token_url);

But I was wondering if there's any way I can do it without any redirects?

A: I think there's no solution for common browsers, because Facebook set the header X-Frame-Options:DENY in the oauth page, which denies the usage of iframe in this case.

A: Here is my coding, you can try...
$code = $_REQUEST["code"];
$response = file_get_contents(
    "https://graph.facebook.com/oauth/access_token?" .
    "client_id=" . $client_id .
    "&redirect_uri=" . $redirect_url .
    "&client_secret=" . $client_secret .
    "&code=" . $code
);
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token'];
$user_data = json_decode(file_get_contents($graph_url));
$user = $user_data->id; //get active fb user id
$facebook->setAccessToken($params['access_token']);

P.S. $params['access_token'] for access_token value...


text:
Q: Jenkins job automatically building all SVN branches available is there a possibility to Setup a Job which builds all available branches automatically?
<svn-repo>/branches/*

Further it should ignore one Folder which is:
<svn-repo>/branches/closed

It's a time-triggered Job.

A: You have to configure jobs for each branch, then define the periodicity


text:
Q: Unity UIElemens changing style.cursor in code How do I set the cursor style for a VisualElement to one of the predefined classes in code? (Arrow, Text, Split Resize Left Down, etc)
I am aware the cursor can be set using the CursorStyle property
style.cursor = SomeCursorStyle;
The problem is I want to use the SplitResizeLeftRight cursor and I can't seem to find where the static classes are defined. Obviously I can do this though a stylesheet, but I want to do it through code. An alternative is to create my own CursorStyle and point it to the appropriate cursor textuer, but again, I can't seem to find where those are located.
According to these docs and the UIElement Debugger I know I can change the style of the cursors. I just can't figure out how to set it to one of those in code.

A: The UIElementsEditorUtility class no longer exists. I found a solution for the more recent version of Unity (2022.1.7 In my case) but it includes some C# Reflection...
//using System.Reflection;

public static void SetCursor(this VisualElement element, MouseCursor cursor)
{
    object objCursor = new Cursor();
    PropertyInfo fields = typeof(Cursor).GetProperty("defaultCursorId", BindingFlags.NonPublic | BindingFlags.Instance);
    fields.SetValue(objCursor, (int)cursor);
    element.style.cursor = new StyleCursor((Cursor)objCursor);
}

I hope it will help those who have the same problem

A: Take a look at the MouceCursor enum:
https://docs.unity3d.com/ScriptReference/MouseCursor.html

"Custom mouse cursor shapes used with EditorGUIUtility.AddCursorRect."

It defines multiple cursor shapes, one of them is SplitResizeLeftRight. Usage example:
EditorGUIUtility.AddCursorRect(new Rect(20, 20, 140, 40), MouseCursor.SplitResizeLeftRight);

I hope this helps you.

A: By some miracle I stumbled upon this class: UIElementsEditorUtility
At the time of posting the class can not be found in Unity docs.
So here is an example of how to use it:
style.cursor = UIElementsEditorUtility.CreateDefaultCursorStyle(MouseCursor.ResizeHorizontal);


text:
Q: JPA is not saving data Im trying to save data to the database, but instead of it JPA is saving null to the database, I am usually doing it with dto, but since it s a very small project, I want to do it without it
Entity
  @Setter
@Getter
@Entity
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String surname;
    private String department;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "STUDENT_COURSE_TABLE",
    joinColumns = {
            @JoinColumn(name="student_id",referencedColumnName = "id")
    }, inverseJoinColumns = {
            @JoinColumn(name = "couse_id",referencedColumnName = "id")
    })
    @JsonManagedReference
    private Set<Course> courses;
}

DAO
    @Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}

Controller
@RestController
@RequestMapping("/api")
public class StudentCourseController {

    private final StudentRepository studentRepository;

    private final CourseRepository courseRepository;

    public StudentCourseController(StudentRepository studentRepository,
                                   CourseRepository courseRepository) {
        this.studentRepository = studentRepository;
        this.courseRepository = courseRepository;
    }

    @PostMapping
    public Student addStudent (Student student){
        return studentRepository.save(student);
    }

}

and in my application.properties
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialec

t

A: Make sure is deserialization correct in controller method "addStudent" - If You want to pass Student entity in request body, add annotation @RequestBody to method parameter like:
 @PostMapping
    public Student addStudent (@RequestBody Student student){
        return studentRepository.save(student);
    }

If You do not do that - there is possibility to null/empty parameter, what can lead to saving nulls into db.
By the way:

*

*Consider using DTO or Request classes to pass entity in/out your REST application - it will help you avoid circular reference in future and problems with de/serialization your entity.

*Consider using ResponseEntity instead of returning object to output - method with ResponseEntity should be like:

   @PostMapping
   public ResponseEntity<Student> addStudent (@RequestBody Student
   student){
       return ResponseEntity.ok(studentRepository.save(student));
   }


text:
Q: When using let in a for loop initialization, why isn't the let variable avaiable in the enclosing scope? This has always been a lingering question for me: If block scopes are created when a let or const identifier is enclosed within curly brackets, then how is the let identifier in the initialization statement of a for loop not available in the enclosing scope but is instead available inside the curly brackets of the for loop?

(function() {
  for (let i = 0; i < 5; i++) {
   console.log(i) // logs current value of i
  }
  console.log(i) // referenceError
})()

A: That's just how things work. A variable declared at the top of a for loop like that is only visible inside the current iteration's for block. You can think of it a bit like this:
<loop> {
  let i = getCount();
  console.log(i) // logs current value of i
}

where getCount runs the logic that increments i.
Variables declared with let are block-scoped - it wouldn't make sense for i to be referenceable outside. If the i was visible outside of the for, what would you expect its value to be? You already have a separate i binding for every iteration of the loop. It wouldn't make sense to somewhat-arbitrarily pick one of those bindings to be visible outside.

A: Because it's a local variable in the for loop and not outside it. If you had declared it outside the loop, you could access it correctly.

(function() {
  let i;
  for (i = 0; i < 5; i++) {
   console.log(i);
  }
  console.log(i);
})();

A: If you don't want to change your syntax, you could use var.
(function() {
    for (var i = 0; i < 5; i++) {
        console.log(i);
    }
    console.log(i);
    // this should work.
})()

Otherwise, a variable declared with let or const has what's called Block Scope meaning that it's only visible inside the curly braces it was defined in. That's essentially the fundamental difference between let and var. A variable declared with var has Function Scope (It's visible throughout the function, even before it's lexical definition, it's value will just be undefined)
(function() {
    console.log(i); // undefined
    var i = 10;
    console.log(i); // 10
 })();

But the example above will only work if there is no "use strict" anywhere.


text:
Q: Resistor Cube Problem Intuition In the well-known resistor cube problem using a resistor cube with equivalent resistors on all the edges, the prescribed approach to solving it involves merging points of equivalent potential as shown below:

While I can work through the logic superficially, I just can't make sense of it intuitively. Why is it that linking up points of equivalent potential doesn't change the resistance of the circuit, beyond the explanation always given that "current does not flow through the 'phantom' conductor connecting vertices of equal potential". What is the intuition for this solution to the resistor cube problem?

A: There is no intuition other than that no current flows across two points at the same electrical potential. When two or more resistors have the a common node (endpoint) and are identical, the potential drop across them is the same, even if their other nodes are not physically connected. This is functionally equivalent to saying the resistors are in parallel and is essentially what the solution you have quoted is explaining.
Using this approach, the three edges of the resistor cube with the common node H are in parallel, which you can consider group A. This group has the equivalent resistance of $R_A = R/3$, assuming each cube-edge has resistance $R$. Symmetrically, the three resistors at the opposite end with the common node B are also mutually parallel. That is another group, B, again with overall resistance $R_B = R/3$. The slightly tricky one is the remaining group of six resistors. For each of them, if you consider their endpoints which are closer to H, you will notice they are actually at the same potential, since the current through each of them previously had to pass through exactly one identical resistor. The same argument applies to their other nodes (closer to B) -- they are also at the same potential. In other words, the remaining group of six resistors are also mutually parallel -- call it C. This group has the equivalent resistance of $R_C = R/6$.
In summary, you have three groups of mutually parallel resistors which are group-wise in series with each other. Hence, the total resistance is simply the sum: $$R_T = R_A + R_B + R_C = \frac{R}{3} + \frac{R}{3} + \frac{R}{6} = \frac{5R}{6}.$$


text:
Q: MySQL return rows where column contains categories defined by array (and add weight to the results) In my app, the user can type in an indefinite amount of categories to search by. Once the user hits submit, I am using AJAX to call my PHP script to query my DB and return the results that match what the user defined for the categories.
My category column is separated as so for each row: "blue,red,yellow,green" etc.
I have two questions:

*

*How can I pass an array to MySQL (like so: [blue,yellow,green]) and then search for each term in the categories column? If at-least one category is found, it should return that row.

*Can MySQL add weight to a row that has more of the categories that the user typed in, therefor putting it further to the top of the returned results? If MySQL cannot do this, what would be the best way to do this with PHP?

Thanks for taking the time and looking at my issue.

A: For the part 1 you can use the function below:
<?php
function createquery($dataarray){
    $query="select * from table where ";
    $loop=1;
    foreach($dataarray as $data)
    {
      $query.="col='$data'";
      if(count($dataarray)<$loop-1){
        $query.=' or ';
      }
      $loop++;
    }
    return $query;
}

?>

This will return the long query.

A: use this some like this:
mysql_query("select * from table where category in (".implode($yourarray,',').")");

A: 1)
Arrays are not passed to a MySQL database. What's past is a query which is a string that tells the database what action you want to preform. An example would be: SELECT * FROM myTable WHERE id = 1.
Since you are trying to use the values inside your array to search in the database, you could preform a foreach loop to create a valid SQL command with all those columns in PHP, and then send that command / query to the database. For example:
$array = array('blue', 'red', 'yellow', 'green');

$sql = "SELECT ";
foreach ($array as $value)
{
  $sql .= $value.", ";
}
$sql .= " FROM myTable WHERE id = 1";

IMPORTANT! It is highly recommended to used prepared statements and binding your parameters in order not to get hacked with sql injection!
2)
You are able to order the results you obtained in whichever way you like. An example of ordering your results would be as follows:
SELECT * FROM myTable WHERE SALARY > 2000 ORDER BY column1, column2 DESC


text:
Q: control the order of execution of tasks in a certain name space I'm new to Capistrano and I was wondering how you can control the
order of execution of tasks in a certain name space.
For example, I have some extra tasks in my deploy namespace.  I wanted
deploy:bundle and deploy:assets to run before deploy:restart so I
added these lines
after 'deploy:update_code', 'deploy:bundle'
after 'deploy:bundle', 'deploy:assets'
after 'deploy:assets', 'deploy:restart'

I'm not sure if this how you're supposed to do it.  Please let me know
if you guys have any tips for me!
namespace :deploy do
  task :start do ; end
  task :stop do ; end
  task :restart, :roles => :app, :except => { :no_release => true }
do
    run "touch #{current_path}/tmp/restart.txt"
  end

 task :bundle do
   run "cd #{current_path} && bundle install"
 end

 task :assets do
    run "cd #{current_path} && bundle exec rake assets:precompile"
 end

 end

after 'deploy:update_code', 'deploy:bundle'
after 'deploy:bundle', 'deploy:assets'
after 'deploy:assets', 'deploy:restart'


text:
Q: How can I access a Vault secret using a token created from a policy? I'm running Hashicorp Vault v1.1.0 locally in a docker container in developer mode.  I exec into the container to use the cli, and I cannot complete a basic proof of concept with a policy and token which allow me to access only one secret.
Below is a transcript of the actions I've taken using v2 of the secrets engine.  What am I doing wrong here?
/ # VAULT_TOKEN=myroot vault kv enable-versioning secret/
Success! Tuned the secrets engine at: secret/

/ # VAULT_TOKEN=myroot vault kv put secret/message value=mypassword
Key              Value
---              -----
created_time     2019-04-11T20:23:25.0149145Z
deletion_time    n/a
destroyed        false
version          5

/ # cat p.hcl
path "secret/message" {
     capabilities = ["read"]
}

/ # VAULT_TOKEN=myroot vault policy write message-readonly p.hcl
Success! Uploaded policy: message-readonly

/ # VAULT_TOKEN=myroot vault token create -policy="message-readonly"
Key                  Value
---                  -----
token                s.hZNCq7Q5plwA4XjcGAcsd5tg
token_accessor       vpcxkGMbDBswfJPTGzzfY4he
token_duration       768h
token_renewable      true
token_policies       ["default" "message-readonly"]
identity_policies    []
policies             ["default" "message-readonly"]

/ # VAULT_TOKEN=s.hZNCq7Q5plwA4XjcGAcsd5tg vault kv get secret/message
Error reading secret/data/message: Error making API request.

URL: GET http://127.0.0.1:1234/v1/secret/data/message
Code: 403. Errors:

* 1 error occurred:
    * permission denied

/ #

A: When you craft a policy for version 2 of the KV backend you need to specify the API paths, not the logical paths that "vault kv" uses.  Your policy should look like this:
    path "secret/data/message" {
         capabilities = ["read"]
    }

There's a bunch of other quirks you need to be aware of when crafting KV2 policies.  See https://www.vaultproject.io/docs/secrets/kv/kv-v2.html for more information.