Programs & Examples On #Spring integration

Use this tag for questions about the Spring Integration project. It is not intended for general questions about integrating other Spring projects with other technologies.

Could not extract response: no suitable HttpMessageConverter found for response type

public class Application {

    private static List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
        converters.add(new MappingJacksonHttpMessageConverter());
        return converters;
    }   

    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();

        restTemplate.setMessageConverters(getMessageConverters());
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        //Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class);

        ResponseEntity<Page> response = 
                  restTemplate.exchange("http://graph.facebook.com/skbh86", HttpMethod.GET, entity, Page.class, "1");
        Page page = response.getBody();
        System.out.println("Name:    " + page.getId());
        System.out.println("About:   " + page.getFirst_name());
        System.out.println("Phone:   " + page.getLast_name());
        System.out.println("Website: " + page.getMiddle_name());
        System.out.println("Website: " + page.getName());
    }
}

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

To complete @cpu-100 answer,

in case you don't want to enable/use web interface, you can create a new credentials using command line like below and use it in your code to connect to RabbitMQ.

$ rabbitmqctl add_user YOUR_USERNAME YOUR_PASSWORD
$ rabbitmqctl set_user_tags YOUR_USERNAME administrator
$ rabbitmqctl set_permissions -p / YOUR_USERNAME ".*" ".*" ".*"

Sum values from an array of key-value pairs in JavaScript

I would use reduce

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0], ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);

var sum = myData.reduce(function(a, b) {
    return a + b[1];
}, 0);

$("#result").text(sum);

Available on jsfiddle

How to create a TextArea in Android

Use TextView inside a ScrollView to display messages with any no.of lines. User can't edit the text in this view as in EditText.

I think this is good for your requirement. Try it once.

You can change the default color and text size in XML file only if you want to fix them as below:

<TextView 
    android:id="@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="100px"
    android:textColor="#f00"
    android:textSize="25px"
    android:typeface="serif"
    android:textStyle="italic"/>

or if you want to change dynamically whenever you want use as below:

TextView textarea = (TextView)findViewById(R.id.tv);  // tv is id in XML file for TextView
textarea.setTextSize(20);
textarea.setTextColor(Color.rgb(0xff, 0, 0));
textarea.setTypeface(Typeface.SERIF, Typeface.ITALIC);

Returning a value from callback function in Node.js

If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:

Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.

Basically, you can do something like this:

function doCall(urlToCall) {
  return co(function *(){
    var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.                             
    var statusCode = response.statusCode;
    finalData = getResponseJson(statusCode, data.toString());
    return finalData;
  });
}

Then,

var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.

By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.

Typedef function pointer?

If you can use C++11 you may want to use std::function and using keyword.

using FunctionFunc = std::function<void(int arg1, std::string arg2)>;

Center Align on a Absolutely Positioned Div

Or you can use relative units, e.g.

#thing {
    position: absolute;
    width: 50vw;
    right: 25vw;
}

How to parse JSON in Kotlin?

i am using my custom implementation in kotlin:

/**
 * Created by Anton Kogan on 10/9/2020
 */
object JsonParser {

    val TAG = "JsonParser"
    /**
 * parse json object
 * @param objJson
 * @param include - all  keys, that you want to display
 * @return  Map<String, String>
 * @throws JSONException
 */
    @Throws(JSONException::class)
    fun parseJson(objJson: Any?, map :HashMap<String, String>, include : Array<String>?): Map<String, String> {
        // If obj is a json array
        if (objJson is JSONArray) {
            for (i in 0 until objJson.length()) {
                parseJson(objJson[i], map, include)
            }
        } else if (objJson is JSONObject) {
            val it: Iterator<*> = objJson.keys()
            while (it.hasNext()) {
                val key = it.next().toString()
                // If you get an array
                when (val jobject = objJson[key]) {
                    is JSONArray -> {
                        Log.e(TAG, " JSONArray: $jobject")
                        parseJson(
                            jobject, map, include
                        )
                    }
                    is JSONObject -> {
                        Log.e(TAG, " JSONObject: $jobject")
                        parseJson(
                            jobject, map, include
                        )
                    }
                    else -> {
//
                        if(include == null || include.contains(key)) // here is check for include param
                        {
                            map[key] = jobject.toString()
                            Log.e(TAG, " adding to map: $key $jobject")
                        }
                    }
                }
            }
        }
        return map
    }

    /**
     * parse json object
     * @param objJson
     * @param include - all  keys, that you want to display
     * @return  Map<String, String>
     * @throws JSONException
     */
    @Throws(JSONException::class)
    fun parseJson(objJson: Any?, map :HashMap<String, String>): Map<String, String> {
        return parseJson(objJson, map, null)
    }
}

You can use it like:

    val include= arrayOf(
        "atHome",//JSONArray
        "cat",
        "dog",
        "persons",//JSONArray
        "man",
        "woman"
    )
    JsonParser.parseJson(jsonObject, map, include)
    val linearContent: LinearLayout = taskInfoFragmentBinding.infoContainer

here is some useful links:

json parsing :

plugin: https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-

create POJOs from json: https://codebeautify.org/jsonviewer

Retrofit: https://square.github.io/retrofit/

Gson: https://github.com/google/gson

If/else else if in Jquery for a condition

Change the less-than operator to a greater-than-or-equal-to operator:

}elseif($("#seats").val() >= 99999){

Conversion of Char to Binary in C

We show up two functions that prints a SINGLE character to binary.

void printbinchar(char character)
{
    char output[9];
    itoa(character, output, 2);
    printf("%s\n", output);
}

printbinchar(10) will write into the console

    1010

itoa is a library function that converts a single integer value to a string with the specified base. For example... itoa(1341, output, 10) will write in output string "1341". And of course itoa(9, output, 2) will write in the output string "1001".

The next function will print into the standard output the full binary representation of a character, that is, it will print all 8 bits, also if the higher bits are zero.

void printbincharpad(char c)
{
    for (int i = 7; i >= 0; --i)
    {
        putchar( (c & (1 << i)) ? '1' : '0' );
    }
    putchar('\n');
}

printbincharpad(10) will write into the console

    00001010

Now i present a function that prints out an entire string (without last null character).

void printstringasbinary(char* s)
{
    // A small 9 characters buffer we use to perform the conversion
    char output[9];

    // Until the first character pointed by s is not a null character
    // that indicates end of string...
    while (*s)
    {
        // Convert the first character of the string to binary using itoa.
        // Characters in c are just 8 bit integers, at least, in noawdays computers.
        itoa(*s, output, 2);

        // print out our string and let's write a new line.
        puts(output);

        // we advance our string by one character,
        // If our original string was "ABC" now we are pointing at "BC".
        ++s;
    }
}

Consider however that itoa don't adds padding zeroes, so printstringasbinary("AB1") will print something like:

1000001
1000010
110001

Hidden Columns in jqGrid

This feature is built into jqGrid.

setup your grid function as follows.

$('#myGrid').jqGrid({
   ...
   colNames: ['Manager', 'Name', 'HiddenSalary'],
   colModel: [               
               { name: 'Manager', editable: true },
               { name: 'Price', editable: true },
               { name: 'HiddenSalary', hidden: true , editable: true, 
                  editrules: {edithidden:true} 
               }
             ],
   ...
};

There are other editrules that can be applied but this basic setup would hide the manager's salary in the grid view but would allow editing when the edit form was displayed.

Matplotlib scatter plot legend

Other answers seem a bit complex, you can just add a parameter 'label' in scatter function and that will be the legend for your plot.

import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

lo = plt.scatter(random(10), random(10), marker='x', color=colors[0],label='Low Outlier')
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0],label='LoLo')
l  = plt.scatter(random(10), random(10), marker='o', color=colors[1],label='Lo')
a  = plt.scatter(random(10), random(10), marker='o', color=colors[2],label='Average')
h  = plt.scatter(random(10), random(10), marker='o', color=colors[3],label='Hi')
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4],label='HiHi')
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4],label='High Outlier')

plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
          fancybox=True, shadow=True, ncol=4)

plt.show()

This is your output:

img

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

From here.

For IIS7 and above, you also need to add the lines below:

 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

What is the difference between JavaScript and ECMAScript?

ECMAScript is the language, whereas JavaScript, JScript, and even ActionScript 3 are called "dialects". Wikipedia sheds some light on this.

Create Windows service from executable

Many existing answers include human intervention at install time. This can be an error-prone process. If you have many executables wanted to be installed as services, the last thing you want to do is to do them manually at install time.

Towards the above described scenario, I created serman, a command line tool to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run

serman install <path_to_config_file>

will install the service. stdout and stderr are all logged. For more info, take a look at the project website.

A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env> and <persistent_env> below.

<service>
  <id>hello</id>
  <name>hello</name>
  <description>This service runs the hello application</description>

  <executable>node.exe</executable>

  <!-- 
       {{dir}} will be expanded to the containing directory of your 
       config file, which is normally where your executable locates 
   -->
  <arguments>"{{dir}}\hello.js"</arguments>

  <logmode>rotate</logmode>

  <!-- OPTIONAL FEATURE:
       NODE_ENV=production will be an environment variable 
       available to your application, but not visible outside 
       of your application
   -->
  <env name="NODE_ENV" value="production"/>

  <!-- OPTIONAL FEATURE:
       FOO_SERVICE_PORT=8989 will be persisted as an environment
       variable to the system.
   -->
  <persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>

Javac is not found

As far as I can see you have the JRE in your PATH, but not the JDK.

From a command prompt try this:

set PATH=%PATH%;C:\Program Files (x86)\Java\jdk1.7.0_17\bin

Then try javac again - if this works you'll need to permanently modify your environment variables to have PATH include the JDK too.

How do I "decompile" Java class files?

Update February 2016:

www.javadecompilers.com lists JAD as being:

the most popular Java decompiler, but primarily of this age only. Written in C++, so very fast.
Outdated, unsupported and does not decompile correctly Java 5 and later

So your mileage may vary with recent jdk (7, 8).

The same site list other tools.

And javadecompiler, as noted by Salvador Valencia in the comments (Sept 2017), offers a SaaS where you upload the .class file to the cloud and it returns you the decompiled code.


Original answer: Oct. 2008

  • The final release of JSR 176, defining the major features of J2SE 5.0 (Java SE 5), has been published on September 30, 2004.
  • The lastest Java version supported by JAD, the famous Java decompiler written by Mr. Pavel Kouznetsov, is JDK 1.3.
  • Most of the Java decompilers downloadable today from the Internet, such as “DJ Java Decompiler” or “Cavaj Java Decompiler”, are powered by JAD: they can not display Java 5 sources.

Java Decompiler (Yet another Fast Java decompiler) has:

  • Explicit support for decompiling and analyzing Java 5+ “.class” files.
  • A nice GUI:

screenshot

It works with compilers from JDK 1.1.8 up to JDK 1.7.0, and others (Jikes, JRockit, etc.).

It features an online live demo version that is actually fully functional! You can just drop a jar file on the page and see the decompiled source code without installing anything.

Easy way to convert Iterable to Collection

This is not an answer to your question but I believe it is the solution to your problem. The interface org.springframework.data.repository.CrudRepository does indeed have methods that return java.lang.Iterable but you should not use this interface. Instead use sub interfaces, in your case org.springframework.data.mongodb.repository.MongoRepository. This interface has methods that return objects of type java.util.List.

Adding attributes to an XML node

There is also a way to add an attribute to an XmlNode object, that can be useful in some cases.

I found this other method on msdn.microsoft.com.

using System.Xml;

[...]

//Assuming you have an XmlNode called node
XmlNode node;

[...]

//Get the document object
XmlDocument doc = node.OwnerDocument;

//Create a new attribute
XmlAttribute attr = doc.CreateAttribute("attributeName");
attr.Value = "valueOfTheAttribute";

//Add the attribute to the node     
node.Attributes.SetNamedItem(attr);

[...]

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

To call a sub inside another sub you only need to do:

Call Subname()

So where you have CalculateA(Nc,kij, xi, a1, a) you need to have call CalculateA(Nc,kij, xi, a1, a)

As the which runs first problem it's for you to decide, when you want to run a sub you can go to the macro list select the one you want to run and run it, you can also give it a key shortcut, therefore you will only have to press those keys to run it. Although, on secondary subs, I usually do it as Private sub CalculateA(...) cause this way it does not appear in the macro list and it's easier to work

Hope it helps, Bruno

PS: If you have any other question just ask, but this isn't a community where you ask for code, you come here with a question or a code that isn't running and ask for help, not like you did "It would be great if you could write it in the Excel VBA format."

How to document Python code using Doxygen

The doxypy input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well.

What is EOF in the C programming language?

You should change your parenthesis to

while((c = getchar()) != EOF)

Because the "=" operator has a lower precedence than the "!=" operator. Then you will get the expected results. Your expression is equal to

while (c = (getchar()!= EOF))

You are getting the two 1's as output, because you are making the comparison "c!=EOF". This will always become one for the character you entered and then the "\n" that follows by hitting return. Except for the last comparison where c really is EOF it will give you a 0.

EDIT about EOF: EOF is typically -1, but this is not guaranteed by the standard. The standard only defines about EOF in section 7.19.1:

EOF which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream;

It is reasonable to assume that EOF equals -1, but when using EOF you should not test against the specific value, but rather use the macro.

How do I handle the window close event in Tkinter?

You should use destroy() to close a tkinter window.

   from Tkinter import *
   root = Tk()
   Button(root, text="Quit", command=root.destroy).pack()
   root.mainloop()

Explanation:

root.quit() The above line just Bypasses the root.mainloop() i.e root.mainloop() will still be running in background if quit() command is executed.

root.destroy() While destroy() command vanish out root.mainloop() i.e root.mainloop() stops.

So as you just want to quit the program so you should use root.destroy() as it will it stop the mainloop()`.

But if you want to run some infinite loop and you don't want to destroy your Tk window and want to execute some code after root.mainloop() line then you should use root.quit(). Ex:

from Tkinter import *
def quit():
    global root
    root.quit()

root = Tk()
while True:
    Button(root, text="Quit", command=quit).pack()
    root.mainloop()
    #do something

How do I use two submit buttons, and differentiate between which one was used to submit the form?

Give name and values to those submit buttons like:

    <td>
    <input type="submit" name='mybutton' class="noborder" id="save" value="save" alt="Save" tabindex="4" />
    </td>
    <td>
    <input type="submit" name='mybutton' class="noborder" id="publish" value="publish" alt="Publish" tabindex="5" />
    </td>

and then in your php script you could check

if($_POST['mybutton'] == 'save')
{
  ///do save processing
}
elseif($_POST['mybutton'] == 'publish')
{
  ///do publish processing here
}

App installation failed due to application-identifier entitlement

None of the answers above worked for me. My problem: I had installed an App Version from Testflight, so, I just deleted both, the old app and the Testflight version, and is working again.

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript. Just use CSS3. Please take a look at

carousel.carousel-fade

in the CSS of the following examples:

Laravel Controller Subfolder routing

I had this problem recently with laravel 5.8 but i underestand I should define controller in a right way like this below:

php artisan make:controller SubFolder\MyController  // true

Not like this:

php artisan make:controller SubFolder/MyController  // false

Then you can access the controller in routes/web.php like this:

Route::get('/my', 'SubFolder\MyController@index');

Java 8 Distinct by property

Extending Stuart Marks's answer, this can be done in a shorter way and without a concurrent map (if you don't need parallel streams):

public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    final Set<Object> seen = new HashSet<>();
    return t -> seen.add(keyExtractor.apply(t));
}

Then call:

persons.stream().filter(distinctByKey(p -> p.getName());

Two HTML tables side by side, centered on the page

The problem is that the DIV that should center your tables has no width defined. By default, DIVs are block elements and take up the entire width of their parent - in this case the entire document (propagating through the #outer DIV), so the automatic margin style has no effect.

For this technique to work, you simply have to set the width of the div that has margin:auto to anything but "auto" or "inherit" (either a fixed pixel value or a percentage).

php error: Class 'Imagick' not found

Ubuntu

sudo apt-get install php5-dev pecl imagemagick libmagickwand-dev
sudo pecl install imagick
sudo apt-get install php5-imagick
sudo service apache2 restart

Some dependencies will probably already be met but excluding the Apache service, that's everything required for PHP to use the Imagick class.

C char array initialization

This is not how you initialize an array, but for:

  1. The first declaration:

    char buf[10] = "";
    

    is equivalent to

    char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  2. The second declaration:

    char buf[10] = " ";
    

    is equivalent to

    char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  3. The third declaration:

    char buf[10] = "a";
    

    is equivalent to

    char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    

As you can see, no random content: if there are fewer initializers, the remaining of the array is initialized with 0. This the case even if the array is declared inside a function.

RecyclerView - Get view at particular position

You can get a view for a particular position on a recyclerview using the following

int position = 2;
RecyclerView.ViewHolder viewHolder = recyclerview.findViewHolderForItemId(position);
View view = viewHolder.itemView;
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);

Convert a string into an int

Very easy..

int (name of integer) = [(name of string, no ()) intValue];

Change icons of checked and unchecked for Checkbox for Android

it's android:button="@drawable/selector_checkbox" to make it work

C compiling - "undefined reference to"?

seems you need to link with the obj file that implements tolayer5()

Update: your function declaration doesn't match the implementation:

      void tolayer5(int AorB, struct msg msgReceived)
      void tolayer5(int, char data[])

So compiler would treat them as two different functions (you are using c++). and it cannot find the implementation for the one you called in main().

What's the source of Error: getaddrinfo EAI_AGAIN?

In my case the problem was the docker networks ip allocation range, see this post for details

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

Fixed it with -no-pie option in linker stage:

g++-8 -L"/home/pedro/workspace/project/lib" -no-pie ...

How to rearrange Pandas column sequence?

You can do the following:

df =DataFrame({'a':[1,2,3,4],'b':[2,4,6,8]})

df['x']=df.a + df.b
df['y']=df.a - df.b

create column title whatever order you want in this way:

column_titles = ['x','y','a','b']

df.reindex(columns=column_titles)

This will give you desired output

How to convert string to date to string in Swift iOS?

Swift 2 and below

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)

And in Swift 3 and higher this would now be written as:

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.string(from: date)

Android WSDL/SOAP service client

   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set View to register.xml
    setContentView(R.layout.register);
    session = new UserSessionManeger(getApplicationContext());     

    login_id= (EditText) findViewById(R.id.loginid);
    Suponser_id= (EditText) findViewById(R.id.sponserid);
    name=(EditText) findViewById(R.id.name);
    pass=(EditText) findViewById(R.id.pass);
    moblie=(EditText) findViewById(R.id.mobile);
    email= (EditText) findViewById(R.id.email);
    placment= (EditText) findViewById(R.id.placement);
    Adress= (EditText) findViewById(R.id.adress);
    State = (EditText) findViewById(R.id.state);

    city=(EditText) findViewById(R.id.city);
    pincopde=(EditText) findViewById(R.id.pincode);
    counntry= (EditText) findViewById(R.id.country);

    plantype= (EditText) findViewById(R.id.plantype);


    mRegister = (Button)findViewById(R.id.registration); 
  //  session.createUserLoginSession(info.getCustomerID(),info.getName(),info.getMobile(),info.getEmailID(),info.getAccountType());
    mRegister.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


             SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);        

                request.addProperty("LoginCustomerID",login_id.getText().toString());
                request.addProperty("SponsorID",Suponser_id.getText().toString());
                request.addProperty("Name", name.getText().toString());
                request.addProperty("LoginPassword",pass.getText().toString() );
                request.addProperty("MobileNumber",smoblie=moblie.getText().toString());
                request.addProperty("Email",email.getText().toString() );
                request.addProperty("Placement", placment.getText().toString()); 
                request.addProperty("address1",  Adress.getText().toString());
                request.addProperty("StateID", State.getText().toString());
                request.addProperty("CityName",city.getText().toString());

                request.addProperty("Pincode",pincopde.getText().toString());


                request.addProperty("CountryID",counntry.getText().toString());
                request.addProperty("PlanType",plantype.getText().toString());



                //Declare the version of the SOAP request
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

                envelope.setOutputSoapObject(request);
                envelope.dotNet = true;
                try {

                    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                    //this is the actual part that will call the webservice
                     androidHttpTransport.call(SOAP_ACTION1, envelope);


                    SoapObject result = (SoapObject)envelope.getResponse();  
                    Log.e("value of result", " result"+result);
                    if(result!= null)
                    {


                        Toast.makeText(getApplicationContext(), "successfully register ", 2000).show()  ;

                    }
                    else {

                        Toast.makeText(getApplicationContext(), "Try Again..", 2000).show() ;   
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }



        }
    });
    }

  }

Why is it common to put CSRF prevention tokens in cookies?

My best guess as to the answer: Consider these 3 options for how to get the CSRF token down from the server to the browser.

  1. In the request body (not an HTTP header).
  2. In a custom HTTP header, not Set-Cookie.
  3. As a cookie, in a Set-Cookie header.

I think the 1st one, request body (while demonstrated by the Express tutorial I linked in the question), is not as portable to a wide variety of situations; not everyone is generating every HTTP response dynamically; where you end up needing to put the token in the generated response might vary widely (in a hidden form input; in a fragment of JS code or a variable accessible by other JS code; maybe even in a URL though that seems generally a bad place to put CSRF tokens). So while workable with some customization, #1 is a hard place to do a one-size-fits-all approach.

The second one, custom header, is attractive but doesn't actually work, because while JS can get the headers for an XHR it invoked, it can't get the headers for the page it loaded from.

That leaves the third one, a cookie carried by a Set-Cookie header, as an approach that is easy to use in all situations (anyone's server will be able to set per-request cookie headers, and it doesn't matter what kind of data is in the request body). So despite its downsides, it was the easiest method for frameworks to implement widely.

Get the current fragment object

I think you can use onAttachFragment event may be useful to catch which fragment is active.

@Override
public void onAttachFragment(Fragment fragment) {
    // TODO Auto-generated method stub
    super.onAttachFragment(fragment);

    Toast.makeText(getApplicationContext(), String.valueOf(fragment.getId()), Toast.LENGTH_SHORT).show();

}

Generate random numbers with a given (numerical) distribution

Since Python 3.6, there's a solution for this in Python's standard library, namely random.choices.

Example usage: let's set up a population and weights matching those in the OP's question:

>>> from random import choices
>>> population = [1, 2, 3, 4, 5, 6]
>>> weights = [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]

Now choices(population, weights) generates a single sample:

>>> choices(population, weights)
4

The optional keyword-only argument k allows one to request more than one sample at once. This is valuable because there's some preparatory work that random.choices has to do every time it's called, prior to generating any samples; by generating many samples at once, we only have to do that preparatory work once. Here we generate a million samples, and use collections.Counter to check that the distribution we get roughly matches the weights we gave.

>>> million_samples = choices(population, weights, k=10**6)
>>> from collections import Counter
>>> Counter(million_samples)
Counter({5: 399616, 6: 200387, 4: 200117, 1: 99636, 3: 50219, 2: 50025})

how to access downloads folder in android?

If you're using a shell, the filepath to the Download (no "s") folder is

/storage/emulated/0/Download

Why a function checking if a string is empty always returns true?

Simple problem actually. Change:

if (strTemp != '')

to

if ($strTemp != '')

Arguably you may also want to change it to:

if ($strTemp !== '')

since != '' will return true if you pass is numeric 0 and a few other cases due to PHP's automatic type conversion.

You should not use the built-in empty() function for this; see comments and the PHP type comparison tables.

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

I have seen this error , for me the issue was there was a space in the absolute path of the persistance.xml , removal of the same helped me.

Identifying Exception Type in a handler Catch Block

You should always catch exceptions as concrete as possible, so you should use

try
{
    //code
}
catch (Web2PDFException ex)
{
    //Handle the exception here
}

You chould of course use something like this if you insist:

try
{
}
catch (Exception err)
{
    if (err is Web2PDFException)
    {
        //Code
    }
}

align divs to the bottom of their container

The modern way to do this is with flexbox, adding align-items: flex-end; on the container.

With this content:

<div class="Container">
  <div>one</div>
  <div>two</div>
</div>

Use this style:

.Container {
  display: flex;
  align-items: flex-end;
}

https://codepen.io/rds/pen/gGMBbg

Add one day to date in javascript

use this i think it is useful for you

var endDate=startDate.setDate(startDate.getDate() + 1);

text-align:center won't work with form <label> tag (?)

label is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center but since the label is only as wide as the text you don't notice.

The best thing to do is to apply a specific width to the label that is greater than the width of the content - this will give you the results you want.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

Here is an expanded solution based on DrewT's answer above that uses cookies if localStorage is not available. It uses Mozilla's docCookies library:

function localStorageGet( pKey ) {
    if( localStorageSupported() ) {
        return localStorage[pKey];
    } else {
        return docCookies.getItem( 'localstorage.'+pKey );
    }
}

function localStorageSet( pKey, pValue ) {
    if( localStorageSupported() ) {
        localStorage[pKey] = pValue;
    } else {
        docCookies.setItem( 'localstorage.'+pKey, pValue );
    }
}

// global to cache value
var gStorageSupported = undefined;
function localStorageSupported() {
    var testKey = 'test', storage = window.sessionStorage;
    if( gStorageSupported === undefined ) {
        try {
            storage.setItem(testKey, '1');
            storage.removeItem(testKey);
            gStorageSupported = true;
        } catch (error) {
            gStorageSupported = false;
        }
    }
    return gStorageSupported;
}

In your source, just use:

localStorageSet( 'foobar', 'yes' );
...
var foo = localStorageGet( 'foobar' );
...

Using Eloquent ORM in Laravel to perform search of database using LIKE

Use double quotes instead of single quote eg :

where('customer.name', 'LIKE', "%$findcustomer%")

Below is my code:

public function searchCustomer($findcustomer)
{
    $customer = DB::table('customer')
                  ->where('customer.name', 'LIKE', "%$findcustomer%")
                  ->orWhere('customer.phone', 'LIKE', "%$findcustomer%")
                  ->get();

    return View::make("your view here");
}

Best way to remove items from a collection

A lot of good responses here; I especially like the lambda expressions...very clean. I was remiss, however, in not specifying the type of Collection. This is a SPRoleAssignmentCollection (from MOSS) that only has Remove(int) and Remove(SPPrincipal), not the handy RemoveAll(). So, I have settled on this, unless there is a better suggestion.

foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)
{
    if (spAssignment.Member.Name != shortName) continue;
    workspace.RoleAssignments.Remove((SPPrincipal)spAssignment.Member);
    break;
}

Generate Json schema from XML schema (XSD)

True, but after turning json to xml with xmlspy, you can use trang application (http://www.thaiopensource.com/relaxng/trang.html) to create an xsd from xml file(s).

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

Another possibile solution is

$sContent = htmlspecialchars($sHTML);
$oDom = new DOMDocument();
$oDom->loadHTML($sContent);
echo html_entity_decode($oDom->saveHTML());

What is the meaning of prepended double colon "::"?

:: is a operator of defining the namespace.

For example, if you want to use cout without mentioning using namespace std; in your code you write this:

std::cout << "test";

When no namespace is mentioned, that it is said that class belongs to global namespace.

R - Concatenate two dataframes?

Try the plyr package:

rbind.fill(a,b,c)

How to write an async method with out parameter?

For developers who REALLY want to keep it in parameter, here might be another workaround.

Change the parameter to an array or List to wrap the actual value up. Remember to initialize the list before sending into the method. After returned, be sure to check value existence before consuming it. Code with caution.

How to parse JSON data with jQuery / JavaScript?

$.ajax({
  url: '//.xml',
  dataType: 'xml',
  success: onTrue,
  error: function (err) {
      console.error('Error: ', err);
  }
});

$('a').each(function () {
  $(this).click(function (e) {
      var l = e.target.text;
      //array.sort(sorteerOp(l));
      //functionToAdaptHtml();
  });
});

Should you commit .gitignore into the Git repos?

You typically do commit .gitignore. In fact, I personally go as far as making sure my index is always clean when I'm not working on something. (git status should show nothing.)

There are cases where you want to ignore stuff that really isn't project specific. For example, your text editor may create automatic *~ backup files, or another example would be the .DS_Store files created by OS X.

I'd say, if others are complaining about those rules cluttering up your .gitignore, leave them out and instead put them in a global excludes file.

By default this file resides in $XDG_CONFIG_HOME/git/ignore (defaults to ~/.config/git/ignore), but this location can be changed by setting the core.excludesfile option. For example:

git config --global core.excludesfile ~/.gitignore

Simply create and edit the global excludesfile to your heart's content; it'll apply to every git repository you work on on that machine.

How to horizontally center an element

If width of the content is unknown you can use the following method. Suppose we have these two elements:

  • .outer -- full width
  • .inner -- no width set (but a max-width could be specified)

Suppose the computed width of the elements are 1000 pixels and 300 pixels respectively. Proceed as follows:

  1. Wrap .inner inside .center-helper
  2. Make .center-helper an inline block; it becomes the same size as .inner making it 300 pixels wide.
  3. Push .center-helper 50% right relative to its parent; this places its left at 500 pixels wrt. outer.
  4. Push .inner 50% left relative to its parent; this places its left at -150 pixels wrt. center helper which means its left is at 500 - 150 = 350 pixels wrt. outer.
  5. Set overflow on .outer to hidden to prevent horizontal scrollbar.

Demo:

_x000D_
_x000D_
body {_x000D_
  font: medium sans-serif;_x000D_
}_x000D_
_x000D_
.outer {_x000D_
  overflow: hidden;_x000D_
  background-color: papayawhip;_x000D_
}_x000D_
_x000D_
.center-helper {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  left: 50%;_x000D_
  background-color: burlywood;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  left: -50%;_x000D_
  background-color: wheat;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="center-helper">_x000D_
    <div class="inner">_x000D_
      <h1>A div with no defined width</h1>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br>_x000D_
          Duis condimentum sem non turpis consectetur blandit.<br>_x000D_
          Donec dictum risus id orci ornare tempor.<br>_x000D_
          Proin pharetra augue a lorem elementum molestie.<br>_x000D_
          Nunc nec justo sit amet nisi tempor viverra sit amet a ipsum.</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Scrolling a flexbox with overflowing content

A little late but this could help: http://webdesign.tutsplus.com/tutorials/how-to-make-responsive-scrollable-panels-with-flexbox--cms-23269

Basically you need to put html,body to height: 100%; and wrap all your content into a <div class="wrap"> <!-- content --> </div>

CSS:

html, body {
  height: 100%;
}

.wrap {
  height: 100vh;
  display: flex;
}

Worked for me. Hope it helps

AppStore - App status is ready for sale, but not in app store

We published it today after having 'Release this version'. It took 15 minutes to show on the App Store.

This is due to App Store will sync the data across servers.

Merge development branch with master

If you are on Mac or Ubuntu, go to the working folder of the branch. In the terminal

suppose harisdev is the branchname.

git checkout master

if there are untracked or uncommitted files you will get an error and you have to commit or delete all the untracked or uncommitted files.

git merge harisdev 

git push origin master

One last command to delete the branch.

$ git branch -d harisdev

How to use a variable in the replacement side of the Perl substitution operator?

I did not manage to make the most popular answers work.

  • The ee method complained when my replacement string contained several consecutive backreferences.
  • Kent Fredric's answer only replaced the first match, and I need my search and replace to be global. I did not figure out a way to make it replace all matches that didn't cause other issues. For example, I tried running the method recursively until it no longer caused the string to change, but that causes an infinite loop if the replacement string contains the search string, whereas a regular global replacement does not do that.

I attempted to come up with a solution of my own using plain old eval:

eval '$var =~ s/' . $find . '/' . $replace . '/gsu;';

Of course, this allows for code injection. But as far as I know, the only way to escape the regex query and inject code is to insert two forward slashes in $find or one in $replace, followed by a semi-colon, after which you can add add code. For example, if I set the variables this way:

my $find = 'foo';
my $replace = 'bar/; print "You\'ve just been hacked!\n"; #';

The evaluated code is this:

$var =~ s/foo/bar/; print "You've just been hacked!\n"; #/gsu;';

So what I do is make sure the strings don't contain any unescaped forward slashes.

First, I copy the strings into dummy strings.

my $findTest = $find;
my $replaceTest = $replace;

Then, I remove all escaped backslashes (backslash pairs) from the dummy strings. This allows me to find forward slashes that are not escaped, without falling into the trap of considering a forward slash escaped if it's preceded by an escaped backslash. For example: \/ contains an escaped forward slash, but \\/ contains a literal forward slash, because the backslash is escaped.

$findTest =~ s/\\\\//gmu;
$replaceTest =~ s/\\\\//gmu;

Now if any forward slash that is not preceded by a backslash remains in the strings, I throw a fatal error, as that would allow the user to insert arbitrary code.

if ($findTest =~ /(?<!\\)\// || $replaceTest =~ /(?<!\\)\//)
{
  print "String must not contain unescaped slashes.\n";
  exit 1;
}

Then I eval.

eval '$var =~ s/' . $find . '/' . $replace . '/gsu;';

I'm not an expert at preventing code injection, but I'm the only one using my script, so I'm content using this solution without fully knowing if it's vulnerable. But as far as I know, it may be, so if anyone knows if there is or isn't any way to inject code into this, please provide your insight in a comment.

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

Mysqli makes use of object oriented programming. Try using this approach instead:

function dbCon() {
        if($mysqli = new mysqli('$hostname','$username','$password','$databasename')) return $mysqli; else return false;
}

if(!dbCon())
exit("<script language='javascript'>alert('Unable to connect to database')</script>");
else $con=dbCon();

if (isset($_GET['part'])){
    $partid = $_GET['part'];
    $sql = "SELECT * 
        FROM $usertable 
        WHERE PartNumber = $partid";

    $result=$con->query($sql_query);
    $row = $result->fetch_assoc();

    $partnumber = $partid;
    $nsn = $row["NSN"];
    $description = $row["Description"];
    $quantity = $row["Quantity"];
    $condition = $row["Conditio"];
}

Let me know if you have any questions, I could not test this code so you might need to tripple check it!

How to import a module given the full path?

Adding this to the list of answers as I couldn't find anything that worked. This will allow imports of compiled (pyd) python modules in 3.4:

import sys
import importlib.machinery

def load_module(name, filename):
    # If the Loader finds the module name in this list it will use
    # module_name.__file__ instead so we need to delete it here
    if name in sys.modules:
        del sys.modules[name]
    loader = importlib.machinery.ExtensionFileLoader(name, filename)
    module = loader.load_module()
    locals()[name] = module
    globals()[name] = module

load_module('something', r'C:\Path\To\something.pyd')
something.do_something()

How can one create an overlay in css?

Quick answer without seeing examples of your current HTML and CSS is to use z-index

css:

#div1 {
position: relative;
z-index: 1;
}

#div2 {
position: relative;
z-index: 2;
}

Where div2 is the overlay

How do I prevent 'git diff' from using a pager?

--no-pager to Git will tell it to not use a pager. Passing the option -F to less will tell it to not page if the output fits in a single screen.

Usage:

git --no-pager diff

Other options from the comments include:

# Set an evaporating environment variable to use 'cat' for your pager
GIT_PAGER=cat git diff

# Tells 'less' not to paginate if less than a page
export LESS="-F -X $LESS"
# ...then Git as usual
git diff

Disable scrolling in webview?

This should be the complete answer. As suggested by @GDanger . Extend WebView to override the scroll methods and embed the custom webview within layout xml.

public class ScrollDisabledWebView extends WebView {

    private boolean scrollEnabled = false;

    public ScrollDisabledWebView(Context context) {
        super(context);
        initView(context);
    }

    public ScrollDisabledWebView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        initView(context);
    }
    // this is important. Otherwise it throws Binary Inflate Exception.
    private void initView(Context context) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY,
                                   int scrollRangeX, int scrollRangeY, int maxOverScrollX,
                                   int maxOverScrollY, boolean isTouchEvent) {
        if (scrollEnabled) {
            return super.overScrollBy(deltaX, deltaY, scrollX, scrollY,
                    scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
        }
        return false;
    }

    @Override
    public void scrollTo(int x, int y) {
        if (scrollEnabled) {
            super.scrollTo(x, y);
        }
    }

    @Override
    public void computeScroll() {
        if (scrollEnabled) {
            super.computeScroll();
        }
    }
}

And then embed in layout file as follows

<com.sample.apps.ScrollDisabledWebView
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    tools:context="com.sample.apps.HomeActivity"/>

Then in the Activity, use some additional methods for disabling scrollbars too.

ScrollDisabledWebView webView = (ScrollDisabledWebView) findViewById(R.id.webView);
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);

How to get a list of all valid IP addresses in a local network?

Install nmap,

sudo apt-get install nmap

then

nmap -sP 192.168.1.*

or more commonly

nmap -sn 192.168.1.0/24

will scan the entire .1 to .254 range

This does a simple ping scan in the entire subnet to see which hosts are online.

When should I use "this" in a class?

Following are the ways to use ‘this’ keyword in java :

  1. Using this keyword to refer current class instance variables
  2. Using this() to invoke current class constructor
  3. Using this keyword to return the current class instance
  4. Using this keyword as method parameter

https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

set environment variable in python script

There are many good answers here but you should avoid at all cost to pass untrusted variables to subprocess using shell=True as this is a security risk. The variables can escape to the shell and run arbitrary commands! If you just can't avoid it at least use python3's shlex.quote() to escape the string (if you have multiple space-separated arguments, quote each split instead of the full string).

shell=False is always the default where you pass an argument array.

Now the safe solutions...

Method #1

Change your own process's environment - the new environment will apply to python itself and all subprocesses.

os.environ['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)

Method #2

Make a copy of the environment and pass is to the childen. You have total control over the children environment and won't affect python's own environment.

myenv = os.environ.copy()
myenv['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command, env=myenv)

Method #3

Unix only: Execute env to set the environment variable. More cumbersome if you have many variables to modify and not portabe, but like #2 you retain full control over python and children environments.

command = ['env', 'LD_LIBRARY_PATH=my_path', 'sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)

Of course if var1 contain multiple space-separated argument they will now be passed as a single argument with spaces. To retain original behavior with shell=True you must compose a command array that contain the splitted string:

command = ['sqsub', '-np'] + var1.split() + ['/homedir/anotherdir/executable']

How to add Active Directory user group as login in SQL Server

You can use T-SQL:

use master
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName

I use this as a part of restore from production server to testing machine:

USE master
GO
ALTER DATABASE yourDbName SET OFFLINE WITH ROLLBACK IMMEDIATE
RESTORE DATABASE yourDbName FROM DISK = 'd:\DropBox\backup\myDB.bak'
ALTER DATABASE yourDbName SET ONLINE
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO

You will need to use localized name of services in case of German or French Windows, see How to create a SQL Server login for a service account on a non-English Windows?

Parse XML document in C#

Try this:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");

Or alternatively if you have the XML in a string use the LoadXml method.

Once you have it loaded, you can use SelectNodes and SelectSingleNode to query specific values, for example:

XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"

Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:

<Data>
    <Employee>
        <Name>Test</Name>
        <ID>123</ID>
    </Employee>
    <Company>
        <Name>ABC</Name>
        <Email>[email protected]</Email>
    </Company>
</Data>

How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

SQL Server remove milliseconds from datetime

You just have to figure out the millisecond part of the date and subtract it out before comparison, like this:

select * 
from table 
where DATEADD(ms, -DATEPART(ms, date), date) > '2010-07-20 03:21:52'

Embed YouTube Video with No Ads

Whether ads are shown on a video is up to the content owner of that video. It's not something that the embedder can control.

If you had permission from the content owners of the videos to upload copies in your own account, and then ensured that your account was set up with monetization turned off, then that would prevent ads from showing during playback. It's up to you to work out that arrangement/permission with the original videos' owners, of course.

(It's also worth pointing out that if your goal is to help non-profits raise money, then allowing them to monetize their video playbacks is in line with that goal...)

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

If using the docker-compose file, Based on docker compose version 2.x We can set like as below, by overriding the default config.

ulimits:
  nproc: 65535
  nofile:
    soft: 26677
    hard: 46677

https://docs.docker.com/compose/compose-file/

Android Saving created bitmap to directory on sd card

Pass bitmap to the saveImage Method, It will save your bitmap in the name of a saveBitmap, inside created test folder.

private void saveImage(Bitmap data) {
                    File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test");
                    if(!createFolder.exists())
                    createFolder.mkdir();
                    File saveImage = new File(createFolder,"saveBitmap.jpg");
                    try {
                        OutputStream outputStream = new FileOutputStream(saveImage);
                        data.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
                        outputStream.flush();
                        outputStream.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

and use this:

  saveImage(bitmap);

What is a reasonable code coverage % for unit tests (and why)?

Code coverage is great, but functionality coverage is even better. I don't believe in covering every single line I write. But I do believe in writing 100% test coverage of all the functionality I want to provide (even for the extra cool features I came with myself and which were not discussed during the meetings).

I don't care if I would have code which is not covered in tests, but I would care if I would refactor my code and end up having a different behaviour. Therefore, 100% functionality coverage is my only target.

private final static attribute vs private final attribute

very little, and static

There isn't much difference as they are both constants. For most class data objects, static would mean something associated with the class itself, there being only one copy no matter how many objects were created with new.

Since it is a constant, it may not actually be stored in either the class or in an instance, but the compiler still isn't going to let you access instance objects from a static method, even if it knows what they would be. The existence of the reflection API may also require some pointless work if you don't make it static.

How do I get the path of a process in Unix / Linux

On Linux, the symlink /proc/<pid>/exe has the path of the executable. Use the command readlink -f /proc/<pid>/exe to get the value.

On AIX, this file does not exist. You could compare cksum <actual path to binary> and cksum /proc/<pid>/object/a.out.

Regex to check if valid URL that ends in .jpg, .png, or .gif

This expression will match all the image urls -

^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+(?:png|jpg|jpeg|gif|svg)+$

Examples -

Valid -

https://itelligencegroup.com/wp-content/usermedia/de_home_teaser-box_puzzle_in_the_sun.png
http://sweetytextmessages.com/wp-content/uploads/2016/11/9-Happy-Monday-images.jpg
example.com/de_home_teaser-box_puzzle_in_the_sun.png
www.example.com/de_home_teaser-box_puzzle_in_the_sun.png
https://www.greetingseveryday.com/wp-content/uploads/2016/08/Happy-Independence-Day-Greetings-Cards-Pictures-in-Urdu-Marathi-1.jpg
http://thuglifememe.com/wp-content/uploads/2017/12/Top-Happy-tuesday-quotes-1.jpg
https://1.bp.blogspot.com/-ejYG9pr06O4/Wlhn48nx9cI/AAAAAAAAC7s/gAVN3tEV3NYiNPuE-Qpr05TpqLiG79tEQCLcBGAs/s1600/Republic-Day-2017-Wallpapers.jpg

Invalid -

https://www.example.com
http://www.example.com
www.example.com
example.com
http://blog.example.com
http://www.example.com/product
http://www.example.com/products?id=1&page=2
http://www.example.com#up
http://255.255.255.255
255.255.255.255
http://invalid.com/perl.cgi?key= | http://web-site.com/cgi-bin/perl.cgi?key1=value1&key2
http://www.siteabcd.com:8008

How to remove leading zeros using C#

This is the code you need:

string strInput = "0001234";
strInput = strInput.TrimStart('0');

Get variable from PHP to JavaScript

<?php 
$j=1;
?>
<script>
var i = "<?php echo $j; ?>";
//Do something
</script>
<?php
echo $j;
?>

This is the easiest way of passing a php variable to javascript without Ajax.

You can also use something like this:

var i = "<?php echo json_encode($j); ?>";

This said to be safer or more secure. i think

Get properties of a class

Just for fun

class A {
    private a1 = void 0;
    private a2 = void 0;
}

class B extends A {
    private a3 = void 0;
    private a4 = void 0;
}

class C extends B {
    private a5 = void 0;
    private a6 = void 0;
}

class Describer {
    private static FRegEx = new RegExp(/(?:this\.)(.+?(?= ))/g); 
    static describe(val: Function, parent = false): string[] {
        var result = [];
        if (parent) {
            var proto = Object.getPrototypeOf(val.prototype);
            if (proto) {
                result = result.concat(this.describe(proto.constructor, parent));
            } 
        }
        result = result.concat(val.toString().match(this.FRegEx) || []);
        return result;
    }
}

console.log(Describer.describe(A)); // ["this.a1", "this.a2"]
console.log(Describer.describe(B)); // ["this.a3", "this.a4"]
console.log(Describer.describe(C, true)); // ["this.a1", ..., "this.a6"]

Update: If you are using custom constructors, this functionality will break.

How do I clear all options in a dropdown box?

I think that is the best sol. is

 $("#myselectid").html(''); 

Text file in VBA: Open/Find Replace/SaveAs/Close File

Why involve Notepad?

Sub ReplaceStringInFile()

Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String

' Edit as needed
sFileName = "C:\Temp\test.txt"

iFileNum = FreeFile
Open sFileName For Input As iFileNum

Do Until EOF(iFileNum)
    Line Input #iFileNum, sBuf
    sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum

sTemp = Replace(sTemp, "THIS", "THAT")

iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum

End Sub

Equivalent of explode() to work with strings in MySQL

This is actually a modified version of the selected answer in order to support Unicode characters but I don't have enough reputation to comment there.

CREATE FUNCTION SPLIT_STRING(str VARCHAR(255) CHARSET utf8, delim VARCHAR(12), pos INT) RETURNS varchar(255) CHARSET utf8
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(str, delim, pos),
       CHAR_LENGTH(SUBSTRING_INDEX(str, delim, pos-1)) + 1),
       delim, '')

The modifications are the following:

  • The first parameter is set as utf8
  • The function is set to return utf8
  • The code uses CHAR_LENGTH() instead of LENGTH() to calculate the character length and not the byte length.

Best JavaScript compressor

KJScompress

http://opensource.seznam.cz/KJScompress/index.html

Kjscompress/csskompress is set of two applications (kjscompress a csscompress) to remove non-significant whitespaces and comments from files containing JavaScript and CSS. Both are command-line applications for GNU/Linux operating system.

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

With Python 3.8 this workes for me. For instance to execute a python script within the venv:

    import subprocess
    import sys
    res = subprocess.run([
              sys.executable,            # venv3.8/bin/python
              'main.py', '--help',], 
            stdout=PIPE, 
            text=True)
    print(res.stdout)

How can I disable inherited css styles?

The cleanest solution is probably to specify your divs as exact children.

Try changing this:

div.rounded div div {
    background: url('bl.gif') no-repeat bottom left;
}

To this:

div.rounded > div > div {
    background: url('bl.gif') no-repeat bottom left;
}

How do I get the name of the current executable in C#?

System.AppDomain.CurrentDomain.FriendlyName - Returns the filename with extension (e.g. MyApp.exe).

System.Diagnostics.Process.GetCurrentProcess().ProcessName - Returns the filename without extension (e.g. MyApp).

System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName - Returns the full path and filename (e.g. C:\Examples\Processes\MyApp.exe). You could then pass this into System.IO.Path.GetFileName() or System.IO.Path.GetFileNameWithoutExtension() to achieve the same results as the above.

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

This is my solution to handle nested tabs. I just added a function to check if the active tab has a parent tab to be activated. This is the function:

function activateParentTab(tab) {
    $('.tab-pane').each(function() {
        var cur_tab = $(this);
        if ( $(this).find('#' + tab).length > 0 ) {
            $('.nav-tabs a[href=#'+ cur_tab.attr('id') +']').tab('show');
            return false;
        }
    });
}

And can be called like this (Based on @flynfish's solution):

var hash = document.location.hash;
var prefix = "";
if (hash) {
    $('.nav-tabs a[href='+hash.replace(prefix,"")+']').tab('show');
    activateParentTab(hash);
} 

// Change hash for page-reload
$('.nav-tabs a').on('shown', function (e) {
    window.location.hash = e.target.hash.replace("#", "#" + prefix);
});

This solution works pretty fine to me at the moment. Hope this can be useful for someone else ;)

Generate SHA hash in C++ using OpenSSL library

OpenSSL has a horrible documentation with no code examples, but here you are:

#include <openssl/sha.h>

bool simpleSHA256(void* input, unsigned long length, unsigned char* md)
{
    SHA256_CTX context;
    if(!SHA256_Init(&context))
        return false;

    if(!SHA256_Update(&context, (unsigned char*)input, length))
        return false;

    if(!SHA256_Final(md, &context))
        return false;

    return true;
}

Usage:

unsigned char md[SHA256_DIGEST_LENGTH]; // 32 bytes
if(!simpleSHA256(<data buffer>, <data length>, md))
{
    // handle error
}

Afterwards, md will contain the binary SHA-256 message digest. Similar code can be used for the other SHA family members, just replace "256" in the code.

If you have larger data, you of course should feed data chunks as they arrive (multiple SHA256_Update calls).

Where are include files stored - Ubuntu Linux, GCC

The \#include files of gcc are stored in /usr/include . The standard include files of g++ are stored in /usr/include/c++.

How to execute a Ruby script in Terminal?

In case someone is trying to run a script in a RAILS environment, rails provide a runner to execute scripts in rails context via

rails runner my_script.rb

More details here: https://guides.rubyonrails.org/command_line.html#rails-runner

Chrome - ERR_CACHE_MISS

This is an issue distinct to Chrome, but there are two paths you can take to fix it.

I noticed the error once I added this specific header to my PHP script.

header('Content-Type: application/json');

The error appears to be related to PHP sessions when sending response headers. So according to chromium bug report 424599, this was fixed and you can just update to a newer version of Chrome. But if for some reason you can't or don't want to update, the workaround would be to remove these response headers from your PHP script if possible (that's what I did because it wasn't required).

Select all from table with Laravel and Eloquent

Query
// Select all data of model table
Model::all();
// Select all data of model table
Model::get();

Model::where('foo', '=', 'bar')->get();

Model::find(1);
Model::find([1, 2, 3]);
Model::findOrFail(1);

Triggering change detection manually in Angular

In Angular 2+, try the @Input decorator

It allows for some nice property binding between parent and child components.

First create a global variable in the parent to hold the object/property that will be passed to the child.

Next create a global variable in the child to hold the object/property passed from the parent.

Then in the parent html, where the child template is used, add square brackets notation with the name of the child variable, then set it equal to the name of the parent variable. Example:

<child-component-template [childVariable] = parentVariable>
</child-component-template>

Finally, where the child property is defined in the child component, add the Input decorator:

@Input()
public childVariable: any

When your parent variable is updated, it should pass the updates to the child component, which will update its html.

Also, to trigger a function in the child component, take a look at ngOnChanges.

How can I run dos2unix on an entire directory?

If it's a large directory you may want to consider running with multiple processors:

find . -type f -print0 | xargs -0 -n 1 -P 4 dos2unix 

This will pass 1 file at a time, and use 4 processors.

Adding padding to a tkinter widget only on one side

There are multiple ways of doing that you can use either place or grid or even the packmethod.

Sample code:

from tkinter import *
root = Tk()

l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.

To place a widget to on basis of columns and rows , use the grid method:

but = Button(root, text="hello" )
but.grid(row=0, column=1)

Passing Arrays to Function in C++

The simple answer is that arrays are ALWAYS passed by reference and the int arg[] simply lets the compiler know to expect an array

Reading file input from a multipart/form-data POST

I've had some issues with parser that are based on string parsing particularly with large files I found it would run out of memory and fail to parse binary data.

To cope with these issues I've open sourced my own attempt at a C# multipart/form-data parser here

Features:

  • Handles very large files well. (Data is streamed in and streamed out while reading)
  • Can handle multiple file uploads and automatically detects if a section is a file or not.
  • Returns files as a stream not as a byte[] (good for large files).
  • Full documentation for the library including a MSDN-style generated website.
  • Full unit tests.

Restrictions:

  • Doesn't handle non-multipart data.
  • Code is more complicated then Lorenzo's

Just use the MultipartFormDataParser class like so:

Stream data = GetTheStream();

// Boundary is auto-detected but can also be specified.
var parser = new MultipartFormDataParser(data, Encoding.UTF8);

// The stream is parsed, if it failed it will throw an exception. Now we can use
// your data!

// The key of these maps corresponds to the name field in your
// form
string username = parser.Parameters["username"].Data;
string password = parser.Parameters["password"].Data

// Single file access:
var file = parser.Files.First();
string filename = file.FileName;
Stream data = file.Data;

// Multi-file access
foreach(var f in parser.Files)
{
    // Do stuff with each file.
}

In the context of a WCF service you could use it like this:

public ResponseClass MyMethod(Stream multipartData)
{
    // First we need to get the boundary from the header, this is sent
    // with the HTTP request. We can do that in WCF using the WebOperationConext:
    var type = WebOperationContext.Current.IncomingRequest.Headers["Content-Type"];

    // Now we want to strip the boundary out of the Content-Type, currently the string
    // looks like: "multipart/form-data; boundary=---------------------124123qase124"
    var boundary = type.Substring(type.IndexOf('=')+1);

    // Now that we've got the boundary we can parse our multipart and use it as normal
    var parser = new MultipartFormDataParser(data, boundary, Encoding.UTF8);

    ...
}

Or like this (slightly slower but more code friendly):

public ResponseClass MyMethod(Stream multipartData)
{
    var parser = new MultipartFormDataParser(data, Encoding.UTF8);
}

Documentation is also available, when you clone the repository simply navigate to HttpMultipartParserDocumentation/Help/index.html

How to create a DataFrame from a text file in Spark

I have given different ways to create DataFrame from text file

val conf = new SparkConf().setAppName(appName).setMaster("local")
val sc = SparkContext(conf)

raw text file

val file = sc.textFile("C:\\vikas\\spark\\Interview\\text.txt")
val fileToDf = file.map(_.split(",")).map{case Array(a,b,c) => 
(a,b.toInt,c)}.toDF("name","age","city")
fileToDf.foreach(println(_))

spark session without schema

import org.apache.spark.sql.SparkSession
val sparkSess = 
SparkSession.builder().appName("SparkSessionZipsExample")
.config(conf).getOrCreate()

val df = sparkSess.read.option("header", 
"false").csv("C:\\vikas\\spark\\Interview\\text.txt")
df.show()

spark session with schema

import org.apache.spark.sql.types._
val schemaString = "name age city"
val fields = schemaString.split(" ").map(fieldName => StructField(fieldName, 
StringType, nullable=true))
val schema = StructType(fields)

val dfWithSchema = sparkSess.read.option("header", 
"false").schema(schema).csv("C:\\vikas\\spark\\Interview\\text.txt")
dfWithSchema.show()

using sql context

import org.apache.spark.sql.SQLContext

val fileRdd = 
sc.textFile("C:\\vikas\\spark\\Interview\\text.txt").map(_.split(",")).map{x 
=> org.apache.spark.sql.Row(x:_*)}
val sqlDf = sqlCtx.createDataFrame(fileRdd,schema)
sqlDf.show()

Change a column type from Date to DateTime during ROR migration

Also, if you're using Rails 3 or newer you don't have to use the up and down methods. You can just use change:

class ChangeFormatInMyTable < ActiveRecord::Migration
  def change
    change_column :my_table, :my_column, :my_new_type
  end
end

SQL UPDATE with sub-query that references the same table in MySQL

UPDATE user_account student

SET (student.student_education_facility_id) = (

   SELECT teacher.education_facility_id

   FROM user_account teacher

   WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'

)

WHERE student.user_type = 'ROLE_STUDENT';

delete vs delete[] operators in C++

When I asked this question, my real question was, "is there a difference between the two? Doesn't the runtime have to keep information about the array size, and so will it not be able to tell which one we mean?" This question does not appear in "related questions", so just to help out those like me, here is the answer to that: "why do we even need the delete[] operator?"

Why can't a text column have a default value in MySQL?

As the main question:

Anybody know why this is not allowed?

is still not answered, I did a quick search and found a relatively new addition from a MySQL developer at MySQL Bugs:

[17 Mar 2017 15:11] Ståle Deraas

Posted by developer:

This is indeed a valid feature request, and at first glance it might seem trivial to add. But TEXT/BLOBS values are not stored directly in the record buffer used for reading/updating tables. So it is a bit more complex to assign default values for them.

This is no definite answer, but at least a starting point for the why question.

In the mean time, I'll just code around it and either make the column nullable or explicitly assign a (default '') value for each insert from the application code...

recursion versus iteration

Short answer: the trade off is recursion is faster and for loops take up less memory in almost all cases. However there are usually ways to change the for loop or recursion to make it run faster

How can I create an editable dropdownlist in HTML?

I am not sure there is a way to do it automatically without javascript.

What you need is something which runs on the browser side to submit your form back to the server when they user makes a selection - hence, javascript.

Also, ensure you have an alternate means (i.e. a submit button) for those who have javascript turned off.

A good example: Combo-Box Viewer

I had even a more sophisticated combo-box yesterday, with this dhtmlxCombo , using ajax to retrieve pertinent values amongst large quantity of data.

Unit testing with Spring Security

You are quite right to be concerned - static method calls are particularly problematic for unit testing as you cannot easily mock your dependencies. What I am going to show you is how to let the Spring IoC container do the dirty work for you, leaving you with neat, testable code. SecurityContextHolder is a framework class and while it may be ok for your low-level security code to be tied to it, you probably want to expose a neater interface to your UI components (i.e. controllers).

cliff.meyers mentioned one way around it - create your own "principal" type and inject an instance into consumers. The Spring <aop:scoped-proxy/> tag introduced in 2.x combined with a request scope bean definition, and the factory-method support may be the ticket to the most readable code.

It could work like following:

public class MyUserDetails implements UserDetails {
    // this is your custom UserDetails implementation to serve as a principal
    // implement the Spring methods and add your own methods as appropriate
}

public class MyUserHolder {
    public static MyUserDetails getUserDetails() {
        Authentication a = SecurityContextHolder.getContext().getAuthentication();
        if (a == null) {
            return null;
        } else {
            return (MyUserDetails) a.getPrincipal();
        }
    }
}

public class MyUserAwareController {        
    MyUserDetails currentUser;

    public void setCurrentUser(MyUserDetails currentUser) { 
        this.currentUser = currentUser;
    }

    // controller code
}

Nothing complicated so far, right? In fact you probably had to do most of this already. Next, in your bean context define a request-scoped bean to hold the principal:

<bean id="userDetails" class="MyUserHolder" factory-method="getUserDetails" scope="request">
    <aop:scoped-proxy/>
</bean>

<bean id="controller" class="MyUserAwareController">
    <property name="currentUser" ref="userDetails"/>
    <!-- other props -->
</bean>

Thanks to the magic of the aop:scoped-proxy tag, the static method getUserDetails will be called every time a new HTTP request comes in and any references to the currentUser property will be resolved correctly. Now unit testing becomes trivial:

protected void setUp() {
    // existing init code

    MyUserDetails user = new MyUserDetails();
    // set up user as you wish
    controller.setCurrentUser(user);
}

Hope this helps!

How can I make my own event in C#?

You can declare an event with the following code:

public event EventHandler MyOwnEvent;

A custom delegate type instead of EventHandler can be used if needed.

You can find detailed information/tutorials on the use of events in .NET in the article Events Tutorial (MSDN).

Converting list to *args when calling function

yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.

so:

>>> def printer(*args):
 print args


>>> printer(2,3,4)
(2, 3, 4)
>>> printer(*range(2, 5))
(2, 3, 4)
>>> printer(range(2, 5))
([2, 3, 4],)
>>> 

Specifying java version in maven - differences between properties and compiler plugin

None of the solutions above worked for me straight away. So I followed these steps:

  1. Add in pom.xml:
<properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
</properties>
  1. Go to Project Properties > Java Build Path, then remove the JRE System Library pointing to JRE1.5.

  2. Force updated the project.

Parse string to DateTime in C#

var dateStr = @"2011-03-21 13:26";
var dateTime = DateTime.ParseExact(dateStr, "yyyy-MM-dd HH:mm", CultureInfo.CurrentCulture);

Check out this link for other format strings!

Convert integer to hex and hex to integer

Maksym Kozlenko has a nice solution, and others come close to unlocking it's full potential but then miss completely to realized that you can define any sequence of characters, and use it's length as the Base. Which is why I like this slightly modified version of his solution, because it can work for base 16, or base 17, and etc.

For example, what if you wanted letters and numbers, but don't like I's for looking like 1's and O's for looking like 0's. You can define any sequence this way. Below is a form of a "Base 36" that skips the I and O to create a "modified base 34". Un-comment the hex line instead to run as hex.

declare @value int = 1234567890

DECLARE @seq varchar(100) = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ' -- modified base 34
--DECLARE @seq varchar(100) = '0123456789ABCDEF' -- hex
DECLARE @result varchar(50)
DECLARE @digit char(1)
DECLARE @baseSize int = len(@seq)
DECLARE @workingValue int = @value

SET @result = SUBSTRING(@seq, (@workingValue%@baseSize)+1, 1)

WHILE @workingValue > 0
BEGIN
    SET @digit = SUBSTRING(@seq, ((@workingValue/@baseSize)%@baseSize)+1, 1)

    SET @workingValue = @workingValue/@baseSize
    IF @workingValue <> 0 SET @result = @digit + @result
END 

select @value as Value, @baseSize as BaseSize, @result as Result

Value, BaseSize, Result

1234567890, 34, T5URAA

I also moved value over to a working value, and then work from the working value copy, as a personal preference.

Below is additional for reversing the transformation, for any sequence, with the base defined as the length of the sequence.

declare @value varchar(50) = 'T5URAA'

DECLARE @seq varchar(100) = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ' -- modified base 34
--DECLARE @seq varchar(100) = '0123456789ABCDEF' -- hex
DECLARE @result int = 0
DECLARE @digit char(1)
DECLARE @baseSize int = len(@seq)
DECLARE @workingValue varchar(50) = @value

DECLARE @PositionMultiplier int = 1
DECLARE @digitPositionInSequence int = 0

WHILE len(@workingValue) > 0
BEGIN
    SET @digit = right(@workingValue,1)
    SET @digitPositionInSequence = CHARINDEX(@digit,@seq)
    SET @result = @result + ( (@digitPositionInSequence -1) * @PositionMultiplier)

    --select @digit, @digitPositionInSequence, @PositionMultiplier, @result

    SET @workingValue = left(@workingValue,len(@workingValue)-1)
    SET @PositionMultiplier = @PositionMultiplier * @baseSize
END 

select @value as Value, @baseSize as BaseSize, @result as Result

What is the difference between range and xrange functions in Python 2.X?

range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 elements.

xrange is a generator, so it is a sequence object is a that evaluates lazily.

This is true, but in Python 3, range() will be implemented by the Python 2 xrange(). If you need to actually generate the list, you will need to do:

list(range(1,100))

How to add 10 days to current time in Rails

Use

Time.now + 10.days

or even

10.days.from_now

Both definitely work. Are you sure you're in Rails and not just Ruby?

If you definitely are in Rails, where are you trying to run this from? Note that Active Support has to be loaded.

How to make a simple collection view with Swift

Delegates and Datasources of UICollectionView

//MARK: UICollectionViewDataSource

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1     //return number of sections in collection view
}

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10    //return number of rows in section
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath)
    configureCell(cell, forItemAtIndexPath: indexPath)
    return cell      //return your cell
}

func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.blackColor()


    //Customise your cell

}

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    let view =  collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", forIndexPath: indexPath) as UICollectionReusableView
    return view
}

//MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
      // When user selects the cell
}

override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
     // When user deselects the cell
}

Update just one gem with bundler

It appears that with newer versions of bundler (>= 1.14) it's:

bundle update --conservative gem-name

An App ID with Identifier '' is not available. Please enter a different string

for me, i had to make sure an app with that bundle id was already created in the itunesconnect portal : /

Description Box using "onmouseover"

The CSS Tooltip allows you to format the popup as you like as any div section! And no Javascript needed.

System.web.mvc missing

I have the same situation: Visual Studio 2010, no NuGet installed, and an ASP.NET application using System.Web.Mvc version 3.

What worked for me, was to set each C# project that uses System.Web.Mvc, to go to References in the Solution Explorer, and set properties on System.Web.Mvc, with Copy Local to true, and Specific Version to false - the last one caused the Version field to show the current version on that machine.

How to determine day of week by passing specific date?

There is a challenge on hackerrank Java Date and Time

personally, I prefer the LocalDate class.

  1. Import java.time.LocalDate
  2. Retrieve localDate by using "of" method which takes 3 arguments in "int" format.
  3. finally, get the name of that day using "getDayOfWeek" method.

There is one video on this challenge.

Java Date and Time Hackerrank solution

I hope it will help :)

Centering a Twitter Bootstrap button

Wrap in a div styled with "text-center" class.

HTML Button : Navigate to Other Page - Different Approaches

I use method 3 because it's the most understandable for others (whenever you see an <a> tag, you know it's a link) and when you are part of a team, you have to make simple things ;).

And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.

@selector() in Swift?

For swift 3

let timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.test), userInfo: nil, repeats: true)

Function declaration In same class:

@objc func test()
{
    // my function
} 

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I in no way want to compete with Mark's answer, but just wanted to highlight the piece that finally made everything click as someone new to Javascript inheritance and its prototype chain.

Only property reads search the prototype chain, not writes. So when you set

myObject.prop = '123';

It doesn't look up the chain, but when you set

myObject.myThing.prop = '123';

there's a subtle read going on within that write operation that tries to look up myThing before writing to its prop. So that's why writing to object.properties from the child gets at the parent's objects.

Override and reset CSS style: auto or none don't work

"none" does not do what you assume it does. In order to "clear" a CSS property, you must set it back to its default, which is defined by the CSS standard. Thus you should look up the defaults in your favorite reference.

table.other {
    width: auto;
    min-width: 0;
    display:table;
}

Fine control over the font size in Seaborn plots for academic papers

It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:

sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:

axs.set_ylabel('mylabel',size=6)

you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.

def set_pubfig:
    sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.

Note: If you specify these numbers, specifying font_scale in sns.set_context is ignored for all specified font elements, even if you set it.

Format an Integer using Java String Format

String.format("%03d", 1)  // => "001"
//              ¦¦¦   +-- print the number one
//              ¦¦+------ ... as a decimal integer
//              ¦+------- ... minimum of 3 characters wide
//              +-------- ... pad with zeroes instead of spaces

See java.util.Formatter for more information.

Python timedelta in years

Get the number of days, then divide by 365.2425 (the mean Gregorian year) for years. Divide by 30.436875 (the mean Gregorian month) for months.

jQuery adding 2 numbers from input fields

Use this code for adding two numbers by using jquery

<!DOCTYPE html>
    <html lang="en-US">
    <head>
        <title>HTML Tutorial</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <meta charset="windows-1252">
    <script>

    $(document).ready(function(){
        $("#submit").on("click", function(){
        var a = parseInt($('#a').val());
        var b = parseInt($('#b').val());
           var sum = a + b;
            alert(sum);
        })
    })
    </script>
    </head>
    <body>
       <input type="text" id="a" name="option">
       <input type="text" id="b" name="task">
    <input id="submit" type="button" value="press me">

    </body>

    </html>

C#: How do you edit items and subitems in a listview?

Click the items in the list view. Add a button that will edit the selected items. Add the code

try
{              
    LSTDEDUCTION.SelectedItems[0].SubItems[1].Text = txtcarName.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[0].Text = txtcarBrand.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[2].Text = txtCarName.Text;
}
catch{}

Global Git ignore

To create global gitignore from scratch:

$ cd ~
$ touch .gitignore_global
$ git config --global core.excludesfile ~/.gitignore_global
  1. First line changes directory to C:/Users/User
  2. After that you create an empty file with .gitignore_global extension
  3. And finally setting global ignore to that file.
  4. Then you should open it with some kind of notepad and add the needed ignore rules.

What does a question mark represent in SQL queries?

What you are seeing is a parameterized query. They are frequently used when executing dynamic SQL from a program.

For example, instead of writing this (note: pseudocode):

ODBCCommand cmd = new ODBCCommand("SELECT thingA FROM tableA WHERE thingB = 7")
result = cmd.Execute()

You write this:

ODBCCommand cmd = new ODBCCommand("SELECT thingA FROM tableA WHERE thingB = ?")
cmd.Parameters.Add(7)
result = cmd.Execute()

This has many advantages, as is probably obvious. One of the most important: the library functions which parse your parameters are clever, and ensure that strings are escaped properly. For example, if you write this:

string s = getStudentName()
cmd.CommandText = "SELECT * FROM students WHERE (name = '" + s + "')"
cmd.Execute()

What happens when the user enters this?

Robert'); DROP TABLE students; --

(Answer is here)

Write this instead:

s = getStudentName()
cmd.CommandText = "SELECT * FROM students WHERE name = ?"
cmd.Parameters.Add(s)
cmd.Execute()

Then the library will sanitize the input, producing this:

"SELECT * FROM students where name = 'Robert''); DROP TABLE students; --'"

Not all DBMS's use ?. MS SQL uses named parameters, which I consider a huge improvement:

cmd.Text = "SELECT thingA FROM tableA WHERE thingB = @varname"
cmd.Parameters.AddWithValue("@varname", 7)
result = cmd.Execute()

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

I found the answer!

I want to acknowledge the hard work of everyone in trying to find a better way to solve this problem, unfortunately because of a series of larger constraints I am unable to select them as the "answer" (I am voting them up because you deserve points for contributing).

The specific problem I was facing was a JavaScript onScoll event that was firing but a subsequent CSS update that wasn't causing IE8 (in standards mode) to redraw. Even stranger was the fact that in some pages it was redrawing while in others (with no obvious similarity) it wasn't. The solution in the end was to add the following CSS

#ActionBox {
  position: relative;
  float: right;
}

Here is an updated pastbin showing this (I added some more style to show how I am implementing this code). The IE "edit code" then "view output" bug fudgey talked about still occurs (but it seems to be a event binding issue unique to pastbin (and similar services)

I don't know why adding "float: right" allows IE8 to complete a redraw on an event that was already firing, but for some reason it does.

Setting device orientation in Swift iOS

Above code might not be working due to possibility if your view controller belongs to a navigation controller. If yes then it has to obey the rules of the navigation controller even if it has different orientation rules itself. A better approach would be to let the view controller decide for itself and the navigation controller will use the decision of the top most view controller.

We can support both locking to current orientation and autorotating to lock on a specific orientation with this generic extension on UINavigationController: -:

extension UINavigationController {
            public override func shouldAutorotate() -> Bool {
                return visibleViewController.shouldAutorotate()
            }

        public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
            return (visibleViewController?.supportedInterfaceOrientations())!
        }
    }

Now inside your view controller we can

class ViewController: UIViewController {
    // MARK: Autoroate configuration

    override func shouldAutorotate() -> Bool {
        if (UIDevice.currentDevice().orientation == UIDeviceOrientation.Portrait ||
            UIDevice.currentDevice().orientation == UIDeviceOrientation.PortraitUpsideDown ||
            UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
                return true
        }
        else {
            return false
        }
    }

    override func supportedInterfaceOrientations() -> Int {
        return Int(UIInterfaceOrientationMask.Portrait.rawValue) | Int(UIInterfaceOrientationMask.PortraitUpsideDown.rawValue)
    }
}

Hope it helps. Thanks

Oracle SqlPlus - saving output in a file but don't show on screen

Try this:

SET TERMOUT OFF; 
spool M:\Documents\test;
select * from employees;
/
spool off;

Normal arguments vs. keyword arguments

Just suplement/add a way for defining the default value of arguments that is not assigned in key words when calling the function:

def func(**keywargs):
if 'my_word' not in keywargs:
    word = 'default_msg'
else:
    word = keywargs['my_word']
return word

call this by:

print(func())
print(func(my_word='love'))

you'll get:

default_msg
love

read more about *args and **kwargs in python: https://www.digitalocean.com/community/tutorials/how-to-use-args-and-kwargs-in-python-3

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

For me I put my dependencies in the wrong spot.

buildscript {
  dependencies {
    //Don't put dependencies here.
  }
}

dependencies {
 //Put them here
}

Check if Nullable Guid is empty in c#

You should use the HasValue property:

SomeProperty.HasValue

For example:

if (SomeProperty.HasValue)
{
    // Do Something
}
else
{
    // Do Something Else
}

FYI

public Nullable<System.Guid> SomeProperty { get; set; }

is equivalent to:

public System.Guid? SomeProperty { get; set; }

The MSDN Reference: http://msdn.microsoft.com/en-us/library/sksw8094.aspx

How to set downloading file name in ASP.NET Web API

Note: The last line is mandatory.

If we didn't specify Access-Control-Expose-Headers, we will not get File Name in UI.

FileInfo file = new FileInfo(FILEPATH);

HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = file.Name
};
response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

change values in array when doing foreach

To add or delete elements entirely which would alter the index, by way of extension of zhujy_8833 suggestion of slice() to iterate over a copy, simply count the number of elements you have already deleted or added and alter the index accordingly. For example, to delete elements:

let values = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8"];
let count = 0;
values.slice().forEach((value, index) => {
    if (value === "A2" || value === "A5") {
        values.splice(index - count++, 1);
    };
});
console.log(values);

// Expected: [ 'A0', 'A1', 'A3', 'A4', 'A6', 'A7', 'A8' ]

To insert elements before:

if (value === "A0" || value === "A6" || value === "A8") {
    values.splice(index - count--, 0, 'newVal');
};

// Expected: ['newVal', A0, 'A1', 'A2', 'A3', 'A4', 'A5', 'newVal', 'A6', 'A7', 'newVal', 'A8' ]

To insert elements after:

if (value === "A0" || value === "A6" || value === "A8") {
    values.splice(index - --count, 0, 'newVal');
};

// Expected: ['A0', 'newVal', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'newVal', 'A7', 'A8', 'newVal']

To replace an element:

if (value === "A3" || value === "A4" || value === "A7") {
    values.splice(index, 1, 'newVal');
};

// Expected: [ 'A0', 'A1', 'A2', 'newVal', 'newVal', 'A5', 'A6', 'newVal', 'A8' ]

Note: if implementing both 'before' and 'after' inserts, code should handle 'before' inserts first, other way around would not be as expected

Android: Create a toggle button with image and no text

ToggleButton inherits from TextView so you can set drawables to be displayed at the 4 borders of the text. You can use that to display the icon you want on top of the text and hide the actual text

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableTop="@android:drawable/ic_menu_info_details"
    android:gravity="center"
    android:textOff=""
    android:textOn=""
    android:textSize="0dp" />

The result compared to regular ToggleButton looks like

enter image description here

The seconds option is to use an ImageSpan to actually replace the text with an image. Looks slightly better since the icon is at the correct position but can't be done with layout xml directly.

You create a plain ToggleButton

<ToggleButton
    android:id="@+id/toggleButton3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false" />

Then set the "text" programmatially

ToggleButton button = (ToggleButton) findViewById(R.id.toggleButton3);
ImageSpan imageSpan = new ImageSpan(this, android.R.drawable.ic_menu_info_details);
SpannableString content = new SpannableString("X");
content.setSpan(imageSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
button.setText(content);
button.setTextOn(content);
button.setTextOff(content);

The result here in the middle - icon is placed slightly lower since it takes the place of the text.

enter image description here

Contains method for a slice

Mostafa has already pointed out that such a method is trivial to write, and mkb gave you a hint to use the binary search from the sort package. But if you are going to do a lot of such contains checks, you might also consider using a map instead.

It's trivial to check if a specific map key exists by using the value, ok := yourmap[key] idiom. Since you aren't interested in the value, you might also create a map[string]struct{} for example. Using an empty struct{} here has the advantage that it doesn't require any additional space and Go's internal map type is optimized for that kind of values. Therefore, map[string] struct{} is a popular choice for sets in the Go world.

Android emulator: could not get wglGetExtensionsStringARB error

just change your JDK I installed the JDK of SUN not Oracle and it works for me....

What is the best way to left align and right align two div tags?

This solution has left aligned text and button on the far right.

If anyone is looking for a material design answer:

<div layout="column" layout-align="start start">
 <div layout="row" style="width:100%">
    <div flex="grow">Left Aligned text</div>
    <md-button aria-label="help" ng-click="showHelpDialog()">
      <md-icon md-svg-icon="help"></md-icon>
    </md-button>
 </div>
</div>  

Bash array with spaces in elements

If you aren't stuck on using bash, different handling of spaces in file names is one of the benefits of the fish shell. Consider a directory which contains two files: "a b.txt" and "b c.txt". Here's a reasonable guess at processing a list of files generated from another command with bash, but it fails due to spaces in file names you experienced:

# bash
$ for f in $(ls *.txt); { echo $f; }
a
b.txt
b
c.txt

With fish, the syntax is nearly identical, but the result is what you'd expect:

# fish
for f in (ls *.txt); echo $f; end
a b.txt
b c.txt

It works differently because fish splits the output of commands on newlines, not spaces.

If you have a case where you do want to split on spaces instead of newlines, fish has a very readable syntax for that:

for f in (ls *.txt | string split " "); echo $f; end

jQuery UI - Close Dialog When Clicked Outside

I had same problem while making preview modal on one page. After a lot of googling I found this very useful solution. With event and target it is checking where click happened and depending on it triggers the action or does nothing.

Code Snippet Library site

$('#modal-background').mousedown(function(e) {
var clicked = $(e.target);  
if (clicked.is('#modal-content') || clicked.parents().is('#modal-content')) 
    return; 
} else {  
 $('#modal-background').hide();
}
});

Convert from days to milliseconds

In addition to the other answers, there is also the TimeUnit class which allows you to convert one time duration to another. For example, to find out how many milliseconds make up one day:

TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS); //gives 86400000

Note that this method takes a long, so if you have a fraction of a day, you will have to multiply it by the number of milliseconds in one day.

Fastest way to convert a dict's keys & values from `unicode` to `str`?

for a non-nested dict (since the title does not mention that case, it might be interesting for other people)

{str(k): str(v) for k, v in my_dict.items()}

How to get scrollbar position with Javascript?

document.getScroll = function() {
    if (window.pageYOffset != undefined) {
        return [pageXOffset, pageYOffset];
    } else {
        var sx, sy, d = document,
            r = d.documentElement,
            b = d.body;
        sx = r.scrollLeft || b.scrollLeft || 0;
        sy = r.scrollTop || b.scrollTop || 0;
        return [sx, sy];
    }
}

returns an array with two integers- [scrollLeft, scrollTop]

How to iterate over array of objects in Handlebars?

I had a similar issue I was getting the entire object in this but the value was displaying while doing #each.

Solution: I re-structure my array of object like this:

let list = results.map((item)=>{
    return { name:item.name, author:item.author }
});

and then in template file:

{{#each list}}
    <tr>
        <td>{{name }}</td>
        <td>{{author}}</td>      
    </tr>
{{/each}} 

Is it possible to style a mouseover on an image map using CSS?

You can do this by just changing the html. Here's an example:

<hmtl>
  <head>
    <title>Some title</title>
  </head>
  <body> 
  <map name="navigatemap">
    <area shape="rect"  
          coords="166,4,319,41" 
          href="WII.htm"  
          onMouseOut="navbar.src='Assets/NavigationBar(OnHome).png'" 
          onMouseOver="navbar.src='Assets/NavigationBar(OnHome,MouseOverWII).png'" 
    />
    <area shape="rect"
          coords="330,4,483,41" 
          href="OT.htm"  
          onMouseOut="navbar.src='Assets/NavigationBar(OnHome).png'" 
          onMouseOver="navbar.src='Assets/NavigationBar(OnHome,MouseOverOT).png'" 
    />

    <area shape="rect" 
          coords="491,3,645,41" 
          href="OP.htm"  
          onMouseOut="navbar.src='Assets/NavigationBar(OnHome).png'" 
          onMouseOver="navbar.src='Assets/NavigationBar(OnHome,MouseOverOP).png'" 
   />
  </map> 

  <img src="Assets/NavigationBar(OnHome).png" 
     name="navbar" 
     usemap="#navigatemap" />
  </body>
</html>

VB.Net Properties - Public Get, Private Set

I'm not sure what the minimum required version of Visual Studio is, but in VS2015 you can use

Public ReadOnly Property Name As String

It is read-only for public access but can be privately modified using _Name

How to make one Observable sequence wait for another to complete before emitting?

A couple ways I can think of

import {take, publish} from 'rxjs/operators'
import {concat} from 'rxjs'

//Method one

var one = someObservable.pipe(take(1));
var two = someOtherObservable.pipe(take(1));
concat(one, two).subscribe(function() {/*do something */});

//Method two, if they need to be separate for some reason
var one = someObservable.pipe(take(1));
var two = someOtherObservable.pipe(take(1), publish());
two.subscribe(function(){/*do something */});
one.subscribe(function(){/*do something */}, null, two.connect.bind(two));

Class Not Found: Empty Test Suite in IntelliJ

In my case, the problem was fixed by going into my build.gradle and changing

dependencies {
    testImplementation 'junit:junit:4.12'
}

to

dependencies {
    testCompile 'junit:junit:4.12'
}

Test for multiple cases in a switch, like an OR (||)

Since the other answers explained how to do it without actually explaining why it works:

When the switch executes, it finds the first matching case statement and then executes each line of code after the switch until it hits either a break statement or the end of the switch (or a return statement to leave the entire containing function). When you deliberately omit the break so that code under the next case gets executed too that's called a fall-through. So for the OP's requirement:

switch (pageid) {
   case "listing-page":
   case "home-page":
      alert("hello");
      break;

   case "details-page":
      alert("goodbye");
      break;
} 

Forgetting to include break statements is a fairly common coding mistake and is the first thing you should look for if your switch isn't working the way you expected. For that reason some people like to put a comment in to say "fall through" to make it clear when break statements have been omitted on purpose. I do that in the following example since it is a bit more complicated and shows how some cases can include code to execute before they fall-through:

switch (someVar) {
   case 1:
      someFunction();
      alert("It was 1");
      // fall through
   case 2:
      alert("The 2 case");
      // fall through
   case 3:
      // fall through
   case 4:
      // fall through
   case 5:
      alert("The 5 case");
      // fall through
   case 6:
      alert("The 6 case");
      break;

   case 7:
      alert("Something else");
      break;

   case 8:
      // fall through
   default:
      alert("The end");
      break;
}

You can also (optionally) include a default case, which will be executed if none of the other cases match - if you don't include a default and no cases match then nothing happens. You can (optionally) fall through to the default case.

So in my second example if someVar is 1 it would call someFunction() and then you would see four alerts as it falls through multiple cases some of which have alerts under them. Is someVar is 3, 4 or 5 you'd see two alerts. If someVar is 7 you'd see "Something else" and if it is 8 or any other value you'd see "The end".

Eliminate extra separators below UITableView

I was using a table view to show a fixed number of fixed height rows, so I simply resized it and made it non-scrollable.

Retrieve list of tasks in a queue in Celery

If you control the code of the tasks then you can work around the problem by letting a task trigger a trivial retry the first time it executes, then checking inspect().reserved(). The retry registers the task with the result backend, and celery can see that. The task must accept self or context as first parameter so we can access the retry count.

@task(bind=True)
def mytask(self):
    if self.request.retries == 0:
        raise self.retry(exc=MyTrivialError(), countdown=1)
    ...

This solution is broker agnostic, ie. you don't have to worry about whether you are using RabbitMQ or Redis to store the tasks.

EDIT: after testing I've found this to be only a partial solution. The size of reserved is limited to the prefetch setting for the worker.

Convert a JSON string to object in Java ME?

GSON is a good option to convert java object to json object and vise versa.
It is a tool provided by google.

for converting json to java object use: fromJson(jsonObject,javaclassname.class)
for converting java object to json object use: toJson(javaObject)
and rest will be done automatically

For more information and for download

Javascript Append Child AFTER Element

This suffices :

 parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling || null);

since if the refnode (second parameter) is null, a regular appendChild is performed. see here : http://reference.sitepoint.com/javascript/Node/insertBefore

Actually I doubt that the || null is required, try it and see.

Java synchronized method lock on object, or method?

If you have some methods which are not synchronized and are accessing and changing the instance variables. In your example:

 private int a;
 private int b;

any number of threads can access these non synchronized methods at the same time when other thread is in the synchronized method of the same object and can make changes to instance variables. For e.g :-

 public void changeState() {
      a++;
      b++;
    }

You need to avoid the scenario that non synchronized methods are accessing the instance variables and changing it otherwise there is no point of using synchronized methods.

In the below scenario:-

class X {

        private int a;
        private int b;

        public synchronized void addA(){
            a++;
        }

        public synchronized void addB(){
            b++;
        }
     public void changeState() {
          a++;
          b++;
        }
    }

Only one of the threads can be either in addA or addB method but at the same time any number of threads can enter changeState method. No two threads can enter addA and addB at same time(because of Object level locking) but at same time any number of threads can enter changeState.

How to add Google Maps Autocomplete search box?

I am using jQuery here to get the entered text and wrapping all code in $(document).ready(). Make sure you have your API key ready for Google Places API Web service. Replace it in the below script file.

<input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>

Use script file to load the autocomplete class. Your scripts.js file will look something like this.

    // scripts.js custom js file
$(document).ready(function () {
   google.maps.event.addDomListener(window, 'load', initialize);
});

function initialize() {
    var input = document.getElementById('location');
    var autocomplete = new google.maps.places.Autocomplete(input);
}

How to update TypeScript to latest version with npm?

My solution to this error was to update the typescript version with this command:

npm install -g typescript@latest as I was using Windows. However on Mac this can also be doable by sudo npm install -g typescript@latest

Remove leading or trailing spaces in an entire column of data

Without using a formula you can do this with 'Text to columns'.

  • Select the column that has the trailing spaces in the cells.
  • Click 'Text to columns' from the 'Data' tab, then choose option 'Fixed width'.
  • Set a break line so the longest text will fit. If your largest cell has 100 characters you can set the breakline on 200 or whatever you want.
  • Finish the operation.
  • You can now delete the new column Excel has created.

The 'side-effect' is that Excel has removed all trailing spaces in the original column.

Loop through all the resources in a .resx file

With the nuget package System.Resources.ResourceManager (v4.3.0) the ResourceSet and ResourceManager.GetResourceSet are not available.

Using the ResourceReader, as this post suggest: "C# - Cannot getting a string from ResourceManager (from satellite assembly)"

It's still possible to read the key/values of the resource file.

System.Reflection.Assembly resourceAssembly = System.Reflection.Assembly.Load(new System.Reflection.AssemblyName("YourAssemblyName"));
String[] manifests = resourceAssembly.GetManifestResourceNames(); 
using (ResourceReader reader = new ResourceReader(resourceAssembly.GetManifestResourceStream(manifests[0])))
{
   System.Collections.IDictionaryEnumerator dict = reader.GetEnumerator();
   while (dict.MoveNext())
   {
      String key = dict.Key as String;
      String value = dict.Value as String;
   }
}

len() of a numpy array in python

Easy. Use .shape.

>>> nparray.shape
(5, 6) #Returns a tuple of array dimensions.

C++: Converting Hexadecimal to Decimal

    std::cout << "Enter decimal number: " ;
    std::cin >> input ;

    std::cout << "0x" << std::hex << input << '\n' ;

if your adding a input that can be a boolean or float or int it will be passed back in the int main function call...

With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.

Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square. With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.

Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square.

#include <iostream>
 using namespace std;
template <class T>      // function template
T square(T);    /* returns a value of type T and accepts                  type T     (int or float or whatever) */
  void main()
{
int x, y;
float w, z;
cout << "Enter a integer:  ";
cin >> x;
y = square(x);
cout << "The square of that number is:  " << y << endl;
cout << "Enter a float:  ";
cin >> w;
z = square(w);
cout << "The square of that number is:  " << z << endl;
}

template <class T>      // function template
T square(T u) //accepts a parameter u of type T (int or float)
{
return u * u;
}

Here is the output:

Enter a integer:  5
The square of that number is:  25
Enter a float:  5.3
The square of that number is:  28.09

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

How can I mock an ES6 module import using Jest?

The question is already answered, but you can resolve it like this:

File dependency.js

const doSomething = (x) => x
export default doSomething;

File myModule.js

import doSomething from "./dependency";

export default (x) => doSomething(x * 2);

File myModule.spec.js

jest.mock('../dependency');
import doSomething from "../dependency";
import myModule from "../myModule";

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    doSomething.mockImplementation((x) => x * 10)

    myModule(2);

    expect(doSomething).toHaveBeenCalledWith(4);
    console.log(myModule(2)) // 40
  });
});

How to create a numpy array of all True or all False?

ones and zeros, which create arrays full of ones and zeros respectively, take an optional dtype parameter:

>>> numpy.ones((2, 2), dtype=bool)
array([[ True,  True],
       [ True,  True]], dtype=bool)
>>> numpy.zeros((2, 2), dtype=bool)
array([[False, False],
       [False, False]], dtype=bool)

How to add image that is on my computer to a site in css or html?

If you just want to see how your picture will look on the website without uploading it to the server or without running your website on a local server, I think a very simple solution will be to convert your picture into a Base64 and add the contents into an IMG tag or as a background-image with CSS.

How to Install pip for python 3.7 on Ubuntu 18?

Combining the answers from @mpenkon and @dangel, this is what worked for me:

  1. sudo apt install python3-pip

  2. python3.7 -m pip install pip

Step #1 is required (assuming you don't already have pip for python3) for step #2 to work. It uses pip for Python3.6 to install pip for Python 3.7 apparently.

Freeze screen in chrome debugger / DevTools panel for popover inspection?

I tried the other solutions here, they work but I'm lazy so this is my solution

  1. hover over the element to trigger expanded state
  2. ctrl+shift+c
  3. hover over element again
  4. right click
  5. navigate to the debugger

by right clicking it no longer registers mouse event since a context menu pops up, so you can move the mouse away safely

Using Application context everywhere?

I'm using the same approach, I suggest to write the singleton a little better:

public static MyApp getInstance() {

    if (instance == null) {
        synchronized (MyApp.class) {
            if (instance == null) {
                instance = new MyApp ();
            }
        }
    }

    return instance;
}

but I'm not using everywhere, I use getContext() and getApplicationContext() where I can do it!

How set the android:gravity to TextView from Java side in Android

textView.setGravity(Gravity.CENTER | Gravity.BOTTOM);

This will set gravity of your textview.

Docker Repository Does Not Have a Release File on Running apt-get update on Ubuntu

For Linux Mint, this problem is actually referenced in the Docker website:

Note: The lsb_release -cs sub-command below returns the name of your Ubuntu distribution, such as xenial. Sometimes, in a distribution like Linux Mint, you might have to change $(lsb_release -cs) to your parent Ubuntu distribution. For example, if you are using Linux Mint Rafaela, you could use trusty.

amd64:

$ sudo add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) \
stable"

The lsb_release -cs command gives a repository for which Docker has no prepared package - you must change it to xenial.

The correct command for Linux Mint 18 which is based on Ubuntu 16.04 Xenial is

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   xenial \
   stable"

Detailed 500 error message, ASP + IIS 7.5

Fot people who have tried EVERYTHING and just CANNOT get the error details to show, like me, it's a good idea to check the different levels of configuration. I have a config file on Website level and on Application level (inside the website) check both. Also, as it turned out, I had Detailed Errors disabled on the highest node in IIS (just underneath Start Page, it has the name that is the same as the webservers computername). Check the Error Pages there.

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Change IPython/Jupyter notebook working directory

To do the same trick described below for Windows in OS X, create this shell script

#!/bin/bash
cd $(dirname "$0") && pwd
ipython notebook

Call it ipython-notebook.command and make it executable.

Put it in the directory you want to work in, then double-click it.

convert pfx format to p12

I had trouble with a .pfx file with openconnect. Renaming didn't solve the problem. I used keytool to convert it to .p12 and it worked.

keytool -importkeystore -destkeystore new.p12 -deststoretype pkcs12 -srckeystore original.pfx

In my case the password for the new file (new.p12) had to be the same as the password for the .pfx file.

select unique rows based on single distinct column

Quick one in TSQL

SELECT a.*
FROM emails a
INNER JOIN 
  (SELECT email,
    MIN(id) as id
  FROM emails 
  GROUP BY email 
) AS b
  ON a.email = b.email 
  AND a.id = b.id;

Why is document.body null in my javascript?

Add your code to the onload event. The accepted answer shows this correctly, however that answer as well as all the others at the time of writing also suggest putting the script tag after the closing body tag, .

This is not valid html. However it will cause your code to work, because browsers are too kind ;)

See this answer for more info Is it wrong to place the <script> tag after the </body> tag?

Downvoted other answers for this reason.

Joining Spark dataframes on the key

Let me explain with an example

  1. create emp DataFrame

    import spark.sqlContext.implicits._ val emp = Seq((1,"Smith",-1,"2018","10","M",3000), (2,"Rose",1,"2010","20","M",4000), (3,"Williams",1,"2010","10","M",1000), (4,"Jones",2,"2005","10","F",2000), (5,"Brown",2,"2010","40","",-1), (6,"Brown",2,"2010","50","",-1) ) val empColumns = Seq("emp_id","name","superior_emp_id","year_joined", "emp_dept_id","gender","salary")

    val empDF = emp.toDF(empColumns:_*)

  2. Create dept DataFrame

    val dept = Seq(("Finance",10), ("Marketing",20), ("Sales",30), ("IT",40) )

    val deptColumns = Seq("dept_name","dept_id") val deptDF = dept.toDF(deptColumns:_*)

Now let's join emp.emp_dept_id with dept.dept_id

empDF.join(deptDF,empDF("emp_dept_id") ===  deptDF("dept_id"),"inner")
    .show(false)

This results below

+------+--------+---------------+-----------+-----------+------+------+---------+-------+
|emp_id|name    |superior_emp_id|year_joined|emp_dept_id|gender|salary|dept_name|dept_id|
+------+--------+---------------+-----------+-----------+------+------+---------+-------+
|1     |Smith   |-1             |2018       |10         |M     |3000  |Finance  |10     |
|2     |Rose    |1              |2010       |20         |M     |4000  |Marketing|20     |
|3     |Williams|1              |2010       |10         |M     |1000  |Finance  |10     |
|4     |Jones   |2              |2005       |10         |F     |2000  |Finance  |10     |
|5     |Brown   |2              |2010       |40         |      |-1    |IT       |40     |
+------+--------+---------------+-----------+-----------+------+------+---------+-------+

If you are looking in python PySpark Join with example and also find the complete Scala example at Spark Join

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

I faced the same issue, I opened the file: my-project/gradle/wrapper/gradle-wrapper.properties, replaced the distributionUrl to

distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip

I opened the file: my-project/build.gradle, under buildscript -> dependencies, replaced the classpath to

classpath 'com.android.tools.build:gradle:4.0.0'

Sync the project and worked fine

How to get difference between two rows for a column field?

SELECT
   [current].rowInt,
   [current].Value,
   ISNULL([next].Value, 0) - [current].Value
FROM
   sourceTable       AS [current]
LEFT JOIN
   sourceTable       AS [next]
      ON [next].rowInt = (SELECT MIN(rowInt) FROM sourceTable WHERE rowInt > [current].rowInt)

EDIT:

Thinking about it, using a subquery in the select (ala Quassnoi's answer) may be more efficient. I would trial different versions, and look at the execution plans to see which would perform best on the size of data set that you have...


EDIT2:

I still see this garnering votes, though it's unlikely many people still use SQL Server 2005.

If you have access to Windowed Functions such as LEAD(), then use that instead...

SELECT
  RowInt,
  Value,
  LEAD(Value, 1, 0) OVER (ORDER BY RowInt) - Value
FROM
  sourceTable

Subtract minute from DateTime in SQL Server 2005

Use DATEPART to pull apart your interval, and DATEADD to subtract the parts:

select dateadd(
     hh,
    -1 * datepart(hh, cast('1:15' as datetime)),
    dateadd(
        mi,
        -1 * datepart(mi, cast('1:15' as datetime)),
        '2000-01-01 08:30:00'))

or, we can convert to minutes first (though OP would prefer not to):

declare @mins int
select @mins = datepart(mi, cast('1:15' as datetime)) + 60 * datepart(hh, cast('1:15' as datetime)) 
select dateadd(mi, -1 * @mins, '2000-01-01 08:30:00')

How do I make curl ignore the proxy?

I assume curl is reading the proxy address from the environment variable http_proxy and that the variable should keep its value. Then in a shell like bash, export http_proxy=''; before a command (or in a shell script) would temporarily change its value.

(See curl's manual for all the variables it looks at, under the ENVIRONMENT heading.)

MyISAM versus InnoDB

For that ratio of read/writes I would guess InnoDB will perform better. Since you are fine with dirty reads, you might (if you afford) replicate to a slave and let all your reads go to the slave. Also, consider inserting in bulk, rather than one record at a time.

Python JSON serialize a Decimal object

You can create a custom JSON encoder as per your requirement.

import json
from datetime import datetime, date
from time import time, struct_time, mktime
import decimal

class CustomJSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime):
            return str(o)
        if isinstance(o, date):
            return str(o)
        if isinstance(o, decimal.Decimal):
            return float(o)
        if isinstance(o, struct_time):
            return datetime.fromtimestamp(mktime(o))
        # Any other serializer if needed
        return super(CustomJSONEncoder, self).default(o)

The Decoder can be called like this,

import json
from decimal import Decimal
json.dumps({'x': Decimal('3.9')}, cls=CustomJSONEncoder)

and the output will be:

>>'{"x": 3.9}'

Java generics - ArrayList initialization

ArrayList<Integer> a = new ArrayList<Number>(); 

Does not work because the fact that Number is a super class of Integer does not mean that List<Number> is a super class of List<Integer>. Generics are removed during compilation and do not exist on runtime, so parent-child relationship of collections cannot be be implemented: the information about element type is simply removed.

ArrayList<? extends Object> a1 = new ArrayList<Object>();
a1.add(3);

I cannot explain why it does not work. It is really strange but it is a fact. Really syntax <? extends Object> is mostly used for return values of methods. Even in this example Object o = a1.get(0) is valid.

ArrayList<?> a = new ArrayList<?>()

This does not work because you cannot instantiate list of unknown type...

List all employee's names and their managers by manager name using an inner join

No, the correct join is:

inner join Employees m on e.mgr = m.EmpID;

You need to match the ManagerID for the current employee with the EmployeeID of the manager. Not with the ManagerID of the manager.

update
As noted by Andrey Gordeev:
You'd also need to add m.Ename to your SELECT query in order to get the name of the Manager in your result. Otherwise you'd only get the managerID.

orderBy multiple fields in Angular

If you wants to sort on mulitple fields inside controller use this

$filter('orderBy')($scope.property_list, ['firstProp', 'secondProp']);

See also https://docs.angularjs.org/api/ng/filter/orderBy

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.

Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.

The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error