Programs & Examples On #Wunderground

Weather Underground is a commercial weather service that provides real-time weather information via the Internet. Weather Underground provides weather reports for most major cities across the world on its Web site, as well as local weather reports for newspapers and Web sites.

json Uncaught SyntaxError: Unexpected token :

I had the same problem and the solution was to encapsulate the json inside this function

jsonp(

.... your json ...

)

How do I execute .js files locally in my browser?

Around 1:51 in the video, notice how she puts a <script> tag in there? The way it works is like this:

Create an html file (that's just a text file with a .html ending) somewhere on your computer. In the same folder that you put index.html, put a javascript file (that's just a textfile with a .js ending - let's call it game.js). Then, in your index.html file, put some html that includes the script tag with game.js, like Mary did in the video. index.html should look something like this:

<html>
    <head>
        <script src="game.js"></script>
    </head>
</html>

Now, double click on that file in finder, and it should open it up in your browser. To open up the console to see the output of your javascript code, hit Command-alt-j (those three buttons at the same time).

Good luck on your journey, hope it's as fun for you as it has been for me so far :)

ValueError: max() arg is an empty sequence

I realized that I was iterating over a list of lists where some of them were empty. I fixed this by adding this preprocessing step:

tfidfLsNew = [x for x in tfidfLs if x != []]

the len() of the original was 3105, and the len() of the latter was 3101, implying that four of my lists were completely empty. After this preprocess my max() min() etc. were functioning again.

Android - implementing startForeground for a service?

In addition to RAWA answer, this peace of code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    startForegroundService(intent)
} else {
    startService(intent)
}

You can change to:

ContextCompat.startForegroundService(context, yourIntent);

If you will look inside this method then you can see that this method do all checking work for you.

How can I force gradle to redownload dependencies?

You need to redownload it, so you can either manually download and replace the corrupted file and again sync your project . Go to this location C:\users[username].gradle\wrapper\dist\gradle3.3-all\55gk2rcmfc6p2dg9u9ohc3hw9\gradle-3.3-all.zip Here delete gradle3.3allzip and replace it by downloading again from this site https://services.gradle.org/distributions/ Find the same file and download and paste it to that location Then sync your project. Hope it works for you too.

Does IE9 support console.log, and is it a real function?

A simple solution to this console.log problem is to define the following at the beginning of your JS code:

if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };

This works for me in all browsers. This creates a dummy function for console.log when the debugger is not active. When the debugger is active, the method console.log is defined and executes normally.

How do I find the length (or dimensions, size) of a numpy matrix in python?

matrix.size according to the numpy docs returns the Number of elements in the array. Hope that helps.

How to implement a property in an interface

In the interface, you specify the property:

public interface IResourcePolicy
{
   string Version { get; set; }
}

In the implementing class, you need to implement it:

public class ResourcePolicy : IResourcePolicy
{
   public string Version { get; set; }
}

This looks similar, but it is something completely different. In the interface, there is no code. You just specify that there is a property with a getter and a setter, whatever they will do.

In the class, you actually implement them. The shortest way to do this is using this { get; set; } syntax. The compiler will create a field and generate the getter and setter implementation for it.

How do I stop Notepad++ from showing autocomplete for all words in the file

Notepad++ provides 2 types of features:

  • Auto-completion that read the open file and provide suggestion of words and/or functions within the file
  • Suggestion with the arguments of functions (specific to the language)

Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.

To do that, you just need to change a setting.

  1. Go to Settings > Preferences... > Auto-completion
  2. Check Enable Auto-completion on each input
  3. Select Function completion and not Word completion
  4. Check Function parameter hint on input (if you have this option)

On version 6.5.5 of Notepad++, I have this setting settings

Some documentation about auto-completion is available in Notepad++ Wiki.

Check if PHP session has already started

This is what I use to determine if a session has started. By using empty and isset as follows:

if (empty($_SESSION)  && !isset($_SESSION))  {
    session_start();
}

Java "lambda expressions not supported at this language level"

Possible Cause #1 (same as the first 3 answers for this question): Project Structure Settings

  1. File > Project Structure > Under Project Settings, go to Project > set Project SDK to 1.8 (with version 65 or above, latest is 112) and set Project Language Level to 8.

  2. File > Project Structure > Under Platform Settings, go to Project > ensure that your JDK home path is set to 1.8 (with version 65 or above, latest is 112).

If the above does not work, check the target bytecode version of your compiler and move on to Possible Cause #2.

Possible Cause #2: Compiler

  1. File > Settings > Build, Execution, Deployment > Under Compiler, go to Java Compiler > set your Project Bytecode Version to 1.8, as well as all the Target Bytecode Version for your modules. Click Apply and hit OK. Restart your IntelliJ IDE. Lambda expression was accepted in my IDE at this point.

Best wishes :)

Free space in a CMD shell

Is cscript a 3rd party app? I suggest trying Microsoft Scripting, where you can use a programming language (JScript, VBS) to check on things like List Available Disk Space.

The scripting infrastructure is present on all current Windows versions (including 2008).

How to turn off word wrapping in HTML?

white-space: nowrap;: Will never break text, will keep other defaults

white-space: pre;: Will never break text, will keep multiple spaces after one another as multiple spaces, will break if explicitly written to break(pressing enter in html etc)

How to get value of a div using javascript

First of all

<div id="demo" align="center"  value="1"></div>

that is not valid HTML. Read up on custom data attributes or use the following instead:

<div id="demo" align="center" data-value="1"></div>

Since "data-value" is an attribute, you have to use the getAttribute function to retrieve its value.

var cookieValue = document.getElementById("demo").getAttribute("data-value"); 

Regex: match word that ends with "Id"

I would use
\b[A-Za-z]*Id\b
The \b matches the beginning and end of a word i.e. space, tab or newline, or the beginning or end of a string.

The [A-Za-z] will match any letter, and the * means that 0+ get matched. Finally there is the Id.

Note that this will match words that have capital letters in the middle such as 'teStId'.

I use http://www.regular-expressions.info/ for regex reference

Android TextView padding between lines

You can use TextView.setLineSpacing(n,m) function.

Regular expression to allow spaces between words

try .*? to allow white spaces it worked for me

Unsuccessful append to an empty NumPy array

Here's the result of running your code in Ipython. Note that result is a (2,0) array, 2 rows, 0 columns, 0 elements. The append produces a (2,) array. result[0] is (0,) array. Your error message has to do with trying to assign that 2 item array into a size 0 slot. Since result is dtype=float64, only scalars can be assigned to its elements.

In [65]: result=np.asarray([np.asarray([]),np.asarray([])])

In [66]: result
Out[66]: array([], shape=(2, 0), dtype=float64)

In [67]: result[0]
Out[67]: array([], dtype=float64)

In [68]: np.append(result[0],[1,2])
Out[68]: array([ 1.,  2.])

np.array is not a Python list. All elements of an array are the same type (as specified by the dtype). Notice also that result is not an array of arrays.

Result could also have been built as

ll = [[],[]]
result = np.array(ll)

while

ll[0] = [1,2]
# ll = [[1,2],[]]

the same is not true for result.

np.zeros((2,0)) also produces your result.

Actually there's another quirk to result.

result[0] = 1

does not change the values of result. It accepts the assignment, but since it has 0 columns, there is no place to put the 1. This assignment would work in result was created as np.zeros((2,1)). But that still can't accept a list.

But if result has 2 columns, then you can assign a 2 element list to one of its rows.

result = np.zeros((2,2))
result[0] # == [0,0]
result[0] = [1,2]

What exactly do you want result to look like after the append operation?

Getting a list of files in a directory with a glob

What about using NSString's hasSuffix and hasPrefix methods? Something like (if you're searching for "foo*.jpg"):

NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSArray *dirContents = [[NSFileManager defaultManager] directoryContentsAtPath:bundleRoot];
for (NSString *tString in dirContents) {
    if ([tString hasPrefix:@"foo"] && [tString hasSuffix:@".jpg"]) {

        // do stuff

    }
}

For simple, straightforward matches like that it would be simpler than using a regex library.

How to check encoding of a CSV file

In Linux systems, you can use file command. It will give the correct encoding

Sample:

file blah.csv

Output:

blah.csv: ISO-8859 text, with very long lines

Change jsp on button click

If all you are looking for is navigation to page 2 and 3 from page one, replace the buttons with anchor elements as below:

<form name="TrainerMenu" action="TrainerMenu" method="get">

<h1>Benvenuto in LESSON! Scegli l'operazione da effettuare:</h1>
<a href="Page2.jsp" id="CreateCourse" >Creazione Nuovo Corso</a>&nbsp;
<a href="Page3.jsp" id="AuthorizationManager">Gestione Autorizzazioni</a>
<input type="button" value="" name="AuthorizationManager" />
</form>

If for some reason you need to use buttons, try this:

<form name="TrainerMenu" action="TrainerMenu" method="get">

   <h1>Benvenuto in LESSON! Scegli l'operazione da effettuare:</h1>
   <input type="button" value="Creazione Nuovo Corso" name="CreateCourse"
    onclick="openPage('Page2.jsp')"/>
   <input type="button" value="Gestione Autorizzazioni" name="AuthorizationManager"
    onclick="openPage('Page3.jsp')" />

</form>
<script type="text/javascript">
 function openPage(pageURL)
 {
 window.location.href = pageURL;
 }
</script>

Check if all elements in a list are identical

The simple solution is to apply set on list

if all elements are identical len will be 1 else greater than 1

lst = [1,1,1,1,1,1,1,1,1]
len_lst = len(list(set(lst)))

print(len_lst)

1


lst = [1,2,1,1,1,1,1,1,1]
len_lst = len(list(set(lst)))
print(len_lst)

2

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

Although I do like and appreciate Suragch's answer, I would like to leave a note because I found that coding the Adapter (MyRecyclerViewAdapter) to define and expose the Listener method onItemClick isn't the best way to do it, due to not using class encapsulation correctly. So my suggestion is to let the Adapter handle the Listening operations solely (that's his purpose!) and separate those from the Activity that uses the Adapter (MainActivity). So this is how I would set the Adapter class:

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private String[] mData = new String[0];
    private LayoutInflater mInflater;

    // Data is passed into the constructor
    public MyRecyclerViewAdapter(Context context, String[] data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // Inflates the cell layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    // Binds the data to the textview in each cell
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String animal = mData[position];
        holder.myTextView.setText(animal);
    }

    // Total number of cells
    @Override
    public int getItemCount() {
        return mData.length;
    }

    // Stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView myTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            myTextView = (TextView) itemView.findViewById(R.id.info_text);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            onItemClick(view, getAdapterPosition());
        }
    }

    // Convenience method for getting data at click position
    public String getItem(int id) {
        return mData[id];
    }

    // Method that executes your code for the action received
    public void onItemClick(View view, int position) {
        Log.i("TAG", "You clicked number " + getItem(position).toString() + ", which is at cell position " + position);
    }
}

Please note the onItemClick method now defined in MyRecyclerViewAdapter that is the place where you would want to code your tasks for the event/action received.

There is only a small change to be done in order to complete this transformation: the Activity doesn't need to implement MyRecyclerViewAdapter.ItemClickListener anymore, because now that is done completely by the Adapter. This would then be the final modification:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

        // set up the RecyclerView
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvNumbers);
        int numberOfColumns = 6;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }
}

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

loading json data from local file into React JS

You are opening an asynchronous connection, yet you have written your code as if it was synchronous. The reqListener callback function will not execute synchronously with your code (that is, before React.createClass), but only after your entire snippet has run, and the response has been received from your remote location.

Unless you are on a zero-latency quantum-entanglement connection, this is well after all your statements have run. For example, to log the received data, you would:

function reqListener(e) {
    data = JSON.parse(this.responseText);
    console.log(data);
}

I'm not seeing the use of data in the React component, so I can only suggest this theoretically: why not update your component in the callback?

Passing structs to functions

bool data(sampleData *data)
{
}

You need to tell the method which type of struct you are using. In this case, sampleData.

Note: In this case, you will need to define the struct prior to the method for it to be recognized.

Example:

struct sampleData
{
   int N;
   int M;
   // ...
};

bool data(struct *sampleData)
{

}

int main(int argc, char *argv[]) {

      sampleData sd;
      data(&sd);

}

Note 2: I'm a C guy. There may be a more c++ish way to do this.

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

Error 0x80005000 and DirectoryServices

The same error occurs if in DirectoryEntry.Patch is nothing after the symbols "LDAP//:". It is necessary to check the directoryEntry.Path before directorySearcher.FindOne(). Unless explicitly specified domain, and do not need to "LDAP://".

private void GetUser(string userName, string domainName)
{
     DirectoryEntry dirEntry = new DirectoryEntry();

     if (domainName.Length > 0)
     {
          dirEntry.Path = "LDAP://" + domainName;
     }

     DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry);
     dirSearcher.SearchScope = SearchScope.Subtree;
     dirSearcher.Filter = string.Format("(&(objectClass=user)(|(cn={0})(sn={0}*)(givenName={0})(sAMAccountName={0}*)))", userName);
     var searchResults = dirSearcher.FindAll();
     //var searchResults = dirSearcher.FindOne();

     if (searchResults.Count == 0)
     {
          MessageBox.Show("User not found");
     }
     else
     {
          foreach (SearchResult sr in searchResults)
          {
              var de = sr.GetDirectoryEntry();
              string user = de.Properties["SAMAccountName"][0].ToString();
              MessageBox.Show(user); 
          }        
     }
}

How to tell which disk Windows Used to Boot

You can use WMI to figure this out. The Win32_BootConfiguration class will tell you both the logical drive and the physical device from which Windows boots. Specifically, the Caption property will tell you which device you're booting from.

For example, in powershell, just type gwmi Win32_BootConfiguration to get your answer.

Cross-browser custom styling for file upload button

I just came across this problem and have written a solution for those of you who are using Angular. You can write a custom directive composed of a container, a button, and an input element with type file. With CSS you then place the input over the custom button but with opacity 0. You set the containers height and width to exactly the offset width and height of the button and the input's height and width to 100% of the container.

the directive

angular.module('myCoolApp')
  .directive('fileButton', function () {
    return {
      templateUrl: 'components/directives/fileButton/fileButton.html',
      restrict: 'E',
      link: function (scope, element, attributes) {

        var container = angular.element('.file-upload-container');
        var button = angular.element('.file-upload-button');

        container.css({
            position: 'relative',
            overflow: 'hidden',
            width: button.offsetWidth,
            height: button.offsetHeight
        })

      }

    };
  });

a jade template if you are using jade

div(class="file-upload-container") 
    button(class="file-upload-button") +
    input#file-upload(class="file-upload-input", type='file', onchange="doSomethingWhenFileIsSelected()")  

the same template in html if you are using html

<div class="file-upload-container">
   <button class="file-upload-button"></button>
   <input class="file-upload-input" id="file-upload" type="file" onchange="doSomethingWhenFileIsSelected()" /> 
</div>

the css

.file-upload-button {
    margin-top: 40px;
    padding: 30px;
    border: 1px solid black;
    height: 100px;
    width: 100px;
    background: transparent;
    font-size: 66px;
    padding-top: 0px;
    border-radius: 5px;
    border: 2px solid rgb(255, 228, 0); 
    color: rgb(255, 228, 0);
}

.file-upload-input {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
}

How do I add a newline to a windows-forms TextBox?

TextBox2.Text = "Line 1" & Environment.NewLine & "Line 2"

or

TextBox2.Text = "Line 1"
TextBox2.Text += Environment.NewLine
TextBox2.Text += "Line 2"

This, is how it is done.

How do I set adaptive multiline UILabel text?

Programmatically, Swift

label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.titleView.numberOfLines = 2

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

Typically, boolean values that are used in branches immediately after they're calculated like this are never actually stored in variables. Instead, the compiler just branches directly off the condition codes that were set from the preceding comparison. For example,

int a = SomeFunction();
bool result = --a >= 0; // use subtraction as example computation
if ( result ) 
{
   foo(); 
}
else
{
   bar();
}
return;

Usually compiles to something like:

call .SomeFunction  ; calls to SomeFunction(), which stores its return value in eax
sub eax, 1 ; subtract 1 from eax and store in eax, set S (sign) flag if result is negative
jl ELSEBLOCK ; GOTO label "ELSEBLOCK" if S flag is set
call .foo ; this is the "if" black, call foo()
j FINISH ; GOTO FINISH; skip over the "else" block
ELSEBLOCK: ; label this location to the assembler
call .bar
FINISH: ; both paths end up here
ret ; return

Notice how the "bool" is never actually stored anywhere.

pandas unique values multiple columns

here's another way


import numpy as np
set(np.concatenate(df.values))

Mutex lock threads

Below, code snippet, will help you in understanding the mutex-lock-unlock concept. Attempt dry-run on the code. (further by varying the wait-time and process-time, you can build you understanding).

Code for your reference:

#include <stdio.h>
#include <pthread.h>

void in_progress_feedback(int);

int global = 0;
pthread_mutex_t mutex;
void *compute(void *arg) {

    pthread_t ptid = pthread_self();
    printf("ptid : %08x \n", (int)ptid);    

    int i;
    int lock_ret = 1;   
    do{

        lock_ret = pthread_mutex_trylock(&mutex);
        if(lock_ret){
            printf("lock failed(%08x :: %d)..attempt again after 2secs..\n", (int)ptid,  lock_ret);
            sleep(2);  //wait time here..
        }else{  //ret =0 is successful lock
            printf("lock success(%08x :: %d)..\n", (int)ptid, lock_ret);
            break;
        }

    } while(lock_ret);

        for (i = 0; i < 10*10 ; i++) 
        global++;

    //do some stuff here
    in_progress_feedback(10);  //processing-time here..

    lock_ret = pthread_mutex_unlock(&mutex);
    printf("unlocked(%08x :: %d)..!\n", (int)ptid, lock_ret);

     return NULL;
}

void in_progress_feedback(int prog_delay){

    int i=0;
    for(;i<prog_delay;i++){
    printf(". ");
    sleep(1);
    fflush(stdout);
    }

    printf("\n");
    fflush(stdout);
}

int main(void)
{
    pthread_t tid0,tid1;
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid0, NULL, compute, NULL);
    pthread_create(&tid1, NULL, compute, NULL);
    pthread_join(tid0, NULL);
    pthread_join(tid1, NULL);
    printf("global = %d\n", global);
    pthread_mutex_destroy(&mutex);
          return 0;
}

Change Circle color of radio button

There is an xml attribute for it:

android:buttonTint="yourcolor"

One line if-condition-assignment

num1 = 10 + 10*(someBoolValue is True)

That's my new final answer. Prior answer was as follows and was overkill for the stated problem. Getting_too_clever == not Good. Here's the prior answer... still good if you want add one thing for True cond and another for False:

num1 = 10 + (0,10)[someBoolValue is True]

You mentioned num1 would already have a value that should be left alone. I assumed num1 = 10 since that's the first statement of the post, so the operation to get to 20 is to add 10.

num1 = 10
someBoolValue = True

num1 = 10 + (0,10)[someBoolValue is True]

print(f'num1 = {num1}\nsomeBoolValue = {someBoolValue}')

produced this output

num1 = 20
someBoolValue = True

Type or namespace name does not exist

I had the same problem and tried all of the above without any success, then I found out what it was:

I'd created a folder called "System" in one of my projects and then created a class in it. The problem seems to stem from having a namespace called "System" when the .cs file is created, even if it is in a namespace of "MyProject.System".

Looking back I can understand why this would cause problems. It really stumped me at first as the error messages don't initially seem to relate to the problem.

In Java, how do I check if a string contains a substring (ignoring case)?

I also favor the RegEx solution. The code will be much cleaner. I would hesitate to use toLowerCase() in situations where I knew the strings were going to be large, since strings are immutable and would have to be copied. Also, the matches() solution might be confusing because it takes a regular expression as an argument (searching for "Need$le" cold be problematic).

Building on some of the above examples:

public boolean containsIgnoreCase( String haystack, String needle ) {
  if(needle.equals(""))
    return true;
  if(haystack == null || needle == null || haystack .equals(""))
    return false; 

  Pattern p = Pattern.compile(needle,Pattern.CASE_INSENSITIVE+Pattern.LITERAL);
  Matcher m = p.matcher(haystack);
  return m.find();
}

example call: 

String needle = "Need$le";
String haystack = "This is a haystack that might have a need$le in it.";
if( containsIgnoreCase( haystack, needle) ) {
  System.out.println( "Found " + needle + " within " + haystack + "." );
}

(Note: you might want to handle NULL and empty strings differently depending on your needs. I think they way I have it is closer to the Java spec for strings.)

Speed critical solutions could include iterating through the haystack character by character looking for the first character of the needle. When the first character is matched (case insenstively), begin iterating through the needle character by character, looking for the corresponding character in the haystack and returning "true" if all characters get matched. If a non-matched character is encountered, resume iteration through the haystack at the next character, returning "false" if a position > haystack.length() - needle.length() is reached.

How to show PIL images on the screen?

From near the beginning of the PIL Tutorial:

Once you have an instance of the Image class, you can use the methods defined by this class to process and manipulate the image. For example, let's display the image we just loaded:

     >>> im.show()

Update:

Nowadays theImage.show() method is formally documented in the Pillow fork of PIL along with an explanation of how it's implemented on different OSs.

Angular EXCEPTION: No provider for Http

>= Angular 4.3

for the introduced HttpClientModule

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule, // if used
    HttpClientModule,
    JsonpModule // if used
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Angular2 >= RC.5

Import HttpModule to the module where you use it (here for example the AppModule:

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

@NgModule({
  imports: [
    BrowserModule,
    FormsModule, // if used
    HttpModule,
    JsonpModule // if used
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Importing the HttpModule is quite similar to adding HTTP_PROVIDERS in previous version.

How to set image in imageview in android?

        ImageView iv= (ImageView)findViewById(R.id.img_selected_image);
        public static int getDrawable(Context context, String name)//method to get id
        {
         Assert.assertNotNull(context);
         Assert.assertNotNull(name);
        return context.getResources().getIdentifier(name,    //return id
            "your drawable", context.getPackageName());
        }
        image.setImageResource(int Id);//set id using this method

Installing Apple's Network Link Conditioner Tool

It's in an additional download. Use this menu item:

Xcode > Open Developer Tool > More Developer Tools...

and get "Hardware IO Tools for Xcode".

For Xcode 8+, get "Additional Tools for Xcode [version]".

Double-click on a .prefPane file to install. If you already have an older .prefPane installed, you'll need to remove it from /Library/PreferencePanes.

How to add a .dll reference to a project in Visual Studio

Copy the downloaded DLL file in a custom folder on your dev drive, then add the reference to your project using the Browse button in the Add Reference dialog.
Be sure that the new reference has the Copy Local = True.
The Add Reference dialog could be opened right-clicking on the References item in your project in Solution Explorer

UPDATE AFTER SOME YEARS
At the present time the best way to resolve all those problems is through the
Manage NuGet packages menu command of Visual Studio 2017/2019.
You can right click on the References node of your project and select that command. From the Browse tab search for the library you want to use in the NuGet repository, click on the item if found and then Install it. (Of course you need to have a package for that DLL and this is not guaranteed to exist)

Read about NuGet here

How to write logs in text file when using java.util.logging.Logger

Here is an example of how to overwrite Logger configuration from the code. Does not require external configuration file ..

FileLoggerTest.java:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

public class FileLoggerTest {

    public static void main(String[] args) {

        try {
            String h = MyLogHandler.class.getCanonicalName();
            StringBuilder sb = new StringBuilder();
            sb.append(".level=ALL\n");
            sb.append("handlers=").append(h).append('\n');
            LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
        } catch (IOException | SecurityException ex) {
            // Do something about it
        }

        Logger.getGlobal().severe("Global SEVERE log entry");
        Logger.getLogger(FileLoggerTest.class.getName()).log(Level.SEVERE, "This is a SEVERE log entry");
        Logger.getLogger("SomeName").log(Level.WARNING, "This is a WARNING log entry");
        Logger.getLogger("AnotherName").log(Level.INFO, "This is an INFO log entry");
        Logger.getLogger("SameName").log(Level.CONFIG, "This is an CONFIG log entry");
        Logger.getLogger("SameName").log(Level.FINE, "This is an FINE log entry");
        Logger.getLogger("SameName").log(Level.FINEST, "This is an FINEST log entry");
        Logger.getLogger("SameName").log(Level.FINER, "This is an FINER log entry");
        Logger.getLogger("SameName").log(Level.ALL, "This is an ALL log entry");

    }
}

MyLogHandler.java

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;

public final class MyLogHandler extends FileHandler {

    public MyLogHandler() throws IOException, SecurityException {
        super("/tmp/path-to-log.log");
        setFormatter(new SimpleFormatter());
        setLevel(Level.ALL);
    }

    @Override
    public void publish(LogRecord record) {
        System.out.println("Some additional logic");
        super.publish(record);
    }

}

How to extract numbers from string in c?

Or you can make a simple function like this:

// Provided 'c' is only a numeric character
int parseInt (char c) {
    return c - '0';
}

Cygwin Make bash command not found

I faced the same problem too. Look up to the left side, and select (full). (Make), (gcc) and many others will appear. You will be able to chose the search bar to find them easily.

What issues should be considered when overriding equals and hashCode in Java?

There are some issues worth noticing if you're dealing with classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate, if you didn't think this was unreasonably complicated already!

Lazy loaded objects are subclasses

If your objects are persisted using an ORM, in many cases you will be dealing with dynamic proxies to avoid loading object too early from the data store. These proxies are implemented as subclasses of your own class. This means thatthis.getClass() == o.getClass() will return false. For example:

Person saved = new Person("John Doe");
Long key = dao.save(saved);
dao.flush();
Person retrieved = dao.retrieve(key);
saved.getClass().equals(retrieved.getClass()); // Will return false if Person is loaded lazy

If you're dealing with an ORM, using o instanceof Person is the only thing that will behave correctly.

Lazy loaded objects have null-fields

ORMs usually use the getters to force loading of lazy loaded objects. This means that person.name will be null if person is lazy loaded, even if person.getName() forces loading and returns "John Doe". In my experience, this crops up more often in hashCode() and equals().

If you're dealing with an ORM, make sure to always use getters, and never field references in hashCode() and equals().

Saving an object will change its state

Persistent objects often use a id field to hold the key of the object. This field will be automatically updated when an object is first saved. Don't use an id field in hashCode(). But you can use it in equals().

A pattern I often use is

if (this.getId() == null) {
    return this == other;
}
else {
    return this.getId().equals(other.getId());
}

But: you cannot include getId() in hashCode(). If you do, when an object is persisted, its hashCode changes. If the object is in a HashSet, you'll "never" find it again.

In my Person example, I probably would use getName() for hashCode and getId() plus getName() (just for paranoia) for equals(). It's okay if there are some risk of "collisions" for hashCode(), but never okay for equals().

hashCode() should use the non-changing subset of properties from equals()

getting a checkbox array value from POST

Check out the implode() function as an alternative. This will convert the array into a list. The first param is how you want the items separated. Here I have used a comma with a space after it.

$invite = implode(', ', $_POST['invite']);
echo $invite;

Pycharm does not show plot

Change import to:

import matplotlib.pyplot as plt

or use this line:

plt.pyplot.show()

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

You're out of memory. Try adding -Xmx256m to your java command line. The 256m is the amount of memory to give to the JVM (256 megabytes). It usually defaults to 64m.

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

When I tried to make ObjectMapper primary in spring boot 2.0.6 I got errors So I modified the one that spring boot created for me

Also see https://stackoverflow.com/a/48519868/255139

@Lazy
@Autowired
ObjectMapper mapper;

@PostConstruct
public ObjectMapper configureMapper() {
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);

    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, true);
    mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);

    SimpleModule module = new SimpleModule();
    module.addDeserializer(LocalDate.class, new LocalDateDeserializer());
    module.addSerializer(LocalDate.class, new LocalDateSerializer());
    mapper.registerModule(module);

    return mapper;
}

Difference between Groovy Binary and Source release?

The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.

How can I align two divs horizontally?

You need to float the divs in required direction eg left or right.

How to round down to nearest integer in MySQL?

SELECT FLOOR(12345.7344);

Read more here.

Passing an array of parameters to a stored procedure

You could use the STRING_SPLIT function in SQL Server. You can check the documentation here.

DECLARE @YourListOfIds VARCHAR(1000) -- Or VARCHAR(MAX) depending on what you need

SET @YourListOfIds = '1,2,3,4,5,6,7,8'

SELECT * FROM YourTable
WHERE Id IN(SELECT CAST(Value AS INT) FROM STRING_SPLIT(@YourListOfIds, ','))

Store text file content line by line into array

You need to do something like this for your case:-

int i = 0;
while((str = in.readLine()) != null){
    arr[i] = str;
    i++;
}

But note that the arr should be declared properly, according to the number of entries in your file.

Suggestion:- Use a List instead(Look at @Kevin Bowersox post for that)

Returning data from Axios API

    async handleResponse(){
      const result = await this.axiosTest();
    }

    async axiosTest () {
    return await axios.get(url)
    .then(function (response) {
            console.log(response.data);
            return response.data;})
.catch(function (error) {
    console.log(error);
});
}

You can find check https://flaviocopes.com/axios/#post-requests url and find some relevant information in the GET section of this post.

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

I'm astonished to see so many replies requiring coding to change a single use case (GET) in one API instead of using a proper tool what has to be installed once and can be used for any API (own or 3rd party) and all use cases.

So the good answer is:

  1. If you only want to request json or other content type install Requestly or a similar tool and modify the Accept header.
  2. If you want to use POST too and have nicely formatted json, xml, etc. use a proper API testing extension like Postman or ARC.

Formatting Phone Numbers in PHP

Phone numbers are hard. For a more robust, international solution, I would recommend this well-maintained PHP port of Google's libphonenumber library.

Using it like this,

use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;

$phoneUtil = PhoneNumberUtil::getInstance();

$numberString = "+12123456789";

try {
    $numberPrototype = $phoneUtil->parse($numberString, "US");

    echo "Input: " .          $numberString . "\n";
    echo "isValid: " .       ($phoneUtil->isValidNumber($numberPrototype) ? "true" : "false") . "\n";
    echo "E164: " .           $phoneUtil->format($numberPrototype, PhoneNumberFormat::E164) . "\n";
    echo "National: " .       $phoneUtil->format($numberPrototype, PhoneNumberFormat::NATIONAL) . "\n";
    echo "International: " .  $phoneUtil->format($numberPrototype, PhoneNumberFormat::INTERNATIONAL) . "\n";
} catch (NumberParseException $e) {
    // handle any errors
}

you will get the following output:

Input: +12123456789
isValid: true
E164: +12123456789
National: (212) 345-6789
International: +1 212-345-6789

I'd recommend using the E164 format for duplicate checks. You could also check whether the number is a actually mobile number or not (using PhoneNumberUtil::getNumberType()), or whether it's even a US number (using PhoneNumberUtil::getRegionCodeForNumber()).

As a bonus, the library can handle pretty much any input. If you, for instance, choose to run 1-800-JETBLUE through the code above, you will get

Input: 1-800-JETBLUE
isValid: true
E164: +18005382583
National: (800) 538-2583
International: +1 800-538-2583

Neato.

It works just as nicely for countries other than the US. Just use another ISO country code in the parse() argument.

How do I remove all .pyc files from a project?

find . -name "*.pyc"|xargs rm -rf

.htaccess - how to force "www." in a generic way?

I would use this rule:

RewriteEngine On
RewriteCond %{HTTP_HOST} !=""
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

The first condition checks whether the Host value is not empty (in case of HTTP/1.0); the second checks whether the the Host value does not begin with www.; the third checks for HTTPS (%{HTTPS} is either on or off, so %{HTTPS}s is either ons or offs and in case of ons the s is matched). The substitution part of RewriteRule then just merges the information parts to a full URL.

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

How to use protractor to check if an element is visible?

I had a similar issue, in that I only wanted return elements that were visible in a page object. I found that I'm able to use the css :not. In the case of this issue, this should do you...

expect($('i.icon-spinner:not(.ng-hide)').isDisplayed()).toBeTruthy();

In the context of a page object, you can get ONLY those elements that are visible in this way as well. Eg. given a page with multiple items, where only some are visible, you can use:

this.visibileIcons = $$('i.icon:not(.ng-hide)'); 

This will return you all visible i.icons

C++ initial value of reference to non-const must be an lvalue

When you call test with &nKByte, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.

Either do not use a reference for the argument, or better yet don't use a pointer.

TypeScript add Object to array with push

class PushObjects {
    testMethod(): Array<number> { 
        //declaration and initialisation of array onject
        var objs: number[] = [1,2,3,4,5,7];
        //push the elements into the array object
        objs.push(100);
        //pop the elements from the array
        objs.pop();
        return objs;
    }   
}

let pushObj = new PushObjects();
//create the button element from the dom object 
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () { 

    alert(pushObj.testMethod());

} 

document.body.appendChild(btn);

iOS Simulator to test website on Mac

I use this site mostly

Its good one

http://iphone4simulator.com/

Still its better preferred to test on real device..

Hope this info helps you..

How to add scroll bar to the Relative Layout?

Just put yourRelativeLayout inside ScrollView

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  ------- here RelativeLayout ------
</ScrollView>

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

Have you add a default route to this class?

public class RouteConfig {
    public static void RegisterRoutes (RouteCollection routes) {`
        //"HomePage" is the root view of your app
        routes.MapRoute (
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new {
                controller = "Home", action = "HomePage", id = UrlParameter.Optional
            }
        );
    }
}

` After that in Global.asax.cs add this line to Application_Start() method:

RouteConfig.RegisterRoutes (RouteTable.Routes);

I had this problem after I made an upgrade from MVC4 to MVC5 following this post and I had that line commented for a reason that I've forgot.

Hope this helps!

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

It is not an issue it is because of caching...

To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products').

After timestamp it should be axios.get(/api/products?${Date.now()}.

It will resolve your 304 status code.

How to send an email from JavaScript

You can't send an email directly with javascript.

You can, however, open the user's mail client:

window.open('mailto:[email protected]');

There are also some parameters to pre-fill the subject and the body:

window.open('mailto:[email protected]?subject=subject&body=body');

Another solution would be to do an ajax call to your server, so that the server sends the email. Be careful not to allow anyone to send any email through your server.

Why split the <script> tag when writing it with document.write()?

</script> has to be broken up because otherwise it would end the enclosing <script></script> block too early. Really it should be split between the < and the /, because a script block is supposed (according to SGML) to be terminated by any end-tag open (ETAGO) sequence (i.e. </):

Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "</" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.

However in practice browsers only end parsing a CDATA script block on an actual </script> close-tag.

In XHTML there is no such special handling for script blocks, so any < (or &) character inside them must be &escaped; like in any other element. However then browsers that are parsing XHTML as old-school HTML will get confused. There are workarounds involving CDATA blocks, but it's easiest simply to avoid using these characters unescaped. A better way of writing a script element from script that works on either type of parser would be:

<script type="text/javascript">
    document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>');
</script>

Check if a string contains another string

There is also the InStrRev function which does the same type of thing, but starts searching from the end of the text to the beginning.

Per @rene's answer...

Dim pos As Integer
pos = InStrRev("find the comma, in the string", ",")

...would still return 15 to pos, but if the string has more than one of the search string, like the word "the", then:

Dim pos As Integer
pos = InStrRev("find the comma, in the string", "the")

...would return 20 to pos, instead of 6.

Pip install - Python 2.7 - Windows 7

It is possible that in python 2.7 pip is installed by default. if it is not then you can execute

python -m ensurepip --default-pip

This worked for me.

Source: https://docs.python.org/2/installing/

Python: How to get values of an array at certain index positions?

Although you ask about numpy arrays, you can get the same behavior for regular Python lists by using operator.itemgetter.

>>> from operator import itemgetter
>>> a = [0,88,26,3,48,85,65,16,97,83,91]
>>> ind_pos = [1, 5, 7]
>>> print itemgetter(*ind_pos)(a)
(88, 85, 16)

How to pass a value to razor variable from javascript variable?

Razor View Server Side variable can be read to Client Side JavaScript using @ While and JavaScript client side variable can read to Razor View using @:

What are the differences between the different saving methods in Hibernate?

This link explains in good manner :

http://www.stevideter.com/2008/12/07/saveorupdate-versus-merge-in-hibernate/

We all have those problems that we encounter just infrequently enough that when we see them again, we know we’ve solved this, but can’t remember how.

The NonUniqueObjectException thrown when using Session.saveOrUpdate() in Hibernate is one of mine. I’ll be adding new functionality to a complex application. All my unit tests work fine. Then in testing the UI, trying to save an object, I start getting an exception with the message “a different object with the same identifier value was already associated with the session.” Here’s some example code from Java Persistence with Hibernate.

            Session session = sessionFactory1.openSession();
            Transaction tx = session.beginTransaction();
            Item item = (Item) session.get(Item.class, new Long(1234));
            tx.commit();
            session.close(); // end of first session, item is detached

            item.getId(); // The database identity is "1234"
            item.setDescription("my new description");
            Session session2 = sessionFactory.openSession();
            Transaction tx2 = session2.beginTransaction();
            Item item2 = (Item) session2.get(Item.class, new Long(1234));
            session2.update(item); // Throws NonUniqueObjectException
            tx2.commit();
            session2.close();

To understand the cause of this exception, it’s important to understand detached objects and what happens when you call saveOrUpdate() (or just update()) on a detached object.

When we close an individual Hibernate Session, the persistent objects we are working with are detached. This means the data is still in the application’s memory, but Hibernate is no longer responsible for tracking changes to the objects.

If we then modify our detached object and want to update it, we have to reattach the object. During that reattachment process, Hibernate will check to see if there are any other copies of the same object. If it finds any, it has to tell us it doesn’t know what the “real” copy is any more. Perhaps other changes were made to those other copies that we expect to be saved, but Hibernate doesn’t know about them, because it wasn’t managing them at the time.

Rather than save possibly bad data, Hibernate tells us about the problem via the NonUniqueObjectException.

So what are we to do? In Hibernate 3, we have merge() (in Hibernate 2, use saveOrUpdateCopy()). This method will force Hibernate to copy any changes from other detached instances onto the instance you want to save, and thus merges all the changes in memory before the save.

        Session session = sessionFactory1.openSession();
        Transaction tx = session.beginTransaction();
        Item item = (Item) session.get(Item.class, new Long(1234));
        tx.commit();
        session.close(); // end of first session, item is detached

        item.getId(); // The database identity is "1234"
        item.setDescription("my new description");
        Session session2 = sessionFactory.openSession();
        Transaction tx2 = session2.beginTransaction();
        Item item2 = (Item) session2.get(Item.class, new Long(1234));
        Item item3 = session2.merge(item); // Success!
        tx2.commit();
        session2.close();

It’s important to note that merge returns a reference to the newly updated version of the instance. It isn’t reattaching item to the Session. If you test for instance equality (item == item3), you’ll find it returns false in this case. You will probably want to work with item3 from this point forward.

It’s also important to note that the Java Persistence API (JPA) doesn’t have a concept of detached and reattached objects, and uses EntityManager.persist() and EntityManager.merge().

I’ve found in general that when using Hibernate, saveOrUpdate() is usually sufficient for my needs. I usually only need to use merge when I have objects that can have references to objects of the same type. Most recently, the cause of the exception was in the code validating that the reference wasn’t recursive. I was loading the same object into my session as part of the validation, causing the error.

Where have you encountered this problem? Did merge work for you or did you need another solution? Do you prefer to always use merge, or prefer to use it only as needed for specific cases

AngularJs ReferenceError: angular is not defined

Always make sure that js file (angular.min.js) is referenced first in the HTML file. For example:

----------------- This reference will THROW error -------------------------

< script src="otherXYZ.js"></script>
< script src="angular.min.js"></script>

----------------- This reference will WORK as expected -------------------

< script src="angular.min.js"></script>
< script src="otherXYZ.js"></script>

Xcopy Command excluding files and folders

Just give full path to exclusion file: eg..

-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt

In this example the file would be located " C:\list-of-excluded-files.txt "

or...

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt

In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "

Full path fixes syntax error.

What is the "right" JSON date format?

When in doubt simply go to the javascript web console of a modern browser by pressing F12 (Ctrl+Shift+K in Firefox) and write the following:

new Date().toISOString()

Will output:

"2019-07-04T13:33:03.969Z"

Ta-da!!

How can I show a hidden div when a select option is selected?

you can use the following common function.

<div>
     <select class="form-control" 
             name="Extension for area validity sought for" 
             onchange="CommonShowHide('txtc1opt2', this, 'States')"
     >
         <option value="All India">All India</option>
         <option value="States">States</option>
     </select>

     <input type="text" 
            id="txtc1opt2" 
            style="display:none;" 
            name="Extension for area validity sought for details" 
            class="form-control" 
            value="" 
            placeholder="">

</div>
<script>
    function CommonShowHide(ElementId, element, value) {
         document
             .getElementById(ElementId)
             .style
             .display = element.value == value ? 'block' : 'none';
    }
</script>

Is a view faster than a simple query?

It all depends on the situation. MS SQL Indexed views are faster than a normal view or query but indexed views can not be used in a mirrored database invironment (MS SQL).

A view in any kind of a loop will cause serious slowdown because the view is repopulated each time it is called in the loop. Same as a query. In this situation a temporary table using # or @ to hold your data to loop through is faster than a view or a query.

So it all depends on the situation.

How to convert a Map to List in Java?

    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("java", 20);
    map.put("C++", 45);

    Set <Entry<String, Integer>> set = map.entrySet();

    List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);

we can have both key and value pair in list.Also can get key and value using Map.Entry by iterating over list.

Vector erase iterator

Because the method erase in vector return the next iterator of the passed iterator.

I will give example of how to remove element in vector when iterating.

void test_del_vector(){
    std::vector<int> vecInt{0, 1, 2, 3, 4, 5};

    //method 1
    for(auto it = vecInt.begin();it != vecInt.end();){
        if(*it % 2){// remove all the odds
            it = vecInt.erase(it); // note it will = next(it) after erase
        } else{
            ++it;
        }
    }

    // output all the remaining elements
    for(auto const& it:vecInt)std::cout<<it;
    std::cout<<std::endl;

    // recreate vecInt, and use method 2
    vecInt = {0, 1, 2, 3, 4, 5};
    //method 2
    for(auto it=std::begin(vecInt);it!=std::end(vecInt);){
        if (*it % 2){
            it = vecInt.erase(it);
        }else{
            ++it;
        }
    }

    // output all the remaining elements
    for(auto const& it:vecInt)std::cout<<it;
    std::cout<<std::endl;

    // recreate vecInt, and use method 3
    vecInt = {0, 1, 2, 3, 4, 5};
    //method 3
    vecInt.erase(std::remove_if(vecInt.begin(), vecInt.end(),
                 [](const int a){return a % 2;}),
                 vecInt.end());

    // output all the remaining elements
    for(auto const& it:vecInt)std::cout<<it;
    std::cout<<std::endl;

}

output aw below:

024
024
024

A more generate method:

template<class Container, class F>
void erase_where(Container& c, F&& f)
{
    c.erase(std::remove_if(c.begin(), c.end(),std::forward<F>(f)),
            c.end());
}

void test_del_vector(){
    std::vector<int> vecInt{0, 1, 2, 3, 4, 5};
    //method 4
    auto is_odd = [](int x){return x % 2;};
    erase_where(vecInt, is_odd);

    // output all the remaining elements
    for(auto const& it:vecInt)std::cout<<it;
    std::cout<<std::endl;    
}

Cannot run emulator in Android Studio

Short answer: try to create the same image using the old school <AndroidSDK>\AVD Manager.exe.

Working in Android Studio, running all the integrated tools, it became natural to me not to use the old managers (AVD/SDK).

In my case, I had this problem when used the new (integrated) AVD Manager to create devices with old system images (API 11 and below, as I've tested).

When I tried to use the old school AVD Manager tool (located in <AndroidSDK>\AVD Manager.exe) to create these old device images, I had success.

how to increase java heap memory permanently?

This worked for me:

export _JAVA_OPTIONS="-Xmx1g"

It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:

java -XshowSettings:vm

and it will tell you:

Picked up _JAVA_OPTIONS: -Xmx1g

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

Check this out :

http://jsfiddle.net/PTbGc/

Your issue seems to have been fixed.


What shows up for me (under Chrome and Mac OS X)

1. one
2. two
  2.1. two.one
  2.2. two.two
  2.3. two.three
3. three
  3.1 three.one
  3.2 three.two
    3.2.1 three.two.one
    3.2.2 three.two.two
4. four

How I did it


Instead of :

<li>Item 1</li>
<li>Item 2</li>
   <ol>
        <li>Subitem 1</li>
        <li>Subitem 2</li>
   </ol>

Do :

<li>Item 1</li>
<li>Item 2
   <ol>
        <li>Subitem 1</li>
        <li>Subitem 2</li>
   </ol>
</li>

Difference between F5, Ctrl + F5 and click on refresh button?

CTRL+F5 Reloads the current page, ignoring cached content and generating the expected result.

Zoom in on a point (using scale and translate)

you can use scrollto(x,y) function to handle the position of scrollbar right to the point that you need to be showed after zooming.for finding the position of mouse use event.clientX and event.clientY. this will help you

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

Hard reset of a single file

Since Git 2.23 (August 2019) you can use restore (more info):

git restore pathTo/MyFile

The above will restore MyFile on HEAD (the last commit) on the current branch.

If you want to get the changes from other commit you can go backwards on the commit history. The below command will get MyFile two commits previous to the last one. You need now the -s (--source) option since now you use master~2 and not master (the default) as you restore source:

git restore -s master~2 pathTo/MyFile

You can also get the file from other branch!

git restore -s my-feature-branch pathTo/MyFile

Can I execute a function after setState is finished updating?

render will be called every time you setState to re-render the component if there are changes. If you move your call to drawGrid there rather than calling it in your update* methods, you shouldn't have a problem.

If that doesn't work for you, there is also an overload of setState that takes a callback as a second parameter. You should be able to take advantage of that as a last resort.

Get IP address of visitors using Flask for Python

See the documentation on how to access the Request object and then get from this same Request object, the attribute remote_addr.

Code example

from flask import request
from flask import jsonify

@app.route("/get_my_ip", methods=["GET"])
def get_my_ip():
    return jsonify({'ip': request.remote_addr}), 200

For more information see the Werkzeug documentation.

How to align LinearLayout at the center of its parent?

Below is code to put your Linearlayout at bottom and put its content at center. You have to use RelativeLayout to set Layout at bottom.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#97611F"
    android:gravity="center_horizontal"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:text="View Saved Searches"
        android:textSize="15dp"
        android:textColor="#fff"
        android:gravity="center_vertical"
        android:visibility="visible" />
    <TextView
        android:layout_width="30dp"
        android:layout_height="24dp"
        android:text="12"
        android:textSize="12dp"
        android:textColor="#fff"
        android:gravity="center_horizontal"
        android:padding="1dp"
        android:visibility="visible" />
  </LinearLayout>  
</RelativeLayout>

JavaScript Chart Library

Another is RGraph: Javascript charts and graph library:

http://www.rgraph.net

Canvas based so it's fast and there's roughly 20 different chart types. It's free for non-commercial use too!

Avoid printStackTrace(); use a logger call instead

Let's talk in from company concept. Log gives you flexible levels (see Difference between logger.info and logger.debug). Different people want to see different levels, like QAs, developers, business people. But e.printStackTrace() will print out everything. Also, like if this method will be restful called, this same error may print several times. Then the Devops or Tech-Ops people in your company may be crazy because they will receive the same error reminders. I think a better replacement could be log.error("errors happend in XXX", e) This will also print out whole information which is easy reading than e.printStackTrace()

How can I join multiple SQL tables using the IDs?

Simple INNER JOIN VIEW code....

CREATE VIEW room_view
AS SELECT a.*,b.*
FROM j4_booking a INNER JOIN j4_scheduling b
on a.room_id = b.room_id;

Can anyone recommend a simple Java web-app framework?

Try this: http://skingston.com/SKWeb

It could do with some more features and improvements, but it is simple and it works.

How to store the hostname in a variable in a .bat file?

I'm using the environment variable COMPUTERNAME:

copy "C:\Program Files\Windows Resource Kits\Tools\" %SYSTEMROOT%\system32
srvcheck \\%COMPUTERNAME% > c:\shares.txt
echo %COMPUTERNAME%

How to find specific lines in a table using Selenium?

Well previously, I used the approach that you can find inside the WebElement:

WebElement baseTable = driver.findElement(By.tagName("table"));
WebElement tableRow = baseTable.findElement(By.xpath("//tr[2]")); //should be the third row
webElement cellIneed = tableRow.findElement(By.xpath("//td[2]"));
String valueIneed = cellIneed.getText();

Please note that I find inside the found WebElement instance.

The above is Java code, assuming that driver variable is healthy instance of WebDriver

findAll() in yii

Another simple way get by using findall in yii

$id =101; 
$comments = EmailArchive::model()->findAll(array("condition"=>"':email_id'=$id"));
foreach($comments as $comments_1) 
{ 
echo  "email:".$comments_1['email_id'];
}

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

JSON string to JS object

The string you are returning is not valid JSON. The names in the objects needs to be quoted and the whole string needs to be put in { … } to form an object. JSON also cannot contain something like new Date(). JSON is just a small subset of JavaScript that has only strings, numbers, objects, arrays, true, false and null.

See the JSON grammar for more information.

How do I call a dynamically-named method in Javascript?

Within a ServiceWorker or Worker, replace window with self:

self[method_prefix + method_name](arg1, arg2);

Workers have no access to the DOM, therefore window is an invalid reference. The equivalent global scope identifier for this purpose is self.

How to list all files in a directory and its subdirectories in hadoop hdfs

Code snippet for both recursive and non-recursive approaches:

//helper method to get the list of files from the HDFS path
public static List<String>
    listFilesFromHDFSPath(Configuration hadoopConfiguration,
                          String hdfsPath,
                          boolean recursive) throws IOException,
                                        IllegalArgumentException
{
    //resulting list of files
    List<String> filePaths = new ArrayList<String>();

    //get path from string and then the filesystem
    Path path = new Path(hdfsPath);  //throws IllegalArgumentException
    FileSystem fs = path.getFileSystem(hadoopConfiguration);

    //if recursive approach is requested
    if(recursive)
    {
        //(heap issues with recursive approach) => using a queue
        Queue<Path> fileQueue = new LinkedList<Path>();

        //add the obtained path to the queue
        fileQueue.add(path);

        //while the fileQueue is not empty
        while (!fileQueue.isEmpty())
        {
            //get the file path from queue
            Path filePath = fileQueue.remove();

            //filePath refers to a file
            if (fs.isFile(filePath))
            {
                filePaths.add(filePath.toString());
            }
            else   //else filePath refers to a directory
            {
                //list paths in the directory and add to the queue
                FileStatus[] fileStatuses = fs.listStatus(filePath);
                for (FileStatus fileStatus : fileStatuses)
                {
                    fileQueue.add(fileStatus.getPath());
                } // for
            } // else

        } // while

    } // if
    else        //non-recursive approach => no heap overhead
    {
        //if the given hdfsPath is actually directory
        if(fs.isDirectory(path))
        {
            FileStatus[] fileStatuses = fs.listStatus(path);

            //loop all file statuses
            for(FileStatus fileStatus : fileStatuses)
            {
                //if the given status is a file, then update the resulting list
                if(fileStatus.isFile())
                    filePaths.add(fileStatus.getPath().toString());
            } // for
        } // if
        else        //it is a file then
        {
            //return the one and only file path to the resulting list
            filePaths.add(path.toString());
        } // else

    } // else

    //close filesystem; no more operations
    fs.close();

    //return the resulting list
    return filePaths;
} // listFilesFromHDFSPath

orderBy multiple fields in Angular

Please see this:

http://jsfiddle.net/JSWorld/Hp4W7/32/

<div ng-repeat="division in divisions | orderBy:['group','sub']">{{division.group}}-{{division.sub}}</div>

Redirecting to a new page after successful login

You need to set the location header as follows:

header('Location: http://www.example.com/');

Replacing http://www.example.com of course with the url of your landing page.

Add this where you have finished logging the user in.

Note: When redirecting the user will be immediately redirected so you're message probably won't display.

Additionally, you need to move your PHP code to the top of the file for this solution to work.

On another side note, please see my comment above regarding the use of the deprecated mysql statements and consider using the newer, safer and improved mysqli or PDO statements.

How to calculate the angle between a line and the horizontal axis?

Considering the exact question, putting us in a "special" coordinates system where positive axis means moving DOWN (like a screen or an interface view), you need to adapt this function like this, and negative the Y coordinates:

Example in Swift 2.0

func angle_between_two_points(pa:CGPoint,pb:CGPoint)->Double{
    let deltaY:Double = (Double(-pb.y) - Double(-pa.y))
    let deltaX:Double = (Double(pb.x) - Double(pa.x))
    var a = atan2(deltaY,deltaX)
    while a < 0.0 {
        a = a + M_PI*2
    }
    return a
}

This function gives a correct answer to the question. Answer is in radians, so the usage, to view angles in degrees, is:

let p1 = CGPoint(x: 1.5, y: 2) //estimated coords of p1 in question
let p2 = CGPoint(x: 2, y : 3) //estimated coords of p2 in question

print(angle_between_two_points(p1, pb: p2) / (M_PI/180))
//returns 296.56

How to implement a custom AlertDialog View

After changing the ID it android.R.id.custom, I needed to add the following to get the View to display:

((View) f1.getParent()).setVisibility(View.VISIBLE);

However, this caused the new View to render in a big parent view with no background, breaking the dialog box in two parts (text and buttons, with the new View in between). I finally got the effect that I wanted by inserting my View next to the message:

LinearLayout f1 = (LinearLayout)findViewById(android.R.id.message).getParent().getParent();

I found this solution by exploring the View tree with View.getParent() and View.getChildAt(int). Not really happy about either, though. None of this is in the Android docs and if they ever change the structure of the AlertDialog, this might break.

Using Linq to group a list of objects into a new grouped list of list of objects

For type

public class KeyValue
{
    public string KeyCol { get; set; }
    public string ValueCol { get; set; }
}

collection

var wordList = new Model.DTO.KeyValue[] {
    new Model.DTO.KeyValue {KeyCol="key1", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key2", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key3", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key4", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key5", ValueCol="value3" },
    new Model.DTO.KeyValue {KeyCol="key6", ValueCol="value4" }
};

our linq query look like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList() };

or for array instead of list like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList().ToArray<string>() };

SQLite3 database or disk is full / the database disk image is malformed

I have seen this happen when the database gets corrupted, have you tried cloning it into a new one ?

Safley copy a s SQLite db

Safely copy a SQLite database

It's trivially easy to copy a SQLite database. It's less trivial to do this in a way that won't corrupt it. Here's how:

shell$ sqlite3 some.db
sqlite> begin immediate;
<press CTRL+Z>
shell$ cp some.db some.db.backup
shell$ exit
sqlite> rollback;

This will give you a nice clean backup that's sure to be in a proper state, since writing to the database half-way through your copying process is impossible.

How do I check for a network connection?

You can check for a network connection in .NET 2.0 using GetIsNetworkAvailable():

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

To monitor changes in IP address or changes in network availability use the events from the NetworkChange class:

System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged

Does WGET timeout?

The default timeout is 900 second. You can specify different timeout.

-T seconds
--timeout=seconds

The default is to retry 20 times. You can specify different tries.

-t number
--tries=number

link: wget man document

What is base 64 encoding used for?

Mostly, I've seen it used to encode binary data in contexts that can only handle ascii - or a simple - character sets.

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

use property UseSimpleDictionaryFormat on DataContractJsonSerializer and set it to true.

Does the job :)

Android: Test Push Notification online (Google Cloud Messaging)

POSTMAN : A google chrome extension

Use postman to send message instead of server. Postman settings are as follows :

Request Type: POST

URL: https://android.googleapis.com/gcm/send

Header
  Authorization  : key=your key //Google API KEY
  Content-Type : application/json

JSON (raw) :
{       
  "registration_ids":["yours"],
  "data": {
    "Hello" : "World"
  } 
}

on success you will get

Response :
{
  "multicast_id": 6506103988515583000,
  "success": 1,
  "failure": 0,
  "canonical_ids": 0,
  "results": [
    {
      "message_id": "0:1432811719975865%54f79db3f9fd7ecd"
    }
  ]
}

Request exceeded the limit of 10 internal redirects due to probable configuration error

i solved this by http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/ just uncomment or add this:

RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

to your .htaccess file

Laravel - Route::resource vs Route::controller

For route controller method we have to define only one route. In get or post method we have to define the route separately.

And the resources method is used to creates multiple routes to handle a variety of Restful actions.

Here the Laravel documentation about this.

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

How can I login to a website with Python?

Websites in general can check authorization in many different ways, but the one you're targeting seems to make it reasonably easy for you.

All you need is to POST to the auth/login URL a form-encoded blob with the various fields you see there (forget the labels for, they're decoration for human visitors). handle=whatever&password-clear=pwd and so on, as long as you know the values for the handle (AKA email) and password you should be fine.

Presumably that POST will redirect you to some "you've successfully logged in" page with a Set-Cookie header validating your session (be sure to save that cookie and send it back on further interaction along the session!).

Make a nav bar stick

You can do it with CSS only by creating your menu twice. It's not ideal but it gives you the opportunity have a different design for the menu once it's on top and you'll have nothing else than CSS, no jquery. Here is an example with DIV (you can of course change it to NAV if you prefer):

<div id="hiddenmenu">
 THIS IS MY HIDDEN MENU
</div>
<div id="header">
 Here is my header with a lot of text and my main menu
</div>
<div id="body">
 MY BODY
</div>

And then have the following CSS:

#hiddenmenu {
position: fixed;
top: 0;
z-index:1;
 }
#header {
top: 0;
position:absolute;
z-index:2;
 }
#body {
padding-top: 80px;
position:absolute;
z-index: auto;
 }

Here is a fiddle for you to see: https://jsfiddle.net/brghtk4z/1/

jquery loop on Json data using $.each

Have you converted your data from string to JavaScript object?

You can do it with data = eval('(' + string_data + ')'); or, which is safer, data = JSON.parse(string_data); but later will only works in FF 3.5 or if you include json2.js

jQuery since 1.4.1 also have function for that, $.parseJSON().

But actually, $.getJSON() should give you already parsed json object, so you should just check everything thoroughly, there is little mistake buried somewhere, like you might have forgotten to quote something in json, or one of the brackets is missing.

Move to another EditText when Soft Keyboard Next is clicked on Android

android:inputType="text"

should bring the same effect. After hiting next to bring the focus to the next element.

android:nextFocusDown="@+id/.."

use this in addition if you dont want the next view to get the focus

How to check whether a string contains a substring in Ruby

You can also do this...

my_string = "Hello world"

if my_string["Hello"]
  puts 'It has "Hello"'
else
  puts 'No "Hello" found'
end

# => 'It has "Hello"'

This example uses Ruby's String #[] method.

Return None if Dictionary key is not available

You should use the get() method from the dict class

d = {}
r = d.get('missing_key', None)

This will result in r == None. If the key isn't found in the dictionary, the get function returns the second argument.

Django URL Redirect

In Django 1.8, this is how I did mine.

from django.views.generic.base import RedirectView

url(r'^$', views.comingSoon, name='homepage'),
# whatever urls you might have in here
# make sure the 'catch-all' url is placed last
url(r'^.*$', RedirectView.as_view(pattern_name='homepage', permanent=False))

Instead of using url, you can use the pattern_name, which is a bit un-DRY, and will ensure you change your url, you don't have to change the redirect too.

The APR based Apache Tomcat Native library was not found on the java.library.path

Regarding the original question asked in the title ...

  • sudo apt-get install libtcnative-1

  • or if you are on RHEL Linux yum install tomcat-native

The documentation states you need http://tomcat.apache.org/native-doc/

  • sudo apt-get install libapr1.0-dev libssl-dev
  • or RHEL yum install apr-devel openssl-devel

Parsing JSON with Unix tools

Using standard Unix tools available on most distro's. Also works well with backslashes (\) and quotes (")

WARNING: this doesn't come close to the power of jq and will only work with very simple JSON objects. It's an attempt to answer to the original question and in situations where you can't install additional tools.

function parse_json()
{
    echo $1 | \
    sed -e 's/[{}]/''/g' | \
    sed -e 's/", "/'\",\"'/g' | \
    sed -e 's/" ,"/'\",\"'/g' | \
    sed -e 's/" , "/'\",\"'/g' | \
    sed -e 's/","/'\"---SEPERATOR---\"'/g' | \
    awk -F=':' -v RS='---SEPERATOR---' "\$1~/\"$2\"/ {print}" | \
    sed -e "s/\"$2\"://" | \
    tr -d "\n\t" | \
    sed -e 's/\\"/"/g' | \
    sed -e 's/\\\\/\\/g' | \
    sed -e 's/^[ \t]*//g' | \
    sed -e 's/^"//'  -e 's/"$//'
}


parse_json '{"username":"john, doe","email":"[email protected]"}' username
parse_json '{"username":"john doe","email":"[email protected]"}' email

--- outputs ---

john, doe
[email protected]

How to initialize/instantiate a custom UIView class with a XIB file in Swift

Universal way of loading view from xib:

Example:

let myView = Bundle.loadView(fromNib: "MyView", withType: MyView.self)

Implementation:

extension Bundle {

    static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {
        if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {
            return view
        }

        fatalError("Could not load view with type " + String(describing: type))
    }
}

HTML favicon won't show on google chrome

The path must be via the URI (full).

Like: http://example.com/favicon.png

so in your case:

<!DOCTYPE html>
<html> 
    <head profile="http://www.w3.org/2005/10/profile">
        <title></title>
        <link rel="shortcut icon" 
              type="image/png" 
              href=" http://example.com/favicon.png" />
    </head>
    <body>
    </body>
</html>

Ref: http://www.w3.org/2005/10/howto-favicon

How can I access Google Sheet spreadsheets only with Javascript?

You can read Google Sheets spreadsheets data in JavaScript by using the RGraph sheets connector:

https://www.rgraph.net/canvas/docs/import-data-from-google-sheets.html

Initially (a few years ago) this relied on some RGraph functions to work its magic - but now it can work standalone (ie not requiring the RGraph common library).

Some example code (this example makes an RGraph chart):

<!-- Include the sheets library -->
<script src="RGraph.common.sheets.js"></script>

<!-- Include these two RGraph libraries to make the chart -->
<script src="RGraph.common.key.js"></script>
<script src="RGraph.bar.js"></script>

<script>
    // Create a new RGraph Sheets object using the spreadsheet's key and
    // the callback function that creates the chart. The RGraph.Sheets object is
    // passed to the callback function as an argument so it doesn't need to be
    // assigned to a variable when it's created
    new RGraph.Sheets('1ncvARBgXaDjzuca9i7Jyep6JTv9kms-bbIzyAxbaT0E', function (sheet)
    {
        // Get the labels from the spreadsheet by retrieving part of the first row
        var labels = sheet.get('A2:A7');

        // Use the column headers (ie the names) as the key
        var key = sheet.get('B1:E1');

        // Get the data from the sheet as the data for the chart
        var data   = [
            sheet.get('B2:E2'), // January
            sheet.get('B3:E3'), // February
            sheet.get('B4:E4'), // March
            sheet.get('B5:E5'), // April
            sheet.get('B6:E6'), // May
            sheet.get('B7:E7')  // June
        ];

        // Create and configure the chart; using the information retrieved above
        // from the spreadsheet
        var bar = new RGraph.Bar({
            id: 'cvs',
            data: data,
            options: {
                backgroundGridVlines: false,
                backgroundGridBorder: false,
                xaxisLabels: labels,
                xaxisLabelsOffsety: 5,
                colors: ['#A8E6CF','#DCEDC1','#FFD3B6','#FFAAA5'],
                shadow: false,
                colorsStroke: 'rgba(0,0,0,0)',
                yaxis: false,
                marginLeft: 40,
                marginBottom: 35,
                marginRight: 40,
                key: key,
                keyBoxed: false,
                keyPosition: 'margin',
                keyTextSize: 12,
                textSize: 12,
                textAccessible: false,
                axesColor: '#aaa'
            }
        }).wave();
    });
</script>

Hamcrest compare collections

For list of objects you may need something like this:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
import static org.hamcrest.Matchers.is;

@Test
@SuppressWarnings("unchecked")
public void test_returnsList(){

    arrange();
  
    List<MyBean> myList = act();
    
    assertThat(myList , contains(allOf(hasProperty("id",          is(7L)), 
                                       hasProperty("name",        is("testName1")),
                                       hasProperty("description", is("testDesc1"))),
                                 allOf(hasProperty("id",          is(11L)), 
                                       hasProperty("name",        is("testName2")),
                                       hasProperty("description", is("testDesc2")))));
}

Use containsInAnyOrder if you do not want to check the order of the objects.

P.S. Any help to avoid the warning that is suppresed will be really appreciated.

Compare two files and write it to "match" and "nomatch" files

I had used JCL about 2 years back so cannot write a code for you but here is the idea;

  1. Have 2 steps
  2. First step will have ICETOOl where you can write the matching records to matched file.
  3. Second you can write a file for mismatched by using SORT/ICETOOl or by just file operations.

again i apologize for solution without code, but i am out of touch by 2 yrs+

Create a Maven project in Eclipse complains "Could not resolve archetype"

It is also possible that your settings.xml file defined in maven/conf folder defines a location that it cannot access

How to read data of an Excel file using C#?

First of all, it's important to know what you mean by "open an Excel file for reading and copy it to clipboard..."

This is very important because there are many ways you could do that depending just on what you intend to do. Let me explain:

  1. If you want to read a set of data and copy that in the clipboard and you know the data format (e.g. column names), I suggest you use an OleDbConnection to open the file, this way you can treat the xls file content as a Database Table, so you can read data with SQL instruction and treat the data as you want.

  2. If you want to do operations on the data with the Excel object model then open it in the way you began.

  3. Some time it's possible to treat an xls file as a kind of csv file, there are tools like File Helpers which permit you to treat and open an xls file in a simple way by mapping a structure on an arbitrary object.

Another important point is in which Excel version the file is.

I have, unfortunately I say, a strong experience working with Office automation in all ways, even if bounded in concepts like Application Automation, Data Management and Plugins, and generally I suggest only as the last resort, to using Excel automation or Office automation to read data; just if there aren't better ways to accomplish that task.

Working with automation could be heavy in performance, in terms of resource cost, could involve in other issues related for example to security and more, and last but not at least, working with COM interop it's not so "free".. So my suggestion is think and analyze the situation within your needs and then take the better way.

Remove a JSON attribute

The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.

For example:

var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}

//that will not work.
delete myObj.test.keyToDelete 

instead you would need to use:

delete myObj.test[keyToDelete];

Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

For anyone still strugging (like me...) after the above more expert replies, this works in Visual Studio 2019:

outputString = Regex.Replace(inputString, @"\W", "_");

Remember to add

using System.Text.RegularExpressions;

Smooth scroll to div id jQuery

Here's what I use:

<!-- jquery smooth scroll to id's -->   
<script>
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 500);
        return false;
      }
    }
  });
});
</script>

The beauty with this one is you can use an unlimited number of hash-links and corresponding ids without having to execute a new script for each.

If you’re using WordPress, insert the code in your theme’s footer.php file right before the closing body tag </body>.

If you have no access to the theme files, you can embed the code right inside the post/page editor (you must be editing the post in Text mode) or on a Text widget that will load up on all pages.

If you’re using any other CMS or just HTML, you can insert the code in a section that loads up on all pages right before the closing body tag </body>.

If you need more details on this, check out my quick post here: jQuery smooth scroll to id

Hope that helps, and let me know if you have questions about it.

How to make overlay control above all other controls?

<Canvas Panel.ZIndex="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="570">
  <!-- YOUR XAML CODE -->
</Canvas>

How to enter in a Docker container already running with a new TTY

I started powershell on a running microsoft/iis run as daemon using

docker exec -it <nameOfContainer> powershell

How to declare 2D array in bash

One can simply define two functions to write ($4 is the assigned value) and read a matrix with arbitrary name ($1) and indexes ($2 and $3) exploiting eval and indirect referencing.

#!/bin/bash

matrix_write () {
 eval $1"_"$2"_"$3=$4
 # aux=$1"_"$2"_"$3          # Alternative way
 # let $aux=$4               # ---
}

matrix_read () {
 aux=$1"_"$2"_"$3
 echo ${!aux}
}

for ((i=1;i<10;i=i+1)); do
 for ((j=1;j<10;j=j+1)); do 
  matrix_write a $i $j $[$i*10+$j]
 done
done

for ((i=1;i<10;i=i+1)); do
 for ((j=1;j<10;j=j+1)); do 
  echo "a_"$i"_"$j"="$(matrix_read a $i $j)
 done
done

Create an application setup in visual studio 2013

Apart from Install Shield and WiX, there is Inno Setup. Although I haven't tried it myself I have heard good things about it.

Android selector & text color

Here's my implementation, which behaves exactly as item in list (at least on 2.3)

res/layout/list_video_footer.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/list_video_footer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@android:drawable/list_selector_background"
        android:clickable="true"
        android:gravity="center"
        android:minHeight="98px"
        android:text="@string/more"
        android:textColor="@color/bright_text_dark_focused"
        android:textSize="18dp"
        android:textStyle="bold" />

</FrameLayout>

res/color/bright_text_dark_focused.xml

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

    <item android:state_selected="true" android:color="#444"/>
    <item android:state_focused="true" android:color="#444"/>
    <item android:state_pressed="true" android:color="#444"/>
    <item android:color="#ccc"/>

</selector>

Combine or merge JSON on node.js without jQuery

Let object1 and object2 be two JSON object.

var object1 = [{"name": "John"}];
var object2 = [{"location": "San Jose"}];

object1.push(object2);

This will simply append object2 in object1:

[{"name":"John"},{"location":"San Jose"}]

Convert bytes to a string

I think this way is easy:

>>> bytes_data = [112, 52, 52]
>>> "".join(map(chr, bytes_data))
'p44'

SQL Server: how to create a stored procedure

try this:

create procedure dept_count( @dept_name varchar(20), @d_count INTEGER out)

   AS
   begin
     select count(*) into d_count
     from instructor
     where instructor.dept_name=dept_count.dept_name
   end

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.

After importing PDFKit, you should initialize a PDFView with a local or a remote URL and display it in your view.

if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
    let pdfView = PDFView(frame: view.frame)
    pdfView.document = PDFDocument(url: url)
    view.addSubview(pdfView)
}

Read more about PDFKit in the Apple Developer documentation.

Git refusing to merge unrelated histories on rebase

For Googlers:

If you created a new repo on GitHub and accidentally initialized it with README or .gitignore files.

If you found yourself unable to merge or rebase because .git folder got corrupted.

Then:

  • Create a new folder
  • git clone
  • Paste all your files into this folder

Now the local and remote will have "related histories" and will merge or rebase happily.

SQL Server FOR EACH Loop

You could use a variable table, like this:

declare @num int

set @num = 1

declare @results table ( val int )

while (@num < 6)
begin
  insert into @results ( val ) values ( @num )
  set @num = @num + 1
end

select val from @results

PHP: How do I display the contents of a textfile on my page?

I have to display files of computer code. If special characters are inside the file like less than or greater than, a simple "include" will not display them. Try:

$file = 'code.ino';
$orig = file_get_contents($file);
$a = htmlentities($orig);

echo '<code>';
echo '<pre>';

echo $a;

echo '</pre>';
echo '</code>';

How do I remove the "extended attributes" on a file in Mac OS X?

Use the xattr command. You can inspect the extended attributes:

$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
com.apple.quarantine

and use the -d option to delete one extended attribute:

$ xattr -d com.apple.quarantine s.7z
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms

you can also use the -c option to remove all extended attributes:

$ xattr -c s.7z
$ xattr s.7z

xattr -h will show you the command line options, and xattr has a man page.

Setting transparent images background in IrfanView

If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").

Git: add vs push vs commit

I find this image very meaningful :

enter image description here

(from : Oliver Steele -My Git Workflow (2008) )

How to add one day to a date?

Java 8 Time API:

Instant now = Instant.now(); //current date
Instant after= now.plus(Duration.ofDays(300));
Date dateAfter = Date.from(after);

Docker-compose: node_modules not present in a volume after npm install succeeds

If you want the node_modules folder available to the host during development, you could install the dependencies when you start the container instead of during build-time. I do this to get syntax highlighting working in my editor.

Dockerfile

# We're using a multi-stage build so that we can install dependencies during build-time only for production.

# dev-stage
FROM node:14-alpine AS dev-stage
WORKDIR /usr/src/app
COPY package.json ./
COPY . .
# `yarn install` will run every time we start the container. We're using yarn because it's much faster than npm when there's nothing new to install
CMD ["sh", "-c", "yarn install && yarn run start"]

# production-stage
FROM node:14-alpine AS production-stage
WORKDIR /usr/src/app
COPY package.json ./
RUN yarn install
COPY . .

.dockerignore

Add node_modules to .dockerignore to prevent it from being copied when the Dockerfile runs COPY . .. We use volumes to bring in node_modules.

**/node_modules

docker-compose.yml

node_app:
    container_name: node_app
    build:
        context: ./node_app
        target: dev-stage # `production-stage` for production
    volumes:
        # For development:
        #   If node_modules already exists on the host, they will be copied
        #   into the container here. Since `yarn install` runs after the
        #   container starts, this volume won't override the node_modules.
        - ./node_app:/usr/src/app
        # For production:
        #   
        - ./node_app:/usr/src/app
        - /usr/src/app/node_modules

How do I add comments to package.json for npm install?

You can always abuse the fact that duplicated keys are overwritten. This is what I just wrote:

"dependencies": {
  "grunt": "...",
  "grunt-cli": "...",

  "api-easy": "# Here is the pull request: https://github.com/...",
  "api-easy": "git://..."

  "grunt-vows": "...",
  "vows": "..."
}

However, it is not clear whether JSON allows duplicated keys (see Does JSON syntax allow duplicate keys in an object?. It seems to work with npm, so I take the risk.

The recommened hack is to use "//" keys (from the nodejs mailing list). When I tested it, it did not work with "dependencies" sections, though. Also, the example in the post uses multiple "//" keys, which implies that npm does not reject JSON files with duplicated keys. In other words, the hack above should always be fine.

Update: One annoying disadvantage of the duplicated key hack is that npm install --save silently eliminates all duplicates. Unfortunately, it is very easy to overlook it and your well-intentioned comments are gone.

The "//" hack is still the safest as it seems. However, multi-line comments will be removed by npm install --save, too.

how to set ul/li bullet point color?

http://www.w3schools.com/cssref/pr_list-style-type.asp

You need to use list-style-type: to change bullet type/style and the above link has all of the options listed. As others have stated the color is changed using the color property on the ul itself

To create 'black filled' bullets, use 'disc' instead of 'circle',i.e.:

list-style-type:disc

div hover background-color change?

div hover background color change

Try like this:

.class_name:hover{
    background-color:#FF0000;
}

PHP: Get the key from an array in a foreach loop

you need nested foreach loops

foreach($samplearr as $key => $item){
   echo $key;
    foreach($item as $detail){
       echo $detail['value1'] . " " . $detail['value2']
     }
 }

How to get "their" changes in the middle of conflicting Git rebase?

You want to use:

git checkout --ours foo/bar.java
git add foo/bar.java

If you rebase a branch feature_x against main (i.e. running git rebase main while on branch feature_x), during rebasing ours refers to main and theirs to feature_x.

As pointed out in the git-rebase docs:

Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.

For further details read this thread.

What is "X-Content-Type-Options=nosniff"?

# prevent mime based attacks
Header set X-Content-Type-Options "nosniff"

This header prevents "mime" based attacks. This header prevents Internet Explorer from MIME-sniffing a response away from the declared content-type as the header instructs the browser not to override the response content type. With the nosniff option, if the server says the content is text/html, the browser will render it as text/html.

http://stopmalvertising.com/security/securing-your-website-with-.htaccess/.htaccess-http-headers.html

Run a script in Dockerfile

WORKDIR /scripts
COPY bootstrap.sh .
RUN ./bootstrap.sh 

How to rollback everything to previous commit

I searched for multiple options to get my git reset to specific commit, but most of them aren't so satisfactory.

I generally use this to reset the git to the specific commit in source tree.

  1. select commit to reset on sourcetree.

  2. In dropdowns select the active branch , first Parent Only

  3. And right click on "Reset branch to this commit" and select hard reset option (soft, mixed and hard)

  4. and then go to terminal git push -f

You should be all set!

how to access iFrame parent page using jquery?

how to access iFrame parent page using jquery

window.parent.document.

jQuery is a library on top of JavaScript, not a complete replacement for it. You don't have to replace every last JavaScript expression with something involving $.

How to return JSon object

First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:

I would use an anonymous type filled with your results type:

string json = JsonConvert.SerializeObject(new
{
    results = new List<Result>()
    {
        new Result { id = 1, value = "ABC", info = "ABC" },
        new Result { id = 2, value = "JKL", info = "JKL" }
    }
});

Also, note that the generated JSON has result items with ids of type Number instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id to string in the C#.

I'd also tweak your results type and get rid of the backing fields:

public class Result
{
    public int id { get ;set; }
    public string value { get; set; }
    public string info { get; set; }
}

Furthermore, classes conventionally are PascalCased and not camelCased.

Here's the generated JSON from the code above:

{
  "results": [
    {
      "id": 1,
      "value": "ABC",
      "info": "ABC"
    },
    {
      "id": 2,
      "value": "JKL",
      "info": "JKL"
    }
  ]
}

Why Is `Export Default Const` invalid?

If the component name is explained in the file name MyComponent.js, just don't name the component, keeps code slim.

import React from 'react'

export default (props) =>
    <div id='static-page-template'>
        {props.children}
    </div>

Update: Since this labels it as unknown in stack tracing, it isn't recommended

Tensorflow installation error: not a supported wheel on this platform

For Windows 10 64bit:

I have tried all the suggestions here, but finally got it running as follows:

  1. Uninstall all current versions of Python
  2. Remove all Python references in the PATH system and user Environment variables
  3. Download the latest 64bit version of Python 3.8: Python 3.8.7 currently, NOT the latest 3.9.x version which is the one I was using, and NOT 32bit.
  4. Install with all options selected, including pip, and including PATH Environment variable
  5. pip install tensorflow (in Admin CMD prompt)
  6. Upgrade pip if prompted (optional)

Best Practices for mapping one object to another

This is a possible generic implementation using a bit of reflection (pseudo-code, don't have VS now):

public class DtoMapper<DtoType>
{
    Dictionary<string,PropertyInfo> properties;

    public DtoMapper()
    {
        // Cache property infos
        var t = typeof(DtoType);
        properties = t.GetProperties().ToDictionary(p => p.Name, p => p);
     }

    public DtoType Map(Dto dto)
    {
        var instance = Activator.CreateInstance(typeOf(DtoType));

        foreach(var p in properties)
        {
            p.SetProperty(
                instance, 
                Convert.Type(
                    p.PropertyType, 
                    dto.Items[Array.IndexOf(dto.ItemsNames, p.Name)]);

            return instance;
        }
    }

Usage:

var mapper = new DtoMapper<Model>();
var modelInstance = mapper.Map(dto);

This will be slow when you create the mapper instance but much faster later.

Save a subplot in matplotlib

While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig takes a bbox_inches argument that can be used to selectively save only a portion of a figure to an image.

Here's a quick example:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))

The full figure: Full Example Figure


Area inside the second subplot: Inside second subplot


Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction: Full second subplot

Sending Email in Android using JavaMail API without using the default/built-in app

In case that you are demanded to keep the jar library as small as possible, you can include the SMTP/POP3/IMAP function separately to avoid the "too many methods in the dex" problem.

You can choose the wanted jar libraries from the javanet web page, for example, mailapi.jar + imap.jar can enable you to access icloud, hotmail mail server in IMAP protocol. (with the help of additional.jar and activation.jar)

Multi-key dictionary in c#?

If anyone is looking for a ToMultiKeyDictionary() here is an implementation that should work with most of the answers here (based on Herman's):

public static class Extensions_MultiKeyDictionary {

    public static MultiKeyDictionary<K1, K2, V> ToMultiKeyDictionary<S, K1, K2, V>(this IEnumerable<S> items, Func<S, K1> key1, Func<S, K2> key2, Func<S, V> value) {
        var dict = new MultiKeyDictionary<K1, K2, V>(); 
        foreach (S i in items) { 
            dict.Add(key1(i), key2(i), value(i)); 
        } 
        return dict; 
    }

    public static MultiKeyDictionary<K1, K2, K3, V> ToMultiKeyDictionary<S, K1, K2, K3, V>(this IEnumerable<S> items, Func<S, K1> key1, Func<S, K2> key2, Func<S, K3> key3, Func<S, V> value) {
        var dict = new MultiKeyDictionary<K1, K2, K3, V>(); 
        foreach (S i in items) { 
            dict.Add(key1(i), key2(i), key3(i), value(i)); 
        } 
        return dict; 
    }
}

How to insert &nbsp; in XSLT

One can also do this :

<xsl:text disable-output-escaping="yes"><![CDATA[&nbsp;]]></xsl:text>

How to get your Netbeans project into Eclipse

In Eclipse:

File>Import>General>Existing projects in Workspace

Browse until get the netbeans project folder > Finish

How to detect if javascript files are loaded?

Take a look at jQuery's .load() http://api.jquery.com/load-event/

$('script').load(function () { }); 

How do I replace all line breaks in a string with <br /> elements?

if you send the variable from PHP, you can obtain it with this before sending:

$string=nl2br($string);

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

Copy table without copying data

Only want to clone the structure of table:

CREATE TABLE foo SELECT * FROM bar WHERE 1 = 2;

Also wants to copy the data:

CREATE TABLE foo as SELECT * FROM bar;

How to check if a column exists in a SQL Server table?

A more concise version

IF COL_LENGTH('table_name','column_name') IS NULL
BEGIN
/* Column does not exist or caller does not have permission to view the object */
END

The point about permissions on viewing metadata applies to all answers not just this one.

Note that the first parameter table name to COL_LENGTH can be in one, two, or three part name format as required.

An example referencing a table in a different database is

COL_LENGTH('AdventureWorks2012.HumanResources.Department','ModifiedDate')

One difference with this answer compared to using the metadata views is that metadata functions such as COL_LENGTH always only return data about committed changes irrespective of the isolation level in effect.

Select from table by knowing only date without time (ORACLE)

Convert your date column to the correct format and compare:

SELECT * From my_table WHERE to_char(my_table.my_date_col,'MM/dd/yyyy') = '8/3/2010'

This part

to_char(my_table.my_date_col,'MM/dd/yyyy')

Will result in string '8/3/2010'

Calling ASP.NET MVC Action Methods from JavaScript

If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.

<div class="cart">
      @Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>

That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on

Turning multi-line string into single comma-separated

You can also print like this:

Just awk: using printf

bash-3.2$ cat sample.log
something1:    +12.0   (some unnecessary trailing data (this must go))
something2:    +15.5   (some more unnecessary trailing data)
something4:    +9.0   (some other unnecessary data)
something1:    +13.5  (blah blah blah)

bash-3.2$ awk ' { if($2 != "") { if(NR==1) { printf $2 } else { printf "," $2 } } }' sample.log
+12.0,+15.5,+9.0,+13.5

How to change users in TortoiseSVN

If you want to remove only one saved password, e.g. for "user1":

  • Go to the saved password directory (*c:\Users\USERNAME\AppData\Roaming\Subversion\auth\svn.simple\*)
  • You will find several files in this folder (named with hash value)
  • Find the file which contains the username "user1", which you want to change (open it with Notepad).
  • Remove the file.
  • Next time you will connect to your SVN server, Tortoise will prompt you for new username and password.

What's the safest way to iterate through the keys of a Perl hash?

I woudl say:

  1. Use whatever's easiest to read/understand for most people (so keys, usually, I'd argue)
  2. Use whatever you decide consistently throught the whole code base.

This give 2 major advantages:

  1. It's easier to spot "common" code so you can re-factor into functions/methiods.
  2. It's easier for future developers to maintain.

I don't think it's more expensive to use keys over each, so no need for two different constructs for the same thing in your code.

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

in my case I have used - (Hyphen) in my script name in case of Jenkinsfile Library. Got resolved after replacing Hyphen(-) with Underscore(_)

Connect HTML page with SQL server using javascript

Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.

In the code. I have used VBScript and embedded it in HTML. Try it out!

<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--    

Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset

Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString

dim form1
Set form1 = document.Register

Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value

connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")

End Sub

//-->
</script>
</head>
<body>

<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name:   <input type="text" name="Name">
Age:        <input type="text" name="Age">
Address:        <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form> 
</p>
</pre>
</body>
</html>

Check that a input to UITextField is numeric only

Here are a few one-liners which combine Peter Lewis' answer above (Check that a input to UITextField is numeric only) with NSPredicates

    #define REGEX_FOR_NUMBERS   @"^([+-]?)(?:|0|[1-9]\\d*)(?:\\.\\d*)?$"
    #define REGEX_FOR_INTEGERS  @"^([+-]?)(?:|0|[1-9]\\d*)?$"
    #define IS_A_NUMBER(string) [[NSPredicate predicateWithFormat:@"SELF MATCHES %@", REGEX_FOR_NUMBERS] evaluateWithObject:string]
    #define IS_AN_INTEGER(string) [[NSPredicate predicateWithFormat:@"SELF MATCHES %@", REGEX_FOR_INTEGERS] evaluateWithObject:string]

SQL Error: ORA-00936: missing expression

  1  

     select ename as name,
      2  sal as salary,
      3  dept,deptno,
      4   from (TABLE_NAME or SUBQUERY)
      5   emp, emp2,  dept
      6    where
      7   emp.deptno = dept.deptno and
      8   emp2.deptno = emp.deptno
      9*  order by dept.dname

 from (TABLE_NAME or SUBQUERY)
 *
ERROR at line 4:
ORA-00936: missing expression`  select ename as name,
 sal as salary,
 dept,deptno,
  from (TABLE_NAME or SUBQUERY)
  emp, emp2,  dept
   where
  emp.deptno = dept.deptno and
  emp2.deptno = emp.deptno
  order by dept.dname`

How to install toolbox for MATLAB

For installing standard toolboxes: Just insert your CD/DVD of MATLAB and start installing, when you see typical/Custom, choose custom and check the toolboxes you want to install and uncheck the others which are installed already.

How do I add target="_blank" to a link within a specified div?

Non-jquery:

// Very old browsers
// var linkList = document.getElementById('link_other').getElementsByTagName('a');

// New browsers (IE8+)
var linkList = document.querySelectorAll('#link_other a');

for(var i in linkList){
 linkList[i].setAttribute('target', '_blank');
}

Convert comma separated string to array in PL/SQL

Another possibility is:

create or replace FUNCTION getNth (
  input varchar2,
  nth number
) RETURN varchar2 AS
  nthVal varchar2(80);
BEGIN
  with candidates (s,e,n) as (
      select 1, instr(input,',',1), 1 from dual
      union all
      select e+1, instr(input,',',e+1), n+1
        from candidates where e > 0)
  select substr(input,s,case when e > 0 then e-s else length(input) end) 
    into nthVal
    from candidates where n=nth;
  return nthVal;
END getNth;

It's a little too expensive to run, as it computes the complete split every time the caller asks for one of the items in there...

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

When and why to 'return false' in JavaScript?

Why return false, or in fact, why return anything?

The code return(val); in a function returns the value of val to the caller of the function. Or, to quote MDN web docs, it...

...ends function execution and specifies a value to be returned to the function caller. (Source: MDN Web Docs: return.)

return false; then is useful in event handlers, because this will value is used by the event-handler to determine further action. return false; cancels events that normally take place with a handler, while return true; lets those events to occur. To quote MDN web docs again...

The return value from the handler determines if the event is canceled. (Source: MDN Web Docs: DOM OnEvent Handlers.)

If you are cancelling an event, return false; by itself is insufficient.

You should also use Event.preventDefault(); and Event.stopPropagation();.

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. (Source: MDN Webdocs.)

  • Event.stopPropagation(); : To stop the event from clicking a link within the containing parent's DOM (i.e., if two links overlapped visually in the UI).

The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. (Source: MDN Webdocs.)

Working Demos

In this demo, we cancel an onclick function of a link and prevent the link from being clicked with return false;, preventDefault(), and stopPropagation().

Full Working JSBin Demo.

StackOverflow Demo...

_x000D_
_x000D_
document.getElementById('my-link').addEventListener('click', function(e) {
  console.log('Click happened for: ' + e.target.id);
  e.preventDefault();
  e.stopPropagation();
  return false;
});
_x000D_
<a href="https://www.wikipedia.com/" id="my-link" target="_blank">Link</a>
_x000D_
_x000D_
_x000D_

Convert JSON string to array of JSON objects in Javascript

As simple as that.

var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
 dataObj = JSON.parse(str);

How to convert BigDecimal to Double in Java?

You need to use the doubleValue() method to get the double value from a BigDecimal object.

BigDecimal bd; // the value you get
double d = bd.doubleValue(); // The double you want

android image button

You can just set the onClick of an ImageView and also set it to be clickable, Or set the drawableBottom property of a regular button.

    ImageView iv = (ImageView)findViewById(R.id.ImageView01);
   iv.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
    // TODO Auto-generated method stub

   }
   });