Programs & Examples On #Side effects

A side-effect is a programming term that refers to intended changes in the program behavior, such as a variable changing value. It is in important term when discussing compiler optimization and expression evaluation.

ReactJS: Warning: setState(...): Cannot update during an existing state transition

The solution that I use to open Popover for components is reactstrap (React Bootstrap 4 components).

    class Settings extends Component {
        constructor(props) {
            super(props);

            this.state = {
              popoversOpen: [] // array open popovers
            }
        }

        // toggle my popovers
        togglePopoverHelp = (selected) => (e) => {
            const index = this.state.popoversOpen.indexOf(selected);
            if (index < 0) {
              this.state.popoversOpen.push(selected);
            } else {
              this.state.popoversOpen.splice(index, 1);
            }
            this.setState({ popoversOpen: [...this.state.popoversOpen] });
        }

        render() {
            <div id="settings">
                <button id="PopoverTimer" onClick={this.togglePopoverHelp(1)} className="btn btn-outline-danger" type="button">?</button>
                <Popover placement="left" isOpen={this.state.popoversOpen.includes(1)} target="PopoverTimer" toggle={this.togglePopoverHelp(1)}>
                  <PopoverHeader>Header popover</PopoverHeader>
                  <PopoverBody>Description popover</PopoverBody>
                </Popover>

                <button id="popoverRefresh" onClick={this.togglePopoverHelp(2)} className="btn btn-outline-danger" type="button">?</button>
                <Popover placement="left" isOpen={this.state.popoversOpen.includes(2)} target="popoverRefresh" toggle={this.togglePopoverHelp(2)}>
                  <PopoverHeader>Header popover 2</PopoverHeader>
                  <PopoverBody>Description popover2</PopoverBody>
                </Popover>
            </div>
        }
    }

Visual Studio 2015 or 2017 does not discover unit tests

Just restart Visual Studio and in Test Explorer do "Run All" ... All my tests are discovered then.

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

I'm consciously writing this answer to an old question with this in mind, because the other answers didn't help me.

I got the Illegal Instruction: 4 while running the binary on the same system I had compiled it on, so -mmacosx-version-min didn't help.

I was using gcc in Code Blocks 16 on Mac OS X 10.11.

However, turning off all of Code Blocks' compiler flags for optimization worked. So look at all the flags Code Blocks set (right-click on the Project -> "Build Properties") and turn off all the flags you are sure you don't need, especially -s and the -Oflags for optimization. That did it for me.

If my interface must return Task what is the best way to have a no-operation implementation?

Recently encountered this and kept getting warnings/errors about the method being void.

We're in the business of placating the compiler and this clears it up:

    public async Task MyVoidAsyncMethod()
    {
        await Task.CompletedTask;
    }

This brings together the best of all the advice here so far. No return statement is necessary unless you're actually doing something in the method.

How should I pass multiple parameters to an ASP.Net Web API GET?

Just add a new route to the WebApiConfig entries.

For instance, to call:

public IEnumerable<SampleObject> Get(int pageNumber, int pageSize) { ..

add:

config.Routes.MapHttpRoute(
    name: "GetPagedData",
    routeTemplate: "api/{controller}/{pageNumber}/{pageSize}"
);

Then add the parameters to the HTTP call:

GET //<service address>/Api/Data/2/10 

Convert XmlDocument to String

If you are using Windows.Data.Xml.Dom.XmlDocument version of XmlDocument (used in UWP apps for example), you can use yourXmlDocument.GetXml() to get the XML as a string.

HTTP POST with URL query parameters -- good idea or not?

I would think it could still be quite RESTful to have query arguments that identify the resource on the URL while keeping the content payload confined to the POST body. This would seem to separate the considerations of "What am I sending?" versus "Who am I sending it to?".

How can I declare and use Boolean variables in a shell script?

Long ago, when all we had was sh, Booleans where handled by relying on a convention of the test program where test returns a false exit status if run without any arguments.

This allows one to think of a variable that is unset as false and variable set to any value as true. Today, test is a builtin to Bash and is commonly known by its one-character alias [ (or an executable to use in shells lacking it, as dolmen notes):

FLAG="up or <set>"

if [ "$FLAG" ] ; then
    echo 'Is true'
else
    echo 'Is false'
fi

# Unset FLAG
#    also works
FLAG=

if [ "$FLAG" ] ; then
    echo 'Continues true'
else
    echo 'Turned false'
fi

Because of quoting conventions, script writers prefer to use the compound command [[ that mimics test, but has a nicer syntax: variables with spaces do not need to be quoted; one can use && and || as logical operators with weird precedence, and there are no POSIX limitations on the number of terms.

For example, to determine if FLAG is set and COUNT is a number greater than 1:

FLAG="u p"
COUNT=3

if [[ $FLAG  && $COUNT -gt '1' ]] ; then
    echo 'Flag up, count bigger than 1'
else
    echo 'Nope'
fi

This stuff can get confusing when spaces, zero length strings, and null variables are all needed and also when your script needs to work with several shells.

Android TextView Text not getting wrapped

I'm an Android (and GUI) beginner, but have lots of experience with software. I've gone through a few of the tutorials, and this is my understanding:

layout_width and layout_height are attributes of the TextView. They are instructions for how the TextView should shape itself, they aren't referring to how to handle the content within the TextView.

If you use "fill_parent", you are saying that the TextView should shape itself relative to it's parent view, it should fill it.

If you use "wrap_content", you are saying that you should ignore the parent view, and let the contents of the TextView define it's shape.

I think this is the confusing point. "wrap_content" isn't telling the TextView how to manage it's contents (to wrap the lines), it's telling it that it should shape itself relative to it's contents. In this case, with no new line characters, it shapes itself so that all the text is on a single line (which unfortunately is overflowing the parent).

I think you want it to fill the parent horizontally, and to wrap it's contents vertically.

How to insert values into the database table using VBA in MS access

since you mentioned you are quite new to access, i had to invite you to first remove the errors in the code (the incomplete for loop and the SQL statement). Otherwise, you surely need the for loop to insert dates in a certain range.

Now, please use the code below to insert the date values into your table. I have tested the code and it works. You can try it too. After that, add your for loop to suit your scenario

Dim StrSQL As String
Dim InDate As Date
Dim DatDiff As Integer

InDate = Me.FromDateTxt

StrSQL = "INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );"

DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True

Android Studio Gradle Configuration with name 'default' not found

Try adding Volley library and sync and run the program. if one has pulled and i has volley usage and the error shows as -Android Studio Gradle Configuration with name 'default' not found then follow the step of adding the volley library in your gradle. hope it helps. I cleared my problem this way.

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

How to decide when to use Node.js?

Node best for concurrent request handling -

So, Let’s start with a story. From last 2 years I am working on JavaScript and developing web front end and I am enjoying it. Back end guys provide’s us some API’s written in Java,python (we don’t care) and we simply write a AJAX call, get our data and guess what ! we are done. But in real it is not that easy, If data we are getting is not correct or there is some server error then we stuck and we have to contact our back end guys over the mail or chat(sometimes on whatsApp too :).) This is not cool. What if we wrote our API’s in JavaScript and call those API’s from our front end ? Yes that’s pretty cool because if we face any problem in API we can look into it. Guess what ! you can do this now , How ? – Node is there for you.

Ok agreed that you can write your API in JavaScript but what if I am ok with above problem. Do you have any other reason to use node for rest API ?

so here is the magic begins. Yes I do have other reasons to use node for our API’s.

Let’s go back to our traditional rest API system which is based on either blocking operation or threading. Suppose two concurrent request occurs( r1 and r2) , each of them require database operation. So In traditional system what will happens :

1. Waiting Way : Our server starts serving r1 request and waits for query response. after completion of r1 , server starts to serve r2 and does it in same way. So waiting is not a good idea because we don’t have that much time.

2. Threading Way : Our server will creates two threads for both requests r1 and r2 and serve their purpose after querying database so cool its fast.But it is memory consuming because you can see we started two threads also problem increases when both request is querying same data then you have to deal with deadlock kind of issues . So its better than waiting way but still issues are there.

Now here is , how node will do it:

3. Nodeway : When same concurrent request comes in node then it will register an event with its callback and move ahead it will not wait for query response for a particular request.So when r1 request comes then node’s event loop (yes there is an event loop in node which serves this purpose.) register an event with its callback function and move ahead for serving r2 request and similarly register its event with its callback. Whenever any query finishes it triggers its corresponding event and execute its callback to completion without being interrupted.

So no waiting, no threading , no memory consumption – yes this is nodeway for serving rest API.

Responsive background image in div full width

I also tried this style for ionic hybrid app background. this is also having style for background blur effect.

.bg-image {
   position: absolute;
   background: url(../img/bglogin.jpg) no-repeat;
   height: 100%;
   width: 100%;
   background-size: cover;
   bottom: 0px;
   margin: 0 auto;
   background-position: 50%;


  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);

}

Visual Studio 2015 doesn't have cl.exe

For me that have Visual Studio 2015 this works:
Search this in the start menu: Developer Command Prompt for VS2015 and run the program in the search result.
You can now execute your command in it, for example: cl /?

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

They should have the same time, the update is supposed to be atomic, meaning that whatever how long it takes to perform, the action is supposed to occurs as if all was done at the same time.

If you're experiencing a different behaviour, it's time to change for another DBMS.

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

In Xcode 8 beta 4 does not work...

Use:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
    print("Are we there yet?")
}

for async two ways:

DispatchQueue.main.async {
    print("Async1")
}

DispatchQueue.main.async( execute: {
    print("Async2")
})

Is it necessary to assign a string to a variable before comparing it to another?

You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:

NSString *myString = [NSString stringWithString:@"abc"];
NSString *myString = [NSString stringWithFormat:@"abc %d efg", 42];

How to SUM parts of a column which have same text value in different column in the same row

This can be done by using SUMPRODUCT as well. Update the ranges as you see fit

=SUMPRODUCT(($A$2:$A$7=A2)*($B$2:$B$7=B2)*$C$2:$C$7)

A2:A7 = First name range

B2:B7 = Last Name Range

C2:C7 = Numbers Range

This will find all the names with the same first and last name and sum the numbers in your numbers column

Convert a string into an int

Swift 3.0:

Int("5")

or

let stringToConvert = "5"
Int(stringToConvert)

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

So in Short,

vi ~/.proxy_info

export http_proxy=<username>:<password>@<proxy>:8080
export https_proxy=<username>:<password>@<proxy>:8080

source ~/.proxy_info

Hope this helps someone in hurry :)

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

I experienced this when I updated my JDK manually and removed the previous JDK

Red keywords

Solution

  • In the IntelliJ editor, click on the red keyword (Integer for example) and press ALT + ENTER (or click the light bulb icon)
  • select Setup JDK from the intentions menu

IntelliJ intentions menu

  • click on Configure

Project SDK selection dialog

  • In my case, the JDK path was incorrect (pointed on /opt/jdk1.7.0_51 instead of /opt/jdk1.7.0_65)

Broken Configure SDK dialog

  • Click on the ... and browse to the right JDK path

Fixed Configure SDK dialog

  • Let's clear the cache:

IntelliJ File menu

And everything should be back to life :)

No red keywords

Autowiring fails: Not an managed Type

After encountering this issue and tried different method of adding the entity packaname name to EntityScan, ComponentScan etc, none of it worked.

Added the package to packageScan config in the EntityManagerFactory of the repository config. The below code gives the code based configuration as opposed to XML based ones answered above.

@Primary
@Bean(name = "entityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource);
    emf.setJpaVendorAdapter(jpaVendorAdapter);
    emf.setPackagesToScan("org.package.entity");
    emf.setPersistenceUnitName("default"); 
    emf.afterPropertiesSet();
    return emf.getObject();
}

How to write multiple line string using Bash with variables?

If you do not want variables to be replaced, you need to surround EOL with single quotes.

cat >/tmp/myconfig.conf <<'EOL'
line 1, ${kernel}
line 2, 
line 3, ${distro}
line 4 line
... 
EOL

Previous example:

$ cat /tmp/myconfig.conf 
line 1, ${kernel}
line 2, 
line 3, ${distro}
line 4 line
... 

Matplotlib: "Unknown projection '3d'" error

Try this:

import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.mplot3d import axes3d

fig=plt.figure(figsize=(16,12.5))
ax=fig.add_subplot(2,2,1,projection="3d")

a=ax.scatter(Dataframe['bedrooms'],Dataframe['bathrooms'],Dataframe['floors'])
plt.plot(a)

Rails: How to reference images in CSS within Rails 4

The hash is because the asset pipeline and server Optimize caching http://guides.rubyonrails.org/asset_pipeline.html

Try something like this:

 background-image: url(image_path('check.png'));

Goodluck

MySQL WHERE IN ()

Your query translates to

SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';

It will only return the results that match it.


One way of solving it avoiding the complexity would be, chaning the datatype to SET. Then you could use, FIND_IN_SET

SELECT * FROM table WHERE FIND_IN_SET('1', id);

jquery get all input from specific form

To iterate through all the inputs in a form you can do this:

$("form#formID :input").each(function(){
 var input = $(this); // This is the jquery object of the input, do what you will
});

This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :

$("form#formID input[type=text]")//...

etc.

sed command with -i option failing on Mac, but works on Linux

Here is an option in bash scripts:

#!/bin/bash

GO_OS=${GO_OS:-"linux"}

function detect_os {
    # Detect the OS name
    case "$(uname -s)" in
      Darwin)
        host_os=darwin
        ;;
      Linux)
        host_os=linux
        ;;
      *)
        echo "Unsupported host OS. Must be Linux or Mac OS X." >&2
        exit 1
        ;;
    esac

   GO_OS="${host_os}"
}

detect_os

if [ "${GO_OS}" == "darwin" ]; then
    sed -i '' -e ...
else
    sed -i -e ...
fi

Eclipse "Invalid Project Description" when creating new project from existing source

Copy the project into your workspace, create new Android Application Project with the same name from eclipse file->new->project and voila.

handle textview link click in my android app

for who looks for more options here is a one

// Set text within a `TextView`
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Hey @sarah, where did @jim go? #lost");
// Style clickable spans based on pattern
new PatternEditableBuilder().
    addPattern(Pattern.compile("\\@(\\w+)"), Color.BLUE,
       new PatternEditableBuilder.SpannableClickedListener() {
        @Override
        public void onSpanClicked(String text) {
            Toast.makeText(MainActivity.this, "Clicked username: " + text,
                Toast.LENGTH_SHORT).show();
        }
}).into(textView);

RESOURCE : CodePath

install beautiful soup using pip

If you have more than one version of python installed, run the respective pip command.

For example for python3.6 run the following

pip3.6 install beautifulsoup4

To check the available command/version of pip and python on Mac run

ls /usr/local/bin

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

When this happened to me (out of nowhere) I was about to dive into the top answer above, and then I figured I'd close the project, close Visual Studio, and then re-open everything. Problem solved. VS bug?

XAMPP, Apache - Error: Apache shutdown unexpectedly

In my case it was much easier. I turned off the native windows firewall. Then re-loaded comp launched xampp and started apache again. Then turned the firewall on back.

Disable resizing of a Windows Forms form

More precisely, add the code below to the private void InitializeComponent() method of the Form class:

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;

Read remote file with node.js (http.get)

I'd use request for this:

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:

var request = require('request');
request.get('http://www.whatever.com/my.csv', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var csv = body;
        // Continue with your processing here.
    }
});

etc.

How to overcome the CORS issue in ReactJS

You can have your React development server proxy your requests to that server. Simply send your requests to your local server like this: url: "/" And add the following line to your package.json file

"proxy": "https://awww.api.com"

Though if you are sending CORS requests to multiple sources, you'll have to manually configure the proxy yourself This link will help you set that up Create React App Proxying API requests

How do I delete multiple rows with different IDs?

If you have to select the id:

 DELETE FROM table WHERE id IN (SELECT id FROM somewhere_else)

If you already know them (and they are not in the thousands):

 DELETE FROM table WHERE id IN (?,?,?,?,?,?,?,?)

Conditional statement in a one line lambda function in python?

I found I COULD use "if-then" statements in a lambda. For instance:

eval_op = {
    '|'  : lambda x,y: eval(y) if (eval(x)==0) else eval(x),
    '&'  : lambda x,y: 0 if (eval(x)==0) else eval(y),
    '<'  : lambda x,y: 1 if (eval(x)<eval(y)) else 0,
    '>'  : lambda x,y: 1 if (eval(x)>eval(y)) else 0,
}

What are all the uses of an underscore in Scala?

Besides the usages that JAiro mentioned, I like this one:

def getConnectionProps = {
    ( Config.getHost, Config.getPort, Config.getSommElse, Config.getSommElsePartTwo )
}

If someone needs all connection properties, he can do:

val ( host, port, sommEsle, someElsePartTwo ) = getConnectionProps

If you need just a host and a port, you can do:

val ( host, port, _, _ ) = getConnectionProps

How do I left align these Bootstrap form items?

Just my two cents. If you are using Bootstrap 3 then I would just add an extra style into your own site's stylesheet which controls the text-left style of the control-label.

If you were to add text-left to the label, by default there is another style which overrides this .form-horizontal .control-label. So if you add:

.form-horizontal .control-label.text-left{
    text-align: left;
}

Then the built in text-left style is applied to the label correctly.

Draw on HTML5 Canvas using a mouse

Here is my very simple working canvas draw and erase.

https://jsfiddle.net/richardcwc/d2gxjdva/

_x000D_
_x000D_
//Canvas_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
//Variables_x000D_
var canvasx = $(canvas).offset().left;_x000D_
var canvasy = $(canvas).offset().top;_x000D_
var last_mousex = last_mousey = 0;_x000D_
var mousex = mousey = 0;_x000D_
var mousedown = false;_x000D_
var tooltype = 'draw';_x000D_
_x000D_
//Mousedown_x000D_
$(canvas).on('mousedown', function(e) {_x000D_
    last_mousex = mousex = parseInt(e.clientX-canvasx);_x000D_
 last_mousey = mousey = parseInt(e.clientY-canvasy);_x000D_
    mousedown = true;_x000D_
});_x000D_
_x000D_
//Mouseup_x000D_
$(canvas).on('mouseup', function(e) {_x000D_
    mousedown = false;_x000D_
});_x000D_
_x000D_
//Mousemove_x000D_
$(canvas).on('mousemove', function(e) {_x000D_
    mousex = parseInt(e.clientX-canvasx);_x000D_
    mousey = parseInt(e.clientY-canvasy);_x000D_
    if(mousedown) {_x000D_
        ctx.beginPath();_x000D_
        if(tooltype=='draw') {_x000D_
            ctx.globalCompositeOperation = 'source-over';_x000D_
            ctx.strokeStyle = 'black';_x000D_
            ctx.lineWidth = 3;_x000D_
        } else {_x000D_
            ctx.globalCompositeOperation = 'destination-out';_x000D_
            ctx.lineWidth = 10;_x000D_
        }_x000D_
        ctx.moveTo(last_mousex,last_mousey);_x000D_
        ctx.lineTo(mousex,mousey);_x000D_
        ctx.lineJoin = ctx.lineCap = 'round';_x000D_
        ctx.stroke();_x000D_
    }_x000D_
    last_mousex = mousex;_x000D_
    last_mousey = mousey;_x000D_
    //Output_x000D_
    $('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown);_x000D_
});_x000D_
_x000D_
//Use draw|erase_x000D_
use_tool = function(tool) {_x000D_
    tooltype = tool; //update_x000D_
}
_x000D_
canvas {_x000D_
    cursor: crosshair;_x000D_
    border: 1px solid #000000;_x000D_
}
_x000D_
<canvas id="canvas" width="800" height="500"></canvas>_x000D_
<input type="button" value="draw" onclick="use_tool('draw');" />_x000D_
<input type="button" value="erase" onclick="use_tool('erase');" />_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

When do you use varargs in Java?

I use varargs frequently for constructors that can take some sort of filter object. For example, a large part of our system based on Hadoop is based on a Mapper that handles serialization and deserialization of items to JSON, and applies a number of processors that each take an item of content and either modify and return it, or return null to reject.

PHP to search within txt file and echo the whole line

And a PHP example, multiple matching lines will be displayed:

<?php
$file = 'somefile.txt';
$searchfor = 'name';

// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No matches found";
}

How to get my project path?

This gives you the root folder:

System.AppDomain.CurrentDomain.BaseDirectory

You can navigate from here using .. or ./ etc.. , Appending .. takes you to folder where .sln file can be found

For .NET framework (thanks to Adiono comment)

Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"..\\..\\"))

For .NET core here is a way to do it (thanks to nopara73 comment)

Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\")) ;

What's the "Content-Length" field in HTTP header?

The Content-Length header is a number denoting an the exact byte length of the HTTP body. The HTTP body starts immediately after the first empty line that is found after the start-line and headers.

Generally the Content-Length header is used for HTTP 1.1 so that the receiving party knows when the current response* has finished, so the connection can be reused for another request.

* ...or request, in the case of request methods that have a body, such as POST, PUT or PATCH

Alternatively, Content-Length header can be omitted and a chunked Transfer-Encoding header can be used.

If both Content-Length and Transfer-Encoding headers are missing, then at the end of the response the connection must be closed.

The following resource is a guide that I found very useful when learning about HTTP:

HTTP Made Really Easy.

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

DO NOT USE THIS ANSWER. I HAVE ONLY LEFT IT FOR HISTORICAL PURPOSES. SEE THE COMMENTS BELOW.

There is a simple trick if it is a BOOL parameter.

Pass nil for NO and self for YES. nil is cast to the BOOL value of NO. self is cast to the BOOL value of YES.

This approach breaks down if it is anything other than a BOOL parameter.

Assuming self is a UIView.

//nil will be cast to NO when the selector is performed
[self performSelector:@selector(setHidden:) withObject:nil afterDelay:5.0];

//self will be cast to YES when the selector is performed
[self performSelector:@selector(setHidden:) withObject:self afterDelay:10.0];

throw checked Exceptions from mocks with Mockito

This works for me in Kotlin:

when(list.get(0)).thenThrow(new ArrayIndexOutOfBoundsException());

Note : Throw any defined exception other than Exception()

How to get Git to clone into current directory

git clone ssh://[email protected]/home/user/private/repos/project_hub.git $(pwd)

Pytorch tensor to numpy array

Your question is very poorly worded. Your code (sort of) already does what you want. What exactly are you confused about? x.numpy() answer the original title of your question:

Pytorch tensor to numpy array

you need improve your question starting with your title.

Anyway, just in case this is useful to others. You might need to call detach for your code to work. e.g.

RuntimeError: Can't call numpy() on Variable that requires grad.

So call .detach(). Sample code:

# creating data and running through a nn and saving it

import torch
import torch.nn as nn

from pathlib import Path
from collections import OrderedDict

import numpy as np

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

num_samples = 3
Din, Dout = 1, 1
lb, ub = -1, 1

x = torch.torch.distributions.Uniform(low=lb, high=ub).sample((num_samples, Din))

f = nn.Sequential(OrderedDict([
    ('f1', nn.Linear(Din,Dout)),
    ('out', nn.SELU())
]))
y = f(x)

# save data
y.numpy()
x_np, y_np = x.detach().cpu().numpy(), y.detach().cpu().numpy()
np.savez(path / 'db', x=x_np, y=y_np)

print(x_np)

cpu goes after detach. See: https://discuss.pytorch.org/t/should-it-really-be-necessary-to-do-var-detach-cpu-numpy/35489/5


Also I won't make any comments on the slicking since that is off topic and that should not be the focus of your question. See this:

Understanding slice notation

Uncaught SyntaxError: Unexpected token :

In my case i ran into the same error, while running spring mvc application due to wrong mapping in my mvc controller

@RequestMapping(name="/private/updatestatus")

i changed the above mapping to

 @RequestMapping("/private/updatestatus")

or

 @RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)

Writing .csv files from C++

Change

Morison_File << t;                                 //Printing to file
Morison_File << F;

To

Morison_File << t << ";" << F << endl;                                 //Printing to file

a , would also do instead of ;

Can I make dynamic styles in React Native?

Here is what worked for me:

render() {
  const { styleValue } = this.props;
  const dynamicStyleUpdatedFromProps = {
    height: styleValue,
    width: styleValue,
    borderRadius: styleValue,
  }

  return (
    <View style={{ ...styles.staticStyleCreatedFromStyleSheet, ...dynamicStyleUpdatedFromProps }} />
  );
}

For some reason, this was the only way that mine would update properly.

Parsing JSON with Unix tools

There are a number of tools specifically designed for the purpose of manipulating JSON from the command line, and will be a lot easier and more reliable than doing it with Awk, such as jq:

curl -s 'https://api.github.com/users/lambda' | jq -r '.name'

You can also do this with tools that are likely already installed on your system, like Python using the json module, and so avoid any extra dependencies, while still having the benefit of a proper JSON parser. The following assume you want to use UTF-8, which the original JSON should be encoded in and is what most modern terminals use as well:

Python 3:

curl -s 'https://api.github.com/users/lambda' | \
    python3 -c "import sys, json; print(json.load(sys.stdin)['name'])"

Python 2:

export PYTHONIOENCODING=utf8
curl -s 'https://api.github.com/users/lambda' | \
    python2 -c "import sys, json; print json.load(sys.stdin)['name']"

Frequently Asked Questions

Why not a pure shell solution?

The standard POSIX/Single Unix Specification shell is a very limited language which doesn't contain facilities for representing sequences (list or arrays) or associative arrays (also known as hash tables, maps, dicts, or objects in some other languages). This makes representing the result of parsing JSON somewhat tricky in portable shell scripts. There are somewhat hacky ways to do it, but many of them can break if keys or values contain certain special characters.

Bash 4 and later, zsh, and ksh have support for arrays and associative arrays, but these shells are not universally available (macOS stopped updating Bash at Bash 3, due to a change from GPLv2 to GPLv3, while many Linux systems don't have zsh installed out of the box). It's possible that you could write a script that would work in either Bash 4 or zsh, one of which is available on most macOS, Linux, and BSD systems these days, but it would be tough to write a shebang line that worked for such a polyglot script.

Finally, writing a full fledged JSON parser in shell would be a significant enough enough dependency that you might as well just use an existing dependency like jq or Python instead. It's not going to be a one-liner, or even small five-line snippet, to do a good implementation.

Why not use awk, sed, or grep?

It is possible to use these tools to do some quick extraction from JSON with a known shape and formatted in a known way, such as one key per line. There are several examples of suggestions for this in other answers.

However, these tools are designed for line based or record based formats; they are not designed for recursive parsing of matched delimiters with possible escape characters.

So these quick and dirty solutions using awk/sed/grep are likely to be fragile, and break if some aspect of the input format changes, such as collapsing whitespace, or adding additional levels of nesting to the JSON objects, or an escaped quote within a string. A solution that is robust enough to handle all JSON input without breaking will also be fairly large and complex, and so not too much different than adding another dependency on jq or Python.

I have had to deal with large amounts of customer data being deleted due to poor input parsing in a shell script before, so I never recommend quick and dirty methods that may be fragile in this way. If you're doing some one-off processing, see the other answers for suggestions, but I still highly recommend just using an existing tested JSON parser.

Historical notes

This answer originally recommended jsawk, which should still work, but is a little more cumbersome to use than jq, and depends on a standalone JavaScript interpreter being installed which is less common than a Python interpreter, so the above answers are probably preferable:

curl -s 'https://api.github.com/users/lambda' | jsawk -a 'return this.name'

This answer also originally used the Twitter API from the question, but that API no longer works, making it hard to copy the examples to test out, and the new Twitter API requires API keys, so I've switched to using the GitHub API which can be used easily without API keys. The first answer for the original question would be:

curl 'http://twitter.com/users/username.json' | jq -r '.text'

How do you uninstall all dependencies listed in package.json (NPM)?

Piggy-backing off of VIKAS KOHLI and jedmao, you can do this

single line version:

npm uninstall `ls -1 node_modules | grep -v ^@ | tr '/\n' ' '` `find node_modules/@* -type d -depth 1 2>/dev/null | cut -d/ -f2-3 | tr '\n' ' '`

multi-lined version:

npm uninstall \
`ls -1 node_modules | grep -v ^@ | tr '/\n' ' '` \
`find node_modules/@* -type d -depth 1 2>/dev/null | cut -d/ -f2-3 | tr '\n' ' '`

Sorting dictionary keys in python

my_list = sorted(dict.items(), key=lambda x: x[1])

Detect application heap size in Android

There are two ways to think about your phrase "application heap size available":

  1. How much heap can my app use before a hard error is triggered? And

  2. How much heap should my app use, given the constraints of the Android OS version and hardware of the user's device?

There is a different method for determining each of the above.

For item 1 above: maxMemory()

which can be invoked (e.g., in your main activity's onCreate() method) as follows:

Runtime rt = Runtime.getRuntime();
long maxMemory = rt.maxMemory();
Log.v("onCreate", "maxMemory:" + Long.toString(maxMemory));

This method tells you how many total bytes of heap your app is allowed to use.

For item 2 above: getMemoryClass()

which can be invoked as follows:

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
Log.v("onCreate", "memoryClass:" + Integer.toString(memoryClass));

This method tells you approximately how many megabytes of heap your app should use if it wants to be properly respectful of the limits of the present device, and of the rights of other apps to run without being repeatedly forced into the onStop() / onResume() cycle as they are rudely flushed out of memory while your elephantine app takes a bath in the Android jacuzzi.

This distinction is not clearly documented, so far as I know, but I have tested this hypothesis on five different Android devices (see below) and have confirmed to my own satisfaction that this is a correct interpretation.

For a stock version of Android, maxMemory() will typically return about the same number of megabytes as are indicated in getMemoryClass() (i.e., approximately a million times the latter value).

The only situation (of which I am aware) for which the two methods can diverge is on a rooted device running an Android version such as CyanogenMod, which allows the user to manually select how large a heap size should be allowed for each app. In CM, for example, this option appears under "CyanogenMod settings" / "Performance" / "VM heap size".

NOTE: BE AWARE THAT SETTING THIS VALUE MANUALLY CAN MESS UP YOUR SYSTEM, ESPECIALLY if you select a smaller value than is normal for your device.

Here are my test results showing the values returned by maxMemory() and getMemoryClass() for four different devices running CyanogenMod, using two different (manually-set) heap values for each:

  • G1:
    • With VM Heap Size set to 16MB:
      • maxMemory: 16777216
      • getMemoryClass: 16
    • With VM Heap Size set to 24MB:
      • maxMemory: 25165824
      • getMemoryClass: 16
  • Moto Droid:
    • With VM Heap Size set to 24MB:
      • maxMemory: 25165824
      • getMemoryClass: 24
    • With VM Heap Size set to 16MB:
      • maxMemory: 16777216
      • getMemoryClass: 24
  • Nexus One:
    • With VM Heap size set to 32MB:
      • maxMemory: 33554432
      • getMemoryClass: 32
    • With VM Heap size set to 24MB:
      • maxMemory: 25165824
      • getMemoryClass: 32
  • Viewsonic GTab:
    • With VM Heap Size set to 32:
      • maxMemory: 33554432
      • getMemoryClass: 32
    • With VM Heap Size set to 64:
      • maxMemory: 67108864
      • getMemoryClass: 32

In addition to the above, I tested on a Novo7 Paladin tablet running Ice Cream Sandwich. This was essentially a stock version of ICS, except that I've rooted the tablet through a simple process that does not replace the entire OS, and in particular does not provide an interface that would allow the heap size to be manually adjusted.

For that device, here are the results:

  • Novo7
    • maxMemory: 62914560
    • getMemoryClass: 60

Also (per Kishore in a comment below):

  • HTC One X
    • maxMemory: 67108864
    • getMemoryClass: 64

And (per akauppi's comment):

  • Samsung Galaxy Core Plus
    • maxMemory: (Not specified in comment)
    • getMemoryClass: 48
    • largeMemoryClass: 128

Per a comment from cmcromance:

  • Galaxy S3 (Jelly Bean) large heap
    • maxMemory: 268435456
    • getMemoryClass: 64

And (per tencent's comments):

  • LG Nexus 5 (4.4.3) normal
    • maxMemory: 201326592
    • getMemoryClass: 192
  • LG Nexus 5 (4.4.3) large heap
    • maxMemory: 536870912
    • getMemoryClass: 192
  • Galaxy Nexus (4.3) normal
    • maxMemory: 100663296
    • getMemoryClass: 96
  • Galaxy Nexus (4.3) large heap
    • maxMemory: 268435456
    • getMemoryClass: 96
  • Galaxy S4 Play Store Edition (4.4.2) normal
    • maxMemory: 201326592
    • getMemoryClass: 192
  • Galaxy S4 Play Store Edition (4.4.2) large heap
    • maxMemory: 536870912
    • getMemoryClass: 192

Other Devices

  • Huawei Nexus 6P (6.0.1) normal
    • maxMemory: 201326592
    • getMemoryClass: 192

I haven't tested these two methods using the special android:largeHeap="true" manifest option available since Honeycomb, but thanks to cmcromance and tencent we do have some sample largeHeap values, as reported above.

My expectation (which seems to be supported by the largeHeap numbers above) would be that this option would have an effect similar to setting the heap manually via a rooted OS - i.e., it would raise the value of maxMemory() while leaving getMemoryClass() alone. There is another method, getLargeMemoryClass(), that indicates how much memory is allowable for an app using the largeHeap setting. The documentation for getLargeMemoryClass() states, "most applications should not need this amount of memory, and should instead stay with the getMemoryClass() limit."

If I've guessed correctly, then using that option would have the same benefits (and perils) as would using the space made available by a user who has upped the heap via a rooted OS (i.e., if your app uses the additional memory, it probably will not play as nicely with whatever other apps the user is running at the same time).

Note that the memory class apparently need not be a multiple of 8MB.

We can see from the above that the getMemoryClass() result is unchanging for a given device/OS configuration, while the maxMemory() value changes when the heap is set differently by the user.

My own practical experience is that on the G1 (which has a memory class of 16), if I manually select 24MB as the heap size, I can run without erroring even when my memory usage is allowed to drift up toward 20MB (presumably it could go as high as 24MB, although I haven't tried this). But other similarly large-ish apps may get flushed from memory as a result of my own app's pigginess. And, conversely, my app may get flushed from memory if these other high-maintenance apps are brought to the foreground by the user.

So, you cannot go over the amount of memory specified by maxMemory(). And, you should try to stay within the limits specified by getMemoryClass(). One way to do that, if all else fails, might be to limit functionality for such devices in a way that conserves memory.

Finally, if you do plan to go over the number of megabytes specified in getMemoryClass(), my advice would be to work long and hard on the saving and restoring of your app's state, so that the user's experience is virtually uninterrupted if an onStop() / onResume() cycle occurs.

In my case, for reasons of performance I'm limiting my app to devices running 2.2 and above, and that means that almost all devices running my app will have a memoryClass of 24 or higher. So I can design to occupy up to 20MB of heap and feel pretty confident that my app will play nice with the other apps the user may be running at the same time.

But there will always be a few rooted users who have loaded a 2.2 or above version of Android onto an older device (e.g., a G1). When you encounter such a configuration, ideally, you ought to pare down your memory use, even if maxMemory() is telling you that you can go much higher than the 16MB that getMemoryClass() is telling you that you should be targeting. And if you cannot reliably ensure that your app will live within that budget, then at least make sure that onStop() / onResume() works seamlessly.

getMemoryClass(), as indicated by Diane Hackborn (hackbod) above, is only available back to API level 5 (Android 2.0), and so, as she advises, you can assume that the physical hardware of any device running an earlier version of the OS is designed to optimally support apps occupying a heap space of no more than 16MB.

By contrast, maxMemory(), according to the documentation, is available all the way back to API level 1. maxMemory(), on a pre-2.0 version, will probably return a 16MB value, but I do see that in my (much later) CyanogenMod versions the user can select a heap value as low as 12MB, which would presumably result in a lower heap limit, and so I would suggest that you continue to test the maxMemory() value, even for versions of the OS prior to 2.0. You might even have to refuse to run in the unlikely event that this value is set even lower than 16MB, if you need to have more than maxMemory() indicates is allowed.

undefined reference to 'std::cout'

Yes, using g++ command worked for me:

g++ my_source_code.cpp

CSS Equivalent of the "if" statement

There is no native IF/ELSE for CSS available. CSS preprocessors like SASS (and Compass) can help, but if you’re looking for more feature-specific if/else conditions you should give Modernizr a try. It does feature-detection and then adds classes to the HTML element to indicate which CSS3 & HTML5 features the browser supports and doesn’t support. You can then write very if/else-like CSS right in your CSS without any preprocessing, like this:

.geolocation #someElem {
   /* only apply this if the browser supports Geolocation */
}
.no-geolocation #someElem {
   /* only apply this if the browser DOES NOT support Geolocation */
}

Keep in mind that you should always progressively enhance, so rather than the above example (which illustrates the point better), you should write something more like this:

#someElem {
   /* default styles, suitable for both Geolocation support and lack thereof */
}
.geolocation #someElem {
   /* only properties as needed to overwrite the default styling  */
}

Note that Modernizr does rely on JavaScript, so if JS is disabled you wouldn’t get anything. Hence the progressive enhancement approach of #someElem first, as a no-js foundation.

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

The Works for fine

Go to Path

C:\Program Files\Java\jre7\bin> keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Developer\.android\debug.keystore"

Then enter Ketsore Password and job done!!

ReSharper "Cannot resolve symbol" even when project builds

I was having the same issue in my Visual Studio 2015 with Resharper Ultimate and tried the solutions as suggested above, but none worked for me.

Then upgrading Resharper to latest release solved my issue.

HTTP Error 500.19 and error code : 0x80070021

Please <staticContent /> line and erased it from the web.config.

Git 'fatal: Unable to write new index file'

I think some background backup solutions like Google Backup and Sync block access to the index file. I closed the application and Sourcetree had no issues at all. Seems that Dropbox does the same (@tonymayoral).

How can I send large messages with Kafka (over 15MB)?

You need to adjust three (or four) properties:

  • Consumer side:fetch.message.max.bytes - this will determine the largest size of a message that can be fetched by the consumer.
  • Broker side: replica.fetch.max.bytes - this will allow for the replicas in the brokers to send messages within the cluster and make sure the messages are replicated correctly. If this is too small, then the message will never be replicated, and therefore, the consumer will never see the message because the message will never be committed (fully replicated).
  • Broker side: message.max.bytes - this is the largest size of the message that can be received by the broker from a producer.
  • Broker side (per topic): max.message.bytes - this is the largest size of the message the broker will allow to be appended to the topic. This size is validated pre-compression. (Defaults to broker's message.max.bytes.)

I found out the hard way about number 2 - you don't get ANY exceptions, messages, or warnings from Kafka, so be sure to consider this when you are sending large messages.

How to select a value in dropdown javascript?

function setSelectedIndex(s, v) {
    for ( var i = 0; i < s.options.length; i++ ) {
        if ( s.options[i].value == v ) {
            s.options[i].selected = true;
            return;
        }
    }
}

Where s is the dropdown and v is the value

HTML meta tag for content language

As a complement to other answers note that you can also put the lang attribute on various HTML tags inside a page. For example to give a hint to the spellchecker that the input text should be in english:

<input ... spellcheck="true" lang="en"> ...

See: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang

The maximum recursion 100 has been exhausted before statement completion

Specify the maxrecursion option at the end of the query:

...
from EmployeeTree
option (maxrecursion 0)

That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.

Authenticate with GitHub using a token

The password that you use to login to github.com portal does not work in VS Code CLI/Shell. You should copy PAT Token from URL https://github.com/settings/tokens by generating new token and paste that string in CLI as password.

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

Yet another Googlemare Landmine.... Somehow, if you mess up, the icon line on your .gen file dies. (Empirical proof of mine after struggling 2 hours)

Insert a new icon 72x72 icon on the hdpi folder with a different name from the original, and update the name on the manifest also.

The icon somehow resurrects on the Gen file and voila!! time to move on.

Why do you create a View in a database?

It can function as a good "middle man" between your ORM and your tables.

Example:

We had a Person table that we needed to change the structure on it so the column SomeColumn was going to be moved to another table and would have a one to many relationship to.

However, the majority of the system, with regards to the Person, still used the SomeColumn as a single thing, not many things. We used a view to bring all of the SomeColumns together and put it in the view, which worked out nicely.

This worked because the data layer had changed, but the business requirement hadn't fundamentally changed, so the business objects didn't need to change. If the business objects had to change I don't think this would have been a viable solution, but views definitely function as a good mid point.

Fixing a systemd service 203/EXEC failure (no such file or directory)

When this happened to me it was because my script had DOS line endings, which always messes up the shebang line at the top of the script. I changed it to Unix line endings and it worked.

Passing multiple variables to another page in url

Short answer:

This is what you are trying to do but it poses some security and encoding problems so don't do it.

$url = "http://localhost/main.php?email=" . $email_address . "&eventid=" . $event_id;

Long answer:

All variables in querystrings need to be urlencoded to ensure proper transmission. You should never pass a user's personal information in a url because urls are very leaky. Urls end up in log files, browsing histories, referal headers, etc. The list goes on and on.

As for proper url encoding, it can be achieved using either urlencode() or http_build_query(). Either one of these should work:

$url = "http://localhost/main.php?email=" . urlencode($email_address) . "&eventid=" . urlencode($event_id);

or

$vars = array('email' => $email_address, 'event_id' => $event_id);
$querystring = http_build_query($vars);
$url = "http://localhost/main.php?" . $querystring;

Additionally, if $event_id is in your session, you don't actually need to pass it around in order to access it from different pages. Just call session_start() and it should be available.

Could not load type from assembly error

If this error caused by changing the namespace, make sur that the folder of that project is renamed to the same name, and close VS.NET Edit the project which has the problem with Notepad and replace there nodes

"RootNamespace>New_Name_Of_Folder_Of_Your_Project_Namespace"RootNamespace> "AssemblyName>New_Name_Of_Folder_Of_Your_Project_Namespace"AssemblyName>

Xamarin.Forms ListView: Set the highlight color of a tapped item

Here is the purely cross platform and neat way:

1) Define a trigger action

namespace CustomTriggers {
   public class DeselectListViewItemAction:TriggerAction<ListView> {
       protected override void Invoke(ListView sender) {
                sender.SelectedItem = null;
       }
   }
}

2) Apply the above class instance as an EventTrigger action in XAML as below

 <ListView x:Name="YourListView" ItemsSource="{Binding ViewModelItems}">
    <ListView.Triggers>
        <EventTrigger Event="ItemSelected">
            <customTriggers:DeselectListViewItemAction></customTriggers:DeselectListViewItemAction>
        </EventTrigger>
    </ListView.Triggers>
</ListView>

Don't forget to add xmlns:customTriggers="clr-namespace:CustomTriggers;assembly=ProjectAssembly"

Note: Because none of your items are in selected mode, selection styling will not get applied on either of the platforms.

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

This is building off the work Daniel Little did for this question, but taking into account daylight savings time (works for dates 01-01 1902 and greater due to int limit on dateadd function):

We first need to create a table that will store the date ranges for daylight savings time (source: History of time in the United States):

CREATE TABLE [dbo].[CFG_DAY_LIGHT_SAVINGS_TIME](
  [BEGIN_DATE] [datetime] NULL,
  [END_DATE] [datetime] NULL,
  [YEAR_DATE] [smallint] NULL
) ON [PRIMARY]

GO

INSERT INTO CFG_DAY_LIGHT_SAVINGS_TIME VALUES
('2001-04-01 02:00:00.000',   '2001-10-27 01:59:59.997',    2001),
('2002-04-07 02:00:00.000',   '2002-10-26 01:59:59.997',    2002),
('2003-04-06 02:00:00.000',   '2003-10-25 01:59:59.997',    2003),
('2004-04-04 02:00:00.000',   '2004-10-30 01:59:59.997',    2004),
('2005-04-03 02:00:00.000',   '2005-10-29 01:59:59.997',    2005),
('2006-04-02 02:00:00.000',   '2006-10-28 01:59:59.997',    2006),
('2007-03-11 02:00:00.000',   '2007-11-03 01:59:59.997',    2007),
('2008-03-09 02:00:00.000',   '2008-11-01 01:59:59.997',    2008),
('2009-03-08 02:00:00.000',   '2009-10-31 01:59:59.997',    2009),
('2010-03-14 02:00:00.000',   '2010-11-06 01:59:59.997',    2010),
('2011-03-13 02:00:00.000',   '2011-11-05 01:59:59.997',    2011),
('2012-03-11 02:00:00.000',   '2012-11-03 01:59:59.997',    2012),
('2013-03-10 02:00:00.000',   '2013-11-02 01:59:59.997',    2013),
('2014-03-09 02:00:00.000',   '2014-11-01 01:59:59.997',    2014),
('2015-03-08 02:00:00.000',   '2015-10-31 01:59:59.997',    2015),
('2016-03-13 02:00:00.000',   '2016-11-05 01:59:59.997',    2016),
('2017-03-12 02:00:00.000',   '2017-11-04 01:59:59.997',    2017),
('2018-03-11 02:00:00.000',   '2018-11-03 01:59:59.997',    2018),
('2019-03-10 02:00:00.000',   '2019-11-02 01:59:59.997',    2019),
('2020-03-08 02:00:00.000',   '2020-10-31 01:59:59.997',    2020),
('2021-03-14 02:00:00.000',   '2021-11-06 01:59:59.997',    2021),
('2022-03-13 02:00:00.000',   '2022-11-05 01:59:59.997',    2022),
('2023-03-12 02:00:00.000',   '2023-11-04 01:59:59.997',    2023),
('2024-03-10 02:00:00.000',   '2024-11-02 01:59:59.997',    2024),
('2025-03-09 02:00:00.000',   '2025-11-01 01:59:59.997',    2025),
('1967-04-30 02:00:00.000',   '1967-10-29 01:59:59.997',    1967),
('1968-04-28 02:00:00.000',   '1968-10-27 01:59:59.997',    1968),
('1969-04-27 02:00:00.000',   '1969-10-26 01:59:59.997',    1969),
('1970-04-26 02:00:00.000',   '1970-10-25 01:59:59.997',    1970),
('1971-04-25 02:00:00.000',   '1971-10-31 01:59:59.997',    1971),
('1972-04-30 02:00:00.000',   '1972-10-29 01:59:59.997',    1972),
('1973-04-29 02:00:00.000',   '1973-10-28 01:59:59.997',    1973),
('1974-01-06 02:00:00.000',   '1974-10-27 01:59:59.997',    1974),
('1975-02-23 02:00:00.000',   '1975-10-26 01:59:59.997',    1975),
('1976-04-25 02:00:00.000',   '1976-10-31 01:59:59.997',    1976),
('1977-04-24 02:00:00.000',   '1977-10-31 01:59:59.997',    1977),
('1978-04-30 02:00:00.000',   '1978-10-29 01:59:59.997',    1978),
('1979-04-29 02:00:00.000',   '1979-10-28 01:59:59.997',    1979),
('1980-04-27 02:00:00.000',   '1980-10-26 01:59:59.997',    1980),
('1981-04-26 02:00:00.000',   '1981-10-25 01:59:59.997',    1981),
('1982-04-25 02:00:00.000',   '1982-10-25 01:59:59.997',    1982),
('1983-04-24 02:00:00.000',   '1983-10-30 01:59:59.997',    1983),
('1984-04-29 02:00:00.000',   '1984-10-28 01:59:59.997',    1984),
('1985-04-28 02:00:00.000',   '1985-10-27 01:59:59.997',    1985),
('1986-04-27 02:00:00.000',   '1986-10-26 01:59:59.997',    1986),
('1987-04-05 02:00:00.000',   '1987-10-25 01:59:59.997',    1987),
('1988-04-03 02:00:00.000',   '1988-10-30 01:59:59.997',    1988),
('1989-04-02 02:00:00.000',   '1989-10-29 01:59:59.997',    1989),
('1990-04-01 02:00:00.000',   '1990-10-28 01:59:59.997',    1990),
('1991-04-07 02:00:00.000',   '1991-10-27 01:59:59.997',    1991),
('1992-04-05 02:00:00.000',   '1992-10-25 01:59:59.997',    1992),
('1993-04-04 02:00:00.000',   '1993-10-31 01:59:59.997',    1993),
('1994-04-03 02:00:00.000',   '1994-10-30 01:59:59.997',    1994),
('1995-04-02 02:00:00.000',   '1995-10-29 01:59:59.997',    1995),
('1996-04-07 02:00:00.000',   '1996-10-27 01:59:59.997',    1996),
('1997-04-06 02:00:00.000',   '1997-10-26 01:59:59.997',    1997),
('1998-04-05 02:00:00.000',   '1998-10-25 01:59:59.997',    1998),
('1999-04-04 02:00:00.000',   '1999-10-31 01:59:59.997',    1999),
('2000-04-02 02:00:00.000',   '2000-10-29 01:59:59.997',    2000)
GO

Now we create a function for each American timezone. This is assuming the unix time is in milliseconds. If it is in seconds, remove the /1000 from the code:

Pacific

create function [dbo].[UnixTimeToPacific] 
 (@unixtime bigint)
   returns datetime
   as
   begin
     declare @pacificdatetime datetime
     declare @interimdatetime datetime = dateadd(s, @unixtime/1000, '1970-01-01')
     select  @pacificdatetime =  dateadd(hour,case when @interimdatetime between begin_date and end_date then -7 else -8 end  ,@interimdatetime)
     from cfg_day_light_savings_time  where  year_date = datepart(year,@interimdatetime)
     if @pacificdatetime is null 
       select @pacificdatetime= dateadd(hour, -7, @interimdatetime)
return @pacificdatetime    
end

Eastern

create function [dbo].[UnixTimeToEastern] 
 (@unixtime bigint)
   returns datetime
   as
   begin
     declare @easterndatetime datetime
     declare @interimdatetime datetime = dateadd(s, @unixtime/1000, '1970-01-01')
     select  @easterndatetime =  dateadd(hour,case when @interimdatetime between begin_date and end_date then -4 else -5 end  ,@interimdatetime)
     from cfg_day_light_savings_time  where  year_date = datepart(year,@interimdatetime)
     if @easterndatetime is null 
       select @easterndatetime= dateadd(hour, -4, @interimdatetime)
return @easterndatetime    
end

Central

create function [dbo].[UnixTimeToCentral] 
 (@unixtime bigint)
   returns datetime
   as
   begin
     declare @centraldatetime datetime
     declare @interimdatetime datetime = dateadd(s, @unixtime/1000, '1970-01-01')
     select  @centraldatetime =  dateadd(hour,case when @interimdatetime between begin_date and end_date then -5 else -6 end  ,@interimdatetime)
     from cfg_day_light_savings_time  where  year_date = datepart(year,@interimdatetime)
     if @centraldatetime is null 
       select @centraldatetime= dateadd(hour, -5, @interimdatetime)
return @centraldatetime    
end

Mountain

create function [dbo].[UnixTimeToMountain] 
 (@unixtime bigint)
   returns datetime
   as
   begin
     declare @mountaindatetime datetime
     declare @interimdatetime datetime = dateadd(s, @unixtime/1000, '1970-01-01')
     select  @mountaindatetime =  dateadd(hour,case when @interimdatetime between begin_date and end_date then -6 else -7 end  ,@interimdatetime)
     from cfg_day_light_savings_time  where  year_date = datepart(year,@interimdatetime)
     if @mountaindatetime is null 
       select @mountaindatetime= dateadd(hour, -6, @interimdatetime)
return @mountaindatetime    
end

Hawaii

create function [dbo].[UnixTimeToHawaii] 
 (@unixtime bigint)
   returns datetime
   as
   begin
     declare @hawaiidatetime datetime
     declare @interimdatetime datetime = dateadd(s, @unixtime/1000, '1970-01-01')
     select  @hawaiidatetime =  dateadd(hour,-10,@interimdatetime)
     from cfg_day_light_savings_time  where  year_date = datepart(year,@interimdatetime)

return @hawaiidatetime    
end

Arizona

create function [dbo].[UnixTimeToArizona] 
 (@unixtime bigint)
   returns datetime
   as
   begin
     declare @arizonadatetime datetime
     declare @interimdatetime datetime = dateadd(s, @unixtime/1000, '1970-01-01')
     select  @arizonadatetime =  dateadd(hour,-7,@interimdatetime)
     from cfg_day_light_savings_time  where  year_date = datepart(year,@interimdatetime)

return @arizonadatetime    
end

Alaska

create function [dbo].[UnixTimeToAlaska] 
 (@unixtime bigint)
   returns datetime
   as
   begin
     declare @alaskadatetime datetime
     declare @interimdatetime datetime = dateadd(s, @unixtime/1000, '1970-01-01')
     select  @alaskadatetime =  dateadd(hour,case when @interimdatetime between begin_date and end_date then -8 else -9 end  ,@interimdatetime)
     from cfg_day_light_savings_time  where  year_date = datepart(year,@interimdatetime)
     if @alaskadatetime is null 
       select @alaskadatetime= dateadd(hour, -8, @interimdatetime)
return @alaskadatetime    
end

cmake and libpthread

target_compile_options solution above is wrong, it won't link the library.

Use:

SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")

OR

target_link_libraries(XXX PUBLIC pthread)

OR

set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)

Duplicate headers received from server

Just put a pair of double quotes around your file name like this:

this.Response.AddHeader("Content-disposition", $"attachment; filename=\"{outputFileName}\"");

Copy Paste Values only( xlPasteValues )

You may use this too

Sub CopyPaste()
Sheet1.Range("A:A").Copy

Sheet2.Activate
col = 1
Do Until Sheet2.Cells(1, col) = ""
    col = col + 1
Loop

Sheet2.Cells(1, col).PasteSpecial xlPasteValues
End Sub

How to turn off page breaks in Google Docs?

The only way to remove the dotted line (to my knowledge) is with css hacking using plugin.

  • Install the User CSS (or User JS & CSS) plugin, which allows adding CSS rules per site.

  • Once on Google Docs, click the plugins icon, toggle the OFF to ON button, and add the following css code:

.

.kix-page-compact::before{
    border-top: none;
}

enter image description here

Should work like a charm.

How to dynamically change header based on AngularJS partial view?

None of these answers seemed intuitive enough, so I created a small directive to do this. This way allows you to declare the title in the page, where one would normally do it, and allows it to be dynamic as well.

angular.module('myModule').directive('pageTitle', function() {
    return {
        restrict: 'EA',
        link: function($scope, $element) {
            var el = $element[0];
            el.hidden = true; // So the text not actually visible on the page

            var text = function() {
                return el.innerHTML;
            };
            var setTitle = function(title) {
                document.title = title;
            };
            $scope.$watch(text, setTitle);
        }
    };
});

You'll need to of course change the module name to match yours.

To use it, just throw this in your view, much as you would do for a regular <title> tag:

<page-title>{{titleText}}</page-title>

You can also just include plain text if you don't need it to by dynamic:

<page-title>Subpage X</page-title>

Alternatively, you can use an attribute, to make it more IE-friendly:

<div page-title>Title: {{titleText}}</div>

You can put whatever text you want in the tag of course, including Angular code. In this example, it will look for $scope.titleText in whichever controller the custom-title tag is currently in.

Just make sure you don't have multiple page-title tags on your page, or they'll clobber each other.

Plunker example here http://plnkr.co/edit/nK63te7BSbCxLeZ2ADHV. You'll have to download the zip and run it locally in order to see the title change.

Vertically aligning text next to a radio button

Use it inside a label. Use vertical-align to set it to various values -- bottom, baseline, middle etc.

http://jsfiddle.net/UnA6j/5/

How to solve "Fatal error: Class 'MySQLi' not found"?

Sounds like you just need to install MySQLi.

If you think you've done that and still have a problem, please post your operating system and anything else that might help diagnose it further.

php.ini & SMTP= - how do you pass username & password

  1. Install Postfix (Sendmail-compatible).
  2. Edit /etc/postfix/main.cf to read:
#Relay config
relayhost = smtp.server.net
smtp_use_tls=yes
smtp_sasl_auth_enable=yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/postfix/cacert.pem
smtp_sasl_security_options = noanonymous
  1. Create /etc/postfix/sasl_passwd, enter:
smtp.server.net username:password
  1. Type # /usr/sbin/postmap sasl_passwd

  2. Then run: service postfix reload

Now PHP will run mail as usual with the sendmail -t -i command and Postfix will intercept it and relay it to your SMTP server that you provided.

regex with space and letters only?

Try this demo please: http://jsfiddle.net/sgpw2/

Thanks Jan for spaces \s rest there is some good detail in this link:

http://www.jquery4u.com/syntax/jquery-basic-regex-selector-examples/#.UHKS5UIihlI

Hope it fits your need :)

code

 $(function() {

    $("#field").bind("keyup", function(event) {
        var regex = /^[a-zA-Z\s]+$/;
        if (regex.test($("#field").val())) {
            $('.validation').html('valid');
        } else {
            $('.validation').html("FAIL regex");
        }
    });
});?

Angular.js: set element height on page load

To avoid check on every digest cycle, we can change the height of the div when the window height gets changed.

http://jsfiddle.net/zbjLh/709/

<div ng-app="miniapp" resize>
  Testing
</div>

.

var app = angular.module('miniapp', []);

app.directive('resize', function ($window) {
    return function (scope, element) {
        var w = angular.element($window);
        var changeHeight = function() {element.css('height', (w.height() -20) + 'px' );};  
            w.bind('resize', function () {        
              changeHeight();   // when window size gets changed             
        });  
        changeHeight(); // when page loads          
    }
})

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

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

You probably are looking for AddReference dialog accessible from Project Context Menu (right click..)

From there you can reference dll's, after which you can reference namespaces that you need in your code.

How do I get countifs to select all non-blank cells in Excel?

The best way I've found is to use a combination "IF" and "ISERROR" statement:

=IF(ISERROR(COUNTIF(E5:E356,1)),"---",COUNTIF(E5:E356,1)

This formula will either fill the cell with three dashes (---) if there would be an error (if there is no data in the cells to count/average/etc), or with the count (if there was data in the cells)

The nice part about this logical query is that it will exclude entirely blank rows/columns by making them textual values of "---", so if you have a row counting (or averaging), which was then counted (or averaged) in another spot in your formula, the second formula won't respond with an error because it will ignore the "---" cell.

How do you overcome the svn 'out of date' error?

There is at least one other cause of the message "out of date" error. In my case the problem was .svn/dir-props which was created by running "svn propset svn:ignore -F .gitignore ." for the first time. Deleting .svn/dir-props seems like a bad idea and can cause other errors, so it may be best to use "svn propdel" to clean up the errant "svn propset".

# Normal state, works fine.
> svn commit -m"bump"  
Sending        eac_cpf.xsl
Transmitting file data .
Committed revision 509.

# Set a property, but forget to commit.
> svn propset svn:ignore -F .gitignore .
property 'svn:ignore' set on '.'

# Edit a file. Should have committed before the edit.
> svn commit -m"bump"                   
Sending        .
svn: Commit failed (details follow):
svn: File or directory '.' is out of date; try updating
svn: resource out of date; try updating

# Delete the property.
> svn propdel svn:ignore .              
property 'svn:ignore' deleted from '.'.

# Now the commit works fine.
> svn commit -m"bump"     
Sending        eac_cpf.xsl
Transmitting file data .
Committed revision 510.

Figuring out whether a number is a Double in Java

Use regular expression to achieve this task. Please refer the below code.

public static void main(String[] args) {
    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter your content: ");
        String data = reader.readLine();            
        boolean b1 = Pattern.matches("^\\d+$", data);
        boolean b2 = Pattern.matches("[0-9a-zA-Z([+-]?\\d*\\.+\\d*)]*", data); 
        boolean b3 = Pattern.matches("^([+-]?\\d*\\.+\\d*)$", data);
        if(b1) {
            System.out.println("It is integer.");
        } else if(b2) {
            System.out.println("It is String. ");
        } else if(b3) {
            System.out.println("It is Float. ");
        }           
    } catch (IOException ex) {
        Logger.getLogger(TypeOF.class.getName()).log(Level.SEVERE, null, ex);
    }
}

How to copy a directory structure but only include certain files (using windows batch files)

Thanks To Previous Answers. :)

This script named "r4k4copy.cmd":

@echo off
for %%p in (SOURCE_DIR DEST_DIR FILENAMES_TO_COPY) do set %%p=
cls
echo :: Copy Files Including Folder Tree
echo :: http://stackoverflow.com
rem     /questions/472692/how-to-copy
rem     -a-directory-structure-but-only
rem     -include-certain-files-using-windows
echo :: ReScripted by r4k4
echo.
if "%1"=="" goto :NoParam
if "%2"=="" goto :NoParam
if "%3"=="" goto :NoParam
setlocal enabledelayedexpansion
set SOURCE_DIR=%1
set DEST_DIR=%2
set FILENAMES_TO_COPY=%3
for /R "%SOURCE_DIR%" %%F IN (%FILENAMES_TO_COPY%) do (
if exist "%%F" (
set FILE_DIR=%%~dpF
set FILE_INTERMEDIATE_DIR=!FILE_DIR:%SOURCE_DIR%=!
xcopy /E /I /Y "%%F" "%DEST_DIR%!FILE_INTERMEDIATE_DIR!"
)
)
goto :eof
:NoParam
echo.
echo Syntax: %0 [Source_DIR] [Dest_DIR] [FileName]
echo Eg.   : %0 D:\Root E:\Root\Lev1\Lev2\Lev3 *.JPG
echo Means : Copy *.JPG from D:\Root to E:\Root\Lev1\Lev2\Lev3

It accepts variable of "Source", "Destination", and "FileName". It also can only copying specified type of files or selective filenames.

Any improvement are welcome. :)

Excel - programm cells to change colour based on another cell

Select ColumnB and as two CF formula rules apply:

Green: =AND(B1048576="X",B1="Y")

Red: =AND(B1048576="X",B1="W")

enter image description here

JSONObject - How to get a value?

This may be helpful while searching keys present in nested objects and nested arrays. And this is a generic solution to all cases.

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MyClass
{
    public static Object finalresult = null;
    public static void main(String args[]) throws JSONException
    {
        System.out.println(myfunction(myjsonstring,key));
    }

    public static Object myfunction(JSONObject x,String y) throws JSONException
    {
        JSONArray keys =  x.names();
        for(int i=0;i<keys.length();i++)
        {
            if(finalresult!=null)
            {
                return finalresult;                     //To kill the recursion
            }

            String current_key = keys.get(i).toString();

            if(current_key.equals(y))
            {
                finalresult=x.get(current_key);
                return finalresult;
            }

            if(x.get(current_key).getClass().getName().equals("org.json.JSONObject"))
            {
                myfunction((JSONObject) x.get(current_key),y);
            }
            else if(x.get(current_key).getClass().getName().equals("org.json.JSONArray"))
            {
                for(int j=0;j<((JSONArray) x.get(current_key)).length();j++)
                {
                    if(((JSONArray) x.get(current_key)).get(j).getClass().getName().equals("org.json.JSONObject"))
                    {
                        myfunction((JSONObject)((JSONArray) x.get(current_key)).get(j),y);
                    }
                }
            }
        }
        return null;
    }
}

Possibilities:

  1. "key":"value"
  2. "key":{Object}
  3. "key":[Array]

Logic :

  • I check whether the current key and search key are the same, if so I return the value of that key.
  • If it is an object, I send the value recursively to the same function.
  • If it is an array, I check whether it contains an object, if so I recursively pass the value to the same function.

Removing duplicate characters from a string

As string is a list of characters, converting it to dictionary will remove all duplicates and will retain the order.

"".join(list(dict.fromkeys(foo)))

CSS hide scroll bar if not needed

Set overflow-y property to auto, or remove the property altogether if it is not inherited.

'"SDL.h" no such file or directory found' when compiling

Most times SDL is in /usr/include/SDL. If so then your #include <SDL.h> directive is wrong, it should be #include <SDL/SDL.h>.

An alternative for that is adding the /usr/include/SDL directory to your include directories. To do that you should add -I/usr/include/SDL to the compiler flags...

If you are using an IDE this should be quite easy too...

How to change background and text colors in Sublime Text 3

  1. Go to the preferences
  2. Click on color scheme
  3. Choose your color scheme
  4. I chose plastic, for my case.

Converting JSON to XML in Java

If you have a valid dtd file for the xml then you can easily transform json to xml and xml to json using the eclipselink jar binary.

Refer this: http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html

The article also has a sample project (including the supporting third party jars) as a zip file which can be downloaded for reference purpose.

Getting the SQL from a Django QuerySet

The accepted answer did not work for me when using Django 1.4.4. Instead of the raw query, a reference to the Query object was returned: <django.db.models.sql.query.Query object at 0x10a4acd90>.

The following returned the query:

>>> queryset = MyModel.objects.all()
>>> queryset.query.__str__()

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

You can catch that exception and return whatever you want from there.

open(target, 'a').close()
scores = {};
try:
    with open(target, "rb") as file:
        unpickler = pickle.Unpickler(file);
        scores = unpickler.load();
        if not isinstance(scores, dict):
            scores = {};
except EOFError:
    return {}

How can I format a nullable DateTime with ToString()?

Simple generic extensions

public static class Extensions
{

    /// <summary>
    /// Generic method for format nullable values
    /// </summary>
    /// <returns>Formated value or defaultValue</returns>
    public static string ToString<T>(this Nullable<T> nullable, string format, string defaultValue = null) where T : struct
    {
        if (nullable.HasValue)
        {
            return String.Format("{0:" + format + "}", nullable.Value);
        }

        return defaultValue;
    }
}

PHP - auto refreshing page

you can use

<meta http-equiv="refresh" content="10" > 

just add it after the head tags

where 10 is the time your page will refresh itself

Reading CSV files using C#

private static DataTable ConvertCSVtoDataTable(string strFilePath)
        {
            DataTable dt = new DataTable();
            using (StreamReader sr = new StreamReader(strFilePath))
            {
                string[] headers = sr.ReadLine().Split(',');
                foreach (string header in headers)
                {
                    dt.Columns.Add(header);
                }
                while (!sr.EndOfStream)
                {
                    string[] rows = sr.ReadLine().Split(',');
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < headers.Length; i++)
                    {
                        dr[i] = rows[i];
                    }
                    dt.Rows.Add(dr);
                }

            }

            return dt;
        }

        private static void WriteToDb(DataTable dt)
        {
            string connectionString =
                "Data Source=localhost;" +
                "Initial Catalog=Northwind;" +
                "Integrated Security=SSPI;";

            using (SqlConnection con = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("spInsertTest", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.Add("@policyID", SqlDbType.Int).Value = 12;
                        cmd.Parameters.Add("@statecode", SqlDbType.VarChar).Value = "blagh2";
                        cmd.Parameters.Add("@county", SqlDbType.VarChar).Value = "blagh3";

                        con.Open();
                        cmd.ExecuteNonQuery();
                    }
                }

         }

How do I add an integer value with javascript (jquery) to a value that's returning a string?

The integer is being converted into a string rather than vice-versa. You want:

var newValue = parseInt(currentValue) + 1

How do I profile memory usage in Python?

A simple example to calculate the memory usage of a block of codes / function using memory_profile, while returning result of the function:

import memory_profiler as mp

def fun(n):
    tmp = []
    for i in range(n):
        tmp.extend(list(range(i*i)))
    return "XXXXX"

calculate memory usage before running the code then calculate max usage during the code:

start_mem = mp.memory_usage(max_usage=True)
res = mp.memory_usage(proc=(fun, [100]), max_usage=True, retval=True) 
print('start mem', start_mem)
print('max mem', res[0][0])
print('used mem', res[0][0]-start_mem)
print('fun output', res[1])

calculate usage in sampling points while running function:

res = mp.memory_usage((fun, [100]), interval=.001, retval=True)
print('min mem', min(res[0]))
print('max mem', max(res[0]))
print('used mem', max(res[0])-min(res[0]))
print('fun output', res[1])

Credits: @skeept

How to check if a table contains an element in Lua?

You can put the values as the table's keys. For example:

function addToSet(set, key)
    set[key] = true
end

function removeFromSet(set, key)
    set[key] = nil
end

function setContains(set, key)
    return set[key] ~= nil
end

There's a more fully-featured example here.

Import XXX cannot be resolved for Java SE standard classes

If the project is Maven, you can try this way :

  1. right click the "Maven Dependencies"-->"Build Path"-->"Remove from the build path";
  2. right click the project ,navigate to "Maven"--->"Update project....";

Then the import issue should be solved .

Redirect all output to file using Bash on Linux?

If the server is started on the same terminal, then it's the server's stderr that is presumably being written to the terminal and which you are not capturing.

The best way to capture everything would be to run:

script output.txt

before starting up either the server or the client. This will launch a new shell with all terminal output redirected out output.txt as well as the terminal. Then start the server from within that new shell, and then the client. Everything that you see on the screen (both your input and the output of everything writing to the terminal from within that shell) will be written to the file.

When you are done, type "exit" to exit the shell run by the script command.

AngularJS : The correct way of binding to a service properties

I would rather keep my watchers a less as possible. My reason is based on my experiences and one might argue it theoretically.
The issue with using watchers is that you can use any property on scope to call any of the methods in any component or service you like.
In a real world project, pretty soon you'll end up with a non-tracable (better said hard to trace) chain of methods being called and values being changed which specially makes the on-boarding process tragic.

How to get PHP $_GET array?

You can specify an array in your HTML this way:

<input type="hidden" name="id[]" value="1"/>
<input type="hidden" name="id[]" value="2"/>
<input type="hidden" name="id[]" value="3"/>

This will result in this $_GET array in PHP:

array(
  'id' => array(
    0 => 1,
    1 => 2,
    2 => 3
  )
)

Of course, you can use any sort of HTML input, here. The important thing is that all inputs whose values you want in the 'id' array have the name id[].

Understanding the map function

The map() function is there to apply the same procedure to every item in an iterable data structure, like lists, generators, strings, and other stuff.

Let's look at an example: map() can iterate over every item in a list and apply a function to each item, than it will return (give you back) the new list.

Imagine you have a function that takes a number, adds 1 to that number and returns it:

def add_one(num):
  new_num = num + 1
  return new_num

You also have a list of numbers:

my_list = [1, 3, 6, 7, 8, 10]

if you want to increment every number in the list, you can do the following:

>>> map(add_one, my_list)
[2, 4, 7, 8, 9, 11]

Note: At minimum map() needs two arguments. First a function name and second something like a list.

Let's see some other cool things map() can do. map() can take multiple iterables (lists, strings, etc.) and pass an element from each iterable to a function as an argument.

We have three lists:

list_one = [1, 2, 3, 4, 5]
list_two = [11, 12, 13, 14, 15]
list_three = [21, 22, 23, 24, 25]

map() can make you a new list that holds the addition of elements at a specific index.

Now remember map(), needs a function. This time we'll use the builtin sum() function. Running map() gives the following result:

>>> map(sum, list_one, list_two, list_three)
[33, 36, 39, 42, 45]

REMEMBER:
In Python 2 map(), will iterate (go through the elements of the lists) according to the longest list, and pass None to the function for the shorter lists, so your function should look for None and handle them, otherwise you will get errors. In Python 3 map() will stop after finishing with the shortest list. Also, in Python 3, map() returns an iterator, not a list.

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy and JoinColumn were not working).

I think you were trying to do a bi-directional relationships.

First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:

(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    private List<Post> posts;
}


public class Post {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

By doing so, the table for Post will have a column user_id which store the relationship. Hibernate is getting the relationship by the user in Post (Instead of posts in User. You will notice the difference if you have Post's user but missing User's posts).

You have mentioned mappedBy and JoinColumn is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.


Edit:

Just a bit extra information on the use of mappedBy as it is usually confusing at first. In mappedBy, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

Hello Googlers from the future.

On MacOS >= High Sierra, the SSH key is no longer saved to the KeyChain because of reasons.

Using ssh-add -K no longer survives restarts as well.

Here are 3 possible solutions.

I've used the first method successfully. I've created a file called config in ~/.ssh:

Host *
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/id_rsa

How to count the number of true elements in a NumPy bool array

That question solved a quite similar question for me and I thought I should share :

In raw python you can use sum() to count True values in a list :

>>> sum([True,True,True,False,False])
3

But this won't work :

>>> sum([[False, False, True], [True, False, True]])
TypeError...

How can you customize the numbers in an ordered list?

You can also specify your own numbers in the HTML - e.g. if the numbers are being provided by a database:

_x000D_
_x000D_
ol {_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
ol>li:before {_x000D_
  content: attr(seq) ". ";_x000D_
}
_x000D_
<ol>_x000D_
  <li seq="1">Item one</li>_x000D_
  <li seq="20">Item twenty</li>_x000D_
  <li seq="300">Item three hundred</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

The seq attribute is made visible using a method similar to that given in other answers. But instead of using content: counter(foo), we use content: attr(seq).

Demo in CodePen with more styling

How do I delete everything below row X in VBA/Excel?

Another option is Sheet1.Rows(x & ":" & Sheet1.Rows.Count).ClearContents (or .Clear). The reason you might want to use this method instead of .Delete is because any cells with dependencies in the deleted range (e.g. formulas that refer to those cells, even if empty) will end up showing #REF. This method will preserve formula references to the cleared cells.

How to pass Multiple Parameters from ajax call to MVC Controller

In addition to posts by @xdumain, I prefer creating data object before ajax call so you can debug it.

var dataObject = JSON.stringify({
                    'input': $('#myInput').val(),
                    'name': $('#myName').val(),
                });

Now use it in ajax call

$.ajax({
          url: "/Home/SaveChart",
          type: 'POST',
          async: false,
          dataType: 'json',
          contentType: 'application/json',
          data: dataObject,
          success: function (data) { },
          error: function (xhr) { }            )};

Using Java with Microsoft Visual Studio 2012

Using Visual Studio IDE for porting Java to C#:

Currently I am using Visual Studio IDE environment for porting codes from Java to C#. Why? Java has a huge libraries and C# enables the access to the UWP ecosystem.

For supporting editing and debugging as well as examining Java Bytecode (disassembly), you could try:

For supporting Android (Java/C++) development, you could try:

cor shows only NA or 1 for correlations - Why?

NAs also appear if there are attributes with zero variance (with all elements equal); see for instance:

cor(cbind(a=runif(10),b=rep(1,10)))

which returns:

   a  b
a  1 NA
b NA  1
Warning message:
In cor(cbind(a = runif(10), b = rep(1, 10))) :
  the standard deviation is zero

How to use a wildcard in the classpath to add multiple jars?

From: http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html

Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

This should work in Java6, not sure about Java5

(If it seems it does not work as expected, try putting quotes. eg: "foo/*")

Using :focus to style outer div?

While this can't be achieved with CSS/HTML alone, it can be achieved with JavaScript (without need of a library):

var textareas = document.getElementsByTagName('textarea');

for (i=0;i<textareas.length;i++){
    // you can omit the 'if' if you want to style the parent node regardless of its
    // element type
    if (textareas[i].parentNode.tagName.toString().toLowerCase() == 'div') {
        textareas[i].onfocus = function(){
            this.parentNode.style.borderStyle = 'solid';
        }
        textareas[i].onblur = function(){
            this.parentNode.style.borderStyle = 'dashed';
        }
    }
}

JS Fiddle demo.

Incidentally, with a library, such as jQuery, the above could be condensed down to:

$('textarea').focus(
    function(){
        $(this).parent('div').css('border-style','solid');
    }).blur(
    function(){
        $(this).parent('div').css('border-style','dashed');
    });

JS Fiddle demo.

References:

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

Set-ExecutionPolicy Unrestricted -Scope CurrentUser

This will set the execution policy for the current user (stored in HKEY_CURRENT_USER) rather than the local machine (HKEY_LOCAL_MACHINE). This is useful if you don't have administrative control over the computer.

Why are C# 4 optional parameters defined on interface not enforced on implementing class?

An optional parameter is just tagged with an attribute. This attribute tells the compiler to insert the default value for that parameter at the call-site.

The call obj2.TestMethod(); is replaced by obj2.TestMethod(false); when the C# code gets compiled to IL, and not at JIT-time.

So in a way it's always the caller providing the default value with optional parameters. This also has consequences on binary versioning: If you change the default value but don't recompile the calling code it will continue to use the old default value.

On the other hand, this disconnect means you can't always use the concrete class and the interface interchangeably.

You already can't do that if the interface method was implemented explicitly.

How to import csv file in PHP?

   $filename=mktime().'_'.$_FILES['import']['name'];

      $path='common/csv/'.$filename;

    if(move_uploaded_file($_FILES['import']['tmp_name'],$path))
{

if(mysql_query("load data local infile '".$path."' INTO TABLE tbl_customer FIELDS TERMINATED BY ',' enclosed by '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES (`location`, `maildropdate`,`contact_number`,`first_name`,`mname`,`lastname`,`suffix`,`address`,`city`,`state`,`zip`)"))

    {
      echo "imported successfully";

}

echo "<br>"."Uploaded Successfully".$path;

}

look here for futher info

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

None of the answers to date mention the effect of the innodb_page_size parameter. Possibly because changing this parameter was not a supported operation prior to MySQL 5.7.6. From the documentation:

The maximum row length, except for variable-length columns (VARBINARY, VARCHAR, BLOB and TEXT), is slightly less than half of a database page for 4KB, 8KB, 16KB, and 32KB page sizes. For example, the maximum row length for the default innodb_page_size of 16KB is about 8000 bytes. For an InnoDB page size of 64KB, the maximum row length is about 16000 bytes. LONGBLOB and LONGTEXT columns must be less than 4GB, and the total row length, including BLOB and TEXT columns, must be less than 4GB.

Note that increasing the page size is not without its drawbacks. Again from the documentation:

As of MySQL 5.7.6, 32KB and 64KB page sizes are supported but ROW_FORMAT=COMPRESSED is still unsupported for page sizes greater than 16KB. For both 32KB and 64KB page sizes, the maximum record size is 16KB. For innodb_page_size=32k, extent size is 2MB. For innodb_page_size=64k, extent size is 4MB.

A MySQL instance using a particular InnoDB page size cannot use data files or log files from an instance that uses a different page size. This limitation could affect restore or downgrade operations using data from MySQL 5.6, which does support page sizes other than 16KB.

Error: Jump to case label

JohannesD's answer is correct, but I feel it isn't entirely clear on an aspect of the problem.

The example he gives declares and initializes the variable i in case 1, and then tries to use it in case 2. His argument is that if the switch went straight to case 2, i would be used without being initialized, and this is why there's a compilation error. At this point, one could think that there would be no problem if variables declared in a case were never used in other cases. For example:

switch(choice) {
    case 1:
        int i = 10; // i is never used outside of this case
        printf("i = %d\n", i);
        break;
    case 2:
        int j = 20; // j is never used outside of this case
        printf("j = %d\n", j);
        break;
}

One could expect this program to compile, since both i and j are used only inside the cases that declare them. Unfortunately, in C++ it doesn't compile: as Ciro Santilli ???? ???? ??? explained, we simply can't jump to case 2:, because this would skip the declaration with initialization of i, and even though case 2 doesn't use i at all, this is still forbidden in C++.

Interestingly, with some adjustments (an #ifdef to #include the appropriate header, and a semicolon after the labels, because labels can only be followed by statements, and declarations do not count as statements in C), this program does compile as C:

// Disable warning issued by MSVC about scanf being deprecated
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif

int main() {

    int choice;
    printf("Please enter 1 or 2: ");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            ;
            int i = 10; // i is never used outside of this case
            printf("i = %d\n", i);
            break;
        case 2:
            ;
            int j = 20; // j is never used outside of this case
            printf("j = %d\n", j);
            break;
    }
}

Thanks to an online compiler like http://rextester.com you can quickly try to compile it either as C or C++, using MSVC, GCC or Clang. As C it always works (just remember to set STDIN!), as C++ no compiler accepts it.

Clear contents of cells in VBA using column reference

For anyone like me who came across this and needs a solution that doesn't clear headers, here is the one liner that works for me:

ActiveSheet.Range("A3:A" & Range("A3").End(xlDown).Row).ClearContents

Starts on the third row - change to your liking.

printf with std::string?

Printf is actually pretty good to use if size matters. Meaning if you are running a program where memory is an issue, then printf is actually a very good and under rater solution. Cout essentially shifts bits over to make room for the string, while printf just takes in some sort of parameters and prints it to the screen. If you were to compile a simple hello world program, printf would be able to compile it in less than 60, 000 bits as opposed to cout, it would take over 1 million bits to compile.

For your situation, id suggest using cout simply because it is much more convenient to use. Although, I would argue that printf is something good to know.

How Stuff and 'For Xml Path' work in SQL Server?

I did debugging and finally returned my 'stuffed' query to it it's normal way.

Simply

select * from myTable for xml path('myTable')

gives me contents of the table to write to a log table from a trigger I debug.

Convert date to YYYYMM format

A more efficient method, that uses integer math rather than strings/varchars, that will result in an int type rather than a string type is:

SELECT YYYYMM = (YEAR(GETDATE()) * 100) + MONTH(GETDATE())

Adds two zeros to the right side of the year and then adds the month to the added two zeros.

How can jQuery deferred be used?

You can use a deferred object to make a fluid design that works well in webkit browsers. Webkit browsers will fire resize event for each pixel the window is resized, unlike FF and IE which fire the event only once for each resize. As a result, you have no control over the order in which the functions bound to your window resize event will execute. Something like this solves the problem:

var resizeQueue = new $.Deferred(); //new is optional but it sure is descriptive
resizeQueue.resolve();

function resizeAlgorithm() {
//some resize code here
}

$(window).resize(function() {
    resizeQueue.done(resizeAlgorithm);
});

This will serialize the execution of your code so that it executes as you intended it to. Beware of pitfalls when passing object methods as callbacks to a deferred. Once such method is executed as a callback to deferred, the 'this' reference will be overwritten with reference to the deferred object and will no longer refer to the object the method belongs to.

How to reset par(mfrow) in R

You can reset the mfrow parameter

par(mfrow=c(1,1))

Spring schemaLocation fails when there is no internet connection

Something like this worked for me.

xsi:schemaLocation=
"http://www.springframework.org/schema/beans 
             classpath:org/springframework/beans/factory/xml/spring-beans-3.0.xsd
http://www.springframework.org/schema/context 
             classpath:org/springframework/beans/factory/xml/spring-context-3.0.xsd"

label or @html.Label ASP.net MVC 4

@html.label and @html.textbox are use when you want bind it to your model in a easy way...which cannot be achieve by input etc. in one line

Adding calculated column(s) to a dataframe in pandas

For the second part of your question, you can also use shift, for example:

df['t-1'] = df['t'].shift(1)

t-1 would then contain the values from t one row above.

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

How to get the category title in a post in Wordpress?

Use get_the_category() like this:

<?php
foreach((get_the_category()) as $category) { 
    echo $category->cat_name . ' '; 
} 
?>

It returns a list because a post can have more than one category.

The documentation also explains how to do this from outside the loop.

How to count the number of occurrences of a character in an Oracle varchar value?

I justed faced very similar problem... BUT RegExp_Count couldn't resolved it. How many times string '16,124,3,3,1,0,' contains ',3,'? As we see 2 times, but RegExp_Count returns just 1. Same thing is with ''bbaaaacc' and when looking in it 'aa' - should be 3 times and RegExp_Count returns just 2.

select REGEXP_COUNT('336,14,3,3,11,0,' , ',3,') from dual;
select REGEXP_COUNT('bbaaaacc' , 'aa') from dual;

I lost some time to research solution on web. Couldn't' find... so i wrote my own function that returns TRUE number of occurance. Hope it will be usefull.

CREATE OR REPLACE FUNCTION EXPRESSION_COUNT( pEXPRESSION VARCHAR2, pPHRASE VARCHAR2 ) RETURN NUMBER AS
  vRET NUMBER := 0;
  vPHRASE_LENGTH NUMBER := 0;
  vCOUNTER NUMBER := 0;
  vEXPRESSION VARCHAR2(4000);
  vTEMP VARCHAR2(4000);
BEGIN
  vEXPRESSION := pEXPRESSION;
  vPHRASE_LENGTH := LENGTH( pPHRASE );
  LOOP
    vCOUNTER := vCOUNTER + 1;
    vTEMP := SUBSTR( vEXPRESSION, 1, vPHRASE_LENGTH);
    IF (vTEMP = pPHRASE) THEN        
        vRET := vRET + 1;
    END IF;
    vEXPRESSION := SUBSTR( vEXPRESSION, 2, LENGTH( vEXPRESSION ) - 1);
  EXIT WHEN ( LENGTH( vEXPRESSION ) = 0 ) OR (vEXPRESSION IS NULL);
  END LOOP;
  RETURN vRET;
END;

Playing sound notifications using Javascript?

I wrote a small function that can do it, with the Web Audio API...

var beep = function(duration, type, finishedCallback) {

    if (!(window.audioContext || window.webkitAudioContext)) {
        throw Error("Your browser does not support Audio Context.");
    }

    duration = +duration;

    // Only 0-4 are valid types.
    type = (type % 5) || 0;

    if (typeof finishedCallback != "function") {
        finishedCallback = function() {};   
    }

    var ctx = new (window.audioContext || window.webkitAudioContext);
    var osc = ctx.createOscillator();

    osc.type = type;

    osc.connect(ctx.destination);
    osc.noteOn(0);

    setTimeout(function() {
        osc.noteOff(0);
        finishedCallback();
    }, duration);

};

What is the maximum number of edges in a directed graph with n nodes?

In the graph with self loop

max edges= n*n

such as we have 4 nodes(vertex)

4 nodes = 16 edges= 4*4

Changing ImageView source

If you want to set in imageview an image that is inside the mipmap dirs you can do it like this:

myImageView.setImageDrawable(getResources().getDrawable(R.mipmap.my_picture)

Converting an int into a 4 byte char array (C)

The portable way to do this (ensuring that you get 0x00 0x00 0x00 0xaf everywhere) is to use shifts:

unsigned char bytes[4];
unsigned long n = 175;

bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;

The methods using unions and memcpy() will get a different result on different machines.


The issue you are having is with the printing rather than the conversion. I presume you are using char rather than unsigned char, and you are using a line like this to print it:

printf("%x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);

When any types narrower than int are passed to printf, they are promoted to int (or unsigned int, if int cannot hold all the values of the original type). If char is signed on your platform, then 0xff likely does not fit into the range of that type, and it is being set to -1 instead (which has the representation 0xff on a 2s-complement machine).

-1 is promoted to an int, and has the representation 0xffffffff as an int on your machine, and that is what you see.

Your solution is to either actually use unsigned char, or else cast to unsigned char in the printf statement:

printf("%x %x %x %x\n", (unsigned char)bytes[0],
                        (unsigned char)bytes[1],
                        (unsigned char)bytes[2],
                        (unsigned char)bytes[3]);

String replacement in batch file

You can use the following little trick:

set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%

The call there causes another layer of variable expansion, making it necessary to quote the original % signs but it all works out in the end.

Passing a method parameter using Task.Factory.StartNew

For passing a single integer I agree with Reed Copsey's answer. If in the future you are going to pass more complicated constucts I personally like to pass all my variables as an Anonymous Type. It will look something like this:

foreach(int id in myIdsToCheck)
{
    Task.Factory.StartNew( (Object obj) => 
        {
           var data = (dynamic)obj;
           CheckFiles(data.id, theBlockingCollection,
               cancelCheckFile.Token, 
               TaskCreationOptions.LongRunning, 
               TaskScheduler.Default);
        }, new { id = id }); // Parameter value
}

You can learn more about it in my blog

JavaScript: clone a function

const clonedFunction = Object.assign(() => {}, originalFunction);

Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table

This cannot be done for the table; besides, you even cannot change this default value at all.

The answer is a server variable datetime_format, it is unused.

Android layout replacing a view with another view on run time

it work in my case, oldSensor and newSnsor - oldView and newView:

private void replaceSensors(View oldSensor, View newSensor) {
            ViewGroup parent = (ViewGroup) oldSensor.getParent();

            if (parent == null) {
                return;
            }

            int indexOldSensor = parent.indexOfChild(oldSensor);
            int indexNewSensor = parent.indexOfChild(newSensor);
            parent.removeView(oldSensor);
            parent.addView(oldSensor, indexNewSensor);
            parent.removeView(newSensor);
            parent.addView(newSensor, indexOldSensor);
        }

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

Under dependencyServices nothing of the above helped me, i ended up doing like below:

    class Static_Toast_Android
    {
        private static Context _context
        {
            get { return Android.App.Application.Context; }
        }
        public static void StaticDisplayToast(string message)
        {
            Toast.MakeText(_context, message, ToastLength.Long).Show();
        }
    }
    public class Toast_Android : IToast
    {

        public void DisplayToast(string message)
        {
            Static_Toast_Android.StaticDisplayToast(message);
        }
    }

I must use the "double-class" because an interface cannot be static. L-

How to 'foreach' a column in a DataTable using C#?

This should work:

DataTable dtTable;

MySQLProcessor.DTTable(mysqlCommand, out dtTable);

// On all tables' rows
foreach (DataRow dtRow in dtTable.Rows)
{
    // On all tables' columns
    foreach(DataColumn dc in dtTable.Columns)
    {
      var field1 = dtRow[dc].ToString();
    }
}

Use a LIKE statement on SQL Server XML Datatype

Another option is to search the XML as a string by converting it to a string and then using LIKE. However as a computed column can't be part of a WHERE clause you need to wrap it in another SELECT like this:

SELECT * FROM
    (SELECT *, CONVERT(varchar(MAX), [COLUMNA]) as [XMLDataString] FROM TABLE) x
WHERE [XMLDataString] like '%Test%'

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

When iterating over cell arrays of strings, the loop variable (let's call it f) becomes a single-element cell array. Having to write f{1} everywhere gets tedious, and modifying the loop variable provides a clean workaround.

% This example transposes each field of a struct.
s.a = 1:3;
s.b = zeros(2,3);
s % a: [1 2 3]; b: [2x3 double]
for f = fieldnames(s)'
    s.(f{1}) = s.(f{1})';
end
s % a: [3x1 double]; b: [3x2 double]

% Redefining f simplifies the indexing.
for f = fieldnames(s)'
    f = f{1};
    s.(f) = s.(f)';
end
s % back to a: [1 2 3]; b: [2x3 double]

What is `git push origin master`? Help with git's refs, heads and remotes

Or as a single command:

git push -u origin master:my_test

Pushes the commits from your local master branch to a (possibly new) remote branch my_test and sets up master to track origin/my_test.

Detect iPad users using jQuery?

Although the accepted solution is correct for iPhones, it will incorrectly declare both isiPhone and isiPad to be true for users visiting your site on their iPad from the Facebook app.

The conventional wisdom is that iOS devices have a user agent for Safari and a user agent for the UIWebView. This assumption is incorrect as iOS apps can and do customize their user agent. The main offender here is Facebook.

Compare these user agent strings from iOS devices:

# iOS Safari
iPad: Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7534.48.3
iPhone: Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

# UIWebView
iPad: Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/98176
iPhone: Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/8B117

# Facebook UIWebView
iPad: Mozilla/5.0 (iPad; U; CPU iPhone OS 5_1_1 like Mac OS X; en_US) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.1.1;FBBV/4110.0;FBDV/iPad2,1;FBMD/iPad;FBSN/iPhone OS;FBSV/5.1.1;FBSS/1; FBCR/;FBID/tablet;FBLC/en_US;FBSF/1.0]
iPhone: Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_1_1 like Mac OS X; ru_RU) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.1;FBBV/4100.0;FBDV/iPhone3,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/5.1.1;FBSS/2; tablet;FBLC/en_US]

Note that on the iPad, the Facebook UIWebView's user agent string includes 'iPhone'.

The old way to identify iPhone / iPad in JavaScript:

IS_IPAD = navigator.userAgent.match(/iPad/i) != null;
IS_IPHONE = navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null);

If you were to go with this approach for detecting iPhone and iPad, you would end up with IS_IPHONE and IS_IPAD both being true if a user comes from Facebook on an iPad. That could create some odd behavior!

The correct way to identify iPhone / iPad in JavaScript:

IS_IPAD = navigator.userAgent.match(/iPad/i) != null;
IS_IPHONE = (navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null);
if (IS_IPAD) {
  IS_IPHONE = false;
}

We declare IS_IPHONE to be false on iPads to cover for the bizarre Facebook UIWebView iPad user agent. This is one example of how user agent sniffing is unreliable. The more iOS apps that customize their user agent, the more issues user agent sniffing will have. If you can avoid user agent sniffing (hint: CSS Media Queries), DO IT.

How do I pipe a subprocess call to a text file?

The options for popen can be used in call

args, 
bufsize=0, 
executable=None, 
stdin=None, 
stdout=None, 
stderr=None, 
preexec_fn=None, 
close_fds=False, 
shell=False, 
cwd=None, 
env=None, 
universal_newlines=False, 
startupinfo=None, 
creationflags=0

So...

subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=myoutput)

Then you can do what you want with myoutput (which would need to be a file btw).

Also, you can do something closer to a piped output like this.

dmesg | grep hda

would be:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

There's plenty of lovely, useful info on the python manual page.

How to allow access outside localhost

  • Use ng serve --host<Your IP> --port<Required if any>.

  • ng serve --host=192.111.1.11 --port=4545.

  • You can now see the below line at the end of compilation.

Angular Live Development Server is listening on 192.111.1.11:4545, open your browser on http://192.111.1.11:4545/ **.

How do I encode URI parameter values?

Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.

You said:

For example, given an input:

http://google.com/resource?key=value

I expect the output:

http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue

So:

C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;

public class URLEncodeSample {
    public static void main( String [] args ) throws Throwable {
        System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
    }
}

C:\oreyes\samples\java\URL>javac URLEncodeSample.java

C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue

As expected.

What would be the problem with this?

node.js: read a text file into an array. (Each line an item in the array.)

If you can fit the final data into an array then wouldn't you also be able to fit it in a string and split it, as has been suggested? In any case if you would like to process the file one line at a time you can also try something like this:

var fs = require('fs');

function readLines(input, func) {
  var remaining = '';

  input.on('data', function(data) {
    remaining += data;
    var index = remaining.indexOf('\n');
    while (index > -1) {
      var line = remaining.substring(0, index);
      remaining = remaining.substring(index + 1);
      func(line);
      index = remaining.indexOf('\n');
    }
  });

  input.on('end', function() {
    if (remaining.length > 0) {
      func(remaining);
    }
  });
}

function func(data) {
  console.log('Line: ' + data);
}

var input = fs.createReadStream('lines.txt');
readLines(input, func);

EDIT: (in response to comment by phopkins) I think (at least in newer versions) substring does not copy data but creates a special SlicedString object (from a quick glance at the v8 source code). In any case here is a modification that avoids the mentioned substring (tested on a file several megabytes worth of "All work and no play makes Jack a dull boy"):

function readLines(input, func) {
  var remaining = '';

  input.on('data', function(data) {
    remaining += data;
    var index = remaining.indexOf('\n');
    var last  = 0;
    while (index > -1) {
      var line = remaining.substring(last, index);
      last = index + 1;
      func(line);
      index = remaining.indexOf('\n', last);
    }

    remaining = remaining.substring(last);
  });

  input.on('end', function() {
    if (remaining.length > 0) {
      func(remaining);
    }
  });
}

How to navigate through textfields (Next / Done Buttons)

I tried to solve this problem using a more sophisticated approach based on assigning each cell (or UITextField) in a UITableView a unique tag value that can be later retrieved: activate-next-uitextfield-in-uitableview-ios

I hope this helps!

Search and replace part of string in database

You can do it with an UPDATE statement setting the value with a REPLACE

UPDATE
    Table
SET
    Column = Replace(Column, 'find value', 'replacement value')
WHERE
    xxx

You will want to be extremely careful when doing this! I highly recommend doing a backup first.

Inserting into Oracle and retrieving the generated sequence ID

Expanding a bit on the answers from @Guru and @Ronnis, you can hide the sequence and make it look more like an auto-increment using a trigger, and have a procedure that does the insert for you and returns the generated ID as an out parameter.

create table batch(batchid number,
    batchname varchar2(30),
    batchtype char(1),
    source char(1),
    intarea number)
/

create sequence batch_seq start with 1
/

create trigger batch_bi
before insert on batch
for each row
begin
    select batch_seq.nextval into :new.batchid from dual;
end;
/

create procedure insert_batch(v_batchname batch.batchname%TYPE,
    v_batchtype batch.batchtype%TYPE,
    v_source batch.source%TYPE,
    v_intarea batch.intarea%TYPE,
    v_batchid out batch.batchid%TYPE)
as
begin
    insert into batch(batchname, batchtype, source, intarea)
    values(v_batchname, v_batchtype, v_source, v_intarea)
    returning batchid into v_batchid;
end;
/

You can then call the procedure instead of doing a plain insert, e.g. from an anoymous block:

declare
    l_batchid batch.batchid%TYPE;
begin
    insert_batch(v_batchname => 'Batch 1',
        v_batchtype => 'A',
        v_source => 'Z',
        v_intarea => 1,
        v_batchid => l_batchid);
    dbms_output.put_line('Generated id: ' || l_batchid);

    insert_batch(v_batchname => 'Batch 99',
        v_batchtype => 'B',
        v_source => 'Y',
        v_intarea => 9,
        v_batchid => l_batchid);
    dbms_output.put_line('Generated id: ' || l_batchid);
end;
/

Generated id: 1
Generated id: 2

You can make the call without an explicit anonymous block, e.g. from SQL*Plus:

variable l_batchid number;
exec insert_batch('Batch 21', 'C', 'X', 7, :l_batchid);

... and use the bind variable :l_batchid to refer to the generated value afterwards:

print l_batchid;
insert into some_table values(:l_batch_id, ...);

Search for string within text column in MySQL

You could probably use the LIKE clause to do some simple string matching:

SELECT * FROM items WHERE items.xml LIKE '%123456%'

If you need more advanced functionality, take a look at MySQL's fulltext-search functions here: http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

#include <string.h>
#include <stdio.h>
#include <jni.h>

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

TextView - setting the text size programmatically doesn't seem to work

In My Case Used this Method:

public static float pxFromDp(float dp, Context mContext) {
    return dp * mContext.getResources().getDisplayMetrics().density;
}

Here Set TextView's TextSize Programatically :

textView.setTextSize(pxFromDp(18, YourActivity.this));

Keep Enjoying:)

How to Convert an int to a String?

Use String.valueOf():

int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(String.valueOf(sdRate)); //no more errors

How to include() all PHP files from a directory?

Do no write a function() to include files in a directory. You may lose the variable scopes, and may have to use "global". Just loop on the files.

Also, you may run into difficulties when an included file has a class name that will extend to the other class defined in the other file - which is not yet included. So, be careful.

Inserting values to SQLite table in Android

okk this is fully working code edit it as per your requirement

public class TestProjectActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    SQLiteDatabase db;
    db = openOrCreateDatabase( "Temp.db"        , SQLiteDatabase.CREATE_IF_NECESSARY        , null          );
    try {
        final String CREATE_TABLE_CONTAIN = "CREATE TABLE IF NOT EXISTS tbl_Contain ("
                + "ID INTEGER primary key AUTOINCREMENT,"
                + "DESCRIPTION TEXT,"
                + "expirydate DATETIME,"
                + "AMOUNT TEXT,"
                + "TRNS TEXT," + "isdefault TEXT);";
        db.execSQL(CREATE_TABLE_CONTAIN);
        Toast.makeText(TestProjectActivity.this, "table created ", Toast.LENGTH_LONG).show();
        String sql =
            "INSERT or replace INTO tbl_Contain (DESCRIPTION, expirydate, AMOUNT, TRNS,isdefault) VALUES('this is','03/04/2005','5000','tran','y')" ;       
                db.execSQL(sql);
    }
    catch (Exception e) {
        Toast.makeText(TestProjectActivity.this, "ERROR "+e.toString(), Toast.LENGTH_LONG).show();  
}}}

Hope this is useful for you..
do not use TEXT for date field may be that was casing problem still getting problem let me know :)Pragna

How to write macro for Notepad++?

I found 'Python Script' plugin for Notepad++ more useful since with the plugin, I could write simple macros in the form of python and It has also got very good documentation and sample macros written in python as well. If you are quite comfortable with python, then I think 'Python Script' will provide justice. For more information, refer : http://npppythonscript.sourceforge.net/

Inconsistent Accessibility: Parameter type is less accessible than method

When I received this error, I had a "helper" class that I did not declare as public that caused this issue inside of the class that used the "helper" class. Making the "helper" class public solved this error, as in:

public ServiceClass { public ServiceClass(HelperClass _helper) { } }

public class HelperClass {} // Note the public HelperClass that solved my issue.

This may help someone else who encounters this.

Loading a properties file from Java package

Assuming your using the Properties class, via its load method, and I guess you are using the ClassLoader getResourceAsStream to get the input stream.

How are you passing in the name, it seems it should be in this form: /com/al/common/email/templates/foo.properties

Checking Date format from a string in C#

I think one of the solutions is to use DateTime.ParseExact or DateTime.TryParseExact

DateTime.ParseExact(dateString, format, provider);

source: http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

ERROR 1064 (42000) in MySQL

Do you have a specific database selected like so:

USE database_name

Except for that I can't think of any reason for this error.

Inverse of matrix in R

Note that if you care about speed and do not need to worry about singularities, solve() should be preferred to ginv() because it is much faster, as you can check:

require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)

t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0 

t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1 

How can I increase the size of a bootstrap button?

You can try to use btn-sm, btn-xs and btn-lg classes like this:

.btn-xl {
    padding: 10px 20px;
    font-size: 20px;
    border-radius: 10px;
}

JSFIDDLE DEMO

You can make use of Bootstrap .btn-group-justified css class. Or you can simply add:

.btn-xl {
    padding: 10px 20px;
    font-size: 20px;
    border-radius: 10px;
    width:50%;    //Specify your width here
}

JSFIDDLE DEMO

javax.net.ssl.SSLException: Received fatal alert: protocol_version

On Java 1.8 default TLS protocol is v1.2. On Java 1.6 and 1.7 default is obsoleted TLS1.0. I get this error on Java 1.8, because url use old TLS1.0 (like Your - You see ClientHello, TLSv1). To resolve this error You need to use override defaults for Java 1.8.

System.setProperty("https.protocols", "TLSv1");

More info on the Oracle blog.

What is java pojo class, java bean, normal class?

  1. Normal Class: A Java class

  2. Java Beans:

    • All properties private (use getters/setters)
    • A public no-argument constructor
    • Implements Serializable.
  3. Pojo: Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to

    • Extend prespecified classes
    • Implement prespecified interface
    • Contain prespecified annotations

How to get the last N rows of a pandas DataFrame?

This is because of using integer indices (ix selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).

*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:

df.iloc[-3:]

see the docs.

As Wes points out, in this specific case you should just use tail!

Can't escape the backslash with regex?

From http://www.regular-expressions.info/charclass.html :

Note that the only special characters or metacharacters inside a character class are the closing bracket (]), the backslash (\\), the caret (^) and the hyphen (-). The usual metacharacters are normal characters inside a character class, and do not need to be escaped by a backslash. To search for a star or plus, use [+*]. Your regex will work fine if you escape the regular metacharacters inside a character class, but doing so significantly reduces readability.

To include a backslash as a character without any special meaning inside a character class, you have to escape it with another backslash. [\\x] matches a backslash or an x. The closing bracket (]), the caret (^) and the hyphen (-) can be included by escaping them with a backslash, or by placing them in a position where they do not take on their special meaning. I recommend the latter method, since it improves readability. To include a caret, place it anywhere except right after the opening bracket. [x^] matches an x or a caret. You can put the closing bracket right after the opening bracket, or the negating caret. []x] matches a closing bracket or an x. [^]x] matches any character that is not a closing bracket or an x. The hyphen can be included right after the opening bracket, or right before the closing bracket, or right after the negating caret. Both [-x] and [x-] match an x or a hyphen.

What language are you writing the regex in?

MySQL limit from descending order

This way is comparatively more easy

SELECT doc_id,serial_number,status FROM date_time ORDER BY  date_time DESC LIMIT 0,1;

Trim spaces from start and end of string

I know this is an old post, but just thought I'd share our solution. In the quest for shortest code (doesn't everyone just love terse regex), one could instead use:

title = title.replace(/(^\s+|\s+$)/g, '');

BTW: I ran this same test through the link shared above blog.stevenlevithan.com -- Faster JavaScript Trim and this pattern beat all the other HANDS down!

Using IE8, added test as test13. The results were:

Original length: 226002
trim1: 110ms (length: 225994)
trim2: 79ms (length: 225994)
trim3: 172ms (length: 225994)
trim4: 203ms (length:225994)
trim5: 172ms (length: 225994)
trim6: 312ms (length: 225994)
trim7: 203ms (length: 225994)
trim8: 47ms (length: 225994)
trim9: 453ms (length: 225994)
trim10: 15ms (length: 225994)
trim11: 16ms (length: 225994)
trim12: 31ms (length: 225994)
trim13: 0ms (length: 226002)

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file 
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);

doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
    window.console.log(result);
});

//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
    int userID = int.Parse(queryJson.UserID.Value);
    string userName = queryJson.UserName.Value;
}

//utility function:
public static dynamic ParseHttpGetJson(string query)
{
    if (!string.IsNullOrEmpty(query))
    {
        try
        {
            var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
            json = System.Web.HttpUtility.UrlDecode(json);
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);

            return queryJson;
        }
        catch (System.Exception e)
        {
            throw new ApplicationException("can't deserialize object as wrong string content!", e);
        }
    }
    else
    {
        return null;
    }
}

AngularJS is rendering <br> as text not as a newline

I could be wrong because I've never used Angular, but I believe you are probably using ng-bind, which will create just a TextNode.

You will want to use ng-bind-html instead.

http://docs.angularjs.org/api/ngSanitize.directive:ngBindHtml

Update: It looks like you'll need to use ng-bind-html-unsafe='q.category'

http://docs.angularjs.org/api/ng.directive:ngBindHtmlUnsafe

Here's a demo:

http://jsfiddle.net/VFVMv/

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

In SQL Developer: Everything was working fine and I had all the permissions to login and there was no password change and I could click the table and see the data tab.

But when I run query (simple select statement) it was showing "ORA-01031: insufficient privileges" message.

The solution is simply disconnect the connection and reconnect. Note: only doing Reconnect did not work for me. SQL Developer Disconnect Snapshot

Get all column names of a DataTable into string array using (LINQ/Predicate)

I'd suggest using such extension method:

public static class DataColumnCollectionExtensions
{
    public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
    {
        return source.Cast<DataColumn>();
    }
}

And therefore:

string[] columnNames = dataTable.Columns.AsEnumerable().Select(column => column.Name).ToArray();

You may also implement one more extension method for DataTable class to reduce code:

public static class DataTableExtensions
{
    public static IEnumerable<DataColumn> GetColumns(this DataTable source)
    {
        return source.Columns.AsEnumerable();
    }
}

And use it as follows:

string[] columnNames = dataTable.GetColumns().Select(column => column.Name).ToArray();

How to input a regex in string.replace?

replace method of string objects does not accept regular expressions but only fixed strings (see documentation: http://docs.python.org/2/library/stdtypes.html#str.replace).

You have to use re module:

import re
newline= re.sub("<\/?\[[0-9]+>", "", line)

Pointers in JavaScript?

You refer to 'x' from window object

var x = 0;

function a(key, ref) {
    ref = ref || window;  // object reference - default window
    ref[key]++;
}

a('x');                   // string
alert(x);

What is a practical, real world example of the Linked List?

The way Blame moves around a bunch of software engineers working on different modules in a project.

First, the GUI guy gets blamed for the product not working. He checks his code and sees it's not his fault: the API is screwing up. The API guy checks his code: not his fault, it's a problem with the logger module. Logger module guy now blames database guy, who blames installer guy, who blames...

C++ array initialization

Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 } is an idiomatic universal zero-initializer. This is also almost the case in C++.

Since this initalizer is universal, for bool array you don't really need a different "syntax". 0 works as an initializer for bool type as well, so

bool myBoolArray[ARRAY_SIZE] = { 0 };

is guaranteed to initialize the entire array with false. As well as

char* myPtrArray[ARRAY_SIZE] = { 0 };

in guaranteed to initialize the whole array with null-pointers of type char *.

If you believe it improves readability, you can certainly use

bool myBoolArray[ARRAY_SIZE] = { false };
char* myPtrArray[ARRAY_SIZE] = { nullptr };

but the point is that = { 0 } variant gives you exactly the same result.

However, in C++ = { 0 } might not work for all types, like enum types, for example, which cannot be initialized with integral 0. But C++ supports the shorter form

T myArray[ARRAY_SIZE] = {};

i.e. just an empty pair of {}. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

Depending on what version of the framework you're targeting, you may want to look here to get the correct string:

http://msdn.microsoft.com/en-us/library/ee517334.aspx

I wasted hours trying to figure out why my release targeting .Net 4.0 client required the full version. I used this in the end:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0.30319" 
               sku=".NETFramework,Version=v4.0,Profile=Client" />
</startup>

ASP.Net MVC Redirect To A Different View

The simplest way is use return View.

return View("ViewName");

Remember, the physical name of the "ViewName" should be something like ViewName.cshtml in your project, if your are using MVC C# / .NET.

Print all day-dates between two dates

import datetime

d1 = datetime.date(2008,8,15)
d2 = datetime.date(2008,9,15)
diff = d2 - d1
for i in range(diff.days + 1):
    print (d1 + datetime.timedelta(i)).isoformat()

MINGW64 "make build" error: "bash: make: command not found"

  • Go to ezwinports, https://sourceforge.net/projects/ezwinports/files/

  • Download make-4.2.1-without-guile-w32-bin.zip (get the version without guile)

  • Extract zip
  • Copy the contents to C:\ProgramFiles\Git\mingw64\ merging the folders, but do NOT overwrite/replace any exisiting files.

What are the different types of keys in RDBMS?

Ólafur forgot the surrogate key:

A surrogate key in a database is a unique identifier for either an entity in the modeled world or an object in the database. The surrogate key is not derived from application data.

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

i had this error too as Smutje reffered make sure that you have not a value in foreign key column of your base foreign key table that is not in your reference table i.e(every value in your base foreign key table(value of a column that is foreign key) must also be in your reference table column) its good to empty your base foreign key table first then set foreign keys

Prevent textbox autofill with previously entered values

Autocomplete need to set off from textbox

<asp:TextBox ID="TextBox1" runat="server" autocomplete="off"></asp:TextBox>

Bash: Syntax error: redirection unexpected

Does your script reference /bin/bash or /bin/sh in its hash bang line? The default system shell in Ubuntu is dash, not bash, so if you have #!/bin/sh then your script will be using a different shell than you expect. Dash does not have the <<< redirection operator.

How to make Bootstrap carousel slider use mobile left/right swipe

I'm a bit late to the party, but here's a bit of jQuery I've been using:

$('.carousel').on('touchstart', function(event){
    const xClick = event.originalEvent.touches[0].pageX;
    $(this).one('touchmove', function(event){
        const xMove = event.originalEvent.touches[0].pageX;
        const sensitivityInPx = 5;

        if( Math.floor(xClick - xMove) > sensitivityInPx ){
            $(this).carousel('next');
        }
        else if( Math.floor(xClick - xMove) < -sensitivityInPx ){
            $(this).carousel('prev');
        }
    });
    $(this).on('touchend', function(){
        $(this).off('touchmove');
    });
});

No need for jQuery mobile or any other plugins. If you need to adjust the sensitivity of the swipe adjust the 5 and -5. Hope this helps someone.

How to save to local storage using Flutter?

I was looking for the same, simple local storage but also with a reasonable level of security. The two solutions I've found that make the most sense are flutter_secure_storage (as mentioned by Raouf) for the small stuff, and hive for larger datasets.

Copy all values from fields in one class to another through reflection

I solved the above problem in Kotlin that works fine for me for my Android Apps Development:

 object FieldMapper {

fun <T:Any> copy(to: T, from: T) {
    try {
        val fromClass = from.javaClass

        val fromFields = getAllFields(fromClass)

        fromFields?.let {
            for (field in fromFields) {
                try {
                    field.isAccessible = true
                    field.set(to, field.get(from))
                } catch (e: IllegalAccessException) {
                    e.printStackTrace()
                }

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

}

private fun getAllFields(paramClass: Class<*>): List<Field> {

    var theClass:Class<*>? = paramClass
    val fields = ArrayList<Field>()
    try {
        while (theClass != null) {
            Collections.addAll(fields, *theClass?.declaredFields)
            theClass = theClass?.superclass
        }
    }catch (e:Exception){
        e.printStackTrace()
    }

    return fields
}

}

Why is my method undefined for the type object?

Try this.

public static void main(String[] args) {
    EchoServer0 myServer;
    myServer = new EchoServer0();
    myServer.listen();
}

What you were trying to do was declaring a variable of type Object, not creating anything for that variable to reference, then trying to call a method that didn't exist (in the class Object) on an object that hadn't been created. It was never going to work.

How do I remove blank pages coming between two chapters in Appendix?

You can also use \openany, \openright and \openleft commands:

\documentclass{memoir}
\begin{document}

\openany
\appendix

\openright
\appendixpage
This is the appendix.

\end{document}

How to make a GridLayout fit screen size

After many attempts I found what I was looking for in this layout. Even spaced LinearLayouts with automatically fitted ImageViews, with maintained aspect ratio. Works with landscape and portrait with any screen and image resolution.

Nexus 7 Nexus 5 Nexus 10

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffcc5d00" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">


        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_weight="1"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image1"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image2"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_weight="1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image3"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image4"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</FrameLayout>

How do I use Comparator to define a custom sort order?

Using just simple loops:

public static void compareSortOrder (List<String> sortOrder, List<String> listToCompare){
        int currentSortingLevel = 0;
        for (int i=0; i<listToCompare.size(); i++){
            System.out.println("Item from list: " + listToCompare.get(i));
            System.out.println("Sorting level: " + sortOrder.get(currentSortingLevel));
            if (listToCompare.get(i).equals(sortOrder.get(currentSortingLevel))){

            } else {
                try{
                    while (!listToCompare.get(i).equals(sortOrder.get(currentSortingLevel)))
                        currentSortingLevel++;
                    System.out.println("Changing sorting level to next value: " + sortOrder.get(currentSortingLevel));
                } catch (ArrayIndexOutOfBoundsException e){

                }

            }
        }
    }

And sort order in List

public static List<String> ALARMS_LIST = Arrays.asList(
            "CRITICAL",
            "MAJOR",
            "MINOR",
            "WARNING",
            "GOOD",
            "N/A");