Programs & Examples On #Telephony

related to transmitting or receiving data over telephone networks.

What regular expression will match valid international phone numbers?

Here's an "optimized" version of your regex:

^011(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|
2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
4[987654310]|3[9643210]|2[70]|7|1)\d{0,14}$

You can replace the \ds with [0-9] if your regex syntax doesn't support \d.

Disable Proximity Sensor during call

Proximity Sensor Dial

*#*#7378423#*#*

1) Service Tests - (If present)

2) Proximity Switch

3) Test on sensor (Next to logo(top) of mobile)

4) Yes if works, then u can keep on and proximity switch forever which gives beep all the time and consumes lot of battery

OR

4) No it doesn't work - Then simply clean the mobile screen or screen guard and clear the blocked screen from sensor. It works charm.

Technically, Its not any software solution, but hardware solution will work.

Make a phone call programmatically

Merging the answers of @Cristian Radu and @Craig Mellon, and the comment from @joel.d, you should do:

NSURL *urlOption1 = [NSURL URLWithString:[@"telprompt://" stringByAppendingString:phone]];
NSURL *urlOption2 = [NSURL URLWithString:[@"tel://" stringByAppendingString:phone]];
NSURL *targetURL = nil;

if ([UIApplication.sharedApplication canOpenURL:urlOption1]) {
    targetURL = urlOption1;
} else if ([UIApplication.sharedApplication canOpenURL:urlOption2]) {
    targetURL = urlOption2;
}

if (targetURL) {
    if (@available(iOS 10.0, *)) {
        [UIApplication.sharedApplication openURL:targetURL options:@{} completionHandler:nil];
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        [UIApplication.sharedApplication openURL:targetURL];
#pragma clang diagnostic pop
    }
} 

This will first try to use the "telprompt://" URL, and if that fails, it will use the "tel://" URL. If both fails, you're trying to place a phone call on an iPad or iPod Touch.

Swift Version :

let phone = mymobileNO.titleLabel.text
let phoneUrl = URL(string: "telprompt://\(phone)"
let phoneFallbackUrl = URL(string: "tel://\(phone)"
if(phoneUrl != nil && UIApplication.shared.canOpenUrl(phoneUrl!)) {
  UIApplication.shared.open(phoneUrl!, options:[String:Any]()) { (success) in
    if(!success) {
      // Show an error message: Failed opening the url
    }
  }
} else if(phoneFallbackUrl != nil && UIApplication.shared.canOpenUrl(phoneFallbackUrl!)) {
  UIApplication.shared.open(phoneFallbackUrl!, options:[String:Any]()) { (success) in
    if(!success) {
      // Show an error message: Failed opening the url
    }
  }
} else {
    // Show an error message: Your device can not do phone calls.
}

Vertical Align text in a Label

I came across this trying to add labels o some vertical radio boxes. I had to do this:

<%: Html.RadioButton("RadioGroup1", "Yes") %><label style="display:inline-block;padding-top:2px;">Yes</label><br />
<%: Html.RadioButton("RadioGroup1", "No") %><label style="display:inline-block;padding-top:3px;">No</label><br />
<%: Html.RadioButton("RadioGroup1", "Maybe") %><label style="display:inline-block;padding-top:4px;">Maybe</label><br />

This gets them to display properly, where the label is centered on the radio button, though I had to increment the top padding with each line, as you can see. The code isn't pretty, but the result is.

Android Material Design Button Styles

1) You can create rounded corner button by defining xml drawable and you can increase or decrease radius to increase or decrease roundness of button corner. Set this xml drawable as background of button.

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="4dp"
    android:insetTop="6dp"
    android:insetRight="4dp"
    android:insetBottom="6dp">
    <ripple android:color="?attr/colorControlHighlight">
        <item>
            <shape android:shape="rectangle"
                android:tint="#0091ea">
                <corners android:radius="10dp" />
                <solid android:color="#1a237e" />
                <padding android:bottom="6dp" />
            </shape>
        </item>
    </ripple>
</inset>

rounded corner button

2) To change default shadow and shadow transition animation between button states, you need to define selector and apply it to button using android:stateListAnimator property. For complete button customization reference : http://www.zoftino.com/android-button

Add unique constraint to combination of two columns

In my case, I needed to allow many inactives and only one combination of two keys active, like this:

UUL_USR_IDF  UUL_UND_IDF    UUL_ATUAL
137          18             0
137          19             0
137          20             1
137          21             0

This seems to work:

CREATE UNIQUE NONCLUSTERED INDEX UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL
ON USER_UND(UUL_USR_IDF, UUL_ATUAL)
WHERE UUL_ATUAL = 1;

Here are my test cases:

SELECT * FROM USER_UND WHERE UUL_USR_IDF = 137

insert into USER_UND values (137, 22, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 23, 0) --I CAN
insert into USER_UND values (137, 24, 0) --I CAN

DELETE FROM USER_UND WHERE UUL_USR_ID = 137

insert into USER_UND values (137, 22, 1) --I CAN
insert into USER_UND values (137, 27, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 28, 0) --I CAN
insert into USER_UND values (137, 29, 0) --I CAN

Best way to create a simple python web service

Raw CGI is kind of a pain, Django is kind of heavyweight. There are a number of simpler, lighter frameworks about, e.g. CherryPy. It's worth looking around a bit.

ExpressionChangedAfterItHasBeenCheckedError Explained

Angular runs change detection and when it finds that some values which has been passed to the child component have been changed, Angular throws the following error:

ExpressionChangedAfterItHasBeenCheckedError click for more

In order to correct this we can use the AfterContentChecked life cycle hook and

import { ChangeDetectorRef, AfterContentChecked} from '@angular/core';

  constructor(
  private cdref: ChangeDetectorRef) { }

  ngAfterContentChecked() {

    this.cdref.detectChanges();

  }

When should I use the new keyword in C++?

Are you passing myClass out of a function, or expecting it to exist outside that function? As some others said, it is all about scope when you aren't allocating on the heap. When you leave the function, it goes away (eventually). One of the classic mistakes made by beginners is the attempt to create a local object of some class in a function and return it without allocating it on the heap. I can remember debugging this kind of thing back in my earlier days doing c++.

Javascript getElementsByName.value not working

Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.

_x000D_
_x000D_
function myFunction() {_x000D_
  var selchbox = [];_x000D_
  var inputfields = document.getElementsByName("myCheck");_x000D_
  var ar_inputflds = inputfields.length;_x000D_
_x000D_
  for (var i = 0; i < ar_inputflds; i++) {_x000D_
    if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
      selchbox.push(inputfields[i].value);_x000D_
  }_x000D_
  return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
  var selchb = myFunction();_x000D_
  console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
_x000D_
_x000D_

How do I redirect output to a variable in shell?

Create a function calling it as the command you want to invoke. In this case, I need to use the ruok command.

Then, call the function and assign its result into a variable. In this case, I am assigning the result to the variable health.

function ruok {
  echo ruok | nc *ip* 2181
}

health=echo ruok *ip*

SQL Stored Procedure: If variable is not null, update statement

Another approach when you have many updates would be to use COALESCE:

UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET    
    [ABC]  = COALESCE(@ABC, [ABC]),
    [ABCD] = COALESCE(@ABCD, [ABCD])

How to use glOrtho() in OpenGL?

Minimal runnable example

glOrtho: 2D games, objects close and far appear the same size:

enter image description here

glFrustrum: more real-life like 3D, identical objects further away appear smaller:

enter image description here

main.c

#include <stdlib.h>

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

static int ortho = 0;

static void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();
    if (ortho) {
    } else {
        /* This only rotates and translates the world around to look like the camera moved. */
        gluLookAt(0.0, 0.0, -3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    }
    glColor3f(1.0f, 1.0f, 1.0f);
    glutWireCube(2);
    glFlush();
}

static void reshape(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    if (ortho) {
        glOrtho(-2.0, 2.0, -2.0, 2.0, -1.5, 1.5);
    } else {
        glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
    }
    glMatrixMode(GL_MODELVIEW);
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    if (argc > 1) {
        ortho = 1;
    }
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(100, 100);
    glutCreateWindow(argv[0]);
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_FLAT);
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile:

gcc -ggdb3 -O0 -o main -std=c99 -Wall -Wextra -pedantic main.c -lGL -lGLU -lglut

Run with glOrtho:

./main 1

Run with glFrustrum:

./main

Tested on Ubuntu 18.10.

Schema

Ortho: camera is a plane, visible volume a rectangle:

enter image description here

Frustrum: camera is a point,visible volume a slice of a pyramid:

enter image description here

Image source.

Parameters

We are always looking from +z to -z with +y upwards:

glOrtho(left, right, bottom, top, near, far)
  • left: minimum x we see
  • right: maximum x we see
  • bottom: minimum y we see
  • top: maximum y we see
  • -near: minimum z we see. Yes, this is -1 times near. So a negative input means positive z.
  • -far: maximum z we see. Also negative.

Schema:

Image source.

How it works under the hood

In the end, OpenGL always "uses":

glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

If we use neither glOrtho nor glFrustrum, that is what we get.

glOrtho and glFrustrum are just linear transformations (AKA matrix multiplication) such that:

  • glOrtho: takes a given 3D rectangle into the default cube
  • glFrustrum: takes a given pyramid section into the default cube

This transformation is then applied to all vertexes. This is what I mean in 2D:

Image source.

The final step after transformation is simple:

  • remove any points outside of the cube (culling): just ensure that x, y and z are in [-1, +1]
  • ignore the z component and take only x and y, which now can be put into a 2D screen

With glOrtho, z is ignored, so you might as well always use 0.

One reason you might want to use z != 0 is to make sprites hide the background with the depth buffer.

Deprecation

glOrtho is deprecated as of OpenGL 4.5: the compatibility profile 12.1. "FIXED-FUNCTION VERTEX TRANSFORMATIONS" is in red.

So don't use it for production. In any case, understanding it is a good way to get some OpenGL insight.

Modern OpenGL 4 programs calculate the transformation matrix (which is small) on the CPU, and then give the matrix and all points to be transformed to OpenGL, which can do the thousands of matrix multiplications for different points really fast in parallel.

Manually written vertex shaders then do the multiplication explicitly, usually with the convenient vector data types of the OpenGL Shading Language.

Since you write the shader explicitly, this allows you to tweak the algorithm to your needs. Such flexibility is a major feature of more modern GPUs, which unlike the old ones that did a fixed algorithm with some input parameters, can now do arbitrary computations. See also: https://stackoverflow.com/a/36211337/895245

With an explicit GLfloat transform[] it would look something like this:

glfw_transform.c

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#define GLEW_STATIC
#include <GL/glew.h>

#include <GLFW/glfw3.h>

static const GLuint WIDTH = 800;
static const GLuint HEIGHT = 600;
/* ourColor is passed on to the fragment shader. */
static const GLchar* vertex_shader_source =
    "#version 330 core\n"
    "layout (location = 0) in vec3 position;\n"
    "layout (location = 1) in vec3 color;\n"
    "out vec3 ourColor;\n"
    "uniform mat4 transform;\n"
    "void main() {\n"
    "    gl_Position = transform * vec4(position, 1.0f);\n"
    "    ourColor = color;\n"
    "}\n";
static const GLchar* fragment_shader_source =
    "#version 330 core\n"
    "in vec3 ourColor;\n"
    "out vec4 color;\n"
    "void main() {\n"
    "    color = vec4(ourColor, 1.0f);\n"
    "}\n";
static GLfloat vertices[] = {
/*   Positions          Colors */
     0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
    -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
     0.0f,  0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};

/* Build and compile shader program, return its ID. */
GLuint common_get_shader_program(
    const char *vertex_shader_source,
    const char *fragment_shader_source
) {
    GLchar *log = NULL;
    GLint log_length, success;
    GLuint fragment_shader, program, vertex_shader;

    /* Vertex shader */
    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
    glCompileShader(vertex_shader);
    glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &log_length);
    log = malloc(log_length);
    if (log_length > 0) {
        glGetShaderInfoLog(vertex_shader, log_length, NULL, log);
        printf("vertex shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("vertex shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Fragment shader */
    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
    glCompileShader(fragment_shader);
    glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetShaderInfoLog(fragment_shader, log_length, NULL, log);
        printf("fragment shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("fragment shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Link shaders */
    program = glCreateProgram();
    glAttachShader(program, vertex_shader);
    glAttachShader(program, fragment_shader);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &success);
    glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetProgramInfoLog(program, log_length, NULL, log);
        printf("shader link log:\n\n%s\n", log);
    }
    if (!success) {
        printf("shader link error");
        exit(EXIT_FAILURE);
    }

    /* Cleanup. */
    free(log);
    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);
    return program;
}

int main(void) {
    GLint shader_program;
    GLint transform_location;
    GLuint vbo;
    GLuint vao;
    GLFWwindow* window;
    double time;

    glfwInit();
    window = glfwCreateWindow(WIDTH, HEIGHT, __FILE__, NULL, NULL);
    glfwMakeContextCurrent(window);
    glewExperimental = GL_TRUE;
    glewInit();
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glViewport(0, 0, WIDTH, HEIGHT);

    shader_program = common_get_shader_program(vertex_shader_source, fragment_shader_source);

    glGenVertexArrays(1, &vao);
    glGenBuffers(1, &vbo);
    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    /* Position attribute */
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    /* Color attribute */
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(1);
    glBindVertexArray(0);

    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shader_program);
        transform_location = glGetUniformLocation(shader_program, "transform");
        /* THIS is just a dummy transform. */
        GLfloat transform[] = {
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 1.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 1.0f,
        };
        time = glfwGetTime();
        transform[0] = 2.0f * sin(time);
        transform[5] = 2.0f * cos(time);
        glUniformMatrix4fv(transform_location, 1, GL_FALSE, transform);

        glBindVertexArray(vao);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);
        glfwSwapBuffers(window);
    }
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo);
    glfwTerminate();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile and run:

gcc -ggdb3 -O0 -o glfw_transform.out -std=c99 -Wall -Wextra -pedantic glfw_transform.c -lGL -lGLU -lglut -lGLEW -lglfw -lm
./glfw_transform.out

Output:

enter image description here

The matrix for glOrtho is really simple, composed only of scaling and translation:

scalex, 0,      0,      translatex,
0,      scaley, 0,      translatey,
0,      0,      scalez, translatez,
0,      0,      0,      1

as mentioned in the OpenGL 2 docs.

The glFrustum matrix is not too hard to calculate by hand either, but starts getting annoying. Note how frustum cannot be made up with only scaling and translations like glOrtho, more info at: https://gamedev.stackexchange.com/a/118848/25171

The GLM OpenGL C++ math library is a popular choice for calculating such matrices. http://glm.g-truc.net/0.9.2/api/a00245.html documents both an ortho and frustum operations.

Create SQLite database in android

Better example is here

 try {
   myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);

   /* Create a Table in the Database. */
   myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");

   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Saranga', 22);");

   /*retrieve data from database */
   Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);

   int Column1 = c.getColumnIndex("Field1");
   int Column2 = c.getColumnIndex("Field2");

   // Check if our result was valid.
   c.moveToFirst();
   if (c != null) {
    // Loop through all Results
    do {
     String Name = c.getString(Column1);
     int Age = c.getInt(Column2);
     Data =Data +Name+"/"+Age+"\n";
    }while(c.moveToNext());
   }

How to upload & Save Files with Desired name

You can try this,

$info = pathinfo($_FILES['userFile']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "newname.".$ext; 

$target = 'images/'.$newname;
move_uploaded_file( $_FILES['userFile']['tmp_name'], $target);

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

https://stackoverflow.com/a/30640097/2569475

For This Issue check My answer at above given url

Using a request scoped bean outside of an actual web request

Java 8: Lambda-Streams, Filter by Method with Exception

You can potentially roll your own Stream variant by wrapping your lambda to throw an unchecked exception and then later unwrapping that unchecked exception on terminal operations:

@FunctionalInterface
public interface ThrowingPredicate<T, X extends Throwable> {
    public boolean test(T t) throws X;
}

@FunctionalInterface
public interface ThrowingFunction<T, R, X extends Throwable> {
    public R apply(T t) throws X;
}

@FunctionalInterface
public interface ThrowingSupplier<R, X extends Throwable> {
    public R get() throws X;
}

public interface ThrowingStream<T, X extends Throwable> {
    public ThrowingStream<T, X> filter(
            ThrowingPredicate<? super T, ? extends X> predicate);

    public <R> ThrowingStream<T, R> map(
            ThrowingFunction<? super T, ? extends R, ? extends X> mapper);

    public <A, R> R collect(Collector<? super T, A, R> collector) throws X;

    // etc
}

class StreamAdapter<T, X extends Throwable> implements ThrowingStream<T, X> {
    private static class AdapterException extends RuntimeException {
        public AdapterException(Throwable cause) {
            super(cause);
        }
    }

    private final Stream<T> delegate;
    private final Class<X> x;

    StreamAdapter(Stream<T> delegate, Class<X> x) {
        this.delegate = delegate;
        this.x = x;
    }

    private <R> R maskException(ThrowingSupplier<R, X> method) {
        try {
            return method.get();
        } catch (Throwable t) {
            if (x.isInstance(t)) {
                throw new AdapterException(t);
            } else {
                throw t;
            }
        }
    }

    @Override
    public ThrowingStream<T, X> filter(ThrowingPredicate<T, X> predicate) {
        return new StreamAdapter<>(
                delegate.filter(t -> maskException(() -> predicate.test(t))), x);
    }

    @Override
    public <R> ThrowingStream<R, X> map(ThrowingFunction<T, R, X> mapper) {
        return new StreamAdapter<>(
                delegate.map(t -> maskException(() -> mapper.apply(t))), x);
    }

    private <R> R unmaskException(Supplier<R> method) throws X {
        try {
            return method.get();
        } catch (AdapterException e) {
            throw x.cast(e.getCause());
        }
    }

    @Override
    public <A, R> R collect(Collector<T, A, R> collector) throws X {
        return unmaskException(() -> delegate.collect(collector));
    }
}

Then you could use this the same exact way as a Stream:

Stream<Account> s = accounts.values().stream();
ThrowingStream<Account, IOException> ts = new StreamAdapter<>(s, IOException.class);
return ts.filter(Account::isActive).map(Account::getNumber).collect(toSet());

This solution would require quite a bit of boilerplate, so I suggest you take a look at the library I already made which does exactly what I have described here for the entire Stream class (and more!).

pod install -bash: pod: command not found

I'm using OS Catalina and used the solution of Babul Prabhakar. But when I closed the terminal, pod still was unable.

So I put the exports:

$ export GEM_HOME=$HOME/Software/ruby
$ export PATH=$PATH:$HOME/Software/ruby/bin

inside this file(put this command below inside the terminal):

nano ~/.bash_profile

Then save the file, close the terminal and open it up again and type:

pod --version

How to specify in crontab by what user to run script?

Instead of creating a crontab to run as the root user, create a crontab for the user that you want to run the script. In your case, crontab -u www-data -e will edit the crontab for the www-data user. Just put your full command in there and remove it from the root user's crontab.

How do I create a comma-separated list from an array in PHP?

Result with and in the end:

$titleString = array('apple', 'banana', 'pear', 'grape');
$totalTitles = count($titleString);
if ($totalTitles>1) {
    $titleString = implode(', ', array_slice($titleString, 0, $totalTitles-1)) . ' and ' . end($titleString);
} else {
    $titleString = implode(', ', $titleString);
}

echo $titleString; // apple, banana, pear and grape

What is the best/safest way to reinstall Homebrew?

Process is to clean up and then reinstall with the following commands:

rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install )"

Notes:

Replace missing values with column mean

With the data.table package you could use the set() function and loop over the columns and replace the NAs or whatever you like with an aggregate or value of your choice (here: mean):

require(data.table)

# data
dt = copy(iris[ ,-5])
setDT(dt)
dt[1:4, Sepal.Length := NA] # introduce NAs

# replace NAs with mean (or whatever function you like)
for (j in seq_along(names(dt))) {
  set(dt,
      i = which(is.na(dt[[j]])),
      j = j, 
      value = mean(dt[[j]], na.rm = TRUE))
}

How to execute a query in ms-access in VBA code?

Take a look at this tutorial for how to use SQL inside VBA:

http://www.ehow.com/how_7148832_access-vba-query-results.html

For a query that won't return results, use (reference here):

DoCmd.RunSQL

For one that will, use (reference here):

Dim dBase As Database
dBase.OpenRecordset

how to prevent "directory already exists error" in a makefile when using mkdir

On UNIX Just use this:

mkdir -p $(OBJDIR)

The -p option to mkdir prevents the error message if the directory exists.

How to secure MongoDB with username and password

You need to start mongod with the --auth option after setting up the user.

From the MongoDB Site:

Run the database (mongod process) with the --auth option to enable security. You must either have added a user to the admin db before starting the server with --auth, or add the first user from the localhost interface.

MongoDB Authentication

Specifying Font and Size in HTML table

Enclose your code with the html and body tags. Size attribute does not correspond to font-size and it looks like its domain does not go beyond value 7. Furthermore font tag is not supported in HTML5. Consider this code for your case

<!DOCTYPE html>
<html>
<body>

<font size="2" face="Courier New" >
<table width="100%">
    <tr>
        <td><b>Client</b></td>
        <td><b>InstanceName</b></td>
        <td><b>dbname</b></td>
        <td><b>Filename</b></td>
        <td><b>KeyName</b></td>
        <td><b>Rotation</b></td>
        <td><b>Path</b></td>
    </tr>
    <tr>
        <td>NEWDEV6</td>
        <td>EXPRESS2012</td>
        <td>master</td><td>master.mdf</td>
        <td>test_key_16</td><td>0</td>
        <td>d:\Program&nbsp;Files\Microsoft&nbsp;SQL&nbsp;Server\MSSQL11.EXPRESS2012\MSSQL\DATA\master.mdf</td>
    </tr>
</table>
</font>
<font size="5" face="Courier New" >
<table width="100%">
    <tr>
        <td><b>Client</b></td>
        <td><b>InstanceName</b></td>
        <td><b>dbname</b></td>
        <td><b>Filename</b></td>
        <td><b>KeyName</b></td>
        <td><b>Rotation</b></td>
        <td><b>Path</b></td></tr>
    <tr>
        <td>NEWDEV6</td>
        <td>EXPRESS2012</td>
        <td>master</td>
        <td>master.mdf</td>
        <td>test_key_16</td>
        <td>0</td>
        <td>d:\Program&nbsp;Files\Microsoft&nbsp;SQL&nbsp;Server\MSSQL11.EXPRESS2012\MSSQL\DATA\master.mdf</td></tr>
</table></font>
</body>
</html>

How to get the text node of an element?

This will ignore the whitespace as well so, your never got the Blank textNodes..code using core Javascript.

var oDiv = document.getElementById("MyDiv");
var firstText = "";
for (var i = 0; i < oDiv.childNodes.length; i++) {
    var curNode = oDiv.childNodes[i];
    whitespace = /^\s*$/;
    if (curNode.nodeName === "#text" && !(whitespace.test(curNode.nodeValue))) {
        firstText = curNode.nodeValue;
        break;
    }
}

Check it on jsfiddle : - http://jsfiddle.net/webx/ZhLep/

What's a decent SFTP command-line client for windows?

WinSCP has the command line functionality:

c:\>winscp.exe /console /script=example.txt

where scripting is done in example.txt.

See http://winscp.net/eng/docs/guide_automation

Refer to http://winscp.net/eng/docs/guide_automation_advanced for details on how to use a scripting language such as Windows command interpreter/php/perl.

FileZilla does have a command line but it is limited to only opening the GUI with a pre-defined server that is in the Site Manager.

jQuery checkbox checked state changed event

$(document).ready(function () {
    $(document).on('change', 'input[Id="chkproperty"]', function (e) {
        alert($(this).val());
    });
});

Clear text input on click with AngularJS

$scope.clearSearch = function () {
    $scope.searchAll = "";
};

http://jsfiddle.net/nzPJD/

JsFiddle of how you could do it without using inline JS.

create multiple tag docker image

How not to do it:

When building an image, you could also tag it this way.

docker build -t ubuntu:14.04 .

Then you build it again with another tag:

docker build -t ubuntu:latest .

If your Dockerfile makes good use of the cache, the same image should come out, and it effectively does the same as retagging the same image. If you do docker images then you will see that they have the same ID.

There's probably a case where this goes wrong though... But like @david-braun said, you can't create tags with Dockerfiles themselves, just with the docker command.

How can I install Visual Studio Code extensions offline?

As of today the download URL for the latest version of the extension is embedded verbatim in the source of the page on Marketplace, e.g. source at URL:

https://marketplace.visualstudio.com/items?itemName=lukasz-wronski.ftp-sync

contains string:

https://lukasz-wronski.gallerycdn.vsassets.io/extensions/lukasz-wronski/ftp-sync/0.3.3/1492669004156/Microsoft.VisualStudio.Services.VSIXPackage

I use following Python regexp to extract dl URL:

urlre = re.search(r'source.+(http.+Microsoft\.VisualStudio\.Services\.VSIXPackage)', content)
if urlre:
    return urlre.group(1)

How to get old Value with onchange() event in text box

element.defaultValue will give you the original value.

Please note that this only works on the initial value.

If you are needing this to persist the "old" value every time it changes, an expando property or similar method will meet your needs

Rails ActiveRecord date between

there are several ways. You can use this method:

start = @selected_date.beginning_of_day
end = @selected_date.end_of_day
@comments = Comment.where("DATE(created_at) BETWEEN ? AND ?", start, end)

Or this:

@comments = Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)

PLS-00201 - identifier must be declared

you should give permission on your db

grant execute on (packageName or tableName) to user;

How to choose an AWS profile when using boto3 to connect to CloudFront

This section of the boto3 documentation is helpful.

Here's what worked for me:

session = boto3.Session(profile_name='dev')
client = session.client('cloudfront')

What is an Android PendingIntent?

What is an Intent?

An Intent is a specific command in Android that allows you to send a command to the Android OS to do something specific. Think of it as an action that needs to take place. There are many actions that can be done such as sending an email, or attaching a photo to an email, or even launching an application. The logical workflow of creating an intent is usually as follows: a. Create the Intent b. Add Intent options -> Ex. what type of intent we are sending to the OS or any attributes associated with that intent, such as a text string or something being passed along with the intent c. RUN the Intent

Real-Life Example: Let's say I wake up in the morning and I "INTEND" to go to the washroom. I will first have to THINK about going to the washroom, but that DOESN'T really gets me to the washroom. I will then have to tell my brain to get out of bed first, then walk to the washroom, and then release, then go and wash my hands, then go and wipe my hands. Once I know where I'm going I SEND the command to begin and my body takes action.

What is Pending Intents?

Continuing from the real-life example, let's say I want to take a shower but I want to shower AFTER I brush my teeth and eat breakfast. So I know I won't be showering until at least 30-40 minutes. I still have in my head that I need to prepare my clothes, and then walk up the stairs back to the bathroom, then undress and then shower. However, this will not happen until 30-40 minutes have passed. I now have a PENDING intent to shower. It is PENDING for 30-40 minutes.

That is pretty much the difference between a Pending Intent and a Regular Intent. Regular Intents can be created without a Pending Intent, however, in order to create a Pending Intent you need to have a Regular Intent setup first.

How do I navigate to a parent route from a child route?

constructor(private router: Router) {}

navigateOnParent() {
  this.router.navigate(['../some-path-on-parent']);
}

The router supports

  • absolute paths /xxx - started on the router of the root component
  • relative paths xxx - started on the router of the current component
  • relative paths ../xxx - started on the parent router of the current component

Get CPU Usage from Windows Command Prompt

For anyone that stumbles upon this page, none of the solutions here worked for me. I found this is the way to do it (in a batch file):

@for /f "skip=1" %%p in ('wmic cpu get loadpercentage /VALUE') do (
   for /F "tokens=2 delims==" %%J in ("%%p") do echo %%J
)

Value of type 'T' cannot be converted to

If you're checking for explicit types, why are you declaring those variables as T's?

T HowToCast<T>(T t)
{
    if (typeof(T) == typeof(string))
    {
        var newT1 = "some text";
        var newT2 = t;  //this builds but I'm not sure what it does under the hood.
        var newT3 = t.ToString();  //for sure the string you want.
    }

    return t;
}

"Conversion to Dalvik format failed with error 1" on external JAR

This answer is basically what many people try to say, but many people may not understand. So...

"Another reason can be if you have a JAR file located somewhere in your project folder and then added it as a Java Path Library. It does not show up under the Package Explorer, so you don't notice it, but it does get counted twice, causing the dreaded Dalvik error." answered Jan 2 '12 at 6:23 Rashmi.B

Meaning:

If you have for instance these two libraries (.jar) in your lib folder: Libraries (.jar) in your *lib* folder

and then these two folders are also added to your build path: Libraries in your build path

means that they are counted twice, thus giving you the error!

Solution:

  1. Remove these libraries from your build path AND remove "Android Dependencies" as well: Remove libs that are in your *lib* folder from the build path!
  2. Clean all projects
  3. Export you project
  4. Enjoy! :)

Shell script "for" loop syntax

Try the arithmetic-expression version of for:

max=10
for (( i=2; i <= $max; ++i ))
do
    echo "$i"
done

This is available in most versions of bash, and should be Bourne shell (sh) compatible also.

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

I had that issue and I solved by doing this:

.done(function() {
                    $(this).find("input").val("");
                    $("#feedback").trigger("reset");
                });

I added this code after my script as I used jQuery. Try same)

<script type="text/JavaScript">

        $(document).ready(function() {
            $("#feedback").submit(function(event) {
                event.preventDefault();
                $.ajax({
                    url: "feedback_lib.php",
                    type: "post",
                    data: $("#feedback").serialize()
                }).done(function() {
                    $(this).find("input").val("");
                    $("#feedback").trigger("reset");
                });
            });
        });
    </script>
    <form id="feedback" action="" name="feedback" method="post">
        <input id="name" name="name" placeholder="name" />
        <br />
        <input id="surname" name="surname" placeholder="surname" />
        <br />
        <input id="enquiry" name="enquiry" placeholder="enquiry" />
        <br />
        <input id="organisation" name="organisation" placeholder="organisation" />
        <br />
        <input id="email" name="email" placeholder="email" />
        <br />
        <textarea id="message" name="message" rows="7" cols="40" placeholder="?????????"></textarea>
        <br />
        <button id="send" name="send">send</button>
    </form>

Cannot bulk load because the file could not be opened. Operating System Error Code 3

I have solved this issue,

login to server computer where SQL Server is installed get you csv file on server computer and execute your query it will insert the records.

If you will give datatype compatibility issue change the datatype for that column

How do I fix MSB3073 error in my post-build event?

If the problem still persists even after putting the after build in the correct project try using "copy" instead of xcopy. This worked for me.

Run MySQLDump without Locking Tables

--skip-add-locks helped for me

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

The two calls have different meanings that have nothing to do with performance; the fact that it speeds up the execution time is (or might be) just a side effect. You should understand what each of them does and not blindly include them in every program because they look like an optimization.

ios_base::sync_with_stdio(false);

This disables the synchronization between the C and C++ standard streams. By default, all standard streams are synchronized, which in practice allows you to mix C- and C++-style I/O and get sensible and expected results. If you disable the synchronization, then C++ streams are allowed to have their own independent buffers, which makes mixing C- and C++-style I/O an adventure.

Also keep in mind that synchronized C++ streams are thread-safe (output from different threads may interleave, but you get no data races).

cin.tie(NULL);

This unties cin from cout. Tied streams ensure that one stream is flushed automatically before each I/O operation on the other stream.

By default cin is tied to cout to ensure a sensible user interaction. For example:

std::cout << "Enter name:";
std::cin >> name;

If cin and cout are tied, you can expect the output to be flushed (i.e., visible on the console) before the program prompts input from the user. If you untie the streams, the program might block waiting for the user to enter their name but the "Enter name" message is not yet visible (because cout is buffered by default, output is flushed/displayed on the console only on demand or when the buffer is full).

So if you untie cin from cout, you must make sure to flush cout manually every time you want to display something before expecting input on cin.

In conclusion, know what each of them does, understand the consequences, and then decide if you really want or need the possible side effect of speed improvement.

Javascript seconds to minutes and seconds

Put my two cents in :

function convertSecondsToMinutesAndSeconds(seconds){
            var minutes;
            var seconds;
            minutes = Math.floor(seconds/60);
            seconds = seconds%60;

            return [minutes, seconds];
        }

So this :

var minutesAndSeconds = convertSecondsToMinutesAndSeconds(101);

Will have the following output :

[1,41];

Then you can print it like so :

console.log('TIME : ' +  minutesSeconds[0] + ' minutes, ' + minutesSeconds[1] + ' seconds');

//TIME : 1 minutes, 41 seconds

Regex for not empty and not whitespace

/^$|\s+/ if this matched, there's whitespace or its empty.

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

I resolved my problem doing this:

  • The .php file is encoded to ANSI. In this file is the function to create the .json file.
  • I use json_encode($array, JSON_UNESCAPED_UNICODE) to encode the data;

The result is a .json file encoded to ANSI as UTF-8.

Convert an image to grayscale in HTML/CSS

You can use one of the functions of jFunc - use the function "jFunc_CanvasFilterGrayscale" http://jfunc.com/jFunc-functions.aspx

Develop Android app using C#

Here is a new one (Note: in Tech Preview stage): http://www.dot42.com

It is basically a Visual Studio add-in that lets you compile your C# code directly to DEX code. This means there is no run-time requirement such as Mono.

Disclosure: I work for this company


UPDATE: all sources are now on https://github.com/dot42

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Change bootstrap datepicker date format on select

this works for me

Open the file bootstrap-datepicker.js

Go to line 1399 and find format: 'mm/dd/yyyy'.

Now you can change the date format here.

How to convert Blob to String and String to Blob in java

How are you setting blob to DB? You should do:

 //imagine u have a a prepared statement like:
 PreparedStatement ps = conn.prepareStatement("INSERT INTO table VALUES (?)");
 String blobString= "This is the string u want to convert to Blob";
oracle.sql.BLOB myBlob = oracle.sql.BLOB.createTemporary(conn, false,oracle.sql.BLOB.DURATION_SESSION);
 byte[] buff = blobString.getBytes();
 myBlob.putBytes(1,buff);
 ps.setBlob(1, myBlob);
 ps.executeUpdate();

How to convert CSV to JSON in Node.js

Here is a solution that does not require a separate module. However, it is very crude, and does not implement much error handling. It could also use more tests, but it will get you going. If you are parsing very large files, you may want to seek an alternative. Also, see this solution from Ben Nadel.

Node Module Code, csv2json.js:

/*
 * Convert a CSV String to JSON
 */
exports.convert = function(csvString) {
    var json = [];
    var csvArray = csvString.split("\n");

    // Remove the column names from csvArray into csvColumns.
    // Also replace single quote with double quote (JSON needs double).
    var csvColumns = JSON
            .parse("[" + csvArray.shift().replace(/'/g, '"') + "]");

    csvArray.forEach(function(csvRowString) {

        var csvRow = csvRowString.split(",");

        // Here we work on a single row.
        // Create an object with all of the csvColumns as keys.
        jsonRow = new Object();
        for ( var colNum = 0; colNum < csvRow.length; colNum++) {
            // Remove beginning and ending quotes since stringify will add them.
            var colData = csvRow[colNum].replace(/^['"]|['"]$/g, "");
            jsonRow[csvColumns[colNum]] = colData;
        }
        json.push(jsonRow);
    });

    return JSON.stringify(json);
};

Jasmine Test, csv2jsonSpec.js:

var csv2json = require('csv2json.js');

var CSV_STRING = "'col1','col2','col3'\n'1','2','3'\n'4','5','6'";
var JSON_STRING = '[{"col1":"1","col2":"2","col3":"3"},{"col1":"4","col2":"5","col3":"6"}]';

/* jasmine specs for csv2json */
describe('csv2json', function() {

    it('should convert a csv string to a json string.', function() {
        expect(csv2json.convert(CSV_STRING)).toEqual(
                JSON_STRING);
    });
});

How to center canvas in html5

The above answers only work if your canvas is the same width as the container.

This works regardless:

_x000D_
_x000D_
#container {_x000D_
  width: 100px;_x000D_
  height:100px;_x000D_
  border: 1px solid red;_x000D_
  _x000D_
  _x000D_
  margin: 0px auto;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
#canvas {_x000D_
  border: 1px solid blue;_x000D_
  width: 50px;_x000D_
  height: 100px;_x000D_
  _x000D_
}
_x000D_
<div id="container">_x000D_
  <canvas id="canvas" width="100" height="100"></canvas>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Time part of a DateTime Field in SQL

If you want only the hour of your datetime, then you can use DATEPART() - SQL Server:

declare @dt datetime
set @dt = '2012-09-10 08:25:53'

select datepart(hour, @dt) -- returns 8

In SQL Server 2008+ you can CAST() as time:

declare @dt datetime
set @dt = '2012-09-10 08:25:53'

select CAST(@dt as time) -- returns 08:25:53

Python Library Path

I think you're looking for sys.path

import sys
print (sys.path)

PHP - Modify current object in foreach loop

Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?

Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.

For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.

<?php

$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);

vs

<?php

$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
    $arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);

If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

Share cookie between subdomain and domain

Simple solution

setcookie("NAME", "VALUE", time()+3600, '/', EXAMPLE.COM);

Setcookie's 5th parameter determines the (sub)domains that the cookie is available to. Setting it to (EXAMPLE.COM) makes it available to any subdomain (eg: SUBDOMAIN.EXAMPLE.COM )

Reference: http://php.net/manual/en/function.setcookie.php

Is there an easy way to strike through text in an app widget?

I've done this on a regular (local) TextView, and it should work on the remote variety since the docs list the method as equivalent between the two:

remote_text_view.setText(Html.fromHtml("This is <del>crossed off</del>."));

Pod install is staying on "Setting up CocoaPods Master repo"

I'm monitoring the download progress by using

while true; 
do   
du -sh ~/.cocoapods/;   
sleep 3; 
done

the progress is very slow... and failed few times. But somehow after increasing the git buffer limit by using this command line git config --global http.postBuffer 2M The download speed is improving greatly and after downloading in total 347 Mb on ./cocoapods folder, the progress seems to stop and network activity is also stopping. but after waiting few minutes, turn out that cocoapod is verifying and extracting the repo and makes the total size up to 853 Mb.

notes: I'm doing it on 23 Oct 2016.

How to remove leading and trailing zeros in a string? Python

Assuming you have other data types (and not only string) in your list try this. This removes trailing and leading zeros from strings and leaves other data types untouched. This also handles the special case s = '0'

e.g

a = ['001', '200', 'akdl00', 200, 100, '0']

b = [(lambda x: x.strip('0') if isinstance(x,str) and len(x) != 1 else x)(x) for x in a]

b
>>>['1', '2', 'akdl', 200, 100, '0']

How to write a CSS hack for IE 11?

Use a combination of Microsoft specific CSS rules to filter IE11:

<!doctype html>
<html>
 <head>
  <title>IE10/11 Media Query Test</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <style>
    @media all and (-ms-high-contrast:none)
     {
     .foo { color: green } /* IE10 */
     *::-ms-backdrop, .foo { color: red } /* IE11 */
     }
  </style>
 </head>
 <body>
  <div class="foo">Hi There!!!</div>
 </body>
</html>

Filters such as this work because of the following:

When a user agent cannot parse the selector (i.e., it is not valid CSS 2.1), it must ignore the selector and the following declaration block (if any) as well.

_x000D_
_x000D_
<!doctype html>_x000D_
<html>_x000D_
 <head>_x000D_
  <title>IE10/11 Media Query Test</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
  <style>_x000D_
    @media all and (-ms-high-contrast:none)_x000D_
     {_x000D_
     .foo { color: green } /* IE10 */_x000D_
     *::-ms-backdrop, .foo { color: red } /* IE11 */_x000D_
     }_x000D_
  </style>_x000D_
 </head>_x000D_
 <body>_x000D_
  <div class="foo">Hi There!!!</div>_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

References

How to use count and group by at the same select statement

If you want to order by count (sound simple but i can`t found an answer on stack of how to do that) you can do:

        SELECT town, count(town) as total FROM user
        GROUP BY town ORDER BY total DESC

How to parse XML in Bash?

Well, you can use xpath utility. I guess perl's XML::Xpath contains it.

Common CSS Media Queries Break Points

I've been using:

@media only screen and (min-width: 768px) {
    /* tablets and desktop */
}

@media only screen and (max-width: 767px) {
    /* phones */
}

@media only screen and (max-width: 767px) and (orientation: portrait) {
    /* portrait phones */
}

It keeps things relatively simple and allows you to do something a bit different for phones in portrait mode (a lot of the time I find myself having to change various elements for them).

Change hover color on a button with Bootstrap customization

The color for your buttons comes from the btn-x classes (e.g., btn-primary, btn-success), so if you want to manually change the colors by writing your own custom css rules, you'll need to change:

/*This is modifying the btn-primary colors but you could create your own .btn-something class as well*/
.btn-primary {
    color: #fff;
    background-color: #0495c9;
    border-color: #357ebd; /*set the color you want here*/
}
.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open>.dropdown-toggle.btn-primary {
    color: #fff;
    background-color: #00b3db;
    border-color: #285e8e; /*set the color you want here*/
}

Swift - How to hide back button in navigation item?

enter image description here

Go to attributes inspector and uncheck show Navigation Bar to hide back button.

Cannot connect to MySQL 4.1+ using old authentication

you can do these line on your mysql query browser or something

SET old_passwords = 0;
UPDATE mysql.user SET Password = PASSWORD('testpass') WHERE User = 'testuser' limit 1;
SELECT LENGTH(Password) FROM mysql.user WHERE User = 'testuser';
FLUSH PRIVILEGES;

note:your username and password

after that it should able to work. I just solved mine too

jQuery UI Dialog - missing close icon

This is a comment on the top answer, but I felt it was worth its own answer because it helped me answer the problem.

If you want to keep Bootstrap declared after JQuery UI (I did because I wanted to use the Bootstrap tooltip), declaring the following (I declared it after $(document).ready) will allow the button to appear again (answer from https://stackoverflow.com/a/23428433/4660870)

var bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton            // give $().bootstrapBtn the Bootstrap functionality

JavaScript replace/regex

You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):

  "$TESTONE $TESTONE".replace( new RegExp("\\$TESTONE","gm"),"foo")

Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).

Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.

Float right and position absolute doesn't work together

I was able to absolutely position a right-floated element with one layer of nesting and a tricky margin:

_x000D_
_x000D_
function test() {_x000D_
  document.getElementById("box").classList.toggle("hide");_x000D_
}
_x000D_
.right {_x000D_
  float:right;_x000D_
}_x000D_
#box {_x000D_
  position:absolute; background:#feb;_x000D_
  width:20em; margin-left:-20em; padding:1ex;_x000D_
}_x000D_
#box.hide {_x000D_
  display:none;_x000D_
}
_x000D_
<div>_x000D_
  <div class="right">_x000D_
    <button onclick="test()">box</button>_x000D_
    <div id="box">Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
      sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
      Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
      nisi ut aliquip ex ea commodo consequat._x000D_
    </div>_x000D_
  </div>_x000D_
  <p>_x000D_
    Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
    nisi ut aliquip ex ea commodo consequat._x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I decided to make this toggleable so you can see how it does not affect the flow of the surrounding text (run it and press the button to show/hide the floated absolute box).

PHP PDO with foreach and fetch

foreach over a statement is just a syntax sugar for the regular one-way fetch() loop. If you want to loop over your data more than once, select it as a regular array first

$sql = "SELECT * FROM users";
$stm = $dbh->query($sql);
// here you go:
$users = $stm->fetchAll();

foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Also quit that try..catch thing. Don't use it, but set the proper error reporting for PHP and PDO

composer laravel create project

  1. Create project
  2. Open: Root (htdocs)\
  3. Press: Shift + Open command windows here
  4. Type: php composer.phar create-project --prefer-dist laravel/laravel lar-project "5.7.*"

How to determine the longest increasing subsequence using dynamic programming?

Simplest LIS solution in C++ with O(nlog(n)) time complexity

#include <iostream>
#include "vector"
using namespace std;

// binary search (If value not found then it will return the index where the value should be inserted)
int ceilBinarySearch(vector<int> &a,int beg,int end,int value)
{
    if(beg<=end)
    {
        int mid = (beg+end)/2;
        if(a[mid] == value)
            return mid;
        else if(value < a[mid])
            return ceilBinarySearch(a,beg,mid-1,value);
        else
            return ceilBinarySearch(a,mid+1,end,value);

    return 0;
    }

    return beg;

}
int lis(vector<int> arr)
{
    vector<int> dp(arr.size(),0);
    int len = 0;
    for(int i = 0;i<arr.size();i++)
    {
        int j = ceilBinarySearch(dp,0,len-1,arr[i]);
        dp[j] = arr[i];
        if(j == len)
            len++;

    }
    return len;
}

int main()
{
    vector<int> arr  {2, 5,-1,0,6,1,2};
    cout<<lis(arr);
    return 0;
}

OUTPUT:
4

How exactly does the android:onClick XML attribute differ from setOnClickListener?

The best way to do this is with the following code:

 Button button = (Button)findViewById(R.id.btn_register);
 button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //do your fancy method
            }
        });

Best way to resolve file path too long exception

There's a library called Zeta Long Paths that provides a .NET API to work with long paths.

Here's a good article that covers this issue for both .NET and PowerShell: ".NET, PowerShell Path too Long Exception and a .NET PowerShell Robocopy Clone"

Controlling Maven final name of jar artifact

All of the provided answers are more complicated than necessary. Assuming you are building a jar file, all you need to do is add a <jar.finalName> tag to your <properties> section:

<properties>
    <jar.finalName>${project.name}</jar.finalName>
</properties>

This will generate a jar:

project/target/${project.name}.jar

This is in the documentation - note the User Property:

finalName:
Name of the generated JAR.
Type: java.lang.String
Required: No
User Property: jar.finalName
Default: ${project.build.finalName}

Command Line Usage

You should also be able to use this option on the command line with:

mvn -Djar.finalName=myCustomName ...

You should get myCustomName.jar, although I haven't tested this.

CSV parsing in Java - working example..?

Basically you will need to read the file line by line.

Then you will need to split each line by the delimiter, say a comma (CSV stands for comma-separated values), with

String[] strArr=line.split(",");

This will turn it into an array of strings which you can then manipulate, for example with

String name=strArr[0];
int yearOfBirth = Integer.valueOf(strArr[1]);
int monthOfBirth = Integer.valueOf(strArr[2]);
int dayOfBirth = Integer.valueOf(strArr[3]);
GregorianCalendar dob=new GregorianCalendar(yearOfBirth, monthOfBirth, dayOfBirth);
Student student=new Student(name, dob); //lets pretend you are creating instances of Student

You will need to do this for every line so wrap this code into a while loop. (If you don't know the delimiter just open the file in a text editor.)

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

SQL Server Reporting Services (SSRS)
SSRS can remain active even if you uninstall SQL Server.
To stop the service:

Open SQL Server Configuration Manager. Select “SQL Server Services” in the left-hand pane. Double-click “SQL Server Reporting Services”. Hit Stop. Switch to the Service tab and set the Start Mode to “Manual”.


Skype
Irritatingly, Skype can switch to port 80. To disable it, select
Tools > Options > Advanced > Connection then uncheck
“Use port 80 and 443 as alternatives for incoming connections”.


IIS (Microsoft Internet Information Server)

For Windows 7 (or vista) its the most likely culprit. You can stop the service from the command line.

Open command line cmd.exe and type:

net stop was /y

For older versions of Windows type:

net stop iisadmin /y

Other

If this does not solve the problem further detective work is necessary if IIS, SSRS and Skype are not to blame. Enter the following on the command line:

netstat -ao

The active TCP addresses and ports will be listed. Locate the line with local address “0.0.0.0:80" and note the PID value. Start Task Manager. Navigate to the Processes tab and, if necessary, click View > Select Columns to ensure “PID (Process Identifier)” is checked. You can now locate the PID you noted above. The description and properties should help you determine which application is using the port.

select dept names who have more than 2 employees whose salary is greater than 1000

hope this helps

select DeptName from DEPARTMENT inner join EMPLOYEE using (DeptId) where Salary>1000 group by DeptName having count(*)>2

Response to preflight request doesn't pass access control check

enter image description here

Using the Cors option in the API gateway, I used the following settings shown above

Also, note, that your function must return a HTTP status 200 in response to an OPTIONS request, or else CORS will also fail.

document.getElementById('btnid').disabled is not working in firefox and chrome

use setAttribute() and removeAttribute()

function disbtn(e) { 
    if ( someCondition == true ) {
       document.getElementById('btn1').setAttribute("disabled","disabled");
    } else {
       document.getElementById('btn1').removeAttribute("disabled");
    }
}

SEE DEMO

Row Offset in SQL Server

Following will display 25 records excluding first 50 records works in SQL Server 2012.

SELECT * FROM MyTable ORDER BY ID OFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY;

you can replace ID as your requirement

how to set default culture info for entire c# application

With 4.0, you will need to manage this yourself by setting the culture for each thread as Alexei describes. But with 4.5, you can define a culture for the appdomain and that is the preferred way to handle this. The relevant apis are CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture.

How to log in to phpMyAdmin with WAMP, what is the username and password?

In my case it was

username : root
password : mysql

Using : Wamp server 3.1.0

The name 'ConfigurationManager' does not exist in the current context

Adding the System.Configuration as reference to all the projects will solve this.

  1. Go to Project -> Add Reference

  2. In the box that appears, click the All assemblies list tab in the left hand list.

  3. In the central list, scroll to System.Configuration and make sure the box is checked.

  4. Click ok to apply, and you'll now be able to access the ConfigurationManager class.

Executing set of SQL queries using batch file?

Save the commands in a .SQL file, ex: ClearTables.sql, say in your C:\temp folder.

Contents of C:\Temp\ClearTables.sql

Delete from TableA;
Delete from TableB;
Delete from TableC;
Delete from TableD;
Delete from TableE;

Then use sqlcmd to execute it as follows. Since you said the database is remote, use the following syntax (after updating for your server and database instance name).

sqlcmd -S <ComputerName>\<InstanceName> -i C:\Temp\ClearTables.sql

For example, if your remote computer name is SQLSVRBOSTON1 and Database instance name is MyDB1, then the command would be.

sqlcmd -E -S SQLSVRBOSTON1\MyDB1 -i C:\Temp\ClearTables.sql

Also note that -E specifies default authentication. If you have a user name and password to connect, use -U and -P switches.

You will execute all this by opening a CMD command window.

Using a Batch File.

If you want to save it in a batch file and double-click to run it, do it as follows.

Create, and save the ClearTables.bat like so.

echo off
sqlcmd -E -S SQLSVRBOSTON1\MyDB1 -i C:\Temp\ClearTables.sql
set /p delExit=Press the ENTER key to exit...:

Then double-click it to run it. It will execute the commands and wait until you press a key to exit, so you can see the command output.

receiver type *** for instance message is a forward declaration

Check if you imported the header files of classes that are throwing this error.

Sort Java Collection

You can also use:

Collections.sort(list, new Comparator<CustomObject>() {
    public int compare(CustomObject obj1, CustomObject obj2) {
        return obj1.id - obj2.id;
    }
});
System.out.println(list);

Real time data graphing on a line chart with html5

I believe this is exactly what you're looking for:

http://www.highcharts.com/demo/dynamic-update

Open source (although a license is required for commercial websites), cross device/browser, fast.

Node.js: Gzip compression?

For compressing the file you can use below code

var fs = require("fs");
var zlib = require('zlib');
fs.createReadStream('input.txt').pipe(zlib.createGzip())
.pipe(fs.createWriteStream('input.txt.gz'));
console.log("File Compressed.");

For decompressing the same file you can use below code

var fs = require("fs");
var zlib = require('zlib');
fs.createReadStream('input.txt.gz')
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream('input.txt'));
console.log("File Decompressed.");

How to change date format using jQuery?

You don't need any date-specific functions for this, it's just string manipulation:

var parts = fecha2.value.split('-');
var newdate = parts[1]+'-'+parts[2]+'-'+(parseInt(parts[0], 10)%100);

Converting binary to decimal integer output

You can use int and set the base to 2 (for binary):

>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> int(binary, 2)
25
>>>

However, if you cannot use int like that, then you could always do this:

binary = raw_input('enter a number: ')
decimal = 0
for digit in binary:
    decimal = decimal*2 + int(digit)
print decimal

Below is a demonstration:

>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> decimal = 0
>>> for digit in binary:
...     decimal = decimal*2 + int(digit)
...
>>> print decimal
25
>>>

Search a text file and print related lines in Python?

searchfile = open("file.txt", "r")
for line in searchfile:
    if "searchphrase" in line: print line
searchfile.close()

To print out multiple lines (in a simple way)

f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

The comma in print l, prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.

Or better yet (stealing back from Mark Ransom):

with open("file.txt", "r") as f:
    searchlines = f.readlines()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

How to add text to JFrame?

when I create my JLabel and enter the text to it, there is no wordwrap or anything

HTML formatting can be used to cause word wrap in any Swing component that offers styled text. E.G. as demonstrated in this answer.

Youtube - downloading a playlist - youtube-dl

The easiest thing to do is to create a file.txt file and pass the link url link so:

https://www.youtube.com/watch?v=5Lj1BF0Kn8c&list=PL9YFoJnn53xyf9GNZrtiraspAIKc80s1i

make sure to include the -a parameter in terminal:

youtube-dl -a file.txt

How does System.out.print() work?

You can convert anything to a String as long as you choose what to print. The requirement was quite simple since Objet.toString() can return a default dumb string: package.classname + @ + object number.

If your print method should return an XML or JSON serialization, the basic result of toString() wouldn't be acceptable. Even though the method succeed.

Here is a simple example to show that Java can be dumb

public class MockTest{

String field1;

String field2;

public MockTest(String field1,String field2){
this.field1=field1;
this.field2=field2;
}

}

System.out.println(new MockTest("a","b");

will print something package.Mocktest@3254487 ! Even though you only have two String members and this could be implemented to print

Mocktest@3254487{"field1":"a","field2":"b"}

(or pretty much how it appears in the debbuger)

std::cin input with spaces?

THE C WAY

You can use gets function found in cstdio(stdio.h in c):

#include<cstdio>
int main(){

char name[256];
gets(name); // for input
puts(name);// for printing 
}

THE C++ WAY

gets is removed in c++11.

[Recommended]:You can use getline(cin,name) which is in string.h or cin.getline(name,256) which is in iostream itself.

#include<iostream>
#include<string>
using namespace std;
int main(){

char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}

How can I scroll a div to be visible in ReactJS?

In you keyup/down handler you just need to set the scrollTop property of the div you want to scroll to make it scroll down (or up).

For example:

JSX:

<div ref="foo">{content}</div>

keyup/down handler:

this.refs.foo.getDOMNode().scrollTop += 10

If you do something similar to above, your div will scroll down 10 pixels (assuming the div is set to overflow auto or scroll in css, and your content is overflowing of course).

You will need to expand on this to find the offset of the element inside your scrolling div that you want to scroll the div down to, and then modify the scrollTop to scroll far enough to show the element based on it's height.

Have a look at MDN's definitions of scrollTop, and offsetTop here:

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop

while EOF in JAVA?

Each call to nextLine() moves onto the next line, so when you are actually at the last readable line and the while check passes inspection, the next call to nextLine() will return EOF.


Perhaps you could do one of the following instead:

If fileReader is of type Scanner:

while ((line = fileReader.hasNextLine()) != null) {
    String line = fileReader.nextLine(); 
    System.out.println(line);
}

If fileReader is of type BufferedReader:

String line;
while ((line = fileReader.readLine()) != null) {
    System.out.println(line);
}

So you're reading the current line in the while condition and saving the line in a string for later use.

TypeError: document.getElementbyId is not a function

JavaScript is case-sensitive. The b in getElementbyId should be capitalized.

var content = document.getElementById("edit").innerHTML;

How do I tell if .NET 3.5 SP1 is installed?

Take a look at this article which shows the registry keys you need to look for and provides a .NET library that will do this for you.

First, you should to determine if .NET 3.5 is installed by looking at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install, which is a DWORD value. If that value is present and set to 1, then that version of the Framework is installed.

Look at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP, which is a DWORD value which indicates the Service Pack level (where 0 is no service pack).

To be correct about things, you really need to ensure that .NET Fx 2.0 and .NET Fx 3.0 are installed first and then check to see if .NET 3.5 is installed. If all three are true, then you can check for the service pack level.

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

How do I convert Long to byte[] and back in java

I find this method to be most friendly.

var b = BigInteger.valueOf(x).toByteArray();

var l = new BigInteger(b);

UITableView, Separator color where to set?

Swift version:

override func viewDidLoad() {
    super.viewDidLoad()

    // Assign your color to this property, for example here we assign the red color.
    tableView.separatorColor = UIColor.redColor()
}

Angular 2 How to redirect to 404 or other path if the path does not exist

My preferred option on 2.0.0 and up is to create a 404 route and also allow a ** route path to resolve to the same component. This allows you to log and display more information about the invalid route rather than a plain redirect which can act to hide the error.

Simple 404 example:

{ path '/', component: HomeComponent },
// All your other routes should come first    
{ path: '404', component: NotFoundComponent },
{ path: '**', component: NotFoundComponent }

To display the incorrect route information add in import to router within NotFoundComponent:

import { Router } from '@angular/router';

Add it to the constructior of NotFoundComponent:

constructor(public router: Router) { }

Then you're ready to reference it from your HTML template e.g.

The page <span style="font-style: italic">{{router.url}}</span> was not found.

How to fire AJAX request Periodically?

I tried the below code,

    function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});

This didn't work as expected for the specified interval,the page didn't load completely and the function was been called continuously. Its better to call setTimeout(executeQuery, 5000); outside executeQuery() in a separate function as below,

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  updateCall();
}

function updateCall(){
setTimeout(function(){executeQuery()}, 5000);
}

$(document).ready(function() {
  executeQuery();
});

This worked exactly as intended.

The operation cannot be completed because the DbContext has been disposed error

using(var database=new DatabaseEntities()){}

Don't use using statement. Just write like that

DatabaseEntities database=new DatabaseEntities ();{}

It will work.

For documentation on the using statement see here.

Is there a MySQL option/feature to track history of changes to records?

It's subtle.

If the business requirement is "I want to audit the changes to the data - who did what and when?", you can usually use audit tables (as per the trigger example Keethanjan posted). I'm not a huge fan of triggers, but it has the great benefit of being relatively painless to implement - your existing code doesn't need to know about the triggers and audit stuff.

If the business requirement is "show me what the state of the data was on a given date in the past", it means that the aspect of change over time has entered your solution. Whilst you can, just about, reconstruct the state of the database just by looking at audit tables, it's hard and error prone, and for any complicated database logic, it becomes unwieldy. For instance, if the business wants to know "find the addresses of the letters we should have sent to customers who had outstanding, unpaid invoices on the first day of the month", you likely have to trawl half a dozen audit tables.

Instead, you can bake the concept of change over time into your schema design (this is the second option Keethanjan suggests). This is a change to your application, definitely at the business logic and persistence level, so it's not trivial.

For example, if you have a table like this:

CUSTOMER
---------
CUSTOMER_ID PK
CUSTOMER_NAME
CUSTOMER_ADDRESS

and you wanted to keep track over time, you would amend it as follows:

CUSTOMER
------------
CUSTOMER_ID            PK
CUSTOMER_VALID_FROM    PK
CUSTOMER_VALID_UNTIL   PK
CUSTOMER_STATUS
CUSTOMER_USER
CUSTOMER_NAME
CUSTOMER_ADDRESS

Every time you want to change a customer record, instead of updating the record, you set the VALID_UNTIL on the current record to NOW(), and insert a new record with a VALID_FROM (now) and a null VALID_UNTIL. You set the "CUSTOMER_USER" status to the login ID of the current user (if you need to keep that). If the customer needs to be deleted, you use the CUSTOMER_STATUS flag to indicate this - you may never delete records from this table.

That way, you can always find what the status of the customer table was for a given date - what was the address? Have they changed name? By joining to other tables with similar valid_from and valid_until dates, you can reconstruct the entire picture historically. To find the current status, you search for records with a null VALID_UNTIL date.

It's unwieldy (strictly speaking, you don't need the valid_from, but it makes the queries a little easier). It complicates your design and your database access. But it makes reconstructing the world a lot easier.

Check if string begins with something?

First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.

String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);
};

Then you use it like this. Caution! Makes the code extremely readable.

var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here
}

How to create a sticky footer that plays well with Bootstrap 3

Not sure what you have tried so far, but its pretty simple. Just do this: http://plnkr.co/edit/kmEWh7?p=preview

html, body {
  height: 100%;
}

footer {
  position: absolute;
  bottom: 0;
}

Refresh or force redraw the fragment

In my case, detach and attach worked:

 getSupportFragmentManager()
   .beginTransaction()
   .detach(contentFragment)
   .attach(contentFragment)
   .commit();

Can linux cat command be used for writing text to file?

cat can also be used following a | to write to a file, i.e. pipe feeds cat a stream of data

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

In all these scenarios outerScopeVar is modified or assigned a value asynchronously or happening in a later time(waiting or listening for some event to occur),for which the current execution will not wait.So all these cases current execution flow results in outerScopeVar = undefined

Let's discuss each examples(I marked the portion which is called asynchronously or delayed for some events to occur):

1.

enter image description here

Here we register an eventlistner which will be executed upon that particular event.Here loading of image.Then the current execution continuous with next lines img.src = 'lolcat.png'; and alert(outerScopeVar); meanwhile the event may not occur. i.e, funtion img.onload wait for the referred image to load, asynchrously. This will happen all the folowing example- the event may differ.

2.

2

Here the timeout event plays the role, which will invoke the handler after the specified time. Here it is 0, but still it registers an asynchronous event it will be added to the last position of the Event Queue for execution, which makes the guaranteed delay.

3.

enter image description here This time ajax callback.

4.

enter image description here

Node can be consider as a king of asynchronous coding.Here the marked function is registered as a callback handler which will be executed after reading the specified file.

5.

enter image description here

Obvious promise (something will be done in future) is asynchronous. see What are the differences between Deferred, Promise and Future in JavaScript?

https://www.quora.com/Whats-the-difference-between-a-promise-and-a-callback-in-Javascript

How do I get git to default to ssh and not https for new repositories

You need to clone in ssh not in https.

For that you need to set your ssh keys. I have prepared this little script that automates this:

#!/usr/bin/env bash
email="$1"
hostname="$2"
hostalias="$hostname"
keypath="$HOME/.ssh/${hostname}_rsa"
ssh-keygen -t rsa -C $email -f $keypath
if [ $? -eq 0 ]; then
cat >> ~/.ssh/config <<EOF
Host $hostalias
        Hostname $hostname *.$hostname
        User git
    IdentitiesOnly yes
        IdentityFile $keypath
EOF
fi

and run it like

bash script.sh [email protected] github.com

Change your remote url

git remote set-url origin [email protected]:user/foo.git

Add content of ~/.ssh/github.com_rsa.pub to your ssh keys on github.com

Check connection

ssh -T [email protected]

Find row where values for column is maximal in a pandas DataFrame

df.iloc[df['columnX'].argmax()]

argmax() would provide the index corresponding to the max value for the columnX. iloc can be used to get the row of the DataFrame df for this index.

Sort matrix according to first column in R

Be aware that if you want to have values in the reverse order, you can easily do so:

> example = matrix(c(1,1,1,4,3,3,2,349,393,392,459,49,32,94), ncol = 2)
> example[order(example[,1], decreasing = TRUE),]
     [,1] [,2]
[1,]    4  459
[2,]    3   49
[3,]    3   32
[4,]    2   94
[5,]    1  349
[6,]    1  393
[7,]    1  392

Setting JDK in Eclipse

Some additional steps may be needed to set both the project and default workspace JRE correctly, as MayoMan mentioned. Here is the complete sequence in Eclipse Luna:

  • Right click your project > properties
  • Select “Java Build Path” on left, then “JRE System Library”, click Edit…
  • Select "Workspace Default JRE"
  • Click "Installed JREs"
  • If you see JRE you want in the list select it (selecting a JDK is OK too)
  • If not, click Search…, navigate to Computer > Windows C: > Program Files > Java, then click OK
  • Now you should see all installed JREs, select the one you want
  • Click OK/Finish a million times

Easy.... not.

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

How to subtract X days from a date using Java calendar?

You could use the add method and pass it a negative number. However, you could also write a simpler method that doesn't use the Calendar class such as the following

public static void addDays(Date d, int days)
{
    d.setTime( d.getTime() + (long)days*1000*60*60*24 );
}

This gets the timestamp value of the date (milliseconds since the epoch) and adds the proper number of milliseconds. You could pass a negative integer for the days parameter to do subtraction. This would be simpler than the "proper" calendar solution:

public static void addDays(Date d, int days)
{
    Calendar c = Calendar.getInstance();
    c.setTime(d);
    c.add(Calendar.DATE, days);
    d.setTime( c.getTime().getTime() );
}

Note that both of these solutions change the Date object passed as a parameter rather than returning a completely new Date. Either function could be easily changed to do it the other way if desired.

How can I echo a newline in a batch file?

Just like Grimtron suggests - here is a quick example to define it:

@echo off
set newline=^& echo.
echo hello %newline%world

Output

C:\>test.bat
hello
world

typescript - cloning object

Try this:

let copy = (JSON.parse(JSON.stringify(objectToCopy)));

It is a good solution until you are using very large objects or your object has unserializable properties.

In order to preserve type safety you could use a copy function in the class you want to make copies from:

getCopy(): YourClassName{
    return (JSON.parse(JSON.stringify(this)));
}

or in a static way:

static createCopy(objectToCopy: YourClassName): YourClassName{
    return (JSON.parse(JSON.stringify(objectToCopy)));
}

Node.js on multi-core machines

Future version of node will allow you to fork a process and pass messages to it and Ryan has stated he wants to find some way to also share file handlers, so it won't be a straight forward Web Worker implementation.

At this time there is not an easy solution for this but it's still very early and node is one of the fastest moving open source projects I've ever seen so expect something awesome in the near future.

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

I did git revert a multiple times ,and it worked for me make sure un-check the files while reverting you need changes. Stash your changes and pull again.

What is the most "pythonic" way to iterate over a list in chunks?

With Python 3.8 you can use the walrus operator and itertools.islice.

from itertools import islice

list_ = [i for i in range(10, 100)]

def chunker(it, size):
    iterator = iter(it)
    while chunk := list(islice(iterator, size)):
        print(chunk)
In [2]: chunker(list_, 10)                                                         
[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, 49]
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69]
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79]
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

How to use a table type in a SELECT FROM statement?

Thanks for all help at this issue. I'll post here my solution:

Package Header

CREATE OR REPLACE PACKAGE X IS
  TYPE exch_row IS RECORD(
    currency_cd VARCHAR2(9),
    exch_rt_eur NUMBER,
    exch_rt_usd NUMBER);
  TYPE exch_tbl IS TABLE OF X.exch_row;

  FUNCTION GetExchangeRate RETURN X.exch_tbl PIPELINED;
END X;

Package Body

CREATE OR REPLACE PACKAGE BODY X IS
  FUNCTION GetExchangeRate RETURN X.exch_tbl
    PIPELINED AS
    exch_rt_usd NUMBER := 1.0; --todo
    rw exch_row;
  BEGIN

    FOR rw IN (SELECT c.currency_cd AS currency_cd, e.exch_rt AS exch_rt_eur, (e.exch_rt / exch_rt_usd) AS exch_rt_usd
                 FROM exch e, currency c
                WHERE c.currency_key = e.currency_key
                  ) LOOP
      PIPE ROW(rw);
    END LOOP;
  END;


  PROCEDURE DoIt IS
  BEGIN
    DECLARE
      CURSOR c0 IS
        SELECT i.DOC,
               i.doc_currency,
               i.net_value,
               i.net_value / rt.exch_rt_usd AS net_value_in_usd,
               i.net_value / rt.exch_rt_eur AS net_value_in_euro,
          FROM item i, (SELECT * FROM TABLE(X.GetExchangeRate())) rt
         WHERE i.doc_currency = rt.currency_cd;

      TYPE c0_type IS TABLE OF c0%ROWTYPE;

      items c0_type;
    BEGIN
      OPEN c0;

      LOOP
        FETCH c0 BULK COLLECT
          INTO items LIMIT batchsize;

        EXIT WHEN items.COUNT = 0;
        FORALL i IN items.FIRST .. items.LAST SAVE EXCEPTIONS
          INSERT INTO detail_items VALUES items (i);

      END LOOP;

      CLOSE c0;

      COMMIT;

    EXCEPTION
      WHEN OTHERS THEN
        RAISE;
    END;
  END;

END X;

Please review.

How can I tell if a Java integer is null?

ints are value types; they can never be null. Instead, if the parsing failed, parseInt will throw a NumberFormatException that you need to catch.

Custom "confirm" dialog in JavaScript?

_x000D_
_x000D_
var confirmBox = '<div class="modal fade confirm-modal">' +_x000D_
    '<div class="modal-dialog modal-sm" role="document">' +_x000D_
    '<div class="modal-content">' +_x000D_
    '<button type="button" class="close m-4 c-pointer" data-dismiss="modal" aria-label="Close">' +_x000D_
    '<span aria-hidden="true">&times;</span>' +_x000D_
    '</button>' +_x000D_
    '<div class="modal-body pb-5"></div>' +_x000D_
    '<div class="modal-footer pt-3 pb-3">' +_x000D_
    '<a href="#" class="btn btn-primary yesBtn btn-sm">OK</a>' +_x000D_
    '<button type="button" class="btn btn-secondary abortBtn btn-sm" data-dismiss="modal">Abbrechen</button>' +_x000D_
    '</div>' +_x000D_
    '</div>' +_x000D_
    '</div>' +_x000D_
    '</div>';_x000D_
_x000D_
var dialog = function(el, text, trueCallback, abortCallback) {_x000D_
_x000D_
    el.click(function(e) {_x000D_
_x000D_
        var thisConfirm = $(confirmBox).clone();_x000D_
_x000D_
        thisConfirm.find('.modal-body').text(text);_x000D_
_x000D_
        e.preventDefault();_x000D_
        $('body').append(thisConfirm);_x000D_
        $(thisConfirm).modal('show');_x000D_
_x000D_
        if (abortCallback) {_x000D_
            $(thisConfirm).find('.abortBtn').click(function(e) {_x000D_
                e.preventDefault();_x000D_
                abortCallback();_x000D_
                $(thisConfirm).modal('hide');_x000D_
            });_x000D_
        }_x000D_
_x000D_
        if (trueCallback) {_x000D_
            $(thisConfirm).find('.yesBtn').click(function(e) {_x000D_
                e.preventDefault();_x000D_
                trueCallback();_x000D_
                $(thisConfirm).modal('hide');_x000D_
            });_x000D_
        } else {_x000D_
_x000D_
            if (el.prop('nodeName') == 'A') {_x000D_
                $(thisConfirm).find('.yesBtn').attr('href', el.attr('href'));_x000D_
            }_x000D_
_x000D_
            if (el.attr('type') == 'submit') {_x000D_
                $(thisConfirm).find('.yesBtn').click(function(e) {_x000D_
                    e.preventDefault();_x000D_
                    el.off().click();_x000D_
                });_x000D_
            }_x000D_
        }_x000D_
_x000D_
        $(thisConfirm).on('hidden.bs.modal', function(e) {_x000D_
            $(this).remove();_x000D_
        });_x000D_
_x000D_
    });_x000D_
}_x000D_
_x000D_
// custom confirm_x000D_
$(function() {_x000D_
    $('[data-confirm]').each(function() {_x000D_
        dialog($(this), $(this).attr('data-confirm'));_x000D_
    });_x000D_
_x000D_
    dialog($('#customCallback'), "dialog with custom callback", function() {_x000D_
_x000D_
        alert("hi there");_x000D_
_x000D_
    });_x000D_
_x000D_
});
_x000D_
.test {_x000D_
  display:block;_x000D_
  padding: 5p 10px;_x000D_
  background:orange;_x000D_
  color:white;_x000D_
  border-radius:4px;_x000D_
  margin:0;_x000D_
  border:0;_x000D_
  width:150px;_x000D_
  text-align:center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
example 1_x000D_
<a class="test" href="http://example" data-confirm="do you want really leave the website?">leave website</a><br><br>_x000D_
_x000D_
_x000D_
example 2_x000D_
<form action="">_x000D_
<button class="test" type="submit" data-confirm="send form to delete some files?">delete some files</button>_x000D_
</form><br><br>_x000D_
_x000D_
example 3_x000D_
<span class="test"  id="customCallback">with callback</span>
_x000D_
_x000D_
_x000D_

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

How do I encode and decode a base64 string?

    using System;
    using System.Text;

    public static class Base64Conversions
    {
        public static string EncodeBase64(this string text, Encoding encoding = null)
        { 
            if (text == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = encoding.GetBytes(text);
            return Convert.ToBase64String(bytes);
        }

        public static string DecodeBase64(this string encodedText, Encoding encoding = null)
        {
            if (encodedText == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = Convert.FromBase64String(encodedText);
            return encoding.GetString(bytes);
        }
    }

Usage

    var text = "Sample Text";
    var base64 = text.EncodeBase64();
    base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding

Deserialize Java 8 LocalDateTime with JacksonMapper

This worked for me:

 @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", shape = JsonFormat.Shape.STRING)
 private LocalDateTime startDate;

Editing legend (text) labels in ggplot

The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2 package.

An example with your data:

# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")

# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
  geom_point(size=5) +
  labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
        plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))

this results in:

enter image description here

As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888")) instead of scale_color_manual().

What is the purpose of Looper and how to use it?

Simplest Definition of Looper & Handler:

Looper is a class that turns a thread into a Pipeline Thread and Handler gives you a mechanism to push tasks into it from any other threads.

Details in general wording:

So a PipeLine Thread is a thread which can accept more tasks from other threads through a Handler.

The Looper is named so because it implements the loop – takes the next task, executes it, then takes the next one and so on. The Handler is called a handler because it is used to handle or accept that next task each time from any other thread and pass to Looper (Thread or PipeLine Thread).

Example:

A Looper and Handler or PipeLine Thread's very perfect example is to download more than one images or upload them to a server (Http) one by one in a single thread instead of starting a new Thread for each network call in the background.

Read more here about Looper and Handler and the definition of Pipeline Thread:

Android Guts: Intro to Loopers and Handlers

Specify system property to Maven project

If your test and webapp are in the same Maven project, you can use a property in the project POM. Then you can filter certain files which will allow Maven to set the property in those files. There are different ways to filter, but the most common is during the resources phase - http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-description.html

If the test and webapp are in different Maven projects, you can put the property in settings.xml, which is in your maven repository folder (C:\Documents and Settings\username.m2) on Windows. You will still need to use filtering or some other method to read the property into your test and webapp.

How can I get the current date and time in UTC or GMT in Java?

If you're using joda time and want the current time in milliseconds without your local offset you can use this:

long instant = DateTimeZone.UTC.getMillisKeepLocal(DateTimeZone.getDefault(), System.currentTimeMillis());

How do I read the file content from the Internal storage - Android App

I prefer to use java.util.Scanner:

try {
    Scanner scanner = new Scanner(context.openFileInput(filename)).useDelimiter("\\Z");
    StringBuilder sb = new StringBuilder();

    while (scanner.hasNext()) {
        sb.append(scanner.next());
    }

    scanner.close();

    String result = sb.toString();

} catch (IOException e) {}

Is there a way to get version from package.json in nodejs code?

I do this with findup-sync:

var findup = require('findup-sync');
var packagejson = require(findup('package.json'));
console.log(packagejson.version); // => '0.0.1' 

How to sort findAll Doctrine's method?

You need to use a criteria, for example:

<?php

namespace Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Collections\Criteria;

/**
* Thing controller
*/
class ThingController extends Controller
{
    public function thingsAction(Request $request, $id)
    {
        $ids=explode(',',$id);
        $criteria = new Criteria(null, <<DQL ordering expression>>, null, null );

        $rep    = $this->getDoctrine()->getManager()->getRepository('Bundle:Thing');
        $things = $rep->matching($criteria);
        return $this->render('Bundle:Thing:things.html.twig', [
            'entities' => $things,
        ]);
    }
}

How to change the name of a Django app?

Why not just use the option Find and Replace. (every code editor has it)?

For example Visual Studio Code (under Edit option):

Visual Studio Code option: 'Replace in files'

You just type in old name and new name and replace everyhting in the project with one click.

NOTE: This renames only file content, NOT file and folder names. Do not forget renaming folders, eg. templates/my_app_name/ rename it to templates/my_app_new_name/

SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)

Same way for tolerance

=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

You could use dataframe method notnull or inverse of isnull, or numpy.isnan:

In [332]: df[df.EPS.notnull()]
Out[332]:
   STK_ID  RPT_Date  STK_ID.1  EPS  cash
2  600016  20111231    600016  4.3   NaN
4  601939  20111231    601939  2.5   NaN


In [334]: df[~df.EPS.isnull()]
Out[334]:
   STK_ID  RPT_Date  STK_ID.1  EPS  cash
2  600016  20111231    600016  4.3   NaN
4  601939  20111231    601939  2.5   NaN


In [347]: df[~np.isnan(df.EPS)]
Out[347]:
   STK_ID  RPT_Date  STK_ID.1  EPS  cash
2  600016  20111231    600016  4.3   NaN
4  601939  20111231    601939  2.5   NaN

How to set background color of an Activity to white programmatically?

I prefer coloring by theme

<style name="CustomTheme" parent="android:Theme.Light">
    <item name="android:windowBackground">@color/custom_theme_color</item>
    <item name="android:colorBackground">@color/custom_theme_color</item>
</style>

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

How to implement the Softmax function in Python

Here is generalized solution using numpy and comparision for correctness with tensorflow ans scipy:

Data preparation:

import numpy as np

np.random.seed(2019)

batch_size = 1
n_items = 3
n_classes = 2
logits_np = np.random.rand(batch_size,n_items,n_classes).astype(np.float32)
print('logits_np.shape', logits_np.shape)
print('logits_np:')
print(logits_np)

Output:

logits_np.shape (1, 3, 2)
logits_np:
[[[0.9034822  0.3930805 ]
  [0.62397    0.6378774 ]
  [0.88049906 0.299172  ]]]

Softmax using tensorflow:

import tensorflow as tf

logits_tf = tf.convert_to_tensor(logits_np, np.float32)
scores_tf = tf.nn.softmax(logits_np, axis=-1)

print('logits_tf.shape', logits_tf.shape)
print('scores_tf.shape', scores_tf.shape)

with tf.Session() as sess:
    scores_np = sess.run(scores_tf)

print('scores_np.shape', scores_np.shape)
print('scores_np:')
print(scores_np)

print('np.sum(scores_np, axis=-1).shape', np.sum(scores_np,axis=-1).shape)
print('np.sum(scores_np, axis=-1):')
print(np.sum(scores_np, axis=-1))

Output:

logits_tf.shape (1, 3, 2)
scores_tf.shape (1, 3, 2)
scores_np.shape (1, 3, 2)
scores_np:
[[[0.62490064 0.37509936]
  [0.4965232  0.5034768 ]
  [0.64137274 0.3586273 ]]]
np.sum(scores_np, axis=-1).shape (1, 3)
np.sum(scores_np, axis=-1):
[[1. 1. 1.]]

Softmax using scipy:

from scipy.special import softmax

scores_np = softmax(logits_np, axis=-1)

print('scores_np.shape', scores_np.shape)
print('scores_np:')
print(scores_np)

print('np.sum(scores_np, axis=-1).shape', np.sum(scores_np, axis=-1).shape)
print('np.sum(scores_np, axis=-1):')
print(np.sum(scores_np, axis=-1))

Output:

scores_np.shape (1, 3, 2)
scores_np:
[[[0.62490064 0.37509936]
  [0.4965232  0.5034768 ]
  [0.6413727  0.35862732]]]
np.sum(scores_np, axis=-1).shape (1, 3)
np.sum(scores_np, axis=-1):
[[1. 1. 1.]]

Softmax using numpy (https://nolanbconaway.github.io/blog/2017/softmax-numpy) :

def softmax(X, theta = 1.0, axis = None):
    """
    Compute the softmax of each element along an axis of X.

    Parameters
    ----------
    X: ND-Array. Probably should be floats.
    theta (optional): float parameter, used as a multiplier
        prior to exponentiation. Default = 1.0
    axis (optional): axis to compute values along. Default is the
        first non-singleton axis.

    Returns an array the same size as X. The result will sum to 1
    along the specified axis.
    """

    # make X at least 2d
    y = np.atleast_2d(X)

    # find axis
    if axis is None:
        axis = next(j[0] for j in enumerate(y.shape) if j[1] > 1)

    # multiply y against the theta parameter,
    y = y * float(theta)

    # subtract the max for numerical stability
    y = y - np.expand_dims(np.max(y, axis = axis), axis)

    # exponentiate y
    y = np.exp(y)

    # take the sum along the specified axis
    ax_sum = np.expand_dims(np.sum(y, axis = axis), axis)

    # finally: divide elementwise
    p = y / ax_sum

    # flatten if X was 1D
    if len(X.shape) == 1: p = p.flatten()

    return p


scores_np = softmax(logits_np, axis=-1)

print('scores_np.shape', scores_np.shape)
print('scores_np:')
print(scores_np)

print('np.sum(scores_np, axis=-1).shape', np.sum(scores_np, axis=-1).shape)
print('np.sum(scores_np, axis=-1):')
print(np.sum(scores_np, axis=-1))

Output:

scores_np.shape (1, 3, 2)
scores_np:
[[[0.62490064 0.37509936]
  [0.49652317 0.5034768 ]
  [0.64137274 0.3586273 ]]]
np.sum(scores_np, axis=-1).shape (1, 3)
np.sum(scores_np, axis=-1):
[[1. 1. 1.]]

Check if object value exists within a Javascript array of objects and if not add a new object to array

function number_present_or_not() { var arr = [ 2,5,9,67,78,8,454,4,6,79,64,688 ] ; var found = 6; var found_two; for (i=0; i

    }
    if ( found_two == found )
    {
        console.log("number present in the array");
    }
    else
    {
        console.log("number not present in the array");
    }
}

How do I check if an integer is even or odd?

For the sake of discussion...

You only need to look at the last digit in any given number to see if it is even or odd. Signed, unsigned, positive, negative - they are all the same with regards to this. So this should work all round: -

void tellMeIfItIsAnOddNumberPlease(int iToTest){
  int iLastDigit;
  iLastDigit = iToTest - (iToTest / 10 * 10);
  if (iLastDigit % 2 == 0){
    printf("The number %d is even!\n", iToTest);
  } else {
    printf("The number %d is odd!\n", iToTest);
  }
}

The key here is in the third line of code, the division operator performs an integer division, so that result are missing the fraction part of the result. So for example 222 / 10 will give 22 as a result. Then multiply it again with 10 and you have 220. Subtract that from the original 222 and you end up with 2, which by magic is the same number as the last digit in the original number. ;-) The parenthesis are there to remind us of the order the calculation is done in. First do the division and the multiplication, then subtract the result from the original number. We could leave them out, since the priority is higher for division and multiplication than of subtraction, but this gives us "more readable" code.

We could make it all completely unreadable if we wanted to. It would make no difference whatsoever for a modern compiler: -

printf("%d%s\n",iToTest,0==(iToTest-iToTest/10*10)%2?" is even":" is odd");

But it would make the code way harder to maintain in the future. Just imagine that you would like to change the text for odd numbers to "is not even". Then someone else later on want to find out what changes you made and perform a svn diff or similar...

If you are not worried about portability but more about speed, you could have a look at the least significant bit. If that bit is set to 1 it is an odd number, if it is 0 it's an even number. On a little endian system, like Intel's x86 architecture it would be something like this: -

if (iToTest & 1) {
  // Even
} else {
  // Odd
}

How Should I Set Default Python Version In Windows?

Running 'py' command will tell you what version you have running. If you currently running 3.x and you need to switch to 2.x, you will need to use switch '-2'

py -2

If you need to switch from python 2.x to python 3.x you will have to use '-3' switch

py -3

If you would like to have Python 3.x as a default version, then you will need to create environment variable 'PY_PYTHON' and set it's value to 3.

Split array into chunks of N length

It could be something like that:

_x000D_
_x000D_
var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

var arrays = [], size = 3;
    
while (a.length > 0)
  arrays.push(a.splice(0, size));

console.log(arrays);
_x000D_
_x000D_
_x000D_

See splice Array's method.

Get current controller in view

You can use any of the below code to get the controller name

@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();

If you are using MVC 3 you can use

@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue

How to center an iframe horizontally?

The simplest code to align the iframe element:

<div align="center"><iframe width="560" height="315" src="www.youtube.com" frameborder="1px"></iframe></div>

What are the git concepts of HEAD, master, origin?

I highly recommend the book "Pro Git" by Scott Chacon. Take time and really read it, while exploring an actual git repo as you do.

HEAD: the current commit your repo is on. Most of the time HEAD points to the latest commit in your current branch, but that doesn't have to be the case. HEAD really just means "what is my repo currently pointing at".

In the event that the commit HEAD refers to is not the tip of any branch, this is called a "detached head".

master: the name of the default branch that git creates for you when first creating a repo. In most cases, "master" means "the main branch". Most shops have everyone pushing to master, and master is considered the definitive view of the repo. But it's also common for release branches to be made off of master for releasing. Your local repo has its own master branch, that almost always follows the master of a remote repo.

origin: the default name that git gives to your main remote repo. Your box has its own repo, and you most likely push out to some remote repo that you and all your coworkers push to. That remote repo is almost always called origin, but it doesn't have to be.

HEAD is an official notion in git. HEAD always has a well-defined meaning. master and origin are common names usually used in git, but they don't have to be.

Format cell if cell contains date less than today

=$W$4<=TODAY()

Returns true for dates up to and including today, false otherwise.

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

You could roll your own:

function resolve(objectToGetValueFrom, stringOfDotSeparatedParameters) {
    var returnObject = objectToGetValueFrom,
        parameters = stringOfDotSeparatedParameters.split('.'),
        i,
        parameter;

    for (i = 0; i < parameters.length; i++) {
        parameter = parameters[i];

        returnObject = returnObject[parameter];

        if (returnObject === undefined) {
            break;
        }
    }
    return returnObject;
};

And use it like this:

var result = resolve(obj, 'a.b.c.d'); 

* result is undefined if any one of a, b, c or d is undefined.

How to print React component on click of a button?

On 6/19/2017 This worked perfect for me.

import React, { Component } from 'react'

class PrintThisComponent extends Component {
  render() {
    return (
      <div>
        <button onClick={() => window.print()}>PRINT</button>
        <p>Click above button opens print preview with these words on page</p>
      </div>
    )
  }
}

export default PrintThisComponent

How can I select from list of values in SQL Server

If you want to select only certain values from a single table you can try this

select distinct(*) from table_name where table_field in (1,1,2,3,4,5)

eg:

select first_name,phone_number from telephone_list where district id in (1,2,5,7,8,9)

if you want to select from multiple tables then you must go for UNION.

If you just want to select the values 1, 1, 1, 2, 5, 1, 6 then you must do this

select 1 
union select 1 
union select 1 
union select 2 
union select 5 
union select 1 
union select 6

Send HTML in email via PHP

You can easily send the email with HTML content via PHP. Use the following script.

<?php
$to = '[email protected]';
$subject = "Send HTML Email Using PHP";

$htmlContent = '
<html>
<body>
    <h1>Send HTML Email Using PHP</h1>
    <p>This is a HTMl email using PHP by CodexWorld</p>
</body>
</html>';

// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// Additional headers
$headers .= 'From: CodexWorld<[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";

// Send email
if(mail($to,$subject,$htmlContent,$headers)):
    $successMsg = 'Email has sent successfully.';
else:
    $errorMsg = 'Email sending fail.';
endif;
?>

Source code and live demo can be found from here - Send Beautiful HTML Email using PHP

How to restrict the selectable date ranges in Bootstrap Datepicker?

With selectable date ranges you might want to use something like this. My solution prevents selecting #from_date bigger than #to_date and changes #to_date startDate every time when user selects new date in #from_date box:

http://bootply.com/74352

JS file:

var startDate = new Date('01/01/2012');
var FromEndDate = new Date();
var ToEndDate = new Date();

ToEndDate.setDate(ToEndDate.getDate()+365);

$('.from_date').datepicker({

    weekStart: 1,
    startDate: '01/01/2012',
    endDate: FromEndDate, 
    autoclose: true
})
    .on('changeDate', function(selected){
        startDate = new Date(selected.date.valueOf());
        startDate.setDate(startDate.getDate(new Date(selected.date.valueOf())));
        $('.to_date').datepicker('setStartDate', startDate);
    }); 
$('.to_date')
    .datepicker({

        weekStart: 1,
        startDate: startDate,
        endDate: ToEndDate,
        autoclose: true
    })
    .on('changeDate', function(selected){
        FromEndDate = new Date(selected.date.valueOf());
        FromEndDate.setDate(FromEndDate.getDate(new Date(selected.date.valueOf())));
        $('.from_date').datepicker('setEndDate', FromEndDate);
    });

HTML:

<input class="from_date" placeholder="Select start date" contenteditable="false" type="text">
<input class="to_date" placeholder="Select end date" contenteditable="false" type="text" 

And do not forget to include bootstrap datepicker.js and .css files aswell.

Access images inside public folder in laravel

when you want to access images which are in public/images folder and if you want to access it without using laravel functions, use as follows:

<img src={{url('/images/photo.type')}} width="" height="" alt=""/>

This works fine.

Converting char* to float or double

Code posted by you is correct and should have worked. But check exactly what you have in the char*. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL. Check what you have in the char* against maximum values that float and double can represent on your computer.

Check this page for strtod reference and this page for atof reference.

I have tried the example you provided in both Windows and Linux and it worked fine.

Spring get current ApplicationContext

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-servlet.xml");

Then you can retrieve the bean:

MyClass myClass = (MyClass) context.getBean("myClass");

Reference: springbyexample.org

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

php: catch exception and continue execution, is it possible?

Yes.

try {
    Somecode();
catch (Exception $e) {
    // handle or ignore exception here. 
}

however note that php also has error codes separate from exceptions, a legacy holdover from before php had oop primitives. Most library builtins still raise error codes, not exceptions. To ignore an error code call the function prefixed with @:

@myfunction();

How to Find App Pool Recycles in Event Log

IIS version 8.5 +

To enable Event Tracing for Windows for your website/application

  1. Go to Logging and ensure either ETW event only or Both log file and ETW event ...is selected.

enter image description here

  1. Enable the desired Recycle logs in the Advanced Settings for the Application Pool:

enter image description here

  1. Go to the default Custom View: WebServer filters IIS logs:

Custom Views > ServerRoles > Web Server

enter image description here

  1. ... or System logs:

Windows Logs > System

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

The image below is from the article written by Erwin van der Valk:

image explaining MVC, MVP and MVVM - by Erwin Vandervalk

The article explains the differences and gives some code examples in C#

How to fix: Error device not found with ADB.exe

I switched to a different USB port and it suddenly got recognized...

Chrome hangs after certain amount of data transfered - waiting for available socket

Chrome is a Chromium-based browser and Chromium-based browsers only allow maximum 6 open socket connections at a time, when the 7th connection starts up it will just sit idle and wait for one of the 6 which are running to stop and then it will start running. Hence the error code ‘waiting for available sockets’, the 7th one will wait for one of those 6 sockets to become available and then it will start running.

You can either

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

Below code will be helpful for you

public static IUnityContainer Initialise(IUnityContainer container = null)
{
    if (container == null)
    {
        container = new UnityContainer();
    }
    container.RegisterType<ISettingsManager, SettingsManager>();
    container.Resolve<SettingsManager>();
    container.RegisterType<SettingsManagerController>(new InjectionProperty("_SettingManagerProvider", new ResolvedParameter<ISettingManager>()));
    return container;
}

How to iterate object keys using *ngFor

Angular now has a type of iterate Object for exactly this scenario, called a Set. It fit my needs when I found this question searching. You create the set, "add" to it like you'd "push" to an array, and drop it in an ngFor just like an array. No pipes or anything.

this.myObjList = new Set();

...

this.myObjList.add(obj);

...

<ul>
   <li *ngFor="let object of myObjList">
     {{object}}
   </li>
</ul>

How to get first and last day of previous month (with timestamp) in SQL Server

You can get first and last day of previous month (with timestamp) in SQL Server by executing

--select dateadd(dd,-datepart(dd,getdate())+1,dateadd(mm,-1,getdate())) --first day of previous month 
--select dateadd(dd,-datepart(dd,getdate()),getdate()) -- last day of previous month**

Object passed as parameter to another class, by value or reference?

Assuming someTestObj is a class and not a struct, the object is passed by reference, which means that both obj and someTestObj refer to the same object. E.g. changing name in one will change it in the other. However, unlike if you passed it using the ref keyword, setting obj = somethingElse will not change someTestObj.

How to find index of STRING array in Java from a given value?

An easy way would be to iterate over the items in the array in a loop.

for (var i = 0; i < arrayLength; i++) {
 // (string) Compare the given string with myArray[i]
 // if it matches store/save i and exit the loop.
}

There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.

How to call a SOAP web service on Android

Add Soap Libaray(ksoap2-android-assembly-3.2.0-jar-with-dependencies.jar):

public static String Fn_Confirm_CollectMoney_Approval(

        HashMap < String, String > str1,
        HashMap < String, String > str2,
        HashMap < String, String > str3) {

    Object response = null;
    String METHOD_NAME = "CollectMoney";
    String NAMESPACE = "http://xxx/yyy/xxx";
    String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
    String SOAP_ACTION = "";

    try {

        SoapObject RequestParent = new SoapObject(NAMESPACE, METHOD_NAME);

        SoapObject Request1 = new SoapObject(NAMESPACE, "req");

        PropertyInfo pi = new PropertyInfo();

        Set mapSet1 = (Set) str1.entrySet();

        Iterator mapIterator1 = mapSet1.iterator();

        while (mapIterator1.hasNext()) {

            Map.Entry mapEntry = (Map.Entry) mapIterator1.next();

            String keyValue = (String) mapEntry.getKey();

            String value = (String) mapEntry.getValue();

            pi = new PropertyInfo();

            pi.setNamespace("java:com.xxx");

            pi.setName(keyValue);

            pi.setValue(value);

            Request1.addProperty(pi);
        }

        mapSet1 = (Set) str3.entrySet();

        mapIterator1 = mapSet1.iterator();

        while (mapIterator1.hasNext()) {

            Map.Entry mapEntry = (Map.Entry) mapIterator1.next();

            // getKey Method of HashMap access a key of map
            String keyValue = (String) mapEntry.getKey();

            // getValue method returns corresponding key's value
            String value = (String) mapEntry.getValue();

            pi = new PropertyInfo();

            pi.setNamespace("java:com.xxx");

            pi.setName(keyValue);

            pi.setValue(value);

            Request1.addProperty(pi);
        }

        SoapObject HeaderRequest = new SoapObject(NAMESPACE, "XXX");

        Set mapSet = (Set) str2.entrySet();

        Iterator mapIterator = mapSet.iterator();

        while (mapIterator.hasNext()) {

            Map.Entry mapEntry = (Map.Entry) mapIterator.next();

            // getKey Method of HashMap access a key of map
            String keyValue = (String) mapEntry.getKey();

            // getValue method returns corresponding key's value
            String value = (String) mapEntry.getValue();

            pi = new PropertyInfo();

            pi.setNamespace("java:com.xxx");

            pi.setName(keyValue);

            pi.setValue(value);

            HeaderRequest.addProperty(pi);
        }

        Request1.addSoapObject(HeaderRequest);

        RequestParent.addSoapObject(Request1);

        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER10);

        soapEnvelope.dotNet = false;

        soapEnvelope.setOutputSoapObject(RequestParent);

        HttpTransportSE transport = new HttpTransportSE(URL, 120000);

        transport.debug = true;

        transport.call(SOAP_ACTION, soapEnvelope);

        response = (Object) soapEnvelope.getResponse();

        int cols = ((SoapObject) response).getPropertyCount();

        Object objectResponse = (Object) ((SoapObject) response)
                .getProperty("Resp");

        SoapObject subObject_Resp = (SoapObject) objectResponse;


        modelObject = new ResposeXmlModel();

        String MsgId = subObject_Resp.getProperty("MsgId").toString();


        modelObject.setMsgId(MsgId);

        String OrgId = subObject_Resp.getProperty("OrgId").toString();


        modelObject.setOrgId(OrgId);

        String ResCode = subObject_Resp.getProperty("ResCode").toString();


        modelObject.setResCode(ResCode);

        String ResDesc = subObject_Resp.getProperty("ResDesc").toString();


        modelObject.setResDesc(ResDesc);

        String TimeStamp = subObject_Resp.getProperty("TimeStamp")
                .toString();


        modelObject.setTimestamp(ResDesc);

        return response.toString();

    } catch (Exception ex) {

        ex.printStackTrace();

        return null;
    }

}

How do I make a semi transparent background?

If you want to make transparent background is gray, pls try:

   .transparent{
       background:rgba(1,1,1,0.5);
   }

Set UITableView content inset permanently

This is how it can be fixed easily through Storyboard (iOS 11 and Xcode 9.1):

Select Table View > Size Inspector > Content Insets: Never

What is the boundary in multipart/form-data?

Is the ??? free to be defined by the user?

Yes.

or is it supplied by the HTML?

No. HTML has nothing to do with that. Read below.

Is it possible for me to define the ??? as abcdefg?

Yes.

If you want to send the following data to the web server:

name = John
age = 12

using application/x-www-form-urlencoded would be like this:

name=John&age=12

As you can see, the server knows that parameters are separated by an ampersand &. If & is required for a parameter value then it must be encoded.

So how does the server know where a parameter value starts and ends when it receives an HTTP request using multipart/form-data?

Using the boundary, similar to &.

For example:

--XXX
Content-Disposition: form-data; name="name"

John
--XXX
Content-Disposition: form-data; name="age"

12
--XXX--

In that case, the boundary value is XXX. You specify it in the Content-Type header so that the server knows how to split the data it receives.

So you need to:

  • Use a value that won't appear in the HTTP data sent to the server.

  • Be consistent and use the same value everywhere in the request message.

Using Google Translate in C#

If you want to translate your resources, just download MAT (Multilingual App Toolkit) for Visual Studio. https://marketplace.visualstudio.com/items?itemName=MultilingualAppToolkit.MultilingualAppToolkit-18308 This is the way to go to translate your projects in Visual Studio. https://blogs.msdn.microsoft.com/matdev/

PHP - concatenate or directly insert variables in string

From the point of view of making thinks simple, readable, consistent and easy to understand (since performance doesn't matter here):

  • Using embedded vars in double quotes can lead to complex and confusing situations when you want to embed object properties, multidimentional arrays etc. That is, generally when reading embedded vars, you cannot be instantly 100% sure of the final behavior of what you are reading.

  • You frequently need add crutches such as {} and \, which IMO adds confusion and makes concatenation readability nearly equivalent, if not better.

  • As soon as you need to wrap a function call around the var, for example htmlspecialchars($var), you have to switch to concatenation.

  • AFAIK, you cannot embed constants.

In some specific cases, "double quotes with vars embedding" can be useful, but generally speaking, I would go for concatenation (using single or double quotes when convenient)

How to create a sticky navigation bar that becomes fixed to the top after scrolling

In answer to Shubham Patwa: This way, the page is "jumpy" soon as the class "navbar-fixed-top" applies. That's because the #mainnav is throwen in and out of the document's DOM flow. This can result in an ugly UX if the page has a "critical height", jumping between fixed and un-fixed #mainnav position.

I altered the code this way, which seems to work fine (not pixel-perfect, but fine):

$(document).ready(function() {
  var navpos = $('#mainnav').offset();
  var navheight = $('#mainnav').outerHeight();

$(window).bind('scroll', function() {
  if ($(window).scrollTop() > navpos.top) {
   $('#mainnav').addClass('navbar-fixed-top');
   $('body').css('marginTop',navheight);
   }
   else {
     $('#mainnav').removeClass('navbar-fixed-top');
     $('body').css('marginTop','0');
   }
});

CSS selectors ul li a {...} vs ul > li > a {...}

1) for example HTML code:

<ul>
    <li>
        <a href="#">firstlink</a>
        <span><a href="#">second link&lt;/a>
    </li>
</ul>

and css rules:

1) ul li a {color:red;} 
2) ul > li > a {color:blue;}

">" - symbol mean that that will be searching only child selector (parentTag > childTag)

so first css rule will apply to all links (first and second) and second rule will apply anly to first link

2) As for efficiency - I think second will be more fast - as in case with JavaScript selectors. This rule read from right to left, this mean that when rule will parse by browser, it get all links on page: - in first case it will find all parent elements for each link on page and filter all links where exist parent tags "ul" and "li" - in second case it will check only parent node of link if it is "li" tag then -> check if parent tag of "li" is "ul"

some thing like this. Hope I describe all properly for you

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

Rename a file using Java

Files.move(file.toPath(), fileNew.toPath()); 

works, but only when you close (or autoclose) ALL used resources (InputStream, FileOutputStream etc.) I think the same situation with file.renameTo or FileUtils.moveFile.

Show Image View from file path?

All the answers are outdated. It is best to use picasso for such purposes. It has a lot of features including background image processing.

Did I mention it is super easy to use:

Picasso.with(context).load(new File(...)).into(imageView);

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

After having all the proposed solutions fail my tests one way or the other, (edit: some were updated to pass the tests after I wrote this) I found the mozilla implementation for Array.indexOf and Array.lastIndexOf

I used those to implement my version of String.prototype.regexIndexOf and String.prototype.regexLastIndexOf as follows:

String.prototype.regexIndexOf = function(elt /*, from*/)
  {
    var arr = this.split('');
    var len = arr.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0) ? Math.ceil(from) : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++) {
      if (from in arr && elt.exec(arr[from]) ) 
        return from;
    }
    return -1;
};

String.prototype.regexLastIndexOf = function(elt /*, from*/)
  {
    var arr = this.split('');
    var len = arr.length;

    var from = Number(arguments[1]);
    if (isNaN(from)) {
      from = len - 1;
    } else {
      from = (from < 0) ? Math.ceil(from) : Math.floor(from);
      if (from < 0)
        from += len;
      else if (from >= len)
        from = len - 1;
    }

    for (; from > -1; from--) {
      if (from in arr && elt.exec(arr[from]) )
        return from;
    }
    return -1;
  };

They seem to pass the test functions I provided in the question.

Obviously they only work if the regular expression matches one character but that is enough for my purpose since I will be using it for things like ( [abc] , \s , \W , \D )

I will keep monitoring the question in case someone provides a better/faster/cleaner/more generic implementation that works on any regular expression.

Why is there no tuple comprehension in Python?

Since Python 3.5, you can also use splat * unpacking syntax to unpack a generator expresion:

*(x for x in range(10)),

Datatables warning(table id = 'example'): cannot reinitialise data table

You are initializing datatables twice, why?

// Take this off
/*
$(document).ready(function() {
    $( '#example' ).dataTable();
} );
*/
$(document).ready( function() {
  $( '#example' ).dataTable( {
   "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
     // Bold the grade for all 'A' grade browsers
     if ( aData[4] == "A" )
     {
       $('td:eq(4)', nRow).html( '<b>A</b>' );
     }
   }
 } );
 } );

ASP.NET MVC DropDownListFor with model of type List<string>

I realize this question was asked a long time ago, but I came here looking for answers and wasn't satisfied with anything I could find. I finally found the answer here:

https://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor

To get the results from the form, use the FormCollection and then pull each individual value out by it's model name thus:

yourRecord.FieldName = Request.Form["FieldNameInModel"];

As far as I could tell it makes absolutely no difference what argument name you give to the FormCollection - use Request.Form["NameFromModel"] to retrieve it.

No, I did not dig down to see how th4e magic works under the covers. I just know it works...

I hope this helps somebody avoid the hours I spent trying different approaches before I got it working.

Append value to empty vector in R?

Just for the sake of completeness, appending values to a vector in a for loop is not really the philosophy in R. R works better by operating on vectors as a whole, as @BrodieG pointed out. See if your code can't be rewritten as:

ouput <- sapply(values, function(v) return(2*v))

Output will be a vector of return values. You can also use lapply if values is a list instead of a vector.

Remove last 3 characters of string or number in javascript

you just need to divide the Date Time stamp by 1000 like:

var a = 1437203995000;
a = (a)/1000;

Implements vs extends: When to use? What's the difference?

Extends : This is used to get attributes of a parent class into base class and may contain already defined methods that can be overridden in the child class.

Implements : This is used to implement an interface (parent class with functions signatures only but not their definitions) by defining it in the child class.

There is one special condition: "What if I want a new Interface to be the child of an existing interface?". In the above condition, the child interface extends the parent interface.

jQuery looping .each() JSON key/value not working

With a simple JSON object, you don't need jQuery:

for (var i in json) {
   for (var j in json[i]) {
     console.log(json[i][j]);
   }
}

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

The mysql_install_db script also needs the datadir parameter:

mysql_install_db --user=root --datadir=$db_datapath

On Maria DB you use the install script mysql_install_db to install and initialize. In my case I use an environment variable for the data path. Not only does mysqld need to know where the data is (specified via commandline), but so does the install script.

Controlling a USB power supply (on/off) with Linux

You could use my tool uhubctl to control USB power per port for compatible USB hubs.

argparse module How to add option without any argument?

To create an option that needs no value, set the action [docs] of it to 'store_const', 'store_true' or 'store_false'.

Example:

parser.add_argument('-s', '--simulate', action='store_true')

Switch focus between editor and integrated terminal in Visual Studio Code

The default keybinding to toggle the integrated terminal is "Ctrl+`" according to VS Code keyboard shortcuts documentation page. If you don't like that shortcut you can change it in your keybindings file by adding something similar to:

{ "key": "ctrl+l", "command": "workbench.action.terminal.toggleTerminal" }

There does not seem to be a default keybinding for simply focusing the bottom panel. So, if you do not want to toggle the bottom panel, you will need to add something similar to the following to your keybindings file:

{ "key": "ctrl+t", "command": "workbench.action.focusPanel" }

Run Python script at startup in Ubuntu

In similar situations, I've done well by putting something like the following into /etc/rc.local:

cd /path/to/my/script
./my_script.py &
cd -
echo `date +%Y-%b-%d_%H:%M:%S` > /tmp/ran_rc_local  # check that rc.local ran

This has worked on multiple versions of Fedora and on Ubuntu 14.04 LTS, for both python and perl scripts.

javascript code to check special characters

If you don't want to include any special character, then try this much simple way for checking special characters using RegExp \W Metacharacter.

var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
if(!(iChars.match(/\W/g)) == "") {
    alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
    return false;
}