Programs & Examples On #Qitemdelegate

Byte array to image conversion

First Install This Package:

Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0007

[SixLabors.ImageSharp][1] [1]: https://www.nuget.org/packages/SixLabors.ImageSharp

Then use Below Code For Cast Byte Array To Image :

Image<Rgba32> image = Image.Load(byteArray); 

For Get ImageFormat Use Below Code:

IImageFormat format = Image.DetectFormat(byteArray);

For Mutate Image Use Below Code:

image.Mutate(x => x.Resize(new Size(1280, 960)));

Difference between id and name attributes in HTML

Generally, it is assumed that name is always superseded by id. This is true, to some extent, but not for form fields and frame names, practically speaking. For example, with form elements the name attribute is used to determine the name-value pairs to be sent to a server-side program and should not be eliminated. Browsers do not use id in that manner. To be on the safe side, you could use name and id attributes on form elements. So, we would write the following:

<form id="myForm" name="myForm">
     <input type="text" id="userName" name="userName" />
</form>

To ensure compatibility, having matching name and id attribute values when both are defined is a good idea. However, be careful—some tags, particularly radio buttons, must have nonunique name values, but require unique id values. Once again, this should reference that id is not simply a replacement for name; they are different in purpose. Furthermore, do not discount the old-style approach, a deep look at modern libraries shows such syntax style used for performance and ease purposes at times. Your goal should always be in favor of compatibility.

Now in most elements, the name attribute has been deprecated in favor of the more ubiquitous id attribute. However, in some cases, particularly form fields (<button>, <input>, <select>, and <textarea>), the name attribute lives on because it continues to be required to set the name-value pair for form submission. Also, we find that some elements, notably frames and links, may continue to use the name attribute because it is often useful for retrieving these elements by name.

There is a clear distinction between id and name. Very often when name continues on, we can set the values the same. However, id must be unique, and name in some cases shouldn’t—think radio buttons. Sadly, the uniqueness of id values, while caught by markup validation, is not as consistent as it should be. CSS implementation in browsers will style objects that share an id value; thus, we may not catch markup or style errors that could affect our JavaScript until runtime.

This is taken from the book JavaScript- The Complete Reference by Thomas-Powell

No module named setuptools

The PyPA recommended tool for installing and managing Python packages is pip. pip is included with Python 3.4 (PEP 453), but for older versions here's how to install it (on Windows, using Python 3.3):

Download https://bootstrap.pypa.io/get-pip.py

>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...

Sample usage:

>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...

In your case it would be this (it appears that pip caches independent of Python version):

C:\Python27>python.exe \code\Python\get-pip.py
Requirement already up-to-date: pip in c:\python27\lib\site-packages
Collecting wheel
  Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB)
    100% |################################| 69kB 255kB/s
Installing collected packages: wheel
Successfully installed wheel-0.29.0

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install twilio
Collecting twilio
  Using cached twilio-5.3.0.tar.gz
Collecting httplib2>=0.7 (from twilio)
  Using cached httplib2-0.9.2.tar.gz
Collecting six (from twilio)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pytz (from twilio)
  Using cached pytz-2015.7-py2.py3-none-any.whl
Building wheels for collected packages: twilio, httplib2
  Running setup.py bdist_wheel for twilio ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e0\f2\a7\c57f6d153c440b93bd24c1243123f276dcacbf43cc43b7f906
  Running setup.py bdist_wheel for httplib2 ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e1\a3\05\e66aad1380335ee0a823c8f1b9006efa577236a24b3cb1eade
Successfully built twilio httplib2
Installing collected packages: httplib2, six, pytz, twilio
Successfully installed httplib2-0.9.2 pytz-2015.7 six-1.10.0 twilio-5.3.0

Two dimensional array list

Here's how to make and print a 2D Multi-Dimensional Array using the ArrayList Object.

import java.util.ArrayList;

public class TwoD_ArrayListExample {
    static public ArrayList<ArrayList<String>> gameBoard = new ArrayList<ArrayList<String>>();

    public static void main(String[] args) {
        insertObjects();
        printTable(gameBoard);
    }

    public static void insertObjects() {
        for (int rowNum = 0; rowNum != 8; rowNum++) {
            ArrayList<String> oneRow = new ArrayList<String>();
            gameBoard.add(rowNum, oneRow);

            for (int columnNum = 0; columnNum != 8; columnNum++) {
                String description= "Description of Objects: row= "+ rowNum + ", column= "+ columnNum;
                    oneRow.add(columnNum, description);
            }
        }
    }

    // The printTable method prints the table to the console
    private static void printTable(ArrayList<ArrayList<String>> table) {
        for (int row = 0; row != 8; row++) {
            for (int col = 0; col != 8; col++) {
                System.out.println("Printing:               row= "+ row+ ", column= "+ col);
                System.out.println(table.get(row).get(col).toString());
            }
        }
        System.out.println("\n");
    }
}

ActionBar text color

i have done with simple one line code

actionBar.setTitle(Html.fromHtml("<font color='#ff0000'>ActionBartitle </font>"));

Refused to load the script because it violates the following Content Security Policy directive

We used this:

<meta http-equiv="Content-Security-Policy" content="default-src gap://ready file://* *; style-src 'self' http://* https://* 'unsafe-inline'; script-src 'self' http://* https://* 'unsafe-inline' 'unsafe-eval'">

Twitter Bootstrap hide css class and jQuery

As dfsq said i just had to use removeClass("hide") instead of toggle()

Simple (I think) Horizontal Line in WPF?

How about add this to your xaml:

<Separator/>

How to show loading spinner in jQuery?

There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.

$('#loadingDiv')
    .hide()  // Hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;

The ajaxStart/Stop functions will fire whenever you do any Ajax calls.

Update: As of jQuery 1.8, the documentation states that .ajaxStart/Stop should only be attached to document. This would transform the above snippet to:

var $loading = $('#loadingDiv').hide();
$(document)
  .ajaxStart(function () {
    $loading.show();
  })
  .ajaxStop(function () {
    $loading.hide();
  });

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

@NotNull is a JSR 303 Bean Validation annotation. It has nothing to do with database constraints itself. As Hibernate is the reference implementation of JSR 303, however, it intelligently picks up on these constraints and translates them into database constraints for you, so you get two for the price of one. @Column(nullable = false) is the JPA way of declaring a column to be not-null. I.e. the former is intended for validation and the latter for indicating database schema details. You're just getting some extra (and welcome!) help from Hibernate on the validation annotations.

How do I format a string using a dictionary in python-3.x?

print("{latitude} {longitude}".format(**geopoint))

How to read keyboard-input?

try

raw_input('Enter your input:')  # If you use Python 2
input('Enter your input:')      # If you use Python 3

and if you want to have a numeric value just convert it:

try:
    mode=int(raw_input('Input:'))
except ValueError:
    print "Not a number"

PHP add elements to multidimensional array with array_push

I know the topic is old, but I just fell on it after a google search so... here is another solution:

$array_merged = array_merge($array_going_first, $array_going_second);

This one seems pretty clean to me, it works just fine!

iOS Swift - Get the Current Local Time and Date Timestamp

First I would recommend you to store your timestamp as a NSNumber in your Firebase Database, instead of storing it as a String.

Another thing worth mentioning here, is that if you want to manipulate dates with Swift, you'd better use Date instead of NSDate, except if you're interacting with some Obj-C code in your app.

You can of course use both, but the Documentation states:

Date bridges to the NSDate class. You can use these interchangeably in code that interacts with Objective-C APIs.

Now to answer your question, I think the problem here is because of the timezone.

For example if you print(Date()), as for now, you would get:

2017-09-23 06:59:34 +0000

This is the Greenwich Mean Time (GMT).

So depending on where you are located (or where your users are located) you need to adjust the timezone before (or after, when you try to access the data for example) storing your Date:

    let now = Date()

    let formatter = DateFormatter()

    formatter.timeZone = TimeZone.current

    formatter.dateFormat = "yyyy-MM-dd HH:mm"

    let dateString = formatter.string(from: now)

Then you have your properly formatted String, reflecting the current time at your location, and you're free to do whatever you want with it :) (convert it to a Date / NSNumber, or store it directly as a String in the database..)

Java random numbers using a seed

Problem is that you seed the random generator again. Every time you seed it the initial state of the random number generator gets reset and the first random number you generate will be the first random number after the initial state

How to install Visual Studio 2015 on a different drive

I found these two links which might help you:

  1. https://www.reddit.com/r/csharp/comments/2agecc/why_must_visual_studio_be_installed_on_my_system/

  2. http://www.placona.co.uk/1196/dotnet/installing-visual-studio-on-a-different-drive/

Basically, at least a portion needs to be installed on a system drive. I'm not sure if your D:\ corresponds to some external drive or an actual system drive but the symlink solution might help.

Good luck

Limitations of SQL Server Express

There are a number of limitations, notably:

  • Constrained to a single CPU (in 2012, this limitation has been changed to "The lesser of one socket or four cores", so multi-threading is possible)
  • 1GB RAM (Same in 2008/2012)
  • 4GB database size (raised to 10GB in SQL 2008 R2 and SQL 2012) per database

http://www.dotnetspider.com/tutorials/SqlServer-Tutorial-158.aspx http://www.microsoft.com/sqlserver/2008/en/us/editions.aspx

With regards to the number of databases, this MSDN article says there's no limit:

The 4 GB database size limit applies only to data files and not to log files. However, there are no limits to the number of databases that can be attached to the server.

However, as mentioned in the comments and above, the database size limit was raised to 10GB in 2008 R2 and 2012. Also, this 10GB limit only applies to relational data, and Filestream data does not count towards this limit (http://msdn.microsoft.com/en-us/library/bb895334.aspx).

Catch an exception thrown by an async void method

Your code doesn't do what you might think it does. Async methods return immediately after the method begins waiting for the async result. It's insightful to use tracing in order to investigate how the code is actually behaving.

The code below does the following:

  • Create 4 tasks
  • Each task will asynchronously increment a number and return the incremented number
  • When the async result has arrived it is traced.

 

static TypeHashes _type = new TypeHashes(typeof(Program));        
private void Run()
{
    TracerConfig.Reset("debugoutput");

    using (Tracer t = new Tracer(_type, "Run"))
    {
        for (int i = 0; i < 4; i++)
        {
            DoSomeThingAsync(i);
        }
    }
    Application.Run();  // Start window message pump to prevent termination
}


private async void DoSomeThingAsync(int i)
{
    using (Tracer t = new Tracer(_type, "DoSomeThingAsync"))
    {
        t.Info("Hi in DoSomething {0}",i);
        try
        {
            int result = await Calculate(i);
            t.Info("Got async result: {0}", result);
        }
        catch (ArgumentException ex)
        {
            t.Error("Got argument exception: {0}", ex);
        }
    }
}

Task<int> Calculate(int i)
{
    var t = new Task<int>(() =>
    {
        using (Tracer t2 = new Tracer(_type, "Calculate"))
        {
            if( i % 2 == 0 )
                throw new ArgumentException(String.Format("Even argument {0}", i));
            return i++;
        }
    });
    t.Start();
    return t;
}

When you observe the traces

22:25:12.649  02172/02820 {          AsyncTest.Program.Run 
22:25:12.656  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.657  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 0    
22:25:12.658  02172/05220 {          AsyncTest.Program.Calculate    
22:25:12.659  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.659  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 1    
22:25:12.660  02172/02756 {          AsyncTest.Program.Calculate    
22:25:12.662  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.662  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 2    
22:25:12.662  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.662  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 3    
22:25:12.664  02172/02756          } AsyncTest.Program.Calculate Duration 4ms   
22:25:12.666  02172/02820          } AsyncTest.Program.Run Duration 17ms  ---- Run has completed. The async methods are now scheduled on different threads. 
22:25:12.667  02172/02756 Information AsyncTest.Program.DoSomeThingAsync Got async result: 1    
22:25:12.667  02172/02756          } AsyncTest.Program.DoSomeThingAsync Duration 8ms    
22:25:12.667  02172/02756 {          AsyncTest.Program.Calculate    
22:25:12.665  02172/05220 Exception   AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 0   
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     
22:25:12.668  02172/02756 Exception   AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 2   
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     
22:25:12.724  02172/05220          } AsyncTest.Program.Calculate Duration 66ms      
22:25:12.724  02172/02756          } AsyncTest.Program.Calculate Duration 57ms      
22:25:12.725  02172/05220 Error       AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 0  

Server stack trace:     
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     

Exception rethrown at [0]:      
   at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()    
   at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()  
   at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 106    
22:25:12.725  02172/02756 Error       AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 2  

Server stack trace:     
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     

Exception rethrown at [0]:      
   at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()    
   at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()  
   at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 0      
22:25:12.726  02172/05220          } AsyncTest.Program.DoSomeThingAsync Duration 70ms   
22:25:12.726  02172/02756          } AsyncTest.Program.DoSomeThingAsync Duration 64ms   
22:25:12.726  02172/05220 {          AsyncTest.Program.Calculate    
22:25:12.726  02172/05220          } AsyncTest.Program.Calculate Duration 0ms   
22:25:12.726  02172/05220 Information AsyncTest.Program.DoSomeThingAsync Got async result: 3    
22:25:12.726  02172/05220          } AsyncTest.Program.DoSomeThingAsync Duration 64ms   

You will notice that the Run method completes on thread 2820 while only one child thread has finished (2756). If you put a try/catch around your await method you can "catch" the exception in the usual way although your code is executed on another thread when the calculation task has finished and your contiuation is executed.

The calculation method traces the thrown exception automatically because I did use the ApiChange.Api.dll from the ApiChange tool. Tracing and Reflector helps a lot to understand what is going on. To get rid of threading you can create your own versions of GetAwaiter BeginAwait and EndAwait and wrap not a task but e.g. a Lazy and trace inside your own extension methods. Then you will get much better understanding what the compiler and what the TPL does.

Now you see that there is no way to get in a try/catch your exception back since there is no stack frame left for any exception to propagate from. Your code might be doing something totally different after you did initiate the async operations. It might call Thread.Sleep or even terminate. As long as there is one foreground thread left your application will happily continue to execute asynchronous tasks.


You can handle the exception inside the async method after your asynchronous operation did finish and call back into the UI thread. The recommended way to do this is with TaskScheduler.FromSynchronizationContext. That does only work if you have an UI thread and it is not very busy with other things.

How to do a GitHub pull request

In order to make a pull request you need to do the following steps:

  1. Fork a repository (to which you want to make a pull request). Just click the fork button the the repository page and you will have a separate github repository preceded with your github username.
  2. Clone the repository to your local machine. The Github software that you installed on your local machine can do this for you. Click the clone button beside the repository name.
  3. Make local changes/commits to the files
  4. sync the changes
  5. go to your github forked repository and click the "Compare & Review" green button besides the branch button. (The button has icon - no text)
  6. A new page will open showing your changes and then click the pull request link, that will send the request to the original owner of the repository you forked.

It took me a while to figure this, hope this will help someone.

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

         ` Adding the following to pom.xml will resolve the issue.      <pluginRepositories>
        <pluginRepository>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <releases>
                <updatePolicy>never</updatePolicy>
            </releases>
        </pluginRepository>
   </pluginRepositories>
    
   <repositories>
        <repository>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
   </repositories>   `

A process crashed in windows .. Crash dump location

I have observed on Windows 2008 the Windows Error Reporting crash dumps get staged in the folder:

C:\Users\All Users\Microsoft\Windows\WER\ReportQueue

Which, starting with Windows Vista, is an alias for:

C:\ProgramData\Microsoft\Windows\WER\ReportQueue

How to step through Python code to help debug issues?

Python Tutor is an online single-step debugger meant for novices. You can put in code on the edit page then click "Visualize Execution" to start it running.

Among other things, it supports:

However it also doesn't support a lot of things, for example:

  • Reading/writing files - use io.StringIO and io.BytesIO instead: demo
  • Code that is too large, runs too long, or defines too many variables or objects
  • Command-line arguments
  • Lots of standard library modules like argparse, csv, enum, html, os, struct, weakref...

What is NODE_ENV and how to use it in Express?

I assume the original question included how does Express use this environment variable.

Express uses NODE_ENV to alter its own default behavior. For example, in development mode, the default error handler will send back a stacktrace to the browser. In production mode, the response is simply Internal Server Error, to avoid leaking implementation details to the world.

React - uncaught TypeError: Cannot read property 'setState' of undefined

you have to bind new event with this keyword as i mention below...

class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta = this.delta.bind(this);
    }

    delta() {
        this.setState({
            count : this.state.count++
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.delta}>+</button>
            </div>
        );
      }
    }

Getting error: ISO C++ forbids declaration of with no type

Your declaration is int ttTreeInsert(int value);

However, your definition/implementation is

ttTree::ttTreeInsert(int value)
{
}

Notice that the return type int is missing in the implementation. Instead it should be

int ttTree::ttTreeInsert(int value)
{
    return 1; // or some valid int
}

Set default option in mat-select

HTML

<mat-form-field>
<mat-select [(ngModel)]="modeSelect" placeholder="Mode">
  <mat-option *ngFor="let obj of Array"  [value]="obj.value">{{obj.value}}</mat-option>
</mat-select>

Now set your default value to

modeSelect

, where you are getting the values in Array variable.

String Pattern Matching In Java

That's just a matter of String.contains:

if (input.contains("{item}"))

If you need to know where it occurs, you can use indexOf:

int index = input.indexOf("{item}");
if (index != -1) // -1 means "not found"
{
    ...
}

That's fine for matching exact strings - if you need real patterns (e.g. "three digits followed by at most 2 letters A-C") then you should look into regular expressions.

EDIT: Okay, it sounds like you do want regular expressions. You might want something like this:

private static final Pattern URL_PATTERN =
    Pattern.compile("/\\{[a-zA-Z0-9]+\\}/");

...

if (URL_PATTERN.matches(input).find())

Change Oracle port from port 8080

I assume you're talking about the Apache server that Oracle installs. Look for the file httpd.conf.

Open this file in a text editor and look for the line
Listen 8080
or
Listen {ip address}:8080

Change the port number and either restart the web server or just reboot the machine.

MySQL Fire Trigger for both Insert and Update

You have to create two triggers, but you can move the common code into a procedure and have them both call the procedure.

How to randomize two ArrayLists in the same fashion?

This can be done using the shuffle method:

private List<Integer> getJumbledList() {
     List<Integer> myArrayList2 = new ArrayList<Integer>();
        myArrayList2.add(8);
        myArrayList2.add(4);
        myArrayList2.add(9);
        Collections.shuffle(myArrayList2);
        return myArrayList2;

Bootstrap4 adding scrollbar to div

      <div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
        <strong>Column 0 </strong><br>
        <strong>Column 1</strong><br>
        <strong>Column 2</strong><br>
        <strong>Column 3</strong><br>
        <strong>Column 4</strong><br>
        <strong>Column 5</strong><br>
        <strong>Column 6</strong><br>
        <strong>Column 7</strong><br>
        <strong>Column 8</strong><br>
        <strong>Column 9</strong><br>
        <strong>Column 10</strong><br>
        <strong>Column 11</strong><br>
        <strong>Column 12</strong><br>
        <strong>Column 13</strong><br>
      </div>
    </div>

get keys of json-object in JavaScript

var jsonData = [{"person":"me","age":"30"},{"person":"you","age":"25"}];

for(var i in jsonData){
    var key = i;
    var val = jsonData[i];
    for(var j in val){
        var sub_key = j;
        var sub_val = val[j];
        console.log(sub_key);
    }
}

EDIT

var jsonObj = {"person":"me","age":"30"};
Object.keys(jsonObj);  // returns ["person", "age"]

Object has a property keys, returns an Array of keys from that Object

Chrome, FF & Safari supports Object.keys

Changing width property of a :before css selector using JQuery

You may try to inherit property from the base class:

_x000D_
_x000D_
var width = 2;_x000D_
var interval = setInterval(function () {_x000D_
    var element = document.getElementById('box');_x000D_
    width += 0.0625;_x000D_
    element.style.width = width + 'em';_x000D_
    if (width >= 7) clearInterval(interval);_x000D_
}, 50);
_x000D_
.box {_x000D_
    /* Set property */_x000D_
    width:4em;_x000D_
    height:2em;_x000D_
    background-color:#d42;_x000D_
    position:relative;_x000D_
}_x000D_
.box:after {_x000D_
    /* Inherit property */_x000D_
    width:inherit;_x000D_
    content:"";_x000D_
    height:1em;_x000D_
    background-color:#2b4;_x000D_
    position:absolute;_x000D_
    top:100%;_x000D_
}
_x000D_
<div id="box" class="box"></div>
_x000D_
_x000D_
_x000D_

How to check for file existence

# file? will only return true for files
File.file?(filename)

and

# Will also return true for directories - watch out!
File.exist?(filename)

Purge Kafka Topic

Temporarily update the retention time on the topic to one second:

kafka-topics.sh --zookeeper <zkhost>:2181 --alter --topic <topic name> --config retention.ms=1000

And in newer Kafka releases, you can also do it with kafka-configs --entity-type topics

kafka-configs.sh --zookeeper <zkhost>:2181 --entity-type topics --alter --entity-name <topic name> --add-config retention.ms=1000

then wait for the purge to take effect (about one minute). Once purged, restore the previous retention.ms value.

Android WebView progress bar

wait until the process is over ...

while(webview.getProgress()< 100){}
progressBar.setVisibility(View.GONE);

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

I had the same issue. Solved it simply; I have (2) google accounts linked to my Play Store. It just so happens that I installed "an" app from "account B", and I was trying to rate it from "account A". So, switched accounts, and voilá.

PHP MySQL Google Chart JSON - Complete Example

Some might encounter this error (I got it while implementing PHP-MySQLi-JSON-Google Chart Example):

You called the draw() method with the wrong type of data rather than a DataTable or DataView.

The solution would be: replace jsapi and just use loader.js with:

google.charts.load('current', {packages: ['corechart']}) and 
google.charts.setOnLoadCallback 

-- according to the release notes --> The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

How to adjust text font size to fit textview

In my case using app:autoSize was not solving all cases, for example it doesn't prevent word breaking

This is what I ended up using, it will resize down the text so that there are no word breaks on multiple lines

/**
 * Resizes down the text size so that there are no word breaks
 */
class AutoFitTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private val paint = Paint()
    private val bounds = Rect()

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        var shouldResize = false
        paint.typeface = typeface
        var textSize = textSize
        paint.textSize = textSize
        val biggestWord: String = text.split(" ").maxByOrNull { it.count() } ?: return

        // Set bounds equal to the biggest word bounds
        paint.getTextBounds(biggestWord, 0, biggestWord.length, bounds)

        // Iterate to reduce the text size so that it makes the biggest word fit the line
        while ((bounds.width() + paddingStart + paddingEnd + paint.fontSpacing) > measuredWidth) {
            textSize--
            paint.textSize = textSize
            paint.getTextBounds(biggestWord, 0, biggestWord.length, bounds)
            shouldResize = true
        }
        if (shouldResize) {
            setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
        }
    }
}

How to Use slideDown (or show) function on a table row?

I'm a bit behind the times on answering this, but I found a way to do it :)

function eventinfo(id) {
    tr = document.getElementById("ei"+id);
    div = document.getElementById("d"+id);
    if (tr.style.display == "none") {
        tr.style.display="table-row";
        $(div).slideDown('fast');
    } else {
        $(div).slideUp('fast');
        setTimeout(function(){tr.style.display="none";}, 200);
    }
}

I just put a div element inside the table data tags. when it is set visible, as the div expands, the whole row comes down. then tell it to fade back up (then timeout so you see the effect) before hiding the table row again :)

Hope this helps someone!

HTML Table width in percentage, table rows separated equally

Use the property table-layout:fixed; on the table to get equally spaced cells. If a column has a width set, then no matter what the content is, it will be the specified width. Columns without a width set will divide whatever room is left over among themselves.

<table style='table-layout:fixed;'>
    <tbody>
        <tr>
            <td>gobble de gook</td>
            <td>mibs</td>
        </tr>
    </tbody>
</table>

Just to throw it out there, you could also use <colgroup><col span='#' style='width:#%;'/></colgroup>, which doesn't require repetition of style per table data or giving the table an id to use in a style sheet. I think setting the widths on the first row is enough though.

working with negative numbers in python

Too hard? Your TA is... well, the phrase would probably get me banned. Anyways, check to see if numb is negative. If it is then multiply numa by -1 and do numb = abs(numb). Then do the loop.

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

Based on Cameron's initial answer, here is what I've just added at my enhanced version of SilverFlow library's FloatingWindowHost (copying from FloatingWindowHost.cs at http://clipflair.codeplex.com source code)

    public int MaxZIndex
    {
      get {
        return FloatingWindows.Aggregate(-1, (maxZIndex, window) => {
          int w = Canvas.GetZIndex(window);
          return (w > maxZIndex) ? w : maxZIndex;
        });
      }
    }

    private void SetTopmost(UIElement element)
    {
        if (element == null)
            throw new ArgumentNullException("element");

        Canvas.SetZIndex(element, MaxZIndex + 1);
    }

Worth noting regarding the code above that Canvas.ZIndex is an attached property available for UIElements in various containers, not just used when being hosted in a Canvas (see Controlling rendering order (ZOrder) in Silverlight without using the Canvas control). Guess one could even make a SetTopmost and SetBottomMost static extension method for UIElement easily by adapting this code.

Get selected text from a drop-down list (select box) using jQuery

This work for me:

$("#city :selected").text();

I'm using jQuery 1.10.2

Why is the time complexity of both DFS and BFS O( V + E )

DFS(analysis):

  • Setting/getting a vertex/edge label takes O(1) time
  • Each vertex is labeled twice
    • once as UNEXPLORED
    • once as VISITED
  • Each edge is labeled twice
    • once as UNEXPLORED
    • once as DISCOVERY or BACK
  • Method incidentEdges is called once for each vertex
  • DFS runs in O(n + m) time provided the graph is represented by the adjacency list structure
  • Recall that Sv deg(v) = 2m

BFS(analysis):

  • Setting/getting a vertex/edge label takes O(1) time
  • Each vertex is labeled twice
    • once as UNEXPLORED
    • once as VISITED
  • Each edge is labeled twice
    • once as UNEXPLORED
    • once as DISCOVERY or CROSS
  • Each vertex is inserted once into a sequence Li
  • Method incidentEdges is called once for each vertex
  • BFS runs in O(n + m) time provided the graph is represented by the adjacency list structure
  • Recall that Sv deg(v) = 2m

Linq Select Group By

This will give you sequence of anonymous objects, containing date string and two properties with average price:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new { 
               LogDate = g.Key,
               AvgGoldPrice = (int)g.Average(x => x.GoldPrice), 
               AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
            };

If you need to get list of PriceLog objects:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new PriceLog { 
               LogDateTime = DateTime.Parse(g.Key),
               GoldPrice = (int)g.Average(x => x.GoldPrice), 
               SilverPrice = (int)g.Average(x => x.SilverPrice)
            };

How can I check if a scrollbar is visible?

This expands on @Reigel's answer. It will return an answer for horizontal or vertical scrollbars.

(function($) {
    $.fn.hasScrollBar = function() {
        var e = this.get(0);
        return {
            vertical: e.scrollHeight > e.clientHeight,
            horizontal: e.scrollWidth > e.clientWidth
        };
    }
})(jQuery);

Example:

element.hasScrollBar()             // Returns { vertical: true/false, horizontal: true/false }
element.hasScrollBar().vertical    // Returns true/false
element.hasScrollBar().horizontal  // Returns true/false

How to create a static library with g++?

You can create a .a file using the ar utility, like so:

ar crf lib/libHeader.a header.o

lib is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a in the directory lib. So, in your current directory, do:

mkdir lib

Then run the above ar command.

When linking all libraries, you can do it like so:

g++ test.o -L./lib -lHeader -o test  

The -L flag will get g++ to add the lib/ directory to the path. This way, g++ knows what directory to search when looking for libHeader. -llibHeader flags the specific library to link.

where test.o is created like so:

g++ -c test.cpp -o test.o 

Circle-Rectangle collision detection (intersection)

For those have to calculate Circle/Rectangle collision in Geographic Coordinates with SQL,
this is my implementation in oracle 11 of e.James suggested algorithm.

In input it requires circle coordinates, circle radius in km and two vertices coordinates of the rectangle:

CREATE OR REPLACE FUNCTION "DETECT_CIRC_RECT_COLLISION"
(
    circleCenterLat     IN NUMBER,      -- circle Center Latitude
    circleCenterLon     IN NUMBER,      -- circle Center Longitude
    circleRadius        IN NUMBER,      -- circle Radius in KM
    rectSWLat           IN NUMBER,      -- rectangle South West Latitude
    rectSWLon           IN NUMBER,      -- rectangle South West Longitude
    rectNELat           IN NUMBER,      -- rectangle North Est Latitude
    rectNELon           IN NUMBER       -- rectangle North Est Longitude
)
RETURN NUMBER
AS
    -- converts km to degrees (use 69 if miles)
    kmToDegreeConst     NUMBER := 111.045;

    -- Remaining rectangle vertices 
    rectNWLat   NUMBER;
    rectNWLon   NUMBER;
    rectSELat   NUMBER;
    rectSELon   NUMBER;

    rectHeight  NUMBER;
    rectWIdth   NUMBER;

    circleDistanceLat   NUMBER;
    circleDistanceLon   NUMBER;
    cornerDistanceSQ    NUMBER;

BEGIN
    -- Initialization of remaining rectangle vertices  
    rectNWLat := rectNELat;
    rectNWLon := rectSWLon;
    rectSELat := rectSWLat;
    rectSELon := rectNELon;

    -- Rectangle sides length calculation
    rectHeight := calc_distance(rectSWLat, rectSWLon, rectNWLat, rectNWLon);
    rectWidth := calc_distance(rectSWLat, rectSWLon, rectSELat, rectSELon);

    circleDistanceLat := abs( (circleCenterLat * kmToDegreeConst) - ((rectSWLat * kmToDegreeConst) + (rectHeight/2)) );
    circleDistanceLon := abs( (circleCenterLon * kmToDegreeConst) - ((rectSWLon * kmToDegreeConst) + (rectWidth/2)) );

    IF circleDistanceLon > ((rectWidth/2) + circleRadius) THEN
        RETURN -1;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    IF circleDistanceLat > ((rectHeight/2) + circleRadius) THEN
        RETURN -1;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    IF circleDistanceLon <= (rectWidth/2) THEN
        RETURN 0;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    IF circleDistanceLat <= (rectHeight/2) THEN
        RETURN 0;   --  -1 => NO Collision ; 0 => Collision Detected
    END IF;


    cornerDistanceSQ := POWER(circleDistanceLon - (rectWidth/2), 2) + POWER(circleDistanceLat - (rectHeight/2), 2);

    IF cornerDistanceSQ <=  POWER(circleRadius, 2) THEN
        RETURN 0;  --  -1 => NO Collision ; 0 => Collision Detected
    ELSE
        RETURN -1;  --  -1 => NO Collision ; 0 => Collision Detected
    END IF;

    RETURN -1;  --  -1 => NO Collision ; 0 => Collision Detected
END;    

jquery save json data object in cookie

With serialize the data as JSON and Base64, dependency jquery.cookie.js :

var putCookieObj = function(key, value) {
    $.cookie(key, btoa(JSON.stringify(value)));
}

var getCookieObj = function (key) {
    var cookie = $.cookie(key);
    if (typeof cookie === "undefined") return null;
    return JSON.parse(atob(cookie));
}

:)

Change background colour for Visual Studio

This is the only one right answer on this whole page as people answered about "Visual Studio", not "Visual Studio Code":

To change color theme in "Visual Studio Code", use:

File -> Preferences -> Color Theme -> select any color theme you like

You can also download other custom themes as extensions. To do that, open extensions tab on sidebar and type "theme" into the search field to filter extensions only to themes related ones. Click any you like, click "download" and then "install". After installation and restarting VSC, you can find newly installed themes next to default themes in the same place:

File -> Preferences -> Color Theme -> select newly downloaded color theme

PS - Microsoft made bad naming decision by calling this new editor Visual Studio Code, it's terrible how many wrong links we have in google and stackoverflow. They should rename it to VSCode or something.

IF - ELSE IF - ELSE Structure in Excel

When FIND returns #VALUE!, it is an error, not a string, so you can't compare FIND(...) with "#VALUE!", you need to check if FIND returns an error with ISERROR. Also FIND can work on multiple characters.

So a simplified and working version of your formula would be:

=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))

Or, to remove the double negations:

=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")

Error occurred during initialization of boot layer FindException: Module not found

I faced same problem when I updated the Java version to 12.x. I was executing my project through Eclipse IDE. I am not sure whether this error is caused by compatibility issues.

However, I removed 12.x from my system and installed 8.x and my project started working fine.

Asynchronously load images with jQuery

No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:

var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
    .on('load', function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            alert('broken image!');
        } else {
            $("#something").append(img);
        }
    });

Fast Linux file count for a large number of files

The first 10 directories with the highest number of files.

dir=/ ; for i in $(ls -1 ${dir} | sort -n) ; { echo "$(find ${dir}${i} \
    -type f | wc -l) => $i,"; } | sort -nr | head -10

Powershell: How can I stop errors from being displayed in a script?

Windows PowerShell provides two mechanisms for reporting errors: one mechanism for terminating errors and another mechanism for non-terminating errors.

Internal CmdLets code can call a ThrowTerminatingError method when an error occurs that does not or should not allow the cmdlet to continue to process its input objects. The script writter can them use exception to catch these error.

EX :

try
{
  Your database code
}
catch
{
  Error reporting/logging
}

Internal CmdLets code can call a WriteError method to report non-terminating errors when the cmdlet can continue processing the input objects. The script writer can then use -ErrorAction option to hide the messages, or use the $ErrorActionPreference to setup the entire script behaviour.

How to get a unix script to run every 15 seconds?

Won't running this in the background do it?

#!/bin/sh
while [ 1 ]; do
    echo "Hell yeah!" &
    sleep 15
done

This is about as efficient as it gets. The important part only gets executed every 15 seconds and the script sleeps the rest of the time (thus not wasting cycles).

Set a div width, align div center and text align left

All of these answers should suffice. However if you don't have a defined width, auto margins will not work.

I have found this nifty little trick to centre some of the more stubborn elements (Particularly images).

.div {
   position: absolute;
   left: 0;
   right: 0;
   margin-left: 0;
   margin-right: 0;
}

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

try this too

pd.set_option("max_columns", None) # show all cols
pd.set_option('max_colwidth', None) # show full width of showing cols
pd.set_option("expand_frame_repr", False) # print cols side by side as it's supposed to be

How to query a MS-Access Table from MS-Excel (2010) using VBA

Option Explicit

Const ConnectionStrngAccessPW As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB-PW.accdb;
Jet OLEDB:Database Password=123pass;"

Const ConnectionStrngAccess As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB.accdb;
Persist Security Info=False;"

'C:\Users\BARON\Desktop\Test.accdb

Sub ModifyingExistingDataOnAccessDB()

    Dim TableConn As ADODB.Connection
    Dim TableData As ADODB.Recordset


    Set TableConn = New ADODB.Connection
    Set TableData = New ADODB.Recordset

    TableConn.ConnectionString = ConnectionStrngAccess

    TableConn.Open

On Error GoTo CloseConnection

    With TableData
        .ActiveConnection = TableConn
        '.Source = "SELECT Emp_Age FROM Roster WHERE Emp_Age > 40;"
        .Source = "Roster"
        .LockType = adLockOptimistic
        .CursorType = adOpenForwardOnly
        .Open
        On Error GoTo CloseRecordset

            Do Until .EOF
                If .Fields("Emp_Age").Value > 40 Then
                    .Fields("Emp_Age").Value = 40
                    .Update
                End If
                .MoveNext
            Loop
            .MoveFirst

        MsgBox "Update Complete"
    End With


CloseRecordset:
    TableData.CancelUpdate
    TableData.Close

CloseConnection:
    TableConn.Close

    Set TableConn = Nothing
    Set TableData = Nothing

End Sub

Sub AddingDataToAccessDB()

    Dim TableConn As ADODB.Connection
    Dim TableData As ADODB.Recordset
    Dim r As Range

    Set TableConn = New ADODB.Connection
    Set TableData = New ADODB.Recordset

    TableConn.ConnectionString = ConnectionStrngAccess

    TableConn.Open

On Error GoTo CloseConnection

    With TableData
        .ActiveConnection = TableConn
        .Source = "Roster"
        .LockType = adLockOptimistic
        .CursorType = adOpenForwardOnly
        .Open
        On Error GoTo CloseRecordset

        Sheet3.Activate
        For Each r In Range("B3", Range("B3").End(xlDown))

            MsgBox "Adding " & r.Offset(0, 1)
            .AddNew
            .Fields("Emp_ID").Value = r.Offset(0, 0).Value
            .Fields("Emp_Name").Value = r.Offset(0, 1).Value
            .Fields("Emp_DOB").Value = r.Offset(0, 2).Value
            .Fields("Emp_SOD").Value = r.Offset(0, 3).Value
            .Fields("Emp_EOD").Value = r.Offset(0, 4).Value
            .Fields("Emp_Age").Value = r.Offset(0, 5).Value
            .Fields("Emp_Gender").Value = r.Offset(0, 6).Value
            .Update

        Next r

        MsgBox "Update Complete"
    End With


CloseRecordset:
    TableData.Close

CloseConnection:
    TableConn.Close

    Set TableConn = Nothing
    Set TableData = Nothing

End Sub

Is it safe to delete a NULL pointer?

I have experienced that it is not safe (VS2010) to delete[] NULL (i.e. array syntax). I'm not sure whether this is according to the C++ standard.

It is safe to delete NULL (scalar syntax).

How to run a command as a specific user in an init script?

If you have start-stop-daemon

start-stop-daemon --start --quiet -u username -g usergroup --exec command ...

How to iterate through XML in Powershell?

PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}

Or shorter

[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
  % {$_.Node.'#text'}

How to convert int to char with leading zeros?

Not very elegant, but I add a set value with the same number of leading zeroes I desire to the numeric I want to convert, and use RIGHT function.

Example:

SELECT RIGHT(CONVERT(CHAR(7),1000000 + @number2),6)

Result: '000867'

Where does Anaconda Python install on Windows?

Open the Anaconda Prompt and type:

> where python

Location of hibernate.cfg.xml in project?

This is an reality example when customize folder structure: Folder structure, and initialize class HibernateUtil

enter image description here

with:

return new Configuration().configure("/config/hibernate.cfg.xml").buildSessionFactory();

mapping: enter image description here


with customize entities mapping files:

        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <mapping class="com.vy.entities.Users"/>
        <mapping class="com.vy.entities.Post"/>
        <mapping resource="config/Users.hbm.xml"/>      
        <mapping resource="config/Post.hbm.xml"/>               
    </session-factory>
</hibernate-configuration>

(Note: Simplest way, if you follow default way, it means put all xml config files inside src folder, when build sessionFactory, only:

return new Configuration().configure().buildSessionFactory();

)

Fatal error: Call to undefined function pg_connect()

install the package needed. if you use yum:

yum search pgsql

then look at the result and find anything that is something like 'php-pgsql' or something like that. copy the name and then:

yum install *paste the name of the package here*

Where are logs located?

You should be checking the root directory and not the app directory.

Look in $ROOT/storage/laravel.log not app/storage/laravel.log, where root is the top directory of the project.

Best way to restrict a text field to numbers only?

Here is my solution: a combination of the working ones below.

var checkInput = function(e) {
        if (!e) {
            e = window.event;
        }

        var code = e.keyCode || e.which;

        if (!e.ctrlKey) {

            //46, 8, 9, 27, 13 = backspace, delete, tab, escape, and enter
            if (code == 8 || code == 13 || code == 9 || code == 27 || code == 46)
                return true;
            //35..39 - home, end, left, right
            if (code >= 35 && code <= 39)
                return true;
            //numpad numbers
            if (code >= 96 && code <= 105)
                return true;
            //keyboard numbers
            if (isNaN(parseInt(String.fromCharCode(code), 10))) {
                e.preventDefault();
                return false;
            }
        }
        return true;
    };

How to set host_key_checking=false in ansible inventory file?

I could not use:

ansible_ssh_common_args='-o StrictHostKeyChecking=no'

in inventory file. It seems ansible does not consider this option in my case (ansible 2.0.1.0 from pip in ubuntu 14.04)

I decided to use:

server ansible_host=192.168.1.1 ansible_ssh_common_args= '-o UserKnownHostsFile=/dev/null'

It helped me.

Also you could set this variable in group instead for each host:

[servers_group:vars]
ansible_ssh_common_args='-o UserKnownHostsFile=/dev/null'

Using jQuery to compare two arrays of Javascript objects

Change array to string and compare

var arr = [1,2,3], 
arr2 = [1,2,3]; 
console.log(arr.toString() === arr2.toString());

Is it a good practice to use try-except-else in Python?

OP, YOU ARE CORRECT. The else after try/except in Python is ugly. it leads to another flow-control object where none is needed:

try:
    x = blah()
except:
    print "failed at blah()"
else:
    print "just succeeded with blah"

A totally clear equivalent is:

try:
    x = blah()
    print "just succeeded with blah"
except:
    print "failed at blah()"

This is far clearer than an else clause. The else after try/except is not frequently written, so it takes a moment to figure what the implications are.

Just because you CAN do a thing, doesn't mean you SHOULD do a thing.

Lots of features have been added to languages because someone thought it might come in handy. Trouble is, the more features, the less clear and obvious things are because people don't usually use those bells and whistles.

Just my 5 cents here. I have to come along behind and clean up a lot of code written by 1st-year out of college developers who think they're smart and want to write code in some uber-tight, uber-efficient way when that just makes it a mess to try and read / modify later. I vote for readability every day and twice on Sundays.

How can I get device ID for Admob

  • Is your app published on Play store -- with live ads:

If your app is on Play store showing live ads -- you can't use live ads for testing -- add your device ID in code to get test ads from Admob on your real device. Never use live ads during development or testing.

To get real device ID in logcat,

  1. Connect your device in USB debug mode to Android Studio

USB debug mode(Developer option)

  1. Open any app on your device which shows live ads from Admob: On the connected device, if you have your app downloaded from play store(showing live ads) open that app or else open any other app that shows live Admob ads. Your device should have an internet connection.

  2. Filter the logcat with 'device' as shown below to get test device

Test Device ID in logcat

Read Admob ad testing on device - device IDs can change for more

how to kill hadoop jobs

An unhandled exception will (assuming it's repeatable like bad data as opposed to read errors from a particular data node) eventually fail the job anyway.

You can configure the maximum number of times a particular map or reduce task can fail before the entire job fails through the following properties:

  • mapred.map.max.attempts - The maximum number of attempts per map task. In other words, framework will try to execute a map task these many number of times before giving up on it.
  • mapred.reduce.max.attempts - Same as above, but for reduce tasks

If you want to fail the job out at the first failure, set this value from its default of 4 to 1.

ESLint not working in VS Code?

I use Use Prettier Formatter and ESLint VS Code extension together for code linting and formating.

enter image description here

enter image description here

now install some packages using given command, if more packages required they will show with installation command as an error in the terminal for you, please install them also.

npm i eslint prettier eslint@^5.16.0 eslint-config-prettier eslint-plugin-prettier eslint-config-airbnb eslint-plugin-node eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks@^2.5.0 --save-dev

now create a new file name .prettierrc in your project home directory, using this file you can configure settings of the prettier extension, my settings are below:

{
  "singleQuote": true
}

now as for the ESlint you can configure it according to your requirement, I am advising you to go Eslint website see the rules (https://eslint.org/docs/rules/)

Now create a file name .eslintrc.json in your project home directory, using that file you can configure eslint, my configurations are below:

{
  "extends": ["airbnb", "prettier", "plugin:node/recommended"],
  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error",
    "spaced-comment": "off",
    "no-console": "warn",
    "consistent-return": "off",
    "func-names": "off",
    "object-shorthand": "off",
    "no-process-exit": "off",
    "no-param-reassign": "off",
    "no-return-await": "off",
    "no-underscore-dangle": "off",
    "class-methods-use-this": "off",
    "prefer-destructuring": ["error", { "object": true, "array": false }],
    "no-unused-vars": ["error", { "argsIgnorePattern": "req|res|next|val" }]
  }
}

Difference between FetchType LAZY and EAGER in Java Persistence API?

Both FetchType.LAZY and FetchType.EAGER are used to define the default fetch plan.

Unfortunately, you can only override the default fetch plan for LAZY fetching. EAGER fetching is less flexible and can lead to many performance issues.

My advice is to restrain the urge of making your associations EAGER because fetching is a query-time responsibility. So all your queries should use the fetch directive to only retrieve what's necessary for the current business case.

How to check for registry value using VbScript

   function readFromRegistry (strRegistryKey, strDefault )
    Dim WSHShell, value

    On Error Resume Next
    Set WSHShell = CreateObject("WScript.Shell")
    value = WSHShell.RegRead( strRegistryKey )

    if err.number <> 0 then
        readFromRegistry= strDefault
    else
        readFromRegistry=value
    end if

    set WSHShell = nothing
end function

Usage :

str = readfromRegistry("HKEY_LOCAL_MACHINE\SOFTWARE\Adobe\ESD\Install_Dir", "ha")
wscript.echo "returned " & str

Original post

Can I check if Bootstrap Modal Shown / Hidden?

if($('.modal').hasClass('in')) {
    alert($('.modal .in').attr('id')); //ID of the opened modal
} else {
    alert("No pop-up opened");
}

Difference between ${} and $() in Bash

The syntax is token-level, so the meaning of the dollar sign depends on the token it's in. The expression $(command) is a modern synonym for `command` which stands for command substitution; it means run command and put its output here. So

echo "Today is $(date). A fine day."

will run the date command and include its output in the argument to echo. The parentheses are unrelated to the syntax for running a command in a subshell, although they have something in common (the command substitution also runs in a separate subshell).

By contrast, ${variable} is just a disambiguation mechanism, so you can say ${var}text when you mean the contents of the variable var, followed by text (as opposed to $vartext which means the contents of the variable vartext).

The while loop expects a single argument which should evaluate to true or false (or actually multiple, where the last one's truth value is examined -- thanks Jonathan Leffler for pointing this out); when it's false, the loop is no longer executed. The for loop iterates over a list of items and binds each to a loop variable in turn; the syntax you refer to is one (rather generalized) way to express a loop over a range of arithmetic values.

A for loop like that can be rephrased as a while loop. The expression

for ((init; check; step)); do
    body
done

is equivalent to

init
while check; do
    body
    step
done

It makes sense to keep all the loop control in one place for legibility; but as you can see when it's expressed like this, the for loop does quite a bit more than the while loop.

Of course, this syntax is Bash-specific; classic Bourne shell only has

for variable in token1 token2 ...; do

(Somewhat more elegantly, you could avoid the echo in the first example as long as you are sure that your argument string doesn't contain any % format codes:

date +'Today is %c. A fine day.'

Avoiding a process where you can is an important consideration, even though it doesn't make a lot of difference in this isolated example.)

How can git be installed on CENTOS 5.5?

yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel

Get the required version of GIT from https://www.kernel.org/pub/software/scm/git/ 

wget https://www.kernel.org/pub/software/scm/git/{version.gz}

tar -xzvf git-version.gz

cd git-version

./configure

make

make install

How to send file contents as body entity using cURL

In my case, @ caused some sort of encoding problem, I still prefer my old way:

curl -d "$(cat /path/to/file)" https://example.com

How do I rename the extension for a bunch of files?

This worked for me on OSX from .txt to .txt_bak

find . -name '*.txt' -exec sh -c 'mv "$0" "${0%.txt}.txt_bak"' {} \;

How to group time by hour or by 10 minutes

finally done with

GROUP BY
DATEPART(YEAR, DT.[Date]),
DATEPART(MONTH, DT.[Date]),
DATEPART(DAY, DT.[Date]),
DATEPART(HOUR, DT.[Date]),
(DATEPART(MINUTE, DT.[Date]) / 10)

phantomjs not waiting for "full" page load

Another approach is to just ask PhantomJS to wait for a bit after the page has loaded before doing the render, as per the regular rasterize.js example, but with a longer timeout to allow the JavaScript to finish loading additional resources:

page.open(address, function (status) {
    if (status !== 'success') {
        console.log('Unable to load the address!');
        phantom.exit();
    } else {
        window.setTimeout(function () {
            page.render(output);
            phantom.exit();
        }, 1000); // Change timeout as required to allow sufficient time 
    }
});

serialize/deserialize java 8 java.time with Jackson JSON mapper

If any one having problem while using SpringBoot here is how I fixed the issue without adding new dependency.

In Spring 2.1.3 Jackson expects date string 2019-05-21T07:37:11.000 in this yyyy-MM-dd HH:mm:ss.SSS format to de-serialize in LocalDateTime. Make sure date string separates the date and time with T not with space. seconds (ss) and milliseconds(SSS) could be ommitted.

@JsonProperty("last_charge_date")
public LocalDateTime lastChargeDate;

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

For Android Studio 3.2.1 Update your

Gradle Version 4.6

Android plugin version 3.2.1

Why does sudo change the PATH?

Er, it's not really a test if you don't add something to your path:

bill@bill-desktop:~$ ls -l /opt/pkg/bin
total 12
-rwxr-xr-x 1 root root   28 2009-01-22 18:58 foo
bill@bill-desktop:~$ which foo
/opt/pkg/bin/foo
bill@bill-desktop:~$ sudo su
root@bill-desktop:/home/bill# which foo
root@bill-desktop:/home/bill# 

Background thread with QThread in PyQt

Based on the Worker objects methods mentioned in other answers, I decided to see if I could expand on the solution to invoke more threads - in this case the optimal number the machine can run and spin up multiple workers with indeterminate completion times. To do this I still need to subclass QThread - but only to assign a thread number and to 'reimplement' the signals 'finished' and 'started' to include their thread number.

I've focused quite a bit on the signals between the main gui, the threads, and the workers.

Similarly, others answers have been a pains to point out not parenting the QThread but I don't think this is a real concern. However, my code also is careful to destroy the QThread objects.

However, I wasn't able to parent the worker objects so it seems desirable to send them the deleteLater() signal, either when the thread function is finished or the GUI is destroyed. I've had my own code hang for not doing this.

Another enhancement I felt was necessary was was reimplement the closeEvent of the GUI (QWidget) such that the threads would be instructed to quit and then the GUI would wait until all the threads were finished. When I played with some of the other answers to this question, I got QThread destroyed errors.

Perhaps it will be useful to others. I certainly found it a useful exercise. Perhaps others will know a better way for a thread to announce it identity.

#!/usr/bin/env python3
#coding:utf-8
# Author:   --<>
# Purpose:  To demonstrate creation of multiple threads and identify the receipt of thread results
# Created: 19/12/15

import sys


from PyQt4.QtCore import QThread, pyqtSlot, pyqtSignal
from PyQt4.QtGui import QApplication, QLabel, QWidget, QGridLayout

import sys
import worker

class Thread(QThread):
    #make new signals to be able to return an id for the thread
    startedx = pyqtSignal(int)
    finishedx = pyqtSignal(int)

    def __init__(self,i,parent=None):
        super().__init__(parent)
        self.idd = i

        self.started.connect(self.starttt)
        self.finished.connect(self.finisheddd)

    @pyqtSlot()
    def starttt(self):
        print('started signal from thread emitted')
        self.startedx.emit(self.idd) 

    @pyqtSlot()
    def finisheddd(self):
        print('finished signal from thread emitted')
        self.finishedx.emit(self.idd)

class Form(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

        self.worker={}
        self.threadx={}
        self.i=0
        i=0

        #Establish the maximum number of threads the machine can optimally handle
        #Generally relates to the number of processors

        self.threadtest = QThread(self)
        self.idealthreadcount = self.threadtest.idealThreadCount()

        print("This machine can handle {} threads optimally".format(self.idealthreadcount))

        while i <self.idealthreadcount:
            self.setupThread(i)
            i+=1

        i=0
        while i<self.idealthreadcount:
            self.startThread(i)
            i+=1

        print("Main Gui running in thread {}.".format(self.thread()))


    def setupThread(self,i):

        self.worker[i]= worker.Worker(i)  # no parent!
        #print("Worker object runningt in thread {} prior to movetothread".format(self.worker[i].thread()) )
        self.threadx[i] = Thread(i,parent=self)  #  if parent isn't specified then need to be careful to destroy thread 
        self.threadx[i].setObjectName("python thread{}"+str(i))
        #print("Thread object runningt in thread {} prior to movetothread".format(self.threadx[i].thread()) )
        self.threadx[i].startedx.connect(self.threadStarted)
        self.threadx[i].finishedx.connect(self.threadFinished)

        self.worker[i].finished.connect(self.workerFinished)
        self.worker[i].intReady.connect(self.workerResultReady)

        #The next line is optional, you may want to start the threads again without having to create all the code again.
        self.worker[i].finished.connect(self.threadx[i].quit)

        self.threadx[i].started.connect(self.worker[i].procCounter)

        self.destroyed.connect(self.threadx[i].deleteLater)
        self.destroyed.connect(self.worker[i].deleteLater)

        #This is the key code that actually get the worker code onto another processor or thread.
        self.worker[i].moveToThread(self.threadx[i])

    def startThread(self,i):
        self.threadx[i].start()

    @pyqtSlot(int)
    def threadStarted(self,i):
        print('Thread {}  started'.format(i))
        print("Thread priority is {}".format(self.threadx[i].priority()))        


    @pyqtSlot(int)
    def threadFinished(self,i):
        print('Thread {} finished'.format(i))




    @pyqtSlot(int)
    def threadTerminated(self,i):
        print("Thread {} terminated".format(i))

    @pyqtSlot(int,int)
    def workerResultReady(self,j,i):
        print('Worker {} result returned'.format(i))
        if i ==0:
            self.label1.setText("{}".format(j))
        if i ==1:
            self.label2.setText("{}".format(j))
        if i ==2:
            self.label3.setText("{}".format(j))
        if i ==3:
            self.label4.setText("{}".format(j)) 

        #print('Thread {} has started'.format(self.threadx[i].currentThreadId()))    

    @pyqtSlot(int)
    def workerFinished(self,i):
        print('Worker {} finished'.format(i))

    def initUI(self):
        self.label1 = QLabel("0")
        self.label2= QLabel("0")
        self.label3= QLabel("0")
        self.label4 = QLabel("0")
        grid = QGridLayout(self)
        self.setLayout(grid)
        grid.addWidget(self.label1,0,0)
        grid.addWidget(self.label2,0,1) 
        grid.addWidget(self.label3,0,2) 
        grid.addWidget(self.label4,0,3) #Layout parents the self.labels

        self.move(300, 150)
        self.setGeometry(0,0,300,300)
        #self.size(300,300)
        self.setWindowTitle('thread test')
        self.show()

    def closeEvent(self, event):
        print('Closing')

        #this tells the threads to stop running
        i=0
        while i <self.idealthreadcount:
            self.threadx[i].quit()
            i+=1

         #this ensures window cannot be closed until the threads have finished.
        i=0
        while i <self.idealthreadcount:
            self.threadx[i].wait() 
            i+=1        


        event.accept()


if __name__=='__main__':
    app = QApplication(sys.argv)
    form = Form()
    sys.exit(app.exec_())

And the worker code below

#!/usr/bin/env python3
#coding:utf-8
# Author:   --<>
# Purpose:  Stack Overflow
# Created: 19/12/15

import sys
import unittest


from PyQt4.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import time
import random


class Worker(QObject):
    finished = pyqtSignal(int)
    intReady = pyqtSignal(int,int)

    def __init__(self, i=0):
        '''__init__ is called while the worker is still in the Gui thread. Do not put slow or CPU intensive code in the __init__ method'''

        super().__init__()
        self.idd = i



    @pyqtSlot()
    def procCounter(self): # This slot takes no params
        for j in range(1, 10):
            random_time = random.weibullvariate(1,2)
            time.sleep(random_time)
            self.intReady.emit(j,self.idd)
            print('Worker {0} in thread {1}'.format(self.idd, self.thread().idd))

        self.finished.emit(self.idd)


if __name__=='__main__':
    unittest.main()

How to set text color in submit button?

Use this CSS:

color: red;

that's all.

PHP json_decode() returns NULL with valid JSON?

I had the same problem and I solved it simply by replacing the quote character before decode.

$json = str_replace('&quot;', '"', $json);
$object = json_decode($json);

My JSON value was generated by JSON.stringify function.

How to print the full NumPy array, without truncation?

You can use the array2string function - docs.

a = numpy.arange(10000).reshape(250,40)
print(numpy.array2string(a, threshold=numpy.nan, max_line_width=numpy.nan))
# [Big output]

Text blinking jQuery

You can try the jQuery UI Pulsate effect:

http://docs.jquery.com/UI/Effects/Pulsate

JQuery DatePicker ReadOnly

Sorry, but Eduardos solution did not work for me. At the end, I realized that disabled datepicker is just a read-only textbox. So you should make it read only and destroy the datepicker. Field will be sent to server upon submit.

Here is a bit generalized code that takes multiple textboxes and makes them read only. It will strip off the datepickers as well.

fields.attr("readonly", "readonly");
fields.each(function(idx, fld) {
    if($(fld).hasClass('hasDatepicker'))
    {
        $(fld).datepicker("destroy");
    }
});

how to delete a specific row in codeigniter?

It will come in the url so you can get it by two ways. Fist one

<td><?php echo anchor('textarea/delete_row', 'DELETE', 'id="$row->id"'); ?></td>
$id = $this->input->get('id');

2nd one.

$id = $this->uri->segment(3);

But in the second method you have to count the no. of segments in the url that on which no. your id come. 2,3,4 etc. then you have to pass. then in the ();

Create Hyperlink in Slack

python

x = "http://xxxxxx"
y = "text title"
text_link = '<{}|{}>'.format(x,y)

post text_link in using python slack client

How to set selected value on select using selectpicker plugin from bootstrap

$('.selectpicker').selectpicker('val', YOUR_VALUE);

How to set background color of view transparent in React Native

Surprisingly no one told about this, which provides some !clarity:

style={{
backgroundColor: 'white',
opacity: 0.7
}}

how to display full stored procedure code?

You can also get by phpPgAdmin if you are configured it in your system,

Step 1: Select your database

Step 2: Click on find button

Step 3: Change search option to functions then click on Find.

You will get the list of defined functions.You can search functions by name also, hope this answer will help others.

What is the difference between cache and persist?

There is no difference. From RDD.scala.

/** Persist this RDD with the default storage level (`MEMORY_ONLY`). */
def persist(): this.type = persist(StorageLevel.MEMORY_ONLY)

/** Persist this RDD with the default storage level (`MEMORY_ONLY`). */
def cache(): this.type = persist()

What's the difference between "app.render" and "res.render" in express.js?

Here are some differences:

  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

jQuery - getting custom attribute from selected option

You're pretty close:

var myTag = $(':selected', element).attr("myTag");

TypeError: tuple indices must be integers, not str

Like the error says, row is a tuple, so you can't do row["pool_number"]. You need to use the index: row[0].

Get the selected value in a dropdown using jQuery.

$('#availability').find('option:selected').val() // For Value 
$('#availability').find('option:selected').text() // For Text
or 
$('#availability option:selected').val() // For Value 
$('#availability option:selected').text() // For Text

What is the $$hashKey added to my JSON.stringify result

It comes with the ng-repeat directive usually. To do dom manipulation AngularJS flags objects with special id.

This is common with Angular. For example if u get object with ngResource your object will embed all the resource API and you'll see methods like $save, etc. With cookies too AngularJS will add a property __ngDebug.

adb connection over tcp not working now

Just a tiny update with built-in wireless debugging in Android 11:

  • Go to Developer options > Wireless debugging
  • Enable > allow
  • Pair device with pairing code, a new port and pairing code generated and shown
  • adb pair [IP_ADDRESS]:[PORT] and type pairing code.
  • done

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

Correct way of getting Client's IP Addresses from http.Request

Looking at http.Request you can find the following member variables:

// HTTP defines that header names are case-insensitive.
// The request parser implements this by canonicalizing the
// name, making the first character and any characters
// following a hyphen uppercase and the rest lowercase.
//
// For client requests certain headers are automatically
// added and may override values in Header.
//
// See the documentation for the Request.Write method.
Header Header

// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request, usually for
// logging. This field is not filled in by ReadRequest and
// has no defined format. The HTTP server in this package
// sets RemoteAddr to an "IP:port" address before invoking a
// handler.
// This field is ignored by the HTTP client.
RemoteAddr string

You can use RemoteAddr to get the remote client's IP address and port (the format is "IP:port"), which is the address of the original requestor or the last proxy (for example a load balancer which lives in front of your server).

This is all you have for sure.

Then you can investigate the headers, which are case-insensitive (per documentation above), meaning all of your examples will work and yield the same result:

req.Header.Get("X-Forwarded-For") // capitalisation
req.Header.Get("x-forwarded-for") // doesn't
req.Header.Get("X-FORWARDED-FOR") // matter

This is because internally http.Header.Get will normalise the key for you. (If you want to access header map directly, and not through Get, you would need to use http.CanonicalHeaderKey first.)

Finally, "X-Forwarded-For" is probably the field you want to take a look at in order to grab more information about client's IP. This greatly depends on the HTTP software used on the remote side though, as client can put anything in there if it wishes to. Also, note the expected format of this field is the comma+space separated list of IP addresses. You will need to parse it a little bit to get a single IP of your choice (probably the first one in the list), for example:

// Assuming format is as expected
ips := strings.Split("10.0.0.1, 10.0.0.2, 10.0.0.3", ", ")
for _, ip := range ips {
    fmt.Println(ip)
}

will produce:

10.0.0.1
10.0.0.2
10.0.0.3

How do I copy a hash in Ruby?

If you're using Rails you can do:

h1 = h0.deep_dup

http://apidock.com/rails/Hash/deep_dup

How to delete all files and folders in a directory?

In Windows 7, if you have just created it manually with Windows Explorer, the directory structure is similar to this one:

C:
  \AAA
    \BBB
      \CCC
        \DDD

And running the code suggested in the original question to clean the directory C:\AAA, the line di.Delete(true) always fails with IOException "The directory is not empty" when trying to delete BBB. It is probably because of some kind of delays/caching in Windows Explorer.

The following code works reliably for me:

static void Main(string[] args)
{
    DirectoryInfo di = new DirectoryInfo(@"c:\aaa");
    CleanDirectory(di);
}

private static void CleanDirectory(DirectoryInfo di)
{
    if (di == null)
        return;

    foreach (FileSystemInfo fsEntry in di.GetFileSystemInfos())
    {
        CleanDirectory(fsEntry as DirectoryInfo);
        fsEntry.Delete();
    }
    WaitForDirectoryToBecomeEmpty(di);
}

private static void WaitForDirectoryToBecomeEmpty(DirectoryInfo di)
{
    for (int i = 0; i < 5; i++)
    {
        if (di.GetFileSystemInfos().Length == 0)
            return;
        Console.WriteLine(di.FullName + i);
        Thread.Sleep(50 * i);
    }
}

How to install 2 Anacondas (Python 2 and 3) on Mac OS

There is no need to install Anaconda again. Conda, the package manager for Anaconda, fully supports separated environments. The easiest way to create an environment for Python 2.7 is to do

conda create -n python2 python=2.7 anaconda

This will create an environment named python2 that contains the Python 2.7 version of Anaconda. You can activate this environment with

source activate python2

This will put that environment (typically ~/anaconda/envs/python2) in front in your PATH, so that when you type python at the terminal it will load the Python from that environment.

If you don't want all of Anaconda, you can replace anaconda in the command above with whatever packages you want. You can use conda to install packages in that environment later, either by using the -n python2 flag to conda, or by activating the environment.

ng: command not found while creating new project using angular-cli

If you are working in windows 7 and you can not run command start with ng

please, update the angular/CLI at once and try to use ng commands

use below comman to update latest CLI

npm install -g @angular/cli@latest

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Actually the answer to the first part of the question is "Yes" in every programming language. For example, this is in the case of C/C++:

#define a   (b++)
int b = 1;
if (a ==1 && a== 2 && a==3) {
    std::cout << "Yes, it's possible!" << std::endl;
} else {
    std::cout << "it's impossible!" << std::endl;
}

How do I concatenate a boolean to a string in Python?

answer = True

myvar = 'the answer is ' + str(answer) #since answer variable is in boolean format, therefore, we have to convert boolean into string format which can be easily done using this

print(myvar)

I need to learn Web Services in Java. What are the different types in it?

Q1) Here are couple things to read or google more :

Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest

It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.

Q2) Here are couple of good tutorials for soap (I had them bookmarked) :

http://united-coders.com/phillip-steffensen/developing-a-simple-soap-webservice-using-spring-301-and-apache-cxf-226

http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/

http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html

Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.

SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.

Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).

Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.

If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development. It's fantastic, not hard to read and not too big either (win win).

How to strip comma in Python string

You want to replace it, not strip it:

s = s.replace(',', '')

Spring Data and Native Query with pagination

This is a hack for program using Spring Data JPA before Version 2.0.4.

Code has worked with PostgreSQL and MySQL :

public interface UserRepository extends JpaRepository<User, Long> {

@Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1 ORDER BY ?#{#pageable}",
       countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
       nativeQuery = true)
   Page<User> findByLastname(String lastname, Pageable pageable);   
}

ORDER BY ?#{#pageable} is for Pageable. countQuery is for Page<User>.

File uploading with Express 4.0: req.files undefined

1) Make sure that your file is really sent from the client side. For example you can check it in Chrome Console: screenshot

2) Here is the basic example of NodeJS backend:

const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();

app.use(fileUpload()); // Don't forget this line!

app.post('/upload', function(req, res) {
   console.log(req.files);
   res.send('UPLOADED!!!');
});

Stop floating divs from wrapping

For me (using bootstrap), only thing that worked was setting display:absolute;z-index:1 on the last cell.

Whats the CSS to make something go to the next line in the page?

Have the element display as a block:

display: block;

Convert integer into byte array (Java)

You can use BigInteger:

From Integers:

byte[] array = BigInteger.valueOf(0xAABBCCDD).toByteArray();
System.out.println(Arrays.toString(array))
// --> {-86, -69, -52, -35 }

The returned array is of the size that is needed to represent the number, so it could be of size 1, to represent 1 for example. However, the size cannot be more than four bytes if an int is passed.

From Strings:

BigInteger v = new BigInteger("AABBCCDD", 16);
byte[] array = v.toByteArray();

However, you will need to watch out, if the first byte is higher 0x7F (as is in this case), where BigInteger would insert a 0x00 byte to the beginning of the array. This is needed to distinguish between positive and negative values.

Using CSS to align a button bottom of the screen using relative positions

<button style="position: absolute; left: 20%; right: 20%; bottom: 5%;"> Button </button>

Missing Microsoft RDLC Report Designer in Visual Studio

Update: The way RDLC Report Designer is installed has changed with Visual Studio 2017 and newer. See other answers for details. Besides that, the ReportViewer Control is now available through NuGet, see here.


original answer below

The Report Designer is part of the Microsoft SQL Server Data Tools.

You can add it using the Visual Studio setup (Programs and Features > Visual Studio 2015 > Change)

screenshot

What is the idiomatic Go equivalent of C's ternary operator?

Foreword: Without arguing that if else is the way to go, we can still play with and find pleasure in language-enabled constructs.

The following If construct is available in my github.com/icza/gox library with lots of other methods, being the gox.If type.


Go allows to attach methods to any user-defined types, including primitive types such as bool. We can create a custom type having bool as its underlying type, and then with a simple type conversion on the condition, we have access to its methods. Methods that receive and select from the operands.

Something like this:

type If bool

func (c If) Int(a, b int) int {
    if c {
        return a
    }
    return b
}

How can we use it?

i := If(condition).Int(val1, val2)  // Short variable declaration, i is of type int
     |-----------|  \
   type conversion   \---method call

For example a ternary doing max():

i := If(a > b).Int(a, b)

A ternary doing abs():

i := If(a >= 0).Int(a, -a)

This looks cool, it's simple, elegant, and efficient (it's also eligible for inlining).

One downside compared to a "real" ternary operator: it always evaluates all operands.

To achieve deferred and only-if-needed evaluation, the only option is to use functions (either declared functions or methods, or function literals), which are only called when / if needed:

func (c If) Fint(fa, fb func() int) int {
    if c {
        return fa()
    }
    return fb()
}

Using it: Let's assume we have these functions to calculate a and b:

func calca() int { return 3 }
func calcb() int { return 4 }

Then:

i := If(someCondition).Fint(calca, calcb)

For example, the condition being current year > 2020:

i := If(time.Now().Year() > 2020).Fint(calca, calcb)

If we want to use function literals:

i := If(time.Now().Year() > 2020).Fint(
    func() int { return 3 },
    func() int { return 4 },
)

Final note: if you would have functions with different signatures, you could not use them here. In that case you may use a function literal with matching signature to make them still applicable.

For example if calca() and calcb() would have parameters too (besides the return value):

func calca2(x int) int { return 3 }
func calcb2(x int) int { return 4 }

This is how you could use them:

i := If(time.Now().Year() > 2020).Fint(
    func() int { return calca2(0) },
    func() int { return calcb2(0) },
)

Try these examples on the Go Playground.

How to convert dd/mm/yyyy string into JavaScript Date object?

I found the default JS date formatting didn't work.

So I used toLocaleString with options

const event = new Date();
const options = { dateStyle: 'short' };
const date = event.toLocaleString('en', options);

to get: DD/MM/YYYY format

See docs for more formatting options: https://www.w3schools.com/jsref/jsref_tolocalestring.asp

Is it possible to remove inline styles with jQuery?

You can set the style using jQuery's css method:

$('something:visible').css('display', 'none');

Convert all strings in a list to int

A little bit more expanded than list comprehension but likewise useful:

def str_list_to_int_list(str_list):
    n = 0
    while n < len(str_list):
        str_list[n] = int(str_list[n])
        n += 1
    return(str_list)

e.g.

>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]

Also:

def str_list_to_int_list(str_list):
    int_list = [int(n) for n in str_list]
    return int_list

Python try-else

Try-except-else is great for combining the EAFP pattern with duck-typing:

try:
  cs = x.cleanupSet
except AttributeError:
  pass
else:
  for v in cs:
    v.cleanup()

You might thing this naïve code is fine:

try:
  for v in x.cleanupSet:
    v.clenaup()
except AttributeError:
  pass

This is a great way of accidentally hiding severe bugs in your code. I typo-ed cleanup there, but the AttributeError that would let me know is being swallowed. Worse, what if I'd written it correctly, but the cleanup method was occasionally being passed a user type that had a misnamed attribute, causing it to silently fail half-way through and leave a file unclosed? Good luck debugging that one.

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

What does "select count(1) from table_name" on any database tables mean?

in oracle i believe these have exactly the same meaning

WP -- Get posts by category?

Create a taxonomy field category (field name = post_category) and import it in your template as shown below:

<?php
          $categ = get_field('post_category');  
          $args = array( 'posts_per_page' => 6,
         'category_name' => $categ->slug );
          $myposts = get_posts( $args );
          foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
            //your code here
          <?php endforeach; 
          wp_reset_postdata();?>

How to parse json string in Android?

Use JSON classes for parsing e.g

JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String  uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");

JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

How to implement a confirmation (yes/no) DialogPreference?

Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below

intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
    Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);

    intentClearCookies.setIntent(clearcookies);
    intentClearCookies.setTitle(R.string.ClearCookies);
    intentClearCookies.setEnabled(true);
    launchPrefCat.addPreference(intentClearCookies);

And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.

public class ClearCookies extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    showDialog();
}

/**
 * @throws NotFoundException
 */
private void showDialog() throws NotFoundException {
    new AlertDialog.Builder(this)
            .setTitle(getResources().getString(R.string.ClearCookies))
            .setMessage(
                    getResources().getString(R.string.ClearCookieQuestion))
            .setIcon(
                    getResources().getDrawable(
                            android.R.drawable.ic_dialog_alert))
            .setPositiveButton(
                    getResources().getString(R.string.PostiveYesButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here

                        }
                    })
            .setNegativeButton(
                    getResources().getString(R.string.NegativeNoButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here
                        }
                    }).show();
}}

As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.

document.getElementById().value and document.getElementById().checked not working for IE

For non-grouped elements, name and id should be same. In this case you gave name as 'sp' and id as 'sp_100'. Don't do that, do it like this:

HTML:

<input type="hidden" id="msg" name="msg" value="" style="display:none"/>
<input type="checkbox" name="sp" value="100" id="sp">

Javascript:

var Msg="abc";
document.getElementById('msg').value = Msg;
document.getElementById('sp').checked = true;

For more details

please visit : http://www.impressivewebs.com/avoiding-problems-with-javascript-getelementbyid-method-in-internet-explorer-7/

Start HTML5 video at a particular position when loading?

You can link directly with Media Fragments URI, just change the filename to file.webm#t=50

Here's an example

This is pretty cool, you can do all sorts of things. But I don't know the current state of browser support.

How to create a trie in Python

Unwind is essentially correct that there are many different ways to implement a trie; and for a large, scalable trie, nested dictionaries might become cumbersome -- or at least space inefficient. But since you're just getting started, I think that's the easiest approach; you could code up a simple trie in just a few lines. First, a function to construct the trie:

>>> _end = '_end_'
>>> 
>>> def make_trie(*words):
...     root = dict()
...     for word in words:
...         current_dict = root
...         for letter in word:
...             current_dict = current_dict.setdefault(letter, {})
...         current_dict[_end] = _end
...     return root
... 
>>> make_trie('foo', 'bar', 'baz', 'barz')
{'b': {'a': {'r': {'_end_': '_end_', 'z': {'_end_': '_end_'}}, 
             'z': {'_end_': '_end_'}}}, 
 'f': {'o': {'o': {'_end_': '_end_'}}}}

If you're not familiar with setdefault, it simply looks up a key in the dictionary (here, letter or _end). If the key is present, it returns the associated value; if not, it assigns a default value to that key and returns the value ({} or _end). (It's like a version of get that also updates the dictionary.)

Next, a function to test whether the word is in the trie:

>>> def in_trie(trie, word):
...     current_dict = trie
...     for letter in word:
...         if letter not in current_dict:
...             return False
...         current_dict = current_dict[letter]
...     return _end in current_dict
... 
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'baz')
True
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'barz')
True
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'barzz')
False
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'bart')
False
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'ba')
False

I'll leave insertion and removal to you as an exercise.

Of course, Unwind's suggestion wouldn't be much harder. There might be a slight speed disadvantage in that finding the correct sub-node would require a linear search. But the search would be limited to the number of possible characters -- 27 if we include _end. Also, there's nothing to be gained by creating a massive list of nodes and accessing them by index as he suggests; you might as well just nest the lists.

Finally, I'll add that creating a directed acyclic word graph (DAWG) would be a bit more complex, because you have to detect situations in which your current word shares a suffix with another word in the structure. In fact, this can get rather complex, depending on how you want to structure the DAWG! You may have to learn some stuff about Levenshtein distance to get it right.

What does [object Object] mean? (JavaScript)

That is because there are different types of objects in Javascript!

For example

  • Function objects:

stringify(function (){}) -> [object Function]

  • Array objects:

stringify([]) -> [object Array]

  • RegExp objects

stringify(/x/) -> [object RegExp]

  • Date objects

stringify(new Date) -> [object Date]

...
  • Object objects!

stringify({}) -> [object Object]

the constructor function is called Object (with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.

When you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.

If you want to see value inside "[Object objects]" use:

console.log(JSON.stringify(result))

taking input of a string word by word

(This is for the benefit of others who may refer)

You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.

#include<iostream>
using namespace std;

main()
{
    char word[50];
    cin>>word;
    while(word){
        //Do stuff with word[]
        cin>>word;
    }
}

How to print (using cout) a number in binary form?

Use on-the-fly conversion to std::bitset. No temporary variables, no loops, no functions, no macros.

Live On Coliru

#include <iostream>
#include <bitset>

int main() {
    int a = -58, b = a>>3, c = -315;

    std::cout << "a = " << std::bitset<8>(a)  << std::endl;
    std::cout << "b = " << std::bitset<8>(b)  << std::endl;
    std::cout << "c = " << std::bitset<16>(c) << std::endl;
}

Prints:

a = 11000110
b = 11111000
c = 1111111011000101

Angular EXCEPTION: No provider for Http

as of RC5 you need to import the HttpModule like so :

import { HttpModule } from '@angular/http';

then include the HttpModule in the imports array as mentioned above by Günter.

Can you have multiline HTML5 placeholder text in a <textarea>?

This can apparently be done by just typing normally,

_x000D_
_x000D_
<textarea name="" id="" placeholder="Hello awesome world. I will break line now

Yup! Line break seems to work."></textarea>
_x000D_
_x000D_
_x000D_

PHP: How can I determine if a variable has a value that is between two distinct constant values?

Try This

if (($val >= 1 && $val <= 10) || ($val >= 20 && $val <= 40))

This will return the value between 1 to 10 & 20 to 40.

How to stop "setInterval"

You have to store the timer id of the interval when you start it, you will use this value later to stop it, using the clearInterval function:

$(function () {
  var timerId = 0;

  $('textarea').focus(function () {
    timerId = setInterval(function () {
      // interval function body
    }, 1000);
  });

  $('textarea').blur(function () {
    clearInterval(timerId);
  });

});

Scale Image to fill ImageView width and keep aspect ratio

I had a similar issue, I found the reason for this is because you need to calculate the dp. Android studio is calculating the ImageView when you load it from the drawable, but when you are using another method, like loading from bitmap the dp is not automatically accounted for,

Here is my xml

<ImageView
  android:id="@+id/imageViewer"
  android:layout_width="match_parent"
  android:layout_height="match_parent"//dp is not automaticly updated, when loading from a other source
  android:scaleType="fitCenter"
  tools:srcCompat="@drawable/a8" />

I'm using Kotlin, and loading drawable from an asset file, here's how I calculate this

val d = Drawable.createFromStream(assets.open("imageData/${imageName}.png"), null)
bitHeight = d.minimumHeight//get the image height
imageViewer.layoutParams.height = (bitHeight * resources.displayMetrics.density).toInt()//set the height
imageViewer.setImageDrawable(d)//set the image from the drawable
imageViewer.requestLayout()//here I apply it to the layout

What does the ELIFECYCLE Node.js error mean?

I had the same error code when I was running npm run build inside node docker container.

Locally it was working while inside a container I had set option to throw error when there is a warning during compilation while locally it wasn't set. So this error can mean anything that is connected with stopping the process being done by NPM

How to get folder path from file path with CMD

I had same problem in my loop where i wanted to extract zip files in the same directory and then delete the zip file. The problem was that 7z requires the output folder, so i had to obtain the folder path of each file. Here is my solution:

FOR /F "usebackq tokens=1" %%i IN (`DIR /S/B *.zip` ) DO (
  7z.exe x %%i -aoa -o%%i\..
) 

%%i was a full filename path and %ii\.. simply returns the parent folder.

hope it helps.

System.Security.SecurityException when writing to Event Log

The solution was to give the "Network Service" account read permission on the EventLog/Security key.

How to remove pip package after deleting it manually

I met the same issue while experimenting with my own Python library and what I've found out is that pip freeze will show you the library as installed if your current directory contains lib.egg-info folder. And pip uninstall <lib> will give you the same error message.

  1. Make sure your current directory doesn't have any egg-info folders
  2. Check pip show <lib-name> to see the details about the location of the library, so you can remove files manually.

how to use font awesome in own css?

you can do so by using the :before or :after pseudo. read more about it here http://astronautweb.co/snippet/font-awesome/

change your code to this

.lb-prev:hover {
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
  opacity: 1;
   text-decoration: none;
}

.lb-prev:before {
    font-family: FontAwesome;
    content: "\f053";
    font-size: 30px;
}

do the same for the other icons. you might want to adjust the color and height of the icons too. anyway here is the fiddle hope this helps

How to create an instance of System.IO.Stream stream

Stream is a base class, you need to create one of the specific types of streams, such as MemoryStream.

How to execute Table valued function

A TVF (table-valued function) is supposed to be SELECTed FROM. Try this:

select * from FN('myFunc')

querying WHERE condition to character length?

Sorry, I wasn't sure which SQL platform you're talking about:

In MySQL:

$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");

in MSSQL

$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");

The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.

Edit

I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.

So, for MySQL there's the CHAR_LENGTH(). The following example highlights the difference between LENGTH() an CHAR_LENGTH():

CREATE TABLE words (
    word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;

INSERT INTO words(word) VALUES('??'), ('happy'), ('hayir');

SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;

+--------+-----------+----------------+
| word   | num_bytes | num_characters |
+--------+-----------+----------------+
| ??    |         6 |              2 |
| happy  |         5 |              5 |
| hayir  |         6 |              5 |
+--------+-----------+----------------+

Be careful if you're dealing with multi-byte characters.

What's the difference between import java.util.*; and import java.util.Date; ?

but what I got is something like this: Date@124bbbf  
while I change the import to: import java.util.Date;  
the code works perfectly, why? 

What do you mean by "works perfectly"? The output of printing a Date object is the same no matter whether you imported java.util.* or java.util.Date. The output that you get when printing objects is the representation of the object by the toString() method of the corresponding class.

Reverse each individual word of "Hello World" string with Java

Know your libraries ;-)

import org.apache.commons.lang.StringUtils;

String reverseWords(String sentence) {
    return StringUtils.reverseDelimited(StringUtils.reverse(sentence), ' ');
}

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

If you're redirect from the JavaScript class

same view - diferent controller

<strike>window.location.href = `'Home'`;</strike>

is not same view

<strike>window.location.href = `'Index/Home'`;</strike>

Post a json object to mvc controller with jquery and ajax

What am I doing incorrectly?

You have to convert html to javascript object, and then as a second step to json throug JSON.Stringify.

How can I receive a json object in the controller?

View:

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://raw.githubusercontent.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializejson.js"></script>

var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
$.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });

<form id="form1" method="post">
<input name="OrderDate" type="text" /><br />
<input name="Item[0][Id]" type="text" /><br />
<input name="Item[1][Id]" type="text" /><br />
<button id="btn" onclick="btnClick()">Button</button>
</form>

Controller:

public void PostRawJson(string json)
{
    var order = System.Web.Helpers.Json.Decode(json);
    var orderDate = order.OrderDate;
    var secondOrderId = order.Item[1].Id;
}

Foreach value from POST from form

If your post keys have to be parsed and the keys are sequences with data, you can try this:

Post data example: Storeitem|14=data14

foreach($_POST as $key => $value){
    $key=Filterdata($key); $value=Filterdata($value);
    echo($key."=".$value."<br>");
}

then you can use strpos to isolate the end of the key separating the number from the key.

How to print jquery object/array

Your result is currently in string format, you need to parse it as json.

var obj = $.parseJSON(result);
alert(obj[0].category);

Additionally, if you set the dataType of the ajax call you are making to json, you can skip the $.parseJSON() step.

Run java jar file on a server as background process

Run in background and add logs to log file using the following:

nohup java -jar /web/server.jar > log.log 2>&1 &

PHP function to make slug (URL string)

On my localhost everything was ok, but on server it helped me “set_locale” and “utf-8” at “mb_strtolower”.

<?
setlocale( LC_ALL, "en_US.UTF8" );
function slug( $str, $char = "-", $tf = "lowercase" )
{
    $str = iconv( "utf-8", "us-ascii//translit//ignore", $str ); // transliterate
    $str = str_replace( "'", "", $str ); // remove “'” generated by iconv
    $str = preg_replace( "~[^a-z0-9]+~ui", $char, $str ); // replace unwanted by single “-”
    $str = trim( $str, $char ); // trim “-”
    if( $tf == "lowercase" ) $str = mb_strtolower( $str, "utf-8" ); // lowercase
    elseif( $tf == "uppercase" ) $str = mb_strtoupper( $str, "utf-8" );
    return $str;
}
?>

Test

$string = "--+ešcržýá091354--––—_-6íé???ß?ac …   elnszzAC  ELNS   Z///+++||||..Z";
echo slug( $string );
echo slug( $string, "?", "uppercase" );

// ? escrzya091354-6iessac-elnszzac-elns-z-z
// ? ESCRZYA091354?6IESSAC?ELNSZZAC?ELNS?Z?Z

Linq select object from list depending on objects attribute

Few things to fix here:

  1. No parenthesis in class declaration
  2. Make the "correct" property as public
  3. And then do the selection

Your code will look something like this

List<Answer> answers = new List<Answer>();
/* test
answers.Add(new Answer() { correct = false });
answers.Add(new Answer() { correct = true });
answers.Add(new Answer() { correct = false });
*/
Answer answer = answers.Single(a => a.correct == true);

and the class

class Answer
{
   public bool correct;
}

Close application and launch home screen on Android

When you launch the second activity, finish() the first one immediately:

startActivity(new Intent(...));
finish();

How to move all HTML element children to another parent using JavaScript?

This answer only really works if you don't need to do anything other than transferring the inner code (innerHTML) from one to the other:

// Define old parent
var oldParent = document.getElementById('old-parent');

// Define new parent
var newParent = document.getElementById('new-parent');

// Basically takes the inner code of the old, and places it into the new one
newParent.innerHTML = oldParent.innerHTML;

// Delete / Clear the innerHTML / code of the old Parent
oldParent.innerHTML = '';

Hope this helps!

How to properly create an SVN tag from trunk?

svn copy http://URL/svn/trukSource http://URL/svn/tagDestination -m "Test tag code" 
  $error[0].Exception | Select-object Data

All you have to do change URL path. This command will create new dir "tagDestination". The second line will be let know you the full error details if any occur. Create svn env variable if not created. Can check (Cmd:- set, Powershell:- Get-ChildItem Env:) Default path is "C:\Program Files\TortoiseSVN\bin\TortoiseProc.exe"

What does enumerate() mean?

I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate instead. I know you asked what enumerate means, but when I understood the following, I also understood how enumerate makes iterating over a list while knowing the index of the current item easier (and more readable).

list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):
    letter = list_of_letters[i]
    print (i, letter)

The output is:

0 a
1 b
2 c

I also used to do something, even sillier before I read about the enumerate function.

i = 0
for n in list_of_letters:
    print (i, n)
    i += 1

It produces the same output.

But with enumerate I just have to write:

list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):
    print (i, letter)

Using "If cell contains #N/A" as a formula condition.

You can also use IFNA(expression, value)

Common sources of unterminated string literal

Scan the code that comes before the line# mentioned by error message. Whatever is unterminated has resulted in something downstream, (the blamed line#), to be flagged.

perform an action on checkbox checked or unchecked event on html form

Given you use JQuery, you can do something like below :

HTML

<form id="myform">
    syn<input type="checkbox" name="checkfield" id="g01-01"  onclick="doalert()"/>
</form>

JS

function doalert() {
  if ($("#g01-01").is(":checked")) {
    alert ("hi");
  } else {
    alert ("bye");
  }
}

Regex match text between tags

Try

str.match(/<b>(.*?)<\/b>/g);

How to set the custom border color of UIView programmatically?

We can create method for it. Simply use it.

public func createBorderForView(color: UIColor, radius: CGFloat, width: CGFloat = 0.7) {
    self.layer.borderWidth = width
    self.layer.cornerRadius = radius
    self.layer.shouldRasterize = false
    self.layer.rasterizationScale = 2
    self.clipsToBounds = true
    self.layer.masksToBounds = true
    let cgColor: CGColor = color.cgColor
    self.layer.borderColor = cgColor
}

Bootstrap 4 align navbar items to the right

I am running Angular 4 (v.4.0.0) and ng-bootstrap (Bootstrap 4). This code won't all be relevant but hoping people can pick and choose what works. It took me sometime to find a solution to get my items to justify right, collapse properly and to implement a dropdown off my google (using OAuth) profile picture.

<div id="header" class="header">
  <nav class="navbar navbar-toggleable-sm navbar-inverse bg-faded fixed-top">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
      aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
    <a class="navbar-brand" href="#">
          <img alt='Brand' src='../assets/images/logo-white.png' class='navbar-logo-img d-inline-block align-top '>
          <span class="navbar-logo-text">Oncoscape</span>
        </a>
    <div class="collapse navbar-collapse justify-content-end" id="navbarSupportedContent">
      <ul class="navbar-nav float-left">
        <a class="navbar-items nav-item nav-link active " *ngIf='authenticated' (click)='goDashboard()'>
          <span class="fa fa-dashboard"></span>Dashboard
        </a>
        <a class="nav-item nav-link navbar-items active" href="http://resources.sttrcancer.org/oncoscape-contact">
          <span class="fa fa-comments"></span>Feedback
        </a>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <img *ngIf='user && authenticated'  class="navbar-pic" src={{user.thumbnail}} alt="Smiley face">
          </a>
          <div *ngIf='user && authenticated' class="dropdown-menu " aria-labelledby="navbarDropdownMenuLink">
            <a class="dropdown-item" (click)="toProfile()">Account</a>
            <div class="dropdown-item">
              <app-login></app-login>
            </div>
          </div>
        </li>
      </ul>
    </div>
  </nav>
</div>
<router-outlet></router-outlet>

Add a new item to recyclerview programmatically?

if you are adding multiple items to the list use this:

mAdapter.notifyItemRangeInserted(startPosition, itemcount);

This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount

existing item in the dataset still considered up to date.

How to convert String into Hashmap in java

@Test
public void testToStringToMap() {
    Map<String,String> expected = new HashMap<>();
    expected.put("first_name", "naresh");
    expected.put("last_name", "kumar");
    expected.put("gender", "male");
    String mapString = expected.toString();
    Map<String, String> actual = Arrays.stream(mapString.replace("{", "").replace("}", "").split(","))
            .map(arrayData-> arrayData.split("="))
            .collect(Collectors.toMap(d-> ((String)d[0]).trim(), d-> (String)d[1]));

    expected.entrySet().stream().forEach(e->assertTrue(actual.get(e.getKey()).equals(e.getValue())));
}

How to save picture to iPhone photo library?

You can use this function:

UIImageWriteToSavedPhotosAlbum(UIImage *image, 
                               id completionTarget, 
                               SEL completionSelector, 
                               void *contextInfo);

You only need completionTarget, completionSelector and contextInfo if you want to be notified when the UIImage is done saving, otherwise you can pass in nil.

See the official documentation for UIImageWriteToSavedPhotosAlbum().

How to deal with the URISyntaxException

You have to encode your parameters.

Something like this will do:

import java.net.*;
import java.io.*;

public class EncodeParameter { 

    public static void main( String [] args ) throws URISyntaxException ,
                                         UnsupportedEncodingException   { 

        String myQuery = "^IXIC";

        URI uri = new URI( String.format( 
                           "http://finance.yahoo.com/q/h?s=%s", 
                           URLEncoder.encode( myQuery , "UTF8" ) ) );

        System.out.println( uri );

    }
}

http://java.sun.com/javase/6/docs/api/java/net/URLEncoder.html

How to update record using Entity Framework 6?

Like Renat said, remove: db.Books.Attach(book);

Also, change your result query to use "AsNoTracking", because this query is throwing off entity framework's model state. It thinks "result" is the book to track now and you don't want that.

var result = db.Books.AsNoTracking().SingleOrDefault(b => b.BookNumber == bookNumber);

How to send a GET request from PHP?

Remember that if you are using a proxy you need to do a little trick in your php code:

(PROXY WITHOUT AUTENTICATION EXAMPLE)

<?php
$aContext = array(
    'http' => array(
        'proxy' => 'proxy:8080',
        'request_fulluri' => true,
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;
?>

align an image and some text on the same line without using div width?

I know this question is over 6 years old, but still, I would like to share my method using tables and this won't require any CSS.

<table><tr><td><img src="loading.gif"></td><td> Loading...</td></tr></table>

Cheers! Happy Coding

Format date in a specific timezone

A couple of answers already mention that moment-timezone is the way to go with named timezone. I just want to clarify something about this library that was pretty confusing to me. There is a difference between these two statements:

moment.tz(date, format, timezone)

moment(date, format).tz(timezone)

Assuming that a timezone is not specified in the date passed in:

The first code takes in the date and assumes the timezone is the one passed in. The second one will take date, assume the timezone from the browser and then change the time and timezone according to the timezone passed in.

Example:

moment.tz('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss', 'UTC').format() // "2018-07-17T19:00:00Z"

moment('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss').tz('UTC').format() // "2018-07-18T00:00:00Z"

My timezone is +5 from utc. So in the first case it does not change and it sets the date and time to have utc timezone.

In the second case, it assumes the date passed in is in -5, then turns it into UTC, and that's why it spits out the date "2018-07-18T00:00:00Z"

NOTE: The format parameter is really important. If omitted moment might fall back to the Date class which can unpredictable behaviors


Assuming the timezone is specified in the date passed in:

In this case they both behave equally


Even though now I understand why it works that way, I thought this was a pretty confusing feature and worth explaining.

Algorithm to calculate the number of divisors of a given number

The following is a C program to find the number of divisors of a given number.

The complexity of the above algorithm is O(sqrt(n)).

This algorithm will work correctly for the number which are perfect square as well as the numbers which are not perfect square.

Note that the upperlimit of the loop is set to the square-root of number to have the algorithm most efficient.

Note that storing the upperlimit in a separate variable also saves the time, you should not call the sqrt function in the condition section of the for loop, this also saves your computational time.

#include<stdio.h>
#include<math.h>
int main()
{
    int i,n,limit,numberOfDivisors=1;
    printf("Enter the number : ");
    scanf("%d",&n);
    limit=(int)sqrt((double)n);
    for(i=2;i<=limit;i++)
        if(n%i==0)
        {
            if(i!=n/i)
                numberOfDivisors+=2;
            else
                numberOfDivisors++;
        }
    printf("%d\n",numberOfDivisors);
    return 0;
}

Instead of the above for loop you can also use the following loop which is even more efficient as this removes the need to find the square-root of the number.

for(i=2;i*i<=n;i++)
{
    ...
}

Using css transform property in jQuery

If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you. It can be as simple as this : $("#element").transition({x:'90px'}).

Take it from this link : http://ricostacruz.com/jquery.transit/

Automatically start forever (node) on system restart

You can use the following command in your shell to start your node forever:

forever app.js //my node script

You need to keep in mind that the server on which your app is running should always be kept on.

Using XPATH to search text containing &nbsp;

Bear in mind that a standards-compliant XML processor will have replaced any entity references other than XML's five standard ones (&amp;, &gt;, &lt;, &apos;, &quot;) with the corresponding character in the target encoding by the time XPath expressions are evaluated. Given that behavior, PhiLho's and jsulak's suggestions are the way to go if you want to work with XML tools. When you enter &#160; in the XPath expression, it should be converted to the corresponding byte sequence before the XPath expression is applied.

AngularJS : How to watch service variables?

I am late to the part but I found a nicer way to do this than the answer posted above. Instead of assigning a variable to hold the value of the service variable, I created a function attached to the scope, that returns the service variable.

controller

$scope.foo = function(){
 return aService.foo;
}

I think this will do what you want. My controller keeps checking the value of my service with this implementation. Honestly, this is much simpler than the selected answer.

R legend placement in a plot

?legend will tell you:

Arguments

x, y
the x and y co-ordinates to be used to position the legend. They can be specified by keyword or in any way which is accepted by xy.coords: See ‘Details’.

Details:

Arguments x, y, legend are interpreted in a non-standard way to allow the coordinates to be specified via one or two arguments. If legend is missing and y is not numeric, it is assumed that the second argument is intended to be legend and that the first argument specifies the coordinates.

The coordinates can be specified in any way which is accepted by xy.coords. If this gives the coordinates of one point, it is used as the top-left coordinate of the rectangle containing the legend. If it gives the coordinates of two points, these specify opposite corners of the rectangle (either pair of corners, in any order).

The location may also be specified by setting x to a single keyword from the list bottomright, bottom, bottomleft, left, topleft, top, topright, right and center. This places the legend on the inside of the plot frame at the given location. Partial argument matching is used. The optional inset argument specifies how far the legend is inset from the plot margins. If a single value is given, it is used for both margins; if two values are given, the first is used for x- distance, the second for y-distance.

Add st, nd, rd and th (ordinal) suffix to a number

I wrote this function for higher numbers and all test cases

function numberToOrdinal(num) {
    if (num === 0) {
        return '0'
    };
    let i = num.toString(), j = i.slice(i.length - 2), k = i.slice(i.length - 1);
    if (j >= 10 && j <= 20) {
        return (i + 'th')
    } else if (j > 20 && j < 100) {
        if (k == 1) {
            return (i + 'st')
        } else if (k == 2) {
            return (i + 'nd')
        } else if (k == 3) {
            return (i + 'rd')
        } else {
            return (i + 'th')
        }
    } else if (j == 1) {
        return (i + 'st')
    } else if (j == 2) {
        return (i + 'nd')
    } else if (j == 3) {
        return (i + 'rd')
    } else {
        return (i + 'th')
    }
}

How to find the kafka version in linux

Not sure if there's a convenient way, but you can just inspect your kafka/libs folder. You should see files like kafka_2.10-0.8.2-beta.jar, where 2.10 is Scala version and 0.8.2-beta is Kafka version.

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

This appears to fit what you are looking for: https://forums.oracle.com/forums/thread.jspa?threadID=2140801

Basically, you will need to use regular expressions as there appears to be nothing built into oracle for this.

I pulled out the example from the thread and converted it for your purposes. I suck at regex's, though, so that might need tweaked :)

SELECT  *
FROM myTable m
WHERE NOT regexp_like(m.status,'((Done^|Finished except^|In Progress^)')

C++ compile error: has initializer but incomplete type

` Please include either of these:

`#include<sstream>`

using std::istringstream; 

Trim Whitespaces (New Line and Tab space) in a String in Oracle

If at all anyone is looking to convert data in 1 variable that lies in 2 or 3 different lines like below

'Data1

Data2'

And you want to display data as 'Data1 Data2' then use below

select TRANSLATE ('Data1

Data2', ''||CHR(10), ' ') from dual;

it took me hrs to get the right output. Thanks to me I just saved you 1 or 2 hrs :)

ValueError: could not convert string to float: id

I solved the similar situation with basic technique using pandas. First load the csv or text file using pandas.It's pretty simple

data=pd.read_excel('link to the file')

Then set the index of data to the respected column that needs to be changed. For example, if your data has ID as one attribute or column, then set index to ID.

 data = data.set_index("ID")

Then delete all the rows with "id" as the value instead of number using following command.

  data = data.drop("id", axis=0). 

Hope, this will help you.

How to set the default value for radio buttons in AngularJS?

Set a default value for people with ngInit

<div ng-app>
    <div ng-init="people=1" />
        <input type="radio" ng-model="people" value="1"><label>1</label>
        <input type="radio" ng-model="people" value="2"><label>2</label>
        <input type="radio" ng-model="people" value="3"><label>3</label>
    <ul>
        <li>{{10*people}}€</li>
        <li>{{8*people}}€</li>
        <li>{{30*people}}€</li>
    </ul>
</div>

Demo: Fiddle

Grouping functions (tapply, by, aggregate) and the *apply family

On the side note, here is how the various plyr functions correspond to the base *apply functions (from the intro to plyr document from the plyr webpage http://had.co.nz/plyr/)

Base function   Input   Output   plyr function 
---------------------------------------
aggregate        d       d       ddply + colwise 
apply            a       a/l     aaply / alply 
by               d       l       dlply 
lapply           l       l       llply  
mapply           a       a/l     maply / mlply 
replicate        r       a/l     raply / rlply 
sapply           l       a       laply 

One of the goals of plyr is to provide consistent naming conventions for each of the functions, encoding the input and output data types in the function name. It also provides consistency in output, in that output from dlply() is easily passable to ldply() to produce useful output, etc.

Conceptually, learning plyr is no more difficult than understanding the base *apply functions.

plyr and reshape functions have replaced almost all of these functions in my every day use. But, also from the Intro to Plyr document:

Related functions tapply and sweep have no corresponding function in plyr, and remain useful. merge is useful for combining summaries with the original data.

Set the maximum character length of a UITextField

Got it down to 1 line of code :)

Set your text view's delegate to "self" then add the <UITextViewDelegate> in your .h and the following code in your .m .... you can adjust the number "7" to be whatever you want your MAXIMUM number of characters to be.

-(BOOL)textView:(UITextView *)a shouldChangeTextInRange:(NSRange)b replacementText:(NSString *)c {
    return ((a.text.length+c.length<=7)+(c.length<1)+(b.length>=c.length)>0);
}

This code accounts for typing new characters, deleting characters, selecting characters then typing or deleting, selecting characters and cutting, pasting in general, and selecting characters and pasting.

Done!






Alternatively, another cool way to write this code with bit-operations would be

-(BOOL)textView:(UITextView *)a shouldChangeTextInRange:(NSRange)b replacementText:(NSString *)c {
    return 0^((a.text.length+c.length<=7)+(c.length<1)+(b.length>=c.length));
}

Display Records From MySQL Database using JTable in Java

this is the easy way to do that you just need to download the jar file "rs2xml.jar" add it to your project and do that : 1- creat a connection 2- statment and resultset 3- creat a jtable 4- give the result set to DbUtils.resultSetToTableModel(rs) as define in this methode you well get your jtable so easy.

public void afficherAll(String tableName){
        String sql="select * from "+tableName;
        try {
            stmt=con.createStatement();
            rs=stmt.executeQuery(sql);
            tbContTable.setModel(DbUtils.resultSetToTableModel(rs));
        } catch (SQLException e) {
            // TODO Auto-generated catch block
             JOptionPane.showMessageDialog(null, e);
        }       
    }

How to use a variable for a key in a JavaScript object literal?

I couldn't find a simple example about the differences between ES6 and ES5, so I made one. Both code samples create exactly the same object. But the ES5 example also works in older browsers (like IE11), wheres the ES6 example doesn't.

ES6

var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';

matrix[a] = {[b]: {[c]: d}};

ES5

var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';

function addObj(obj, key, value) {
  obj[key] = value;
  return obj;
}

matrix[a] = addObj({}, b, addObj({}, c, d));