Programs & Examples On #Void pointers

A void pointer (void *) in C and C++ is a pointer that points to a memory location with no specified type.

error: cast from 'void*' to 'int' loses precision

The proper way is to cast it to another pointer type. Converting a void* to an int is non-portable way that may work or may not! If you need to keep the returned address, just keep it as void*.

Pointer arithmetic for void pointer in C

Compiler knows by type cast. Given a void *x:

  • x+1 adds one byte to x, pointer goes to byte x+1
  • (int*)x+1 adds sizeof(int) bytes, pointer goes to byte x + sizeof(int)
  • (float*)x+1 addres sizeof(float) bytes, etc.

Althought the first item is not portable and is against the Galateo of C/C++, it is nevertheless C-language-correct, meaning it will compile to something on most compilers possibly necessitating an appropriate flag (like -Wpointer-arith)

What is a void pointer in C++?

A void* pointer is used when you want to indicate a pointer to a hunk of memory without specifying the type. C's malloc returns such a pointer, expecting you to cast it to a particular type immediately. It really isn't useful until you cast it to another pointer type. You're expected to know which type to cast it to, the compiler has no reflection capability to know what the underlying type should be.

Concept of void pointer in C programming

So far my understating on void pointer is as follows.

When a pointer variable is declared using keyword void – it becomes a general purpose pointer variable. Address of any variable of any data type (char, int, float etc.)can be assigned to a void pointer variable.

main()
{
    int *p;

    void *vp;

    vp=p;
} 

Since other data type pointer can be assigned to void pointer, so I used it in absolut_value(code shown below) function. To make a general function.

I tried to write a simple C code which takes integer or float as a an argument and tries to make it +ve, if negative. I wrote the following code,

#include<stdio.h>

void absolute_value ( void *j) // works if used float, obviously it must work but thats not my interest here.
{
    if ( *j < 0 )
        *j = *j * (-1);

}

int main()
{
    int i = 40;
    float f = -40;
    printf("print intiger i = %d \n",i);
    printf("print float f = %f \n",f);
    absolute_value(&i);
    absolute_value(&f);
    printf("print intiger i = %d \n",i);
    printf("print float f = %f \n",f);
    return 0;
}   

But I was getting error, so I came to know my understanding with void pointer is not correct :(. So now I will move towards to collect points why is that so.

The things that i need to understand more on void pointers is that.

We need to typecast the void pointer variable to dereference it. This is because a void pointer has no data type associated with it. There is no way the compiler can know (or guess?) what type of data is pointed to by the void pointer. So to take the data pointed to by a void pointer we typecast it with the correct type of the data holded inside the void pointers location.

void main()

{

    int a=10;

    float b=35.75;

    void *ptr; // Declaring a void pointer

    ptr=&a; // Assigning address of integer to void pointer.

    printf("The value of integer variable is= %d",*( (int*) ptr) );// (int*)ptr - is used for type casting. Where as *((int*)ptr) dereferences the typecasted void pointer variable.

    ptr=&b; // Assigning address of float to void pointer.

    printf("The value of float variable is= %f",*( (float*) ptr) );

}

A void pointer can be really useful if the programmer is not sure about the data type of data inputted by the end user. In such a case the programmer can use a void pointer to point to the location of the unknown data type. The program can be set in such a way to ask the user to inform the type of data and type casting can be performed according to the information inputted by the user. A code snippet is given below.

void funct(void *a, int z)
{
    if(z==1)
    printf("%d",*(int*)a); // If user inputs 1, then he means the data is an integer and type casting is done accordingly.
    else if(z==2)
    printf("%c",*(char*)a); // Typecasting for character pointer.
    else if(z==3)
    printf("%f",*(float*)a); // Typecasting for float pointer
}

Another important point you should keep in mind about void pointers is that – pointer arithmetic can not be performed in a void pointer.

void *ptr;

int a;

ptr=&a;

ptr++; // This statement is invalid and will result in an error because 'ptr' is a void pointer variable.

So now I understood what was my mistake. I am correcting the same.

References :

http://www.antoarts.com/void-pointers-in-c/

http://www.circuitstoday.com/void-pointers-in-c.

The New code is as shown below.


#include<stdio.h>
#define INT 1
#define FLOAT 2

void absolute_value ( void *j, int *n)
{
    if ( *n == INT) {
        if ( *((int*)j) < 0 )
            *((int*)j) = *((int*)j) * (-1);
    }
    if ( *n == FLOAT ) {
        if ( *((float*)j) < 0 )
            *((float*)j) = *((float*)j) * (-1);
    }
}


int main()
{
    int i = 0,n=0;
    float f = 0;
    printf("Press 1 to enter integer or 2 got float then enter the value to get absolute value\n");
    scanf("%d",&n);
    printf("\n");
    if( n == 1) {
        scanf("%d",&i);
        printf("value entered before absolute function exec = %d \n",i);
        absolute_value(&i,&n);
        printf("value entered after absolute function exec = %d \n",i);
    }
    if( n == 2) {
        scanf("%f",&f);
        printf("value entered before absolute function exec = %f \n",f);
        absolute_value(&f,&n);
        printf("value entered after absolute function exec = %f \n",f);
    }
    else
    printf("unknown entry try again\n");
    return 0;
}   

Thank you,

SVN check out linux

There should be svn utility on you box, if installed:

$ svn checkout http://example.com/svn/somerepo somerepo

This will check out a working copy from a specified repository to a directory somerepo on our file system.

You may want to print commands, supported by this utility:

$ svn help

uname -a output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm or the following command:

$ sudo yum install subversion

PDF Blob - Pop up window not showing content

I ended up just downloading my pdf using below code

function downloadPdfDocument(fileName){

var req = new XMLHttpRequest();
req.open("POST", "/pdf/" + fileName, true);
req.responseType = "blob";
fileName += "_" + new Date() + ".pdf";

req.onload = function (event) {

    var blob = req.response;

    //for IE
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {

        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
    }
};

req.send();

}

How to find pg_config path

You can find the pg_config directory using its namesake:

$ pg_config --bindir
/usr/lib/postgresql/9.1/bin
$ 

Tested on Mac and Debian. The only wrinkle is that I can't see how to find the bindir for different versions of postgres installed on the same machine. It's fairly easy to guess though! :-)

Note: I updated my pg_config to 9.5 on Debian with:

sudo apt-get install postgresql-server-dev-9.5

How to ALTER multiple columns at once in SQL Server

Doing multiple ALTER COLUMN actions inside a single ALTER TABLE statement is not possible.

See the ALTER TABLE syntax here

You can do multiple ADD or multiple DROP COLUMN, but just one ALTER COLUMN.

VBA Excel Provide current Date in Text box

I know this is extremely old post, but I've used this before

You can always adjust to activate. Now method is another way. Just an option

Private Sub UserForm_Initialize()

Textbox1.Text = Format(Now(), "mmddyyyhhmmss")

End Sub

How do I update Homebrew?

  • cd /usr/local
  • git status
  • Discard all the changes (unless you actually want to try to commit to Homebrew - you probably don't)
  • git status til it's clean
  • brew update

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

The latest set of guidance is as follows: (from https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables)

Use:

System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);

From the docs:

public static class EnvironmentVariablesExample
{
    [FunctionName("GetEnvironmentVariables")]
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
        log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
    }

    public static string GetEnvironmentVariable(string name)
    {
        return name + ": " +
            System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
    }
}

App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the Values collection in the local.settings.json file. In both environments, local and Azure, GetEnvironmentVariable("<app setting name>") retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains { "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }.

The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use GetEnvironmentVariable as shown here.

How to replace NA values in a table for selected columns

Edit 2020-06-15

Since data.table 1.12.4 (Oct 2019), data.table gains two functions to facilitate this: nafill and setnafill.

nafill operates on columns:

cols = c('a', 'b')
y[ , (cols) := lapply(.SD, nafill, fill=0), .SDcols = cols]

setnafill operates on tables (the replacements happen by-reference/in-place)

setnafill(y, cols=cols, fill=0)
# print y to show the effect
y[]

This will also be more efficient than the other options; see ?nafill for more, the last-observation-carried-forward (LOCF) and next-observation-carried-backward (NOCB) versions of NA imputation for time series.


This will work for your data.table version:

for (col in c("a", "b")) y[is.na(get(col)), (col) := 0]

Alternatively, as David Arenburg points out below, you can use set (side benefit - you can use it either on data.frame or data.table):

for (col in 1:2) set(x, which(is.na(x[[col]])), col, 0)

Is there a way to view past mysql queries with phpmyadmin?

You have to click on query window just below the phpMyAdmin logo, a new window will open. Just click on SQL History tab. There you can see history of SQL Queries.

C++ pointer to objects

First I need to say that your code,

MyClass *myclass;
myclass->DoSomething();

will cause an undefined behavior. Because the pointer "myclass" isn't pointing to any "MyClass" type objects.

Here I have three suggestions for you:-

option 1:- You can simply declare and use a MyClass type object on the stack as below.

MyClass myclass; //allocates memory for the object "myclass", on the stack.
myclass.DoSomething();

option 2:- By using the new operator.

MyClass *myclass = new MyClass();

Three things will hapen here.

i) Allocates memory for the "MyClass" type object on the heap.

ii) Allocates memory for the "MyClass" type pointer "myclass" on the stack.

iii) pointer "myclass" points to the memory address of "MyClass" type object on the heap

Now you can use the pointer to access member functions of the object after dereferencing the pointer by "->"

myclass->DoSomething();

But you should free the memory allocated to "MyClass" type object on the heap, before returning from the scope unless you want it to exists. Otherwise it will cause a memory leak!

delete myclass; // free the memory pointed by the pointer "myclass"

option 3:- you can also do as below.

MyClass myclass; // allocates memory for the "MyClass" type object on the stack.
MyClass *myclassPtr; // allocates memory for the "MyClass" type pointer on the stack.
myclassPtr = &myclass; // "myclassPtr" pointer points to the momory address of myclass object.

Now, pointer and object both are on the stack. Now you can't return this pointer to the outside of the current scope because both allocated memory of the pointer and the object will be freed while stepping outside the scope.

So as a summary, option 1 and 3 will allocate an object on the stack while only the option 2 will do it on the heap.

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

This should be rather a SuperUser question.

Right I have the exact same error inside MacOSX SourceTree, however, inside a iTerm2 terminal, things work just dandy.

However, the problem seemed to be that I've got two ssh-agents running ;(

The first being /usr/bin/ssh-agent (aka MacOSX's) and then also the HomeBrew installed /usr/local/bin/ssh-agent running.

Firing up a terminal from SourceTree, allowed me to see the differences in SSH_AUTH_SOCK, using lsof I found the two different ssh-agents and then I was able to load the keys (using ssh-add) into the system's default ssh-agent (ie. /usr/bin/ssh-agent), SourceTree was working again.

how to use concatenate a fixed string and a variable in Python

I know this is a little old but I wanted to add an updated answer with f-strings which were introduced in Python version 3.6:

msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

I think that replacing:

List<String> list = Arrays.asList(split);

with

List<String> list = new ArrayList<String>(Arrays.asList(split));

resolves the problem.

User Authentication in ASP.NET Web API

I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.

The client side code (CoffeeScript) to get the token is:

getAuthenticationToken = (username, password) ->
    dataToSend = "username=" + username + "&password=" + password
    dataToSend += "&grant_type=password"
    $.post("/token", dataToSend).success saveAccessToken

If successful the following is called, which saves the authentication token locally:

saveAccessToken = (response) ->
    window.authenticationToken = response.access_token

Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:

{ "Authorization": "Bearer " + window.authenticationToken }

Update Query with INNER JOIN between tables in 2 different databases on 1 server

//For Access Database:
UPDATE ((tblEmployee
LEFT JOIN tblCity ON (tblEmployee.CityCode = tblCity.CityCode))
LEFT JOIN tblCountry ON (tblEmployee.CountryCode = tblCountryCode))
SET tblEmployee.CityName = tblCity.CityName, 
tblEmployee.CountryName = tblCountry.CountryName
WHERE (tblEmployee.CityName = '' OR tblEmployee.CountryName = '')

How to check a Long for null in java

If it is Long you can check if it's null unless you go for long (as primitive data types cant be null while Long instance is a object)

_x000D_
_x000D_
Long num; _x000D_
_x000D_
if(num == null) return;
_x000D_
_x000D_
_x000D_

For some context, you can also prefer using Optional with it to make it somehow beautiful for some use cases. Refer @RequestParam in Spring MVC handling optional parameters

How to make a JFrame button open another JFrame class in Netbeans?

Double Click the Login Button in the NETBEANS or add the Event Listener on Click Event (ActionListener)

btnLogin.addActionListener(new ActionListener() 
{
    public void actionPerformed(ActionEvent e) {
        this.setVisible(false);
        new FrmMain().setVisible(true); // Main Form to show after the Login Form..
    }
});

Math.random() explanation

The Random class of Java located in the java.util package will serve your purpose better. It has some nextInt() methods that return an integer. The one taking an int argument will generate a number between 0 and that int, the latter not inclusive.

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

"N/A" is not a string it is an error, try this:

=if(ISNA(A1),C1)

you have to place this fomula in cell B1 so it will get the value of your formula

What is "Linting"?

Linting is the process of checking the source code for Programmatic as well as Stylistic errors. This is most helpful in identifying some common and uncommon mistakes that are made during coding.

A Lint or a Linter is a program that supports linting (verifying code quality). They are available for most languages like JavaScript, CSS, HTML, Python, etc..

Some of the useful linters are JSLint, CSSLint, JSHint, Pylint

How to set the font size in Emacs?

Open emacs in X11, goto menu Options, select "set default font ...", change the font size. Select "save options" in the same menu. Done.

How to get random value out of an array?

In my case, I have to get 2 values what are objects. I share this simple solution.

$ran = array("a","b","c","d");
$ranval = array_map(function($i) use($ran){return $ran[$i];},array_rand($ran,2));

this.getClass().getClassLoader().getResource("...") and NullPointerException

When you use

this.getClass().getResource("myFile.ext")

getResource will try to find the resource relative to the package. If you use:

this.getClass().getResource("/myFile.ext")

getResource will treat it as an absolute path and simply call the classloader like you would have if you'd done.

this.getClass().getClassLoader().getResource("myFile.ext")

The reason you can't use a leading / in the ClassLoader path is because all ClassLoader paths are absolute and so / is not a valid first character in the path.

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.

To change your Platform Toolset:

  1. Right click your project, go to Properties.
  2. Under Configuration Properties, go to General.
  3. Change your Platform Toolset to one of the available ones.

Checking if a string array contains a value, and if so, getting its position

IMO the best way to check if an array contains a given value is to use System.Collections.Generic.IList<T>.Contains(T item) method the following way:

((IList<string>)stringArray).Contains(value)

Complete code sample:

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if (((IList<string>)stringArray).Contains(value)) Console.WriteLine("The array contains "+value);
else Console.WriteLine("The given string was not found in array.");

T[] arrays privately implement a few methods of List<T>, such as Count and Contains. Because it's an explicit (private) implementation, you won't be able to use these methods without casting the array first. This doesn't only work for strings - you can use this trick to check if an array of any type contains any element, as long as the element's class implements IComparable.

Keep in mind not all IList<T> methods work this way. Trying to use IList<T>'s Add method on an array will fail.

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

In GNU/Linux you can use this command

 /etc/init.d/virtualbox

Options

  • start
  • stop
  • stop_vms
  • restart
  • force-reload
  • status

for example

 /etc/init.d/virtualbox force-reload

Good Luck

What's the best way to determine the location of the current PowerShell script?

For PowerShell 3.0

$PSCommandPath
    Contains the full path and file name of the script that is being run. 
    This variable is valid in all scripts.

The function is then:

function Get-ScriptDirectory {
    Split-Path -Parent $PSCommandPath
}

Finish all previous activities

Simply, when you go from the login screen, not when finishing the login screen.

And then in all forward activities, use this for logout:

final Intent intent = new Intent(getBaseContext(), LoginScreen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);

It works perfectly.

Total Number of Row Resultset getRow Method

I have solved that problem. The only I do is:

private int num_rows;

And then in your method using the resultset put this code

while (this.rs.next())
{

    this.num_rows++;
}

That's all

How do I subscribe to all topics of a MQTT broker

You can use mosquitto_sub (which is part of the mosquitto-clients package) and subscribe to the wildcard topic #:

mosquitto_sub -v -h broker_ip -p 1883 -t '#'

Shell script to capture Process ID and kill it if exist

This should kill all processes matching the grep that you are permitted to kill.

-9 means "Kill all processes you can kill".

kill -9 $(ps -ef | grep [s]yncapp | awk '{print $2}')

Convert double/float to string

See if the BSD C Standard Library has fcvt(). You could start with the source for it that rather than writing your code from scratch. The UNIX 98 standard fcvt() apparently does not output scientific notation so you would have to implement it yourself, but I don't think it would be hard.

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

nrow(aaa)
## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

Android 6.0 multiple permissions

Short and sweet :). what I believe in.

int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; // List of permissions required

public void askPermission()
{
    for (String permission : PERMISSIONS) {
        if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(PERMISSIONS, PERMISSION_ALL);
            return;
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                       int[] grantResults) {

    switch (requestCode) {
        case 1:{
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
                //Do your work.
            } else {
                Toast.makeText(this, "Until you grant the permission, we cannot proceed further", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

I encountered this problem when working with COM objects. Under certain circumstances (my fault), I destroyed an external .EXE process, in a parallel thread, a variable tried to access the com interface app.method and a COM-level crash occurred. Task Scheduler noticed this and shut down the app. But if you run the app in the console and don't handle the exception, the app will continue to work ...

Please note that if you use unmanaged code or external objects (AD, Socket, COM ...), you need to monitor them!

MySQL Event Scheduler on a specific time everyday

CREATE EVENT test_event_03
ON SCHEDULE EVERY 1 MINUTE
STARTS CURRENT_TIMESTAMP
ENDS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
   INSERT INTO messages(message,created_at)
   VALUES('Test MySQL recurring Event',NOW());

yii2 redirect in controller action does not work?

I struggled with redirect not working for very long, none of what mentioned above was working for me, until I tried this:

Change:

return $this->redirect('site/secure');

to:

return $this->redirect(['site/secure']);

In other words, needed to enclose it within [] brackets! I am using PHP 7, might be the reason why?

nodejs mysql Error: Connection lost The server closed the connection

Creating and destroying the connections in each query maybe complicated, i had some headaches with a server migration when i decided to install MariaDB instead MySQL. For some reason in the file etc/my.cnf the parameter wait_timeout had a default value of 10 sec (it causes that the persistence can't be implemented). Then, the solution was set it in 28800, that's 8 hours. Well, i hope help somebody with this "güevonada"... excuse me for my bad english.

To show error message without alert box in Java Script

try this

<html>
  <head>
  <script type="text/javascript">
  function validate() {
  if(myform.fname.value.length==0)
  {
   document.getElementById("error").innerHTML="this is invalid name ";
   document.myform.fname.value="";
   document.myform.fname.focus();
  }
  }
  </script>
  </head>
  <body>
  <form name="myform">
  First_Name
  <input type="text" id="fname" name="fname" onblur="validate()"> </input>
<span style="color:red;" id="error" > </span>
  <br> <br>
  Last_Name
  <input type="text" id="lname" name="lname" onblur="validate()"> </input>

  <br>
  <input type=button value=check> 

  </form>
  </body>
</html>

extract digits in a simple way from a python string

Without using regex, you can just do:

def get_num(x):
    return int(''.join(ele for ele in x if ele.isdigit()))

Result:

>>> get_num(x)
120
>>> get_num(y)
90
>>> get_num(banana)
200
>>> get_num(orange)
300

EDIT :

Answering the follow up question.

If we know that the only period in a given string is the decimal point, extracting a float is quite easy:

def get_num(x):
    return float(''.join(ele for ele in x if ele.isdigit() or ele == '.'))

Result:

>>> get_num('dfgd 45.678fjfjf')
45.678

Python function overloading

Use keyword arguments with defaults. E.g.

def add_bullet(sprite, start=default, direction=default, script=default, speed=default):

In the case of a straight bullet versus a curved bullet, I'd add two functions: add_bullet_straight and add_bullet_curved.

How to get the background color code of an element in hex?

There's a bit of a hack for this, since the HTML5 canvas is required to parse color values when certain properties like strokeStyle and fillStyle are set:

var ctx = document.createElement('canvas').getContext('2d');
ctx.strokeStyle = 'rgb(64, 128, 192)';
var hexColor = ctx.strokeStyle;

in_array multiple values

As a developer, you should probably start learning set operations (difference, union, intersection). You can imagine your array as one "set", and the keys you are searching for the other.

Check if ALL needles exist

function in_array_all($needles, $haystack) {
   return empty(array_diff($needles, $haystack));
}

echo in_array_all( [3,2,5], [5,8,3,1,2] ); // true, all 3, 2, 5 present
echo in_array_all( [3,2,5,9], [5,8,3,1,2] ); // false, since 9 is not present

Check if ANY of the needles exist

function in_array_any($needles, $haystack) {
   return !empty(array_intersect($needles, $haystack));
}

echo in_array_any( [3,9], [5,8,3,1,2] ); // true, since 3 is present
echo in_array_any( [4,9], [5,8,3,1,2] ); // false, neither 4 nor 9 is present

Is it possible to use Visual Studio on macOS?

No. Neither Visual Studio or the .NET framework will run on Mac OSX (although the latter is changing). However, if you want to write an application in a similar framework, you could use Mono and MonoDevelop.

installing apache: no VCRUNTIME140.dll

Also, please make sure you installed the correct version of apache on your computer. For example, not install a x86 on a 64bit system. Vice versa.

How do I create a simple 'Hello World' module in Magento?

And,

I suggest you to learn about system configuration.

How to Show All Categories on System Configuration Field?

Here I solved with a good example. It working. You can check and learn the flow of code.

There are other too many examples also that you should learn.

How to add a named sheet at the end of all Excel sheets?


Try switching the order of your code. You must create the worksheet first in order to name it.

Private Sub CreateSheet()
    Dim ws As Worksheet
    Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
    ws.Name = "Tempo"
End Sub

thanks,

How do you install an APK file in the Android emulator?

Now you can just drag and drop the apk in emulator and it will install!

How do I split a string in Rust?

split returns an Iterator, which you can convert into a Vec using collect: split_line.collect::<Vec<_>>(). Going through an iterator instead of returning a Vec directly has several advantages:

  • split is lazy. This means that it won't really split the line until you need it. That way it won't waste time splitting the whole string if you only need the first few values: split_line.take(2).collect::<Vec<_>>(), or even if you need only the first value that can be converted to an integer: split_line.filter_map(|x| x.parse::<i32>().ok()).next(). This last example won't waste time attempting to process the "23.0" but will stop processing immediately once it finds the "1".
  • split makes no assumption on the way you want to store the result. You can use a Vec, but you can also use anything that implements FromIterator<&str>, for example a LinkedList or a VecDeque, or any custom type that implements FromIterator<&str>.

Concrete Javascript Regex for Accented Characters (Diacritics)

from this wiki : https://en.wikipedia.org/wiki/List_of_Unicode_characters#Basic_Latin

for latin letters, I use

/^[A-zÀ-ÖØ-öø-ÿ]+$/ 

it avoids hyphens and specials chars

SecurityException during executing jnlp file (Missing required Permissions manifest attribute in main jar)

JAR File Manifest Attributes for Security

The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.

Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.

Permissions Attribute

The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.

Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:

  • sandbox - runs in the security sandbox and does not require additional permissions.

  • all-permissions - requires access to the user's system resources.

Changes to Security Slider:

The following changes to Security Slider were included in this release(7u51):

  • Block Self-Signed and Unsigned applets on High Security Setting
  • Require Permissions Attribute for High Security Setting
  • Warn users of missing Permissions Attributes for Medium Security Setting

For more information, see Java Control Panel documentation.

enter image description here

sample MANIFEST.MF

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

Run this command :

    sudo chown -R yourUser /home/yourUser/.composer

How to find which views are using a certain table in SQL Server (2008)?

SELECT VIEW_NAME
FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE
WHERE TABLE_NAME = 'Your Table'

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

For a Node.js app, in the server.js file before registering all of my own routes, I put the code below. It sets the headers for all responses. It also ends the response gracefully if it is a pre-flight "OPTIONS" call and immediately sends the pre-flight response back to the client without "nexting" (is that a word?) down through the actual business logic routes. Here is my server.js file. Relevant sections highlighted for Stackoverflow use.

// server.js

// ==================
// BASE SETUP

// import the packages we need
var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var morgan     = require('morgan');
var jwt        = require('jsonwebtoken'); // used to create, sign, and verify tokens

// ====================================================
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Logger
app.use(morgan('dev'));

// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------

//Set CORS header and intercept "OPTIONS" preflight call from AngularJS
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    if (req.method === "OPTIONS") 
        res.send(200);
    else 
        next();
}

// -------------------------------------------------------------
// STACKOVERFLOW -- END OF THIS SECTION, ONE MORE SECTION BELOW
// -------------------------------------------------------------


// =================================================
// ROUTES FOR OUR API

var route1 = require("./routes/route1");
var route2 = require("./routes/route2");
var error404 = require("./routes/error404");


// ======================================================
// REGISTER OUR ROUTES with app

// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------

app.use(allowCrossDomain);

// -------------------------------------------------------------
//  STACKOVERFLOW -- OK THAT IS THE LAST THING.
// -------------------------------------------------------------

app.use("/api/v1/route1/", route1);
app.use("/api/v1/route2/", route2);
app.use('/', error404);

// =================
// START THE SERVER

var port = process.env.PORT || 8080;        // set our port
app.listen(port);
console.log('API Active on port ' + port);

How to download PDF automatically using js?

It is also possible to open the pdf link in a new window and let the browser handle the rest:

window.open(pdfUrl, '_blank');

or:

window.open(pdfUrl);

Why specify @charset "UTF-8"; in your CSS file?

It tells the browser to read the css file as UTF-8. This is handy if your CSS contains unicode characters and not only ASCII.

Using it in the meta tag is fine, but only for pages that include that meta tag.

Read about the rules for character set resolution of CSS files at the w3c spec for CSS 2.

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

I found this implementation very easy to use. Also has a generous BSD-style license:

jsSHA: https://github.com/Caligatio/jsSHA

I needed a quick way to get the hex-string representation of a SHA-256 hash. It only took 3 lines:

var sha256 = new jsSHA('SHA-256', 'TEXT');
sha256.update(some_string_variable_to_hash);
var hash = sha256.getHash("HEX");

modal View controllers - how to display and dismiss

I have solved the issue by using UINavigationController when presenting. In MainVC, when presenting VC1

let vc1 = VC1()
let navigationVC = UINavigationController(rootViewController: vc1)
self.present(navigationVC, animated: true, completion: nil)

In VC1, when I would like to show VC2 and dismiss VC1 in same time (just one animation), I can have a push animation by

let vc2 = VC2()
self.navigationController?.setViewControllers([vc2], animated: true)

And in VC2, when close the view controller, as usual we can use:

self.dismiss(animated: true, completion: nil)

Get index of a key/value pair in a C# dictionary based on the value

In your comment to max's answer, you say that what you really wanted to get is the key in, and not the index of, the KeyValuePair that contains a certain value. You could edit your question to make it more clear.

It is worth pointing out (EricM has touched upon this in his answer) that a value might appear more than once in the dictionary, in which case one would have to think which key he would like to get: e.g. the first that comes up, the last, all of them?

If you are sure that each key has a unique value, you could have another dictionary, with the values from the first acting as keys and the previous keys acting as values. Otherwise, this second dictionary idea (suggested by Jon Skeet) will not work, as you would again have to think which of all the possible keys to use as value in the new dictionary.

If you were asking about the index, though, EricM's answer would be OK. Then you could get the KeyValuePair in question by using:

yourDictionary.ElementAt(theIndexYouFound);

provided that you do not add/remove things in yourDictionary.

PS: I know it's been almost 7 years now, but what the heck. I thought it best to formulate my answer as addressing the OP, but of course by now one can say it is an answer for just about anyone else but the OP. Fully aware of that, thank you.

Python find min max and average of a list (array)

from __future__ import division

somelist =  [1,12,2,53,23,6,17] 
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)

If you want to manually find the minimum as a function:

somelist =  [1,12,2,53,23,6,17] 

def my_min_function(somelist):
    min_value = None
    for value in somelist:
        if not min_value:
            min_value = value
        elif value < min_value:
            min_value = value
    return min_value

Python 3.4 introduced the statistics package, which provides mean and additional stats:

from statistics import mean, median

somelist =  [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)

HTML list-style-type dash

Another way:

li:before {
  content: '\2014\00a0\00a0'; /* em-dash followed by two non-breaking spaces*/
}
li {
  list-style: none;
  text-indent: -1.5em;
  padding-left: 1.5em;    
}

How can I stage and commit all files, including newly added files, using a single command?

Not sure why these answers all dance around what I believe to be the right solution but for what it's worth here is what I use:

1. Create an alias:

git config --global alias.coa "!git add -A && git commit -m"

2. Add all files & commit with a message:

git coa "A bunch of horrible changes"

NOTE: coa is short for commit all and can be replaced with anything your heart desires

Traverse all the Nodes of a JSON Object Tree with JavaScript

I've created library to traverse and edit deep nested JS objects. Check out API here: https://github.com/dominik791

You can also play with the library interactively using demo app: https://dominik791.github.io/obj-traverse-demo/

Examples of usage: You should always have root object which is the first parameter of each method:

var rootObj = {
  name: 'rootObject',
  children: [
    {
      'name': 'child1',
       children: [ ... ]
    },
    {
       'name': 'child2',
       children: [ ... ]
    }
  ]
};

The second parameter is always the name of property that holds nested objects. In above case it would be 'children'.

The third parameter is an object that you use to find object/objects that you want to find/modify/delete. For example if you're looking for object with id equal to 1, then you will pass { id: 1} as the third parameter.

And you can:

  1. findFirst(rootObj, 'children', { id: 1 }) to find first object with id === 1
  2. findAll(rootObj, 'children', { id: 1 }) to find all objects with id === 1
  3. findAndDeleteFirst(rootObj, 'children', { id: 1 }) to delete first matching object
  4. findAndDeleteAll(rootObj, 'children', { id: 1 }) to delete all matching objects

replacementObj is used as the last parameter in two last methods:

  1. findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'}) to change first found object with id === 1 to the { id: 2, name: 'newObj'}
  2. findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'}) to change all objects with id === 1 to the { id: 2, name: 'newObj'}

T-SQL datetime rounded to nearest minute and nearest hours with using functions

I realize this question is ancient and there is an accepted and an alternate answer. I also realize that my answer will only answer half of the question, but for anyone wanting to round to the nearest minute and still have a datetime compatible value using only a single function:

CAST(YourValueHere as smalldatetime);

For hours or seconds, use Jeff Ogata's answer (the accepted answer) above.

How to make the checkbox unchecked by default always

jQuery

$('input[type=checkbox]').removeAttr('checked');

Or

<!-- checked -->
<input type='checkbox' name='foo' value='bar' checked=''/> 

<!-- unchecked -->
<input type='checkbox' class='inputUncheck' name='foo' value='bar' checked=''/> 
<input type='checkbox' class='inputUncheck' name='foo' value='bar'/> 

+

$('input.inputUncheck').removeAttr('checked');

Why is C so fast, and why aren't other languages as fast or faster?

The main factors are that it's a statically-typed language and that's compiled to machine code. Also, since it's a low-level language, it generally doesn't do anything you don't tell it to.

These are some other factors that come to mind.

  • Variables are not automatically initialized
  • No bounds checking on arrays
  • Unchecked pointer manipulation
  • No integer overflow checking
  • Statically-typed variables
  • Function calls are static (unless you use function pointers)
  • Compiler writers have had lots of time to improve the optimizing code. Also, people program in C for the purpose of getting the best performance, so there's pressure to optimize the code.
  • Parts of the language specification are implementation-defined, so compilers are free to do things in the most optimal way

Most static-typed languages could be compiled just as fast or faster than C though, especially if they can make assumptions that C can't because of pointer aliasing, etc.

jquery AJAX and json format

Currently you are sending the data as typical POST values, which look like this:

first_name=somename&last_name=somesurname

If you want to send data as json you need to create an object with data and stringify it.

data: JSON.stringify(someobject)

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

Encrypt and Decrypt text with RSA in PHP

Yes. Look at http://jerrywickey.com/test/testJerrysLibrary.php

It gives sample code examples for RSA encryption and decryption in PHP as well as RSA encryption in javascript.

If you want to encrypt text instead of just base 10 numbers, you'll also need a base to base conversion. That is convert text to a very large number. Text is really just writing in base 63. 26 lowercase letters plus 26 uppercase + 10 numerals + space character. The code for that is below also.

The $GETn parameter is a file name that holds keys for the cryption functions. If you don't figure it out, ask. I'll help.

I actually posted this whole encryption library yesterday, but Brad Larson a mod, killed it and said this kind of stuff isn't really what Stack Overflow is about. But you can still find all the code examples and the whole function library to carry out client/server encryption decryption for AJAX at the link above.

function RSAencrypt( $num, $GETn){
    if ( file_exists( 'temp/bigprimes'.hash( 'sha256', $GETn).'.php')){
        $t= explode( '>,', file_get_contents('temp/bigprimes'.hash( 'sha256', $GETn).'.php'));
        return JL_powmod( $num, $t[4], $t[10]); 
    }else{
        return false;
    }
}

function RSAdecrypt( $num, $GETn){
    if ( file_exists( 'temp/bigprimes'.hash( 'sha256', $GETn).'.php')){
        $t= explode( '>,', file_get_contents('temp/bigprimes'.hash( 'sha256', $GETn).'.php'));
        return JL_powmod( $num, $t[8], $t[10]);     
    }else{
        return false;
    }
}

function JL_powmod( $num, $pow, $mod) {
    if ( function_exists('bcpowmod')) {
        return bcpowmod( $num, $pow, $mod);
    }
    $result= '1';
    do {
        if ( !bccomp( bcmod( $pow, '2'), '1')) {
            $result = bcmod( bcmul( $result, $num), $mod);
        }
       $num = bcmod( bcpow( $num, '2'), $mod);

       $pow = bcdiv( $pow, '2');
    } while ( bccomp( $pow, '0'));
    return $result;
}

function baseToBase ($message, $fromBase, $toBase){
    $from= strlen( $fromBase);
    $b[$from]= $fromBase; 
    $to= strlen( $toBase);
    $b[$to]= $toBase; 

    $result= substr( $b[$to], 0, 1);

    $f= substr( $b[$to], 1, 1);

    $tf= digit( $from, $b[$to]);

    for ($i=strlen($message)-1; $i>=0; $i--){
        $result= badd( $result, bmul( digit( strpos( $b[$from], substr( $message, $i, 1)), $b[$to]), $f, $b[$to]), $b[$to]);
        $f= bmul($f, $tf, $b[$to]);
    }
    return $result;
} 

function digit( $from, $bto){   
    $to= strlen( $bto);
    $b[$to]= $bto; 

    $t[0]= intval( $from);
    $i= 0;
    while ( $t[$i] >= intval( $to)){
        if ( !isset( $t[$i+1])){ 
            $t[$i+1]= 0;
        }
        while ( $t[$i] >= intval( $to)){
            $t[$i]= $t[$i] - intval( $to);
            $t[$i+1]++;
        }
        $i++;
    }

    $res= '';
    for ( $i=count( $t)-1; $i>=0; $i--){ 
        $res.= substr( $b[$to], $t[$i], 1);
    }
    return $res;
}   

function badd( $n1, $n2, $nbase){
    $base= strlen( $nbase);
    $b[$base]= $nbase; 

    while ( strlen( $n1) < strlen( $n2)){
        $n1= substr( $b[$base], 0, 1) . $n1;
    }
    while ( strlen( $n1) > strlen( $n2)){
        $n2= substr( $b[$base], 0, 1) . $n2;
    }
    $n1= substr( $b[$base], 0, 1) . $n1;    
    $n2= substr( $b[$base], 0, 1) . $n2;
    $m1= array();
    for ( $i=0; $i<strlen( $n1); $i++){
        $m1[$i]= strpos( $b[$base], substr( $n1, (strlen( $n1)-$i-1), 1));
    }   
    $res= array();
    $m2= array();
    for ($i=0; $i<strlen( $n1); $i++){
        $m2[$i]= strpos( $b[$base], substr( $n2, (strlen( $n1)-$i-1), 1));
        $res[$i]= 0;
    }           
    for ($i=0; $i<strlen( $n1)  ; $i++){
        $res[$i]= $m1[$i] + $m2[$i] + $res[$i];
        if ($res[$i] >= $base){
            $res[$i]= $res[$i] - $base;
            $res[$i+1]++;
        }
    }
    $o= '';
    for ($i=0; $i<strlen( $n1); $i++){
        $o= substr( $b[$base], $res[$i], 1).$o;
    }   
    $t= false;
    $o= '';
    for ($i=strlen( $n1)-1; $i>=0; $i--){
        if ($res[$i] > 0 || $t){    
            $o.= substr( $b[$base], $res[$i], 1);
            $t= true;
        }
    }
    return $o;
}
function bmul( $n1, $n2, $nbase){
    $base= strlen( $nbase);
    $b[$base]= $nbase; 

    $m1= array();
    for ($i=0; $i<strlen( $n1); $i++){
        $m1[$i]= strpos( $b[$base], substr($n1, (strlen( $n1)-$i-1), 1));
    }   
    $m2= array();
    for ($i=0; $i<strlen( $n2); $i++){
        $m2[$i]= strpos( $b[$base], substr($n2, (strlen( $n2)-$i-1), 1));
    }           
    $res= array();
    for ($i=0; $i<strlen( $n1)+strlen( $n2)+2; $i++){
        $res[$i]= 0;
    }
    for ($i=0; $i<strlen( $n1)  ; $i++){
        for ($j=0; $j<strlen( $n2)  ; $j++){
            $res[$i+$j]= ($m1[$i] * $m2[$j]) + $res[$i+$j];
            while ( $res[$i+$j] >= $base){
                $res[$i+$j]= $res[$i+$j] - $base;
                $res[$i+$j+1]++;
            }
        }
    }
    $t= false;
    $o= '';
    for ($i=count( $res)-1; $i>=0; $i--){
        if ($res[$i]>0 || $t){  
            $o.= substr( $b[$base], $res[$i], 1);
            $t= true;
        }
    }
    return $o;
}

Activity restart on rotation Android

Update for Android 3.2 and higher:

Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must declare android:configChanges="orientation|screenSize". However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

Everyone here is very wrong. All you need is to follow the steps that Apple provides in Managing Your Digital Identities.

It instructs you to export your certificates through Xcode and reimport through Xcode. It works great, but make sure your username is the same on both computers or it will fail.

laravel 5.4 upload image

A good logic for your application could be something like:

 public function uploadGalery(Request $request){
      $this->validate($request, [
        'file' => 'required|image|mimes:jpeg,png,jpg,bmp,gif,svg|max:2048',
      ]);
      if ($request->hasFile('file')) {
        $image = $request->file('file');
        $name = time().'.'.$image->getClientOriginalExtension();
        $destinationPath = public_path('/storage/galeryImages/');
        $image->move($destinationPath, $name);
        $this->save();
        return back()->with('success','Image Upload successfully');
      }

    }

What is the size of column of int(11) in mysql in bytes?

INT(x) will make difference only in term of display, that is to show the number in x digits, and not restricted to 11. You pair it using ZEROFILL, which will prepend the zeros until it matches your length.

So, for any number of x in INT(x)

  • if the stored value has less digits than x, ZEROFILL will prepend zeros.

INT(5) ZEROFILL with the stored value of 32 will show 00032
INT(5) with the stored value of 32 will show 32
INT with the stored value of 32 will show 32

  • if the stored value has more digits than x, it will be shown as it is.

INT(3) ZEROFILL with the stored value of 250000 will show 250000
INT(3) with the stored value of 250000 will show 250000
INT with the stored value of 250000 will show 250000

The actual value stored in database is not affected, the size is still the same, and any calculation will behave normally.

This also applies to BIGINT, MEDIUMINT, SMALLINT, and TINYINT.

Invoke native date picker from web-app on iOS/Android

My answer is over-simplistic. If you like to write simple code that works cross-platform, then use the window.prompt method to ask the user for a date. Obviously you need to validate with a regex and then create the date object.

function onInputClick(e){
var r = window.prompt("Give me a date (YYYY-MM-DD)", "2014-01-01");
if(/[\d]{4}-[\d]{1,2}-[\d]{1,2}/.test(r)){
    //date ok
    e.value=r;
    var split=e.value.split("-");
    var date=new Date(parseInt(split[0]),parseInt(split[1])-1,parseInt(split[2]));
}else{
    alert("Invalid date. Try again.");
}
}

In you HTML:

<input type="text" onclick="onInputClick(this)" value="2014-01-01">

How to determine the screen width in terms of dp or dip at runtime in Android?

Get Screen Width and Height in terms of DP with some good decoration:

Step 1: Create interface

public interface ScreenInterface {

   float getWidth();

   float getHeight();

}

Step 2: Create implementer class

public class Screen implements ScreenInterface {
    private Activity activity;

    public Screen(Activity activity) {
        this.activity = activity;
    }

    private DisplayMetrics getScreenDimension(Activity activity) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics;
    }

    private float getScreenDensity(Activity activity) {
        return activity.getResources().getDisplayMetrics().density;
    }

    @Override
    public float getWidth() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.widthPixels / getScreenDensity(activity);
    }

    @Override
    public float getHeight() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.heightPixels / getScreenDensity(activity);
    }
} 

Step 3: Get width and height in activity:

Screen screen = new Screen(this); // Setting Screen
screen.getWidth();
screen.getHeight();

Add the loading screen in starting of the android application

If the application is not doing anything in that 10 seconds, this will form a bad design only to make the user wait for 10 seconds doing nothing.

If there is something going on in that, or if you wish to implement 10 seconds delay splash screen,Here is the Code :

ProgressDialog pd;
pd = ProgressDialog.show(this,"Please Wait...", "Loading Application..", false, true);
pd.setCanceledOnTouchOutside(false);
Thread t = new Thread()
{ 
      @Override
      public void run()
      {
                try
                {
                    sleep(10000)  //Delay of 10 seconds
                } 
        catch (Exception e) {}
        handler.sendEmptyMessage(0);
        }
} ;
t.start();

//Handles the thread result of the Backup being executed.
private Handler handler = new Handler()
{
    @Override
    public void handleMessage(Message msg) 
    {
        pd.dismiss();
        //Start the Next Activity here...

    }
};

How does a ArrayList's contains() method evaluate objects?

The ArrayList uses the equals method implemented in the class (your case Thing class) to do the equals comparison.

What does the "undefined reference to varName" in C mean?

You need to link both a.o and b.o:

gcc -o program a.c b.c

If you have a main() in each file, you cannot link them together.

However, your a.c file contains a reference to doSomething() and expects to be linked with a source file that defines doSomething() and does not define any function that is defined in a.c (such as main()).

You cannot call a function in Process B from Process A. You cannot send a signal to a function; you send signals to processes, using the kill() system call.

The signal() function specifies which function in your current process (program) is going to handle the signal when your process receives the signal.

You have some serious work to do understanding how this is going to work - how ProgramA is going to know which process ID to send the signal to. The code in b.c is going to need to call signal() with dosomething as the signal handler. The code in a.c is simply going to send the signal to the other process.

Read from file in eclipse

You are searching/reading the file "fiel.txt" in the execution directory (where the class are stored, i think).

If you whish to read the file in a given directory, you have to says so :

File file = new File(System.getProperty("user.dir")+"/"+"file.txt");

You could also give the directory with a relative path, eg "./images/photo.gif) for a subdirecory for example.

Note that there is also a property for the separator (hard-coded to "/" in my exemple)

regards Guillaume

Convert long/lat to pixel x/y on a given picture

Struggled with this - Have both openstreet map and google street map and wanted to project an external graphic image

var map = new OpenLayers.Map({
            div:"map-id",
            allOverlays: true
    });
    var osm = new OpenLayers.Layer.OSM("OpenStreeMao");
    var gmap = new OpenLayers.Layer.Google("Google Streets", {visibility: false});

    map.addLayers([osm,gmap]);

    var vectorLayer = new OpenLayers.Layer.Vector("IconLayer");


    var lonlatObject = new OpenLayers.LonLat(24.938622,60.170421).transform(
            new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()
    );
    console.log(lonlatObject);

    var point = new OpenLayers.Geometry.Point(lonlatObject.lon, lonlatObject.lat);
    console.log(point);

    var point2 = new OpenLayers.Geometry.Point(lonlatObject.x, lonlatObject.y);
    console.log(point2);

    var feature = new OpenLayers.Feature.Vector(point, null, {
        externalGraphic:  "http://cdn1.iconfinder.com/data/icons/SUPERVISTA/networking/png/72/antenna.png",
        graphicWidth: 72,
        graphicHeight: 72,
        fillOpacity: 1
    });


    vectorLayer.addFeatures(feature);

    map.addLayer(vectorLayer);


    map.setCenter(
            new OpenLayers.LonLat(24.938622,60.170421).transform(
            new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()
            ),
            12);

     map.addControl(new OpenLayers.Control.LayerSwitcher());

http://jsfiddle.net/alexcpn/N9dLN/8/

How to remove special characters from a string?

Try replaceAll() method of the String class.

BTW here is the method, return type and parameters.

public String replaceAll(String regex,
                         String replacement)

Example:

String str = "Hello +-^ my + - friends ^ ^^-- ^^^ +!";
str = str.replaceAll("[-+^]*", "");

It should remove all the {'^', '+', '-'} chars that you wanted to remove!

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

Make a copy of existing list and iterate over new copy.

for (String str : new ArrayList<String>(listOfStr))     
{
    listOfStr.remove(/* object reference or index */);
}

Twitter Bootstrap date picker

Some people posted the link to this bootstrap-datepicker.js implementation. I used that one in the following way, it works with Bootstrap 3.

This is the markup I used:

<div class="input-group date col-md-3" data-date-format="dd-mm-yyyy" data-date="01-01-2014">                        
    <input id="txtHomeLoanStartDate" class="form-control" type="text" readonly="" value="01-01-2014" size="14" />
    <span class="input-group-addon add-on">
        <span class="glyphicon glyphicon-calendar"</span>
    </span>
</div>

This is the javascript:

$('.date').datepicker();

I also included the javascript file downloaded from the link above, along with it's css file, and of course, you should remove any bootstrap grid classes like the col-md-3 to suit your needs.

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

For those who are looking for an explanation about jest --runInBand, you can go to the documentation.

Running Puppeteer in CI environments

GitHub - smooth-code/jest-puppeteer: Run your tests using Jest & Puppeteer

varbinary to string on SQL Server

Actually the best answer is

SELECT CONVERT(VARCHAR(1000), varbinary_value, 1);

using "2" cuts off the "0x" at the start of the varbinary.

CXF: No message body writer found for class - automatically mapping non-simple resources

None of the above changes worked for me. Please see my worked configuration below:

Dependencies:

            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-frontend-jaxrs</artifactId>
                <version>3.3.2</version>
            </dependency>
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-rs-extension-providers</artifactId>
                <version>3.3.2</version>
            </dependency>
            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-jaxrs</artifactId>
                <version>1.9.13</version>
            </dependency>
            <dependency>
                <groupId>org.codehaus.jettison</groupId>
                <artifactId>jettison</artifactId>
                <version>1.4.0</version>
            </dependency>

web.xml:

     <servlet>
        <servlet-name>cfxServlet</servlet-name>
        <servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.MyApplication</param-value>
        </init-param>
        <init-param>
            <param-name>jaxrs.providers</param-name>
            <param-value>org.codehaus.jackson.jaxrs.JacksonJsonProvider</param-value>
        </init-param>
        <init-param>
            <param-name>jaxrs.extensions</param-name>
            <param-value> 
            json=application/json 
        </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>cfxServlet</servlet-name>
        <url-pattern>/v1/*</url-pattern>
    </servlet-mapping>

Enjoy coding .. :)

How to reload current page without losing any form data?

You can use localStorage ( http://www.w3schools.com/html/html5_webstorage.asp ) to save values before refreshing the page.

How do I crop an image in Java?

I'm giving this example because this actually work for my use case.

I was trying to use the AWS Rekognition API. The API returns a BoundingBox object:

BoundingBox boundingBox = faceDetail.getBoundingBox();

The code below uses it to crop the image:

import com.amazonaws.services.rekognition.model.BoundingBox;

private BufferedImage cropImage(BufferedImage image, BoundingBox box) {
        Rectangle goal = new Rectangle(Math.round(box.getLeft()* image.getWidth()),Math.round(box.getTop()* image.getHeight()),Math.round(box.getWidth() * image.getWidth()), Math.round(box.getHeight() * image.getHeight()));

        Rectangle clip = goal.intersection(new Rectangle(image.getWidth(), image.getHeight()));

        BufferedImage clippedImg = image.getSubimage(clip.x, clip.y , clip.width, clip.height);

        return clippedImg;
    }

In Chrome 55, prevent showing Download button for HTML 5 video

Google has added a new feature since the last answer was posted here. You can now add the controlList attribute as shown here:

<video width="512" height="380" controls controlsList="nodownload">
    <source data-src="mov_bbb.ogg" type="video/mp4">
</video>

You can find all options of the controllist attribute here:

https://developers.google.com/web/updates/2017/03/chrome-58-media-updates#controlslist

How to initialize an array in angular2 and typescript

you can create and initialize array of any object like this.

hero:Hero[]=[];

How do I dynamically assign properties to an object in TypeScript?

Or all in one go:

  var obj:any = {}
  obj.prop = 5;

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

Taken from C# 3.0 Nutshell book, by Joseph Albahari

Threading in C# - Free E-Book

A ManualResetEvent is a variation on AutoResetEvent. It differs in that it doesn't automatically reset after a thread is let through on a WaitOne call, and so functions like a gate: calling Set opens the gate, allowing any number of threads that WaitOne at the gate through; calling Reset closes the gate, causing, potentially, a queue of waiters to accumulate until its next opened.

One could simulate this functionality with a boolean "gateOpen" field (declared with the volatile keyword) in combination with "spin-sleeping" – repeatedly checking the flag, and then sleeping for a short period of time.

ManualResetEvents are sometimes used to signal that a particular operation is complete, or that a thread's completed initialization and is ready to perform work.

How to read a single character at a time from a file in Python?

I like the accepted answer: it is straightforward and will get the job done. I would also like to offer an alternative implementation:

def chunks(filename, buffer_size=4096):
    """Reads `filename` in chunks of `buffer_size` bytes and yields each chunk
    until no more characters can be read; the last chunk will most likely have
    less than `buffer_size` bytes.

    :param str filename: Path to the file
    :param int buffer_size: Buffer size, in bytes (default is 4096)
    :return: Yields chunks of `buffer_size` size until exhausting the file
    :rtype: str

    """
    with open(filename, "rb") as fp:
        chunk = fp.read(buffer_size)
        while chunk:
            yield chunk
            chunk = fp.read(buffer_size)

def chars(filename, buffersize=4096):
    """Yields the contents of file `filename` character-by-character. Warning:
    will only work for encodings where one character is encoded as one byte.

    :param str filename: Path to the file
    :param int buffer_size: Buffer size for the underlying chunks,
    in bytes (default is 4096)
    :return: Yields the contents of `filename` character-by-character.
    :rtype: char

    """
    for chunk in chunks(filename, buffersize):
        for char in chunk:
            yield char

def main(buffersize, filenames):
    """Reads several files character by character and redirects their contents
    to `/dev/null`.

    """
    for filename in filenames:
        with open("/dev/null", "wb") as fp:
            for char in chars(filename, buffersize):
                fp.write(char)

if __name__ == "__main__":
    # Try reading several files varying the buffer size
    import sys
    buffersize = int(sys.argv[1])
    filenames  = sys.argv[2:]
    sys.exit(main(buffersize, filenames))

The code I suggest is essentially the same idea as your accepted answer: read a given number of bytes from the file. The difference is that it first reads a good chunk of data (4006 is a good default for X86, but you may want to try 1024, or 8192; any multiple of your page size), and then it yields the characters in that chunk one by one.

The code I present may be faster for larger files. Take, for example, the entire text of War and Peace, by Tolstoy. These are my timing results (Mac Book Pro using OS X 10.7.4; so.py is the name I gave to the code I pasted):

$ time python so.py 1 2600.txt.utf-8
python so.py 1 2600.txt.utf-8  3.79s user 0.01s system 99% cpu 3.808 total
$ time python so.py 4096 2600.txt.utf-8
python so.py 4096 2600.txt.utf-8  1.31s user 0.01s system 99% cpu 1.318 total

Now: do not take the buffer size at 4096 as a universal truth; look at the results I get for different sizes (buffer size (bytes) vs wall time (sec)):

   2 2.726 
   4 1.948 
   8 1.693 
  16 1.534 
  32 1.525 
  64 1.398 
 128 1.432 
 256 1.377 
 512 1.347 
1024 1.442 
2048 1.316 
4096 1.318 

As you can see, you can start seeing gains earlier on (and my timings are likely very inaccurate); the buffer size is a trade-off between performance and memory. The default of 4096 is just a reasonable choice but, as always, measure first.

ADB Shell Input Events

If you want to send a text to specific device when multiple devices connected. First look for the attached devices using adb devices

adb devices
List of devices attached
3004e25a57192200        device
31002d9e592b7300        device

then get your specific device id and try the following

adb -s 31002d9e592b7300 shell input text 'your text'

How to change the icon of an Android app in Eclipse?

Rob R.'s answer was definitely the way to go. I tried copying the ic_launcher.png files from another project and Eclipse still wouldn't read them. Going through the manifest is much quicker and easier.

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

It takes up to 24 hours before its available in each and every (country wise) app store. If you have waited more than that, and still have problems, contact Apple.

Sending emails in Node.js?

Nodemailer Module is the simplest way to send emails in node.js.

Try this sample example form: http://www.tutorialindustry.com/nodejs-mail-tutorial-using-nodemailer-module

Additional Info: http://www.nodemailer.com/

Getting value of select (dropdown) before change

This is an improvement on @thisisboris answer. It adds a current value to data, so the code can control when a variable set to the current value is changed.

(function()
{
    // Initialize the previous-attribute
    var selects = $( 'select' );
    $.each( selects, function( index, myValue ) {
        $( myValue ).data( 'mgc-previous', myValue.value );
        $( myValue ).data( 'mgc-current', myValue.value );  
    });

    // Listen on the body for changes to selects
    $('body').on('change', 'select',
        function()
        {
            alert('I am a body alert');
            $(this).data('mgc-previous', $(this).data( 'mgc-current' ) );
            $(this).data('mgc-current', $(this).val() );
        }
    );
})();

How to secure an ASP.NET Web API

Update:

I have added this link to my other answer how to use JWT authentication for ASP.NET Web API here for anyone interested in JWT.


We have managed to apply HMAC authentication to secure Web API, and it worked okay. HMAC authentication uses a secret key for each consumer which both consumer and server both know to hmac hash a message, HMAC256 should be used. Most of the cases, hashed password of the consumer is used as a secret key.

The message normally is built from data in the HTTP request, or even customized data which is added to HTTP header, the message might include:

  1. Timestamp: time that request is sent (UTC or GMT)
  2. HTTP verb: GET, POST, PUT, DELETE.
  3. post data and query string,
  4. URL

Under the hood, HMAC authentication would be:

Consumer sends a HTTP request to web server, after building the signature (output of hmac hash), the template of HTTP request:

User-Agent: {agent}   
Host: {host}   
Timestamp: {timestamp}
Authentication: {username}:{signature}

Example for GET request:

GET /webapi.hmac/api/values

User-Agent: Fiddler    
Host: localhost    
Timestamp: Thursday, August 02, 2012 3:30:32 PM 
Authentication: cuongle:LohrhqqoDy6PhLrHAXi7dUVACyJZilQtlDzNbLqzXlw=

The message to hash to get signature:

GET\n
Thursday, August 02, 2012 3:30:32 PM\n
/webapi.hmac/api/values\n

Example for POST request with query string (signature below is not correct, just an example)

POST /webapi.hmac/api/values?key2=value2

User-Agent: Fiddler    
Host: localhost    
Content-Type: application/x-www-form-urlencoded
Timestamp: Thursday, August 02, 2012 3:30:32 PM 
Authentication: cuongle:LohrhqqoDy6PhLrHAXi7dUVACyJZilQtlDzNbLqzXlw=

key1=value1&key3=value3

The message to hash to get signature

GET\n
Thursday, August 02, 2012 3:30:32 PM\n
/webapi.hmac/api/values\n
key1=value1&key2=value2&key3=value3

Please note that form data and query string should be in order, so the code on the server get query string and form data to build the correct message.

When HTTP request comes to the server, an authentication action filter is implemented to parse the request to get information: HTTP verb, timestamp, uri, form data and query string, then based on these to build signature (use hmac hash) with the secret key (hashed password) on the server.

The secret key is got from the database with the username on the request.

Then server code compares the signature on the request with the signature built; if equal, authentication is passed, otherwise, it failed.

The code to build signature:

private static string ComputeHash(string hashedPassword, string message)
{
    var key = Encoding.UTF8.GetBytes(hashedPassword.ToUpper());
    string hashString;

    using (var hmac = new HMACSHA256(key))
    {
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
        hashString = Convert.ToBase64String(hash);
    }

    return hashString;
}

So, how to prevent replay attack?

Add constraint for the timestamp, something like:

servertime - X minutes|seconds  <= timestamp <= servertime + X minutes|seconds 

(servertime: time of request coming to server)

And, cache the signature of the request in memory (use MemoryCache, should keep in the limit of time). If the next request comes with the same signature with the previous request, it will be rejected.

The demo code is put as here: https://github.com/cuongle/Hmac.WebApi

What's HTML character code 8203?

If you want to search for these invisible characters in your editor and make them visible, you can use a Regular Expression searching for non-ascii characters. Try searching for [^\x00-\x7F]. Tested in IntelliJ IDEA.

How to change background color of cell in table using java script

<table border="1" cellspacing="0" cellpadding= "20">
    <tr>
    <td id="id1" ></td>
    </tr>
</table>
<script>
    document.getElementById('id1').style.backgroundColor='#003F87';
</script>

Put id for cell and then change background of the cell.

How do I convert two lists into a dictionary?

>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> dict(zip(keys, values))
{'food': 'spam', 'age': 42, 'name': 'Monty'}

Center content vertically on Vuetify

Here's another approach using Vuetify grid system available in Vuetify 2.x: https://vuetifyjs.com/en/components/grids

<v-container>
    <v-row align="center">
        Hello I am center to vertically using "grid".
    </v-row>
</v-container>

C++ array initialization

Yes, I believe it should work and it can also be applied to other data types.

For class arrays though, if there are fewer items in the initializer list than elements in the array, the default constructor is used for the remaining elements. If no default constructor is defined for the class, the initializer list must be complete — that is, there must be one initializer for each element in the array.

Composer could not find a composer.json

You could try updating the composer:

sudo composer self-update

If that doest works remove composer files & then use: SSH into terminal & type :

$ cd ~
$ sudo curl -sS https://getcomposer.org/installer | sudo php
$ sudo mv composer.phar /usr/local/bin/composer
$ sudo ln -s /usr/local/bin/composer /usr/bin/composer

If you face an error that says: PHP Fatal error: Uncaught exception 'ErrorException' with message 'proc_open(): fork failed - Cannot allocate memory' in phar

/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1

To install package use:

composer global require "package-name"

How to force addition instead of concatenation in javascript

Should also be able to do this:

total += eval(myInt1) + eval(myInt2) + eval(myInt3);

This helped me in a different, but similar, situation.

Current time formatting with Javascript

_x000D_
_x000D_
let date = new Date();_x000D_
let time = date.format("hh:ss")
_x000D_
_x000D_
_x000D_

Unable to begin a distributed transaction

I was able to resolve this issue (as others mentioned in comments) by disabling "Enable Promotion of Distributed Transactions for RPC" (i.e. setting it to False):

enter image description here

As requested by @WonderWorker, you can do this via SQL script:

EXEC master.dbo.sp_serveroption
     @server = N'[mylinkedserver]',
     @optname = N'remote proc transaction promotion',
     @optvalue = N'false'

How to change Windows 10 interface language on Single Language version

You can download language pack and use "Install or Uninstall display languages" wizard. To do this:

  • Press Win+R, paste lpksetup and press Enter
  • Wizard will appear on the screen
  • Click the Install display languages button
  • In the next page of the wizard, click Browse and pick the *.cab file of the MUI language you downloaded
  • Click the Next button to install language

Store text file content line by line into array

You can use this full code for your problem. For more details you can check it on appucoder.com

class FileDemoTwo{
    public static void main(String args[])throws Exception{
        FileDemoTwo ob = new FileDemoTwo();
        BufferedReader in = new BufferedReader(new FileReader("read.txt"));
        String str;
        List<String> list = new ArrayList<String>();
        while((str =in.readLine()) != null ){
            list.add(str);
        }
        String[] stringArr = list.toArray(new String[0]);
        System.out.println(" "+Arrays.toString(stringArr)); 
    }

}

Get environment value in controller

It Doesn't work in Laravel 5.3+ if you want to try to access the value from the controller like below. It always returns null

<?php

    $value = env('MY_VALUE', 'default_value');

SOLUTION: Rather, you need to create a file in the configuration folder, say values.php and then write the code like below

File values.php

<?php

    return [

        'myvalue' => env('MY_VALUE',null),

        // Add other values as you wish

Then access the value in your controller with the following code

<?php

    $value = \Config::get('values.myvalue')

Where "values" is the filename followed by the key "myvalue".

Xcode is not currently available from the Software Update server

This error can occur if you are using a software update server which doesn't host the required package.

You can check this by running

defaults read /Library/Preferences/com.apple.SoftwareUpdate

and seeing if you have an entry called CatalogURL or AppleCatalogURL

You can point back at the Apple software update server by either removing this entry or using the command

sudo softwareupdate --clear-catalog

And then run the command line tools install again.

How to detect a loop in a linked list?

This approach has space overhead, but a simpler implementation:

Loop can be identified by storing nodes in a Map. And before putting the node; check if node already exists. If node already exists in the map then it means that Linked List has loop.

public boolean loopDetector(Node<E> first) {  
       Node<E> t = first;  
       Map<Node<E>, Node<E>> map = new IdentityHashMap<Node<E>, Node<E>>();  
       while (t != null) {  
            if (map.containsKey(t)) {  
                 System.out.println(" duplicate Node is --" + t  
                           + " having value :" + t.data);  

                 return true;  
            } else {  
                 map.put(t, t);  
            }  
            t = t.next;  
       }  
       return false;  
  }  

How to make sure you don't get WCF Faulted state exception?


Update:

This linked answer describes a cleaner, simpler way of doing the same thing with C# syntax.


Original post

This is Microsoft's recommended way to handle WCF client calls:

For more detail see: Expected Exceptions

try
{
    ...
    double result = client.Add(value1, value2);
    ...
    client.Close();
}
catch (TimeoutException exception)
{
    Console.WriteLine("Got {0}", exception.GetType());
    client.Abort();
}
catch (CommunicationException exception)
{
    Console.WriteLine("Got {0}", exception.GetType());
    client.Abort();
}

Additional information

So many people seem to be asking this question on WCF that Microsoft even created a dedicated sample to demonstrate how to handle exceptions:

c:\WF_WCF_Samples\WCF\Basic\Client\ExpectedExceptions\CS\client

Download the sample: C# or VB

Considering that there are so many issues involving the using statement, (heated?) Internal discussions and threads on this issue, I'm not going to waste my time trying to become a code cowboy and find a cleaner way. I'll just suck it up, and implement WCF clients this verbose (yet trusted) way for my server applications.

How to validate phone number in laravel 5.2?

I used the code below, and it works

'PHONE' => 'required|regex:/(0)[0-9]/|not_regex:/[a-z]/|min:9',

Import Error: No module named numpy

Support for Python 3 was added in NumPy version 1.5.0, so to begin with, you must download/install a newer version of NumPy.

getMinutes() 0-9 - How to display two digit numbers?

I suggest:

var minutes = data.getMinutes();
minutes = minutes > 9 ? minutes : '0' + minutes;

it is one function call fewer. It is always good to think about performance. It is short as well;

Computing cross-correlation function?

I just finished writing my own optimised implementation of normalized cross-correlation for N-dimensional arrays. You can get it from here.

It will calculate cross-correlation either directly, using scipy.ndimage.correlate, or in the frequency domain, using scipy.fftpack.fftn/ifftn depending on whichever will be quickest.

How to generate a number of most distinctive colors in R?

Not an answer to OP's question but it's worth mentioning that there is the viridis package which has good color palettes for sequential data. They are perceptually uniform, colorblind safe and printer-friendly.

To get the palette, simply install the package and use the function viridis_pal(). There are four options "A", "B", "C" and "D" to choose

install.packages("viridis")
library(viridis)
viridis_pal(option = "D")(n)  # n = number of colors seeked

enter image description here

enter image description here

enter image description here

There is also an excellent talk explaining the complexity of good colormaps on YouTube:

A Better Default Colormap for Matplotlib | SciPy 2015 | Nathaniel Smith and Stéfan van der Walt

Pandas - replacing column values

You can also try using apply with get method of dictionary, seems to be little faster than replace:

data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)

Testing with timeit:

%%timeit
data['sex'].replace([0,1],['Female','Male'],inplace=True)

Result:

The slowest run took 5.83 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 510 µs per loop

Using apply:

%%timeit
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)

Result:

The slowest run took 5.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 331 µs per loop

Note: apply with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.

how to count the total number of lines in a text file using python

For the people saying to use with open ("filename.txt","r") as f you can do anyname = open("filename.txt","r")

def main():

    file = open("infile.txt",'r')
    count = 0
    for line in file:
            count+=1

    print (count)

main ()

How to enable C++17 compiling in Visual Studio?

Visual studio 2019 version:

The drop down menu was moved to:

  • Right click on project (not solution)
  • Properties (or Alt + Enter)
  • From the left menu select Configuration Properties
  • General
  • In the middle there is an option called "C++ Language Standard"
  • Next to it is the drop down menu
  • Here you can select Default, ISO C++ 14, 17 or latest

Android : How to read file in bytes?

here it's a simple:

File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
    BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
    buf.read(bytes, 0, bytes.length);
    buf.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Add permission in manifest.xml:

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

IIS7 Cache-Control

there is a easy way: 1. using website's web.config 2. in "staticContent" section remove specific fileExtension and add mimeMap 3. add "clientCache"

<configuration>
  <system.webServer>
    <urlCompression doStaticCompression="true" doDynamicCompression="true" />
    <staticContent>
      <remove fileExtension=".ipa" />
      <remove fileExtension=".apk" />
      <mimeMap fileExtension=".ipa" mimeType="application/iphone" />
      <mimeMap fileExtension=".apk" mimeType="application/vnd.android.package-archive" />
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="777.00:00:00" />
    </staticContent>
  </system.webServer>
</configuration>

Maximum packet size for a TCP connection

The absolute limitation on TCP packet size is 64K (65535 bytes), but in practicality this is far larger than the size of any packet you will see, because the lower layers (e.g. ethernet) have lower packet sizes.

The MTU (Maximum Transmission Unit) for Ethernet, for instance, is 1500 bytes. Some types of networks (like Token Ring) have larger MTUs, and some types have smaller MTUs, but the values are fixed for each physical technology.

IIS URL Rewrite and Web.config

Just tried this rule, and it worked with GoDaddy hosting since they've already have the Microsoft URL Rewriting module installed for every IIS 7 account.

<rewrite>
  <rules>
    <rule name="enquiry" stopProcessing="true">
      <match url="^enquiry$" />
      <action type="Rewrite" url="/Enquiry.aspx" />
    </rule>
  </rules>
</rewrite>

How to insert multiple rows from array using CodeIgniter framework?

You can do it with several ways in codeigniter e.g.

First By loop

foreach($myarray as $row)
{
   $data = array("first"=>$row->first,"second"=>$row->sec);
   $this->db->insert('table_name',$data);
}

Second -- By insert batch

$data = array(
       array(
          'first' => $myarray[0]['first'] ,
          'second' => $myarray[0]['sec'],
        ),
       array(
          'first' => $myarray[1]['first'] ,
          'second' => $myarray[1]['sec'],
        ),
    );

    $this->db->insert_batch('table_name', $data);

Third way -- By multiple value pass

$sql = array(); 
foreach( $myarray as $row ) {
    $sql[] = '("'.mysql_real_escape_string($row['first']).'", '.$row['sec'].')';
}
mysql_query('INSERT INTO table (first, second) VALUES '.implode(',', $sql));

C# Convert a Base64 -> byte[]

You have to use Convert.FromBase64String to turn a Base64 encoded string into a byte[].

Lombok added but getters and setters not recognized in Intellij IDEA

Goto Setting->Plugin->Search for "Lombok Plugin" -> It will show results. Install Lombok Plugin from the list and Restart Intellij

Maven: add a dependency to a jar by relative path

Basically, add this to the pom.xml:

...

<repositories>
   <repository>
       <id>lib_id</id>
       <url>file://${project.basedir}/lib</url>
   </repository>
</repositories>

...

<dependencies>
  ...
  <dependency>
      <groupId>com.mylibrary</groupId>
      <artifactId>mylibraryname</artifactId>
      <version>1.0.0</version>
  </dependency>
  ...
</dependencies>

How can I find out if an .EXE has Command-Line Options?

Sysinternals has another tool you could use, Strings.exe

Example:

strings.exe c:\windows\system32\wuauclt.exe > %temp%\wuauclt_strings.txt && %temp%\wuauclt_strings.txt

Handling back button in Android Navigation Component

A little late to the party, but with the latest release of Navigation Component 1.0.0-alpha09, now we have an AppBarConfiguration.OnNavigateUpListener.

Refer to these links for more information: https://developer.android.com/reference/androidx/navigation/ui/AppBarConfiguration.OnNavigateUpListener https://developer.android.com/jetpack/docs/release-notes

Comparing two maps

As long as you override equals() on each key and value contained in the map, then m1.equals(m2) should be reliable to check for maps equality.

The same result can be obtained also by comparing toString() of each map as you suggested, but using equals() is a more intuitive approach.

May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays.equals(). More details about this see here.

Concatenate two slices in Go

append([]int{1,2}, []int{3,4}...) will work. Passing arguments to ... parameters.

If f is variadic with a final parameter p of type ...T, then within f the type of p is equivalent to type []T.

If f is invoked with no actual arguments for p, the value passed to p is nil.

Otherwise, the value passed is a new slice of type []T with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T. The length and capacity of the slice is therefore the number of arguments bound to p and may differ for each call site.

Given the function and calls

func Greeting(prefix string, who ...string)
Greeting("nobody")
Greeting("hello:", "Joe", "Anna", "Eileen")

How do I drop table variables in SQL-Server? Should I even do this?

Here is a solution

Declare @tablename varchar(20)
DECLARE @SQL NVARCHAR(MAX)

SET @tablename = '_RJ_TEMPOV4'
SET @SQL = 'DROP TABLE dbo.' + QUOTENAME(@tablename) + '';

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@tablename) AND type in (N'U'))
    EXEC sp_executesql @SQL;

Works fine on SQL Server 2014 Christophe

Moving all files from one directory to another using Python

def copy_myfile_dirOne_to_dirSec(src, dest, ext): 

    if not os.path.exists(dest):    # if dest dir is not there then we create here
        os.makedirs(dest);
        
    for item in os.listdir(src):
        if item.endswith(ext):
            s = os.path.join(src, item);
            fd = open(s, 'r');
            data = fd.read();
            fd.close();
            
            fname = str(item); #just taking file name to make this name file is destination dir     
            
            d = os.path.join(dest, fname);
            fd = open(d, 'w');
            fd.write(data);
            fd.close();
    
    print("Files are copyed successfully")

How to use font-awesome icons from node-modules

You will need to copy the files as part of your build process. For example, you can use a npm postinstall script to copy the files to the correct directory:

"postinstall": "cp -R node_modules/font-awesome/fonts ./public/"

For some build tools, there are preexisting font-awesome packages. For example, webpack has font-awesome-webpack which lets you simple require('font-awesome-webpack').

How to set cache: false in jQuery.get call

Set cache: false in jQuery.get call using Below Method

use new Date().getTime(), which will avoid collisions unless you have multiple requests happening within the same millisecond.

Or

The following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.)

$.ajaxSetup({ cache: false });

How can I delete multiple lines in vi?

Commands listed for use in normal mode (prefix with : for command mode).
Tested in Vim.

By line amount:

  • numdd - will delete num lines DOWN starting count from current cursor position (e.g. 5dd will delete current line and 4 lines under it => deletes current line and (num-1) lines under it)
  • numdk - will delete num lines UP from current line and current line itself (e.g. 3dk will delete current line and 3 lines above it => deletes current line and num lines above it)

By line numbers:

  • dnumG - will delete lines from current line (inclusive) UP to line number num (inclusive) (e.g. if cursor is currently on line 5 d2G will delete lines 2-5 inclusive)
  • dnumgg - will delete lines from current line (inclusive) DOWN to the line number num (inclusive) (e.g. if cursor is currently on line 2 d6gg will delete lines 2-6 inclusive)
  • (command mode only) :num1,num2d - will delete lines line number num1 (inclusive) DOWN to the line number num2 (inclusive). Note: if num1 is greater than num2 — vim will react with Backwards range given, OK to swap (y/n)?

How SQL query result insert in temp table?

In MySQL:

create table temp as select * from original_table

Why do we need boxing and unboxing in C#?

Boxing is the conversion of a value to a reference type with the data at some offset in an object on the heap.

As for what boxing actually does. Here are some examples

Mono C++

void* mono_object_unbox (MonoObject *obj)
 {    
MONO_EXTERNAL_ONLY_GC_UNSAFE (void*, mono_object_unbox_internal (obj));
 }

#define MONO_EXTERNAL_ONLY_GC_UNSAFE(t, expr) \
    t result;       \
    MONO_ENTER_GC_UNSAFE;   \
    result = expr;      \
    MONO_EXIT_GC_UNSAFE;    \
    return result;

static inline gpointer
mono_object_unbox_internal (MonoObject *obj)
{
    /* add assert for valuetypes? */
    g_assert (m_class_is_valuetype (mono_object_class (obj)));
    return mono_object_get_data (obj);
}

static inline gpointer
mono_object_get_data (MonoObject *o)
{
    return (guint8*)o + MONO_ABI_SIZEOF (MonoObject);
}

#define MONO_ABI_SIZEOF(type) (MONO_STRUCT_SIZE (type))
#define MONO_STRUCT_SIZE(struct) MONO_SIZEOF_ ## struct
#define MONO_SIZEOF_MonoObject (2 * MONO_SIZEOF_gpointer)

typedef struct {
    MonoVTable *vtable;
    MonoThreadsSync *synchronisation;
} MonoObject;

Unboxing an object in Mono is a process of casting a pointer at an offset of 2 gpointers in the object (e.g. 16 bytes). A gpointer is a void*. This makes sense when looking at the definition of MonoObject as it's clearly just a header for the data.

C++

To box a value in C++ you could do something like:

#include <iostream>
#define Object void*

template<class T> Object box(T j){
  return new T(j);
}

template<class T> T unbox(Object j){
  T temp = *(T*)j;
  delete j;
  return temp;
}

int main() {
  int j=2;
  Object o = box(j);
  int k = unbox<int>(o);
  std::cout << k;
}

How to set the allowed url length for a nginx request (error code: 414, uri too large)

For anyone having issues with this on https://forge.laravel.com, I managed to get this to work using a compilation of SO answers;

You will need the sudo password.

sudo nano /etc/nginx/conf.d/uploads.conf

Replace contents with the following;

fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;

client_max_body_size 24M;
client_body_buffer_size 128k;

client_header_buffer_size 5120k;
large_client_header_buffers 16 5120k;

How to force a line break on a Javascript concatenated string?

You need to use \n inside quotes.

document.getElementById("address_box").value = (title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4)

\n is called a EOL or line-break, \n is a common EOL marker and is commonly refereed to as LF or line-feed, it is a special ASCII character

C dynamically growing array

These posts apparently are in the wrong order! This is #1 in a series of 3 posts. Sorry.

In attempting to use Lie Ryan's code, I had problems retrieving stored information. The vector's elements are not stored contiguously,as you can see by "cheating" a bit and storing the pointer to each element's address (which of course defeats the purpose of the dynamic array concept) and examining them.

With a bit of tinkering, via:

ss_vector* vector; // pull this out to be a global vector

// Then add the following to attempt to recover stored values.

int return_id_value(int i,apple* aa) // given ptr to component,return data item
{   printf("showing apple[%i].id = %i and  other_id=%i\n",i,aa->id,aa->other_id);
    return(aa->id);
}

int Test(void)  // Used to be "main" in the example
{   apple* aa[10]; // stored array element addresses
    vector = ss_init_vector(sizeof(apple));
    // inserting some items
    for (int i = 0; i < 10; i++)
    {   aa[i]=init_apple(i);
        printf("apple id=%i and  other_id=%i\n",aa[i]->id,aa[i]->other_id);
        ss_vector_append(vector, aa[i]);
     }   
 // report the number of components
 printf("nmbr of components in vector = %i\n",(int)vector->size);
 printf(".*.*array access.*.component[5] = %i\n",return_id_value(5,aa[5]));
 printf("components of size %i\n",(int)sizeof(apple));
 printf("\n....pointer initial access...component[0] = %i\n",return_id_value(0,(apple *)&vector[0]));
 //.............etc..., followed by
 for (int i = 0; i < 10; i++)
 {   printf("apple[%i].id = %i at address %i, delta=%i\n",i,    return_id_value(i,aa[i]) ,(int)aa[i],(int)(aa[i]-aa[i+1]));
 }   
// don't forget to free it
ss_vector_free(vector);
return 0;
}

It's possible to access each array element without problems, as long as you know its address, so I guess I'll try adding a "next" element and use this as a linked list. Surely there are better options, though. Please advise.

How to add a ListView to a Column in Flutter?

As have been mentioned by others above,Wrap listview with Expanded is the solution.

But when you deal with nested Columns you will also need to limit your ListView to a certain height (faced this problem a lot).

If anyone have another solution please, mention in comment or add answer.

Example

  SingleChildScrollView(
   child: Column(
     children: <Widget>[
       Image(image: ),//<< any widgets added
       SizedBox(),
       Column(
         children: <Widget>[
           Text('header'),  //<< any widgets added
            Expanded(child: 
            ListView.builder(
              //here your code
               scrollDirection: Axis.horizontal,
        itemCount: items.length,
        itemBuilder: (BuildContext context, int index) {
            return Container();
                   } 
         )
        ),
        Divider(),//<< any widgets added
         ],
       ),

     ],
   ), 
  );

Eclipse : Failed to connect to remote VM. Connection refused.

when you have Failed to connect to remote VM Connection refused error, restart your eclipse

How can I format the output of a bash command in neat columns

If your output is delimited by tabs a quick solution would be to use the tabs command to adjust the size of your tabs.

tabs 20
keys | awk '{ print $1"\t\t" $2 }'

Deleting an SVN branch

Sure: svn rm the unwanted folder, and commit.

To avoid this situation in the future, I would follow the recommended layout for SVN projects:

  • Put your code in the /someproject/trunk folder (or just /trunk if you want to put only one project in the repository)
  • Created branches as /someproject/branches/somebranch
  • Put tags under /someproject/tags

Now when you check out a working copy, be sure to check out only trunk or some individual branch. Don't check everything out in one huge working copy containing all branches.1

1Unless you know what you're doing, in which case you know how to create shallow working copies.

How to remove border from specific PrimeFaces p:panelGrid?

I placed the panelgrid inside datatable, and hence my working solution is

.ui-datatable-scrollable-body .myStyleClass tbody td{border:none;}

for

<h:panelGrid  styleClass="myStyleClass" >...</h:panelGrid>

C fopen vs open

If you have a FILE *, you can use functions like fscanf, fprintf and fgets etc. If you have just the file descriptor, you have limited (but likely faster) input and output routines read, write etc.

Django CharField vs TextField

In some cases it is tied to how the field is used. In some DB engines the field differences determine how (and if) you search for text in the field. CharFields are typically used for things that are searchable, like if you want to search for "one" in the string "one plus two". Since the strings are shorter they are less time consuming for the engine to search through. TextFields are typically not meant to be searched through (like maybe the body of a blog) but are meant to hold large chunks of text. Now most of this depends on the DB Engine and like in Postgres it does not matter.

Even if it does not matter, if you use ModelForms you get a different type of editing field in the form. The ModelForm will generate an HTML form the size of one line of text for a CharField and multiline for a TextField.

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

LINQ-to-SQL is a remarkable piece of technology that is very simple to use, and by and large generates very good queries to the back end. LINQ-to-EF was slated to supplant it, but historically has been extremely clunky to use and generated far inferior SQL. I don't know the current state of affairs, but Microsoft promised to migrate all the goodness of L2S into L2EF, so maybe it's all better now.

Personally, I have a passionate dislike of ORM tools (see my diatribe here for the details), and so I see no reason to favour L2EF, since L2S gives me all I ever expect to need from a data access layer. In fact, I even think that L2S features such as hand-crafted mappings and inheritance modeling add completely unnecessary complexity. But that's just me. ;-)

JMS Topic vs Queues

It is simple as that:

Queues = Insert > Withdraw (send to single subscriber) 1:1

Topics = Insert > Broadcast (send to all subscribers) 1:n

enter image description here

Set focus on textbox in WPF

In XAML:

<StackPanel FocusManager.FocusedElement="{Binding ElementName=Box}">
   <TextBox Name="Box" />
</StackPanel>

Windows Bat file optional argument parsing

Here is the arguments parser. You can mix any string arguments (kept untouched) or escaped options (single or option/value pairs). To test it uncomment last 2 statements and run as:

getargs anystr1 anystr2 /test$1 /test$2=123 /test$3 str anystr3

Escape char is defined as "_SEP_=/", redefine if needed.

@echo off

REM Command line argument parser. Format (both "=" and "space" separators are supported):
REM   anystring1 anystring2 /param1 /param2=value2 /param3 value3 [...] anystring3 anystring4
REM Returns enviroment variables as:
REM   param1=1
REM   param2=value2
REM   param3=value3
REM Leading and traling strings are preserved as %1, %2, %3 ... %9 parameters
REM but maximum total number of strings is 9 and max number of leading strings is 8
REM Number of parameters is not limited!

set _CNT_=1
set _SEP_=/

:PARSE

if %_CNT_%==1 set _PARAM1_=%1 & set _PARAM2_=%2
if %_CNT_%==2 set _PARAM1_=%2 & set _PARAM2_=%3
if %_CNT_%==3 set _PARAM1_=%3 & set _PARAM2_=%4
if %_CNT_%==4 set _PARAM1_=%4 & set _PARAM2_=%5
if %_CNT_%==5 set _PARAM1_=%5 & set _PARAM2_=%6
if %_CNT_%==6 set _PARAM1_=%6 & set _PARAM2_=%7
if %_CNT_%==7 set _PARAM1_=%7 & set _PARAM2_=%8
if %_CNT_%==8 set _PARAM1_=%8 & set _PARAM2_=%9

if "%_PARAM2_%"=="" set _PARAM2_=1

if "%_PARAM1_:~0,1%"=="%_SEP_%" (
  if "%_PARAM2_:~0,1%"=="%_SEP_%" (
    set %_PARAM1_:~1,-1%=1
    shift /%_CNT_%
  ) else (
    set %_PARAM1_:~1,-1%=%_PARAM2_%
    shift /%_CNT_%
    shift /%_CNT_%
  )
) else (
  set /a _CNT_+=1
)

if /i %_CNT_% LSS 9 goto :PARSE

set _PARAM1_=
set _PARAM2_=
set _CNT_=

rem getargs anystr1 anystr2 /test$1 /test$2=123 /test$3 str anystr3
rem set | find "test$"
rem echo %1 %2 %3 %4 %5 %6 %7 %8 %9

:EXIT

Can inner classes access private variables?

First of all, you are trying to access non-static member var outside the class which is not allowed in C++.

Mark's answer is correct.

Anything that is part of Outer should have access to all of Outer's members, public or private.

So you can do two things, either declare var as static or use a reference of an instance of the outer class to access 'var' (because a friend class or function also needs reference to access private data).

Static var

Change var to static If you don't want var to be associated with the instances of the class.

#include <iostream>

class Outer {

private:
    static const char* const MYCONST;
    static int var;

public:
   class Inner {
    public:
        Inner() {
          Outer::var = 1;
        }
        void func() ;
    };
};

int Outer::var = 0;

void Outer::Inner::func() {
    std::cout << "var: "<< Outer::var;
}

int main() {
  Outer outer;
  Outer::Inner inner;
  inner.func();

}

Output- var: 1

Non-static var

An object's reference is must access any non-static member variables.

#include <iostream>

class Outer {

private:
    static const char* const MYCONST;
    int var;

public:
   class Inner {
    public:
        Inner(Outer &outer) {
          outer.var = 1;
        }
        void func(const Outer &outer) ;
    };
};

void Outer::Inner::func(const Outer &outer) {
    std::cout << "var: "<< outer.var;
}

int main() {
  Outer outer;
  Outer::Inner inner(outer);
  inner.func(outer);

}

Output- var: 1

Edit - External links are links to my Blog.

How to get a unique device ID in Swift?

The value of identifierForVendor changes when the user deletes all of that vendor’s apps from the device, if you want to keep the unique ID even for the subsequent fresh installations, you can try to use the following function

func vendorIdentifierForDevice()->String {
    //Get common part of Applicatoin Bundle ID, Note : getCommonPartOfApplicationBundleID is to be defined.
    let commonAppBundleID = getCommonPartOfApplicationBundleID()
    //Read from KeyChain using bunndle ID, Note : readFromKeyChain is to be defined.
    if let vendorID = readFromKeyChain(commonAppBundleID) {
        return vendorID
    } else {
        var vendorID = NSUUID().uuidString
        //Save to KeyChain using bunndle ID, Note : saveToKeyChain is to be defined.
        saveToKeyChain(commonAppBundleID, vendorID)
        return vendorID
    }
}

How to define a two-dimensional array?

You should make a list of lists, and the best way is to use nested comprehensions:

>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

On your [5][5] example, you are creating a list with an integer "5" inside, and try to access its 5th item, and that naturally raises an IndexError because there is no 5th item:

>>> l = [5]
>>> l[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

How to open adb and use it to send commands

You should find it in :

C:\Users\User Name\AppData\Local\Android\sdk\platform-tools

Add that to path, or change directory to there. The command sqlite3 is also there.

In the terminal you can type commands like

adb logcat //for logs
adb shell // for android shell

gnuplot - adjust size of key/legend

To adjust the length of the samples:

set key samplen X

(default is 4)

To adjust the vertical spacing of the samples:

set key spacing X

(default is 1.25)

and (for completeness), to adjust the fontsize:

set key font "<face>,<size>"

(default depends on the terminal)

And of course, all these can be combined into one line:

set key samplen 2 spacing .5 font ",8"

Note that you can also change the position of the key using set key at <position> or any one of the pre-defined positions (which I'll just defer to help key at this point)

Get the current date and time

Get Current DateTime

Now.ToShortDateString()
DateTime.Now
Today.Now

How to find out what is locking my tables?

Plot twist!

You can have orphaned distributed transactions holding exclusive locks and you will not see them if your script assumes there is a session associated with the transaction (there isn't!). Run the script below to identify these transactions:

;WITH ORPHANED_TRAN AS (
SELECT
    dat.name,
    dat.transaction_uow,
    ddt.database_transaction_begin_time,
    ddt.database_transaction_log_bytes_reserved,
    ddt.database_transaction_log_bytes_used
FROM
    sys.dm_tran_database_transactions ddt,
    sys.dm_tran_active_transactions dat,
    sys.dm_tran_locks dtl
WHERE
    ddt.transaction_id = dat.transaction_id AND
    dat.transaction_id = dtl.request_owner_id AND
    dtl.request_session_id = -2 AND
    dtl.request_mode = 'X'
)
SELECT DISTINCT * FROM ORPHANED_TRAN

Once you have identified the transaction, use the transaction_uow column to find it in MSDTC and decide whether to abort or commit it. If the transaction is marked as In Doubt (with a question mark next to it) you will probably want to abort it.

You can also kill the Unit Of Work (UOW) by specifying the transaction_uow in the KILL command:

KILL '<transaction_uow>'

References:

https://docs.microsoft.com/en-us/sql/t-sql/language-elements/kill-transact-sql?view=sql-server-2017#arguments

https://www.mssqltips.com/sqlservertip/4142/how-to-kill-a-blocking-negative-spid-in-sql-server/

How do I get the resource id of an image if I know its name?

You can also try this:

try {
    Class res = R.drawable.class;
    Field field = res.getField("drawableName");
    int drawableId = field.getInt(null);
}
catch (Exception e) {
    Log.e("MyTag", "Failure to get drawable id.", e);
}

I have copied this source codes from below URL. Based on tests done in this page, it is 5 times faster than getIdentifier(). I also found it more handy and easy to use. Hope it helps you as well.

Link: Dynamically Retrieving Resources in Android

Local variable referenced before assignment?

Put a global statement at the top of your function and you should be good:

def onLoadFinished(result):
    global feed
    ...

To demonstrate what I mean, look at this little test:

x = 0
def t():
    x += 1
t()

this blows up with your exact same error where as:

x = 0
def t():
    global x
    x += 1
t()

does not.

The reason for this is that, inside t, Python thinks that x is a local variable. Furthermore, unless you explicitly tell it that x is global, it will try to use a local variable named x in x += 1. But, since there is no x defined in the local scope of t, it throws an error.

How to find all occurrences of a substring?

By slicing we find all the combinations possible and append them in a list and find the number of times it occurs using count function

s=input()
n=len(s)
l=[]
f=input()
print(s[0])
for i in range(0,n):
    for j in range(1,n+1):
        l.append(s[i:j])
if f in l:
    print(l.count(f))

Adding a y-axis label to secondary y-axis in matplotlib

There is a straightforward solution without messing with matplotlib: just pandas.

Tweaking the original example:

table = sql.read_frame(query,connection)

ax = table[0].plot(color=colors[0],ylim=(0,100))
ax2 = table[1].plot(secondary_y=True,color=colors[1], ax=ax)

ax.set_ylabel('Left axes label')
ax2.set_ylabel('Right axes label')

Basically, when the secondary_y=True option is given (eventhough ax=ax is passed too) pandas.plot returns a different axes which we use to set the labels.

I know this was answered long ago, but I think this approach worths it.

Jquery If radio button is checked

Try this:

if ( jQuery('#postageyes').is(':checked') ){ ... }

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

Change Timezone in Lumen or Laravel 5

For me the app.php was here /vendor/laravel/lumen-framework/config/app.php but I also could change it from the .env file where it can be set to any of the values listed here (PHP original documentation here).

How to set timer in android?

I use this way:

String[] array={
       "man","for","think"
}; int j;

then below the onCreate

TextView t = findViewById(R.id.textView);

    new CountDownTimer(5000,1000) {

        @Override
        public void onTick(long millisUntilFinished) {}

        @Override
        public void onFinish() {
            t.setText("I "+array[j] +" You");
            j++;
            if(j== array.length-1) j=0;
            start();
        }
    }.start();

it's easy way to solve this problem.

Convert JSON format to CSV format for MS Excel

I'm not sure what you're doing, but this will go from JSON to CSV using JavaScript. This is using the open source JSON library, so just download JSON.js into the same folder you saved the code below into, and it will parse the static JSON value in json3 into CSV and prompt you to download/open in Excel.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>JSON to CSV</title>
    <script src="scripts/json.js" type="text/javascript"></script>
    <script type="text/javascript">
    var json3 = { "d": "[{\"Id\":1,\"UserName\":\"Sam Smith\"},{\"Id\":2,\"UserName\":\"Fred Frankly\"},{\"Id\":1,\"UserName\":\"Zachary Zupers\"}]" }

    DownloadJSON2CSV(json3.d);

    function DownloadJSON2CSV(objArray)
    {
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

        var str = '';

        for (var i = 0; i < array.length; i++) {
            var line = '';

            for (var index in array[i]) {
                line += array[i][index] + ',';
            }

            // Here is an example where you would wrap the values in double quotes
            // for (var index in array[i]) {
            //    line += '"' + array[i][index] + '",';
            // }

            line.slice(0,line.Length-1); 

            str += line + '\r\n';
        }
        window.open( "data:text/csv;charset=utf-8," + escape(str))
    }

    </script>

</head>
<body>
    <h1>This page does nothing....</h1>
</body>
</html>

MySQL trigger if condition exists

Try to do...

 DELIMITER $$
        CREATE TRIGGER aumentarsalario 
        BEFORE INSERT 
        ON empregados
        FOR EACH ROW
        BEGIN
          if (NEW.SALARIO < 900) THEN 
             set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
          END IF;
        END $$
  DELIMITER ;

When does Git refresh the list of remote branches?

If you are using Eclipse,

  1. Open "Git Repositories"
  2. Find your Repository.
  3. Open up "Branches" then "Remote Tracking".

Git

They should all be in there. Right click and "checkout."

How to call a JavaScript function within an HTML body

Try wrapping the createtable(); statement in a <script> tag:

<table>
        <tr>
            <th>Balance</th>
            <th>Fee</th>

        </tr>
        <script>createtable();</script>
</table>

I would avoid using document.write() and use the DOM if I were you though.

Create whole path automatically when writing to a new file

Use FileUtils to handle all these headaches.

Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.

openOutputStream(File file [, boolean append]) 

Shell Script: How to write a string to file and to stdout on console?

Use the tee command:

echo "hello" | tee logfile.txt

node.js - how to write an array to file

A simple solution is to use writeFile :

require("fs").writeFile(
     somepath,
     arr.map(function(v){ return v.join(', ') }).join('\n'),
     function (err) { console.log(err ? 'Error :'+err : 'ok') }
);

How to import a single table in to mysql database using command line

you can do it in mysql command instead of linux command.
1.login your mysql.
2.excute this in mysql command:
use DATABASE_NAME;
SET autocommit=0 ; source ABSOLUTE_PATH/TABLE_SQL_FILE.sql ; COMMIT ;

What causes javac to issue the "uses unchecked or unsafe operations" warning

This warning also could be raised due to

new HashMap() or new ArrayList() that is generic type has to be specific otherwise the compiler will generate warning.

Please make sure that if you code contains the following you have to change accordingly

new HashMap() => Map map = new HashMap() new HashMap() => Map map = new HashMap<>()

new ArrayList() => List map = new ArrayList() new ArrayList() => List map = new ArrayList<>()

How to read value of a registry key c#

Change:

using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))

To:

 using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))

Eclipse compilation error: The hierarchy of the type 'Class name' is inconsistent

I had the same exact problem marker and solved it by removing the @Override annotation from a method that was in fact the first implementation (the "super" one being an abstract method) and not an override.

java.security.AccessControlException: Access denied (java.io.FilePermission

Just document it here on Windows you need to escape the \ character:

"e:\\directory\\-"

View content of H2 or HSQLDB in-memory database

You can run H2 web server within your application that will access the same in-memory database. You can also access the H2 running in server mode using any generic JDBC client like SquirrelSQL.

UPDATE:

Server webServer = Server.createWebServer("-web,-webAllowOthers,true,-webPort,8082").start();
Server server = Server.createTcpServer("-tcp,-tcpAllowOthers,true,-tcpPort,9092").start();

Now you can connect to your database via jdbc:h2:mem:foo_db URL within the same process or browse the foo_db database using localhost:8082. Remember to close both servers. See also: H2 database in memory mode cannot be accessed by Console.

You can also use Spring:

<bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop" depends-on="h2WebServer">
    <constructor-arg value="-tcp,-tcpAllowOthers,true,-tcpPort,9092"/>
</bean>
<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer" init-method="start" destroy-method="stop">
    <constructor-arg value="-web,-webAllowOthers,true,-webPort,8082"/>
</bean>

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" depends-on="h2Server">
    <property name="driverClass" value="org.h2.Driver"/>
    <property name="jdbcUrl" value="jdbc:h2:mem:foo_db"/>
</bean>

BTW you should only depend on assertions and not on manual peeking the database contents. Use this only for troubleshooting.

N.B. if you use Spring test framework you won't see changes made by a running transaction and this transaction will be rolled back immediately after the test.

Spring JPA and persistence.xml

If anyone wants to use purely Java configuration instead of xml configuration of hibernate, use this:

You can configure Hibernate without using persistence.xml at all in Spring like like this:

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
{
Map<String, Object> properties = new Hashtable<>();
properties.put("javax.persistence.schema-generation.database.action",
"none");
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect"); //you can change this if you have a different DB
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(adapter);
factory.setDataSource(this.springJpaDataSource());
factory.setPackagesToScan("package name");
factory.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
factory.setValidationMode(ValidationMode.NONE);
factory.setJpaPropertyMap(properties);
return factory;
}

Since you are not using persistence.xml, you should create a bean that returns DataSource which you specify in the above method that sets the data source:

@Bean
public DataSource springJpaDataSource()
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl("jdbc:mysql://localhost/SpringJpa");
dataSource.setUsername("tomcatUser");
dataSource.setPassword("password1234");
return dataSource;
}

Then you use @EnableTransactionManagement annotation over this configuration file. Now when you put that annotation, you have to create one last bean:

@Bean
public PlatformTransactionManager jpaTransactionManager()
{
return new JpaTransactionManager(
this.entityManagerFactoryBean().getObject());
}

Now, don't forget to use @Transactional Annotation over those method that deal with DB.

Lastly, don't forget to inject EntityManager in your repository (This repository class should have @Repository annotation over it).

Get index of current item in a PowerShell loop

.NET has some handy utility methods for this sort of thing in System.Array:

PS> $a = 'a','b','c'
PS> [array]::IndexOf($a, 'b')
1
PS> [array]::IndexOf($a, 'c')
2

Good points on the above approach in the comments. Besides "just" finding an index of an item in an array, given the context of the problem, this is probably more suitable:

$letters = { 'A', 'B', 'C' }
$letters | % {$i=0} {"Value:$_ Index:$i"; $i++}

Foreach (%) can have a Begin sciptblock that executes once. We set an index variable there and then we can reference it in the process scripblock where it gets incremented before exiting the scriptblock.

What is a simple command line program or script to backup SQL server databases?

I use ExpressMaint.

To backup all user databases I do for example:

C:\>ExpressMaint.exe -S (local)\sqlexpress -D ALL_USER -T DB -BU HOURS -BV 1 -B c:\backupdir\ -DS

ActiveXObject in Firefox or Chrome (not IE!)

ActiveX resolved in Chrome!
Hello all this is not the solution but the successful workaround and I have implemented as well.
This required some implementation on client machine as well that why is most suitable for intranet environment and not recommended for public sites. Even though one can implement it for public sites as well the only problem is end user has to download/implement solution.
Lets understand the key problem
Chrome cannot communicate with ActiceX
Solution: Since Chorme cannot communicate with ActiveX but still it can communicate with the API hosted on the client machine. So develop API using .Net MVC or any other technology so that through Ajax call it can communicate with the API and API communicate with the ActiveX object situated on the client machine. Since API also resides in Client machine that why there is no problem in communication. This API works as mediator between Chrome browser and ActiveX.
During API implementation you might encounter CORS issues, Use JSONP to deal with it.
Pictorial view of the solution Pictorial view of the solution


Other solution : Use URI Scheme like MailTo: or MS-Word to deal with outlook and word application. If your requirement is different then you can implement your customized URI Scheme.

C/C++ include header file order

I recommend:

  1. The header for the .cc module you're building. (Helps ensure each header in your project doesn't have implicit dependencies on other headers in your project.)
  2. C system files.
  3. C++ system files.
  4. Platform / OS / other header files (e.g. win32, gtk, openGL).
  5. Other header files from your project.

And of course, alphabetical order within each section, where possible.

Always use forward declarations to avoid unnecessary #includes in your header files.

How to add a second x-axis in matplotlib

I'm forced to post this as an answer instead of a comment due to low reputation. I had a similar problem to Matteo. The difference being that I had no map from my first x-axis to my second x-axis, only the x-values themselves. So I wanted to set the data on my second x-axis directly, not the ticks, however, there is no axes.set_xdata. I was able to use Dhara's answer to do this with a modification:

ax2.lines = []

instead of using:

ax2.cla()

When in use also cleared my plot from ax1.

How to convert date in to yyyy-MM-dd Format?

Modern answer: Use LocalDate from java.time, the modern Java date and time API, and its toString method:

    LocalDate date = LocalDate.of(2012, Month.DECEMBER, 1); // get from somewhere
    String formattedDate = date.toString();
    System.out.println(formattedDate);

This prints

2012-12-01

A date (whether we’re talking java.util.Date or java.time.LocalDate) doesn’t have a format in it. All it’s got is a toString method that produces some format, and you cannot change the toString method. Fortunately, LocalDate.toString produces exactly the format you asked for.

The Date class is long outdated, and the SimpleDateFormat class that you tried to use, is notoriously troublesome. I recommend you forget about those classes and use java.time instead. The modern API is so much nicer to work with.

Except: it happens that you get a Date from a legacy API that you cannot change or don’t want to change just now. The best thing you can do with it is convert it to java.time.Instant and do any further operations from there:

    Date oldfashoinedDate = // get from somewhere
    LocalDate date = oldfashoinedDate.toInstant()
            .atZone(ZoneId.of("Asia/Beirut"))
            .toLocalDate();

Please substitute your desired time zone if it didn’t happen to be Asia/Beirut. Then proceed as above.

Link: Oracle tutorial: Date Time, explaining how to use java.time.

ngFor with index as value in attribute

Try this

<div *ngFor="let piece of allPieces; let i=index">
{{i}} // this will give index
</div>

How do I change UIView Size?

This can be achieved in various methods in Swift 3.0 Worked on Latest version MAY- 2019

Directly assign the Height & Width values for a view:

userView.frame.size.height = 0

userView.frame.size.width = 10

Assign the CGRect for the Frame

userView.frame =  CGRect(x:0, y: 0, width:0, height:0)

Method Details:

CGRect(x: point of X, y: point of Y, width: Width of View, height: Height of View)

Using an Extension method for CGRECT

Add following extension code in any swift file,

extension CGRect {

    init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {

        self.init(x:x, y:y, width:w, height:h)
    }
}

Use the following code anywhere in your application for the view to set the size parameters

userView.frame =  CGRect(1, 1, 20, 45)

Defining custom attrs

The traditional approach is full of boilerplate code and clumsy resource handling. That's why I made the Spyglass framework. To demonstrate how it works, here's an example showing how to make a custom view that displays a String title.

Step 1: Create a custom view class.

public class CustomView extends FrameLayout {
    private TextView titleView;

    public CustomView(Context context) {
        super(context);
        init(null, 0, 0);
    }

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0, 0);
    }

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs, defStyleAttr, 0);
    }

    @RequiresApi(21)
    public CustomView(
            Context context, 
            AttributeSet attrs,
            int defStyleAttr,
            int defStyleRes) {

        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs, defStyleAttr, defStyleRes);
    }

    public void setTitle(String title) {
        titleView.setText(title);
    }

    private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        inflate(getContext(), R.layout.custom_view, this);

        titleView = findViewById(R.id.title_view);
    }
}

Step 2: Define a string attribute in the values/attrs.xml resource file:

<resources>
    <declare-styleable name="CustomView">
        <attr name="title" format="string"/>
    </declare-styleable>
</resources>

Step 3: Apply the @StringHandler annotation to the setTitle method to tell the Spyglass framework to route the attribute value to this method when the view is inflated.

@HandlesString(attributeId = R.styleable.CustomView_title)
public void setTitle(String title) {
    titleView.setText(title);
}

Now that your class has a Spyglass annotation, the Spyglass framework will detect it at compile-time and automatically generate the CustomView_SpyglassCompanion class.

Step 4: Use the generated class in the custom view's init method:

private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    inflate(getContext(), R.layout.custom_view, this);

    titleView = findViewById(R.id.title_view);

    CustomView_SpyglassCompanion
            .builder()
            .withTarget(this)
            .withContext(getContext())
            .withAttributeSet(attrs)
            .withDefaultStyleAttribute(defStyleAttr)
            .withDefaultStyleResource(defStyleRes)
            .build()
            .callTargetMethodsNow();
}

That's it. Now when you instantiate the class from XML, the Spyglass companion interprets the attributes and makes the required method call. For example, if we inflate the following layout then setTitle will be called with "Hello, World!" as the argument.

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:width="match_parent"
    android:height="match_parent">

    <com.example.CustomView
        android:width="match_parent"
        android:height="match_parent"
        app:title="Hello, World!"/>
</FrameLayout>

The framework isn't limited to string resources has lots of different annotations for handling other resource types. It also has annotations for defining default values and for passing in placeholder values if your methods have multiple parameters.

Have a look at the Github repo for more information and examples.

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

I managed to work around it by reverting back to the last version that I had the mysql directory in, then deleting the contents of the directory, putting the new contents in it, and checking the new information back in. Although I'm curious if anyone has a better explanation for what the heck was going on there.

Finding index of character in Swift String

As my perspective, The better way with knowing the logic itself is below

 let testStr: String = "I love my family if you Love us to tell us I'm with you"
 var newStr = ""
 let char:Character = "i"

 for value in testStr {
      if value == char {
         newStr = newStr + String(value)
   }

}
print(newStr.count)

Adding minutes to date time in PHP

one line mysql datetime format

$mysql_date_time = (new DateTime())->modify('+15 minutes')->format("Y-m-d H:i:s");

What is the lifetime of a static variable in a C++ function?

The Static variables are come into play once the program execution starts and it remain available till the program execution ends.

The Static variables are created in the Data Segment of the Memory.