Programs & Examples On #Dayofweek

How to group by week in MySQL?

Figured it out... it's a little cumbersome, but here it is.

FROM_DAYS(TO_DAYS(TIMESTAMP) -MOD(TO_DAYS(TIMESTAMP) -1, 7))

And, if your business rules say your weeks start on Mondays, change the -1 to -2.


Edit

Years have gone by and I've finally gotten around to writing this up. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

How to get the day of week and the month of the year?

Use the standard javascript Date class. No need for arrays. No need for extra libraries.

See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

_x000D_
_x000D_
var options = {  weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };_x000D_
var prnDt = 'Printed on ' + new Date().toLocaleTimeString('en-us', options);_x000D_
_x000D_
console.log(prnDt);
_x000D_
_x000D_
_x000D_

How to get the integer value of day of week

Another way to get Monday with integer value 1 and Sunday with integer value 7

int day = ((int)DateTime.Now.DayOfWeek + 6) % 7 + 1;

How to get the week day name from a date?

SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;

DAY
---------
TUESDAY

SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;

DAY
---
TUE

SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;

DAY
---
Tue

(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)

What does "subject" mean in certificate?

The Subject, in security, is the thing being secured. In this case it could be a persons email or a website or a machine.

If we take the example of an email, say my email, then the subject key container would be the protected location containing my private key.

The certificate store usually refers to Microsoft certificate store which contains certificates form trusted roots, machines on the network, people etc. In my case the subjects certificate store would be the place, within this store, holding my certificates.

If you are working within a microsoft domain then the subject name will invariably hold the Distinguished Name, of the subject, which is how the domain references the subject and holds it in its directory. e.g. CN=Mark Sutton, OU=Developers, O=Mycompany C=UK

To look at your certificates on a microsoft machine:-

Log in as you run>mmc Select File>add/remove snap-in and select certificates then select my user account click Finish then close then ok. Look in the personal area of the store.

In the other areas of the store you will see the other trusted certificates used to validate signatures etc.

Angular 2 - innerHTML styling

We pull in content frequently from our CMS as [innerHTML]="content.title". We place the necessary classes in the application's root styles.scss file rather than in the component's scss file. Our CMS purposely strips out in-line styles so we must have prepared classes that the author can use in their content. Remember using {{content.title}} in the template will not render html from the content.

How do I run a batch file from my Java Application?

The following is working fine:

String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);

how to use DEXtoJar

You can decompile your .apk files and download online.

http://www.javadecompilers.com/

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

Building on The Pixel Developer's comment, a snippet using the SPL might look like:

$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::CHILD_FIRST
);

foreach ($files as $fileinfo) {
    $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
    $todo($fileinfo->getRealPath());
}

rmdir($dir);

Note: It does no sanity checking and makes use of the SKIP_DOTS flag introduced with the FilesystemIterator in PHP 5.3.0. Of course, the $todo could be an if/else. The important point is that CHILD_FIRST is used to iterate over the children (files) first before their parent (folders).

Setting a property with an EventTrigger

Just create your own action.

namespace WpfUtil
{
    using System.Reflection;
    using System.Windows;
    using System.Windows.Interactivity;


    /// <summary>
    /// Sets the designated property to the supplied value. TargetObject
    /// optionally designates the object on which to set the property. If
    /// TargetObject is not supplied then the property is set on the object
    /// to which the trigger is attached.
    /// </summary>
    public class SetPropertyAction : TriggerAction<FrameworkElement>
    {
        // PropertyName DependencyProperty.

        /// <summary>
        /// The property to be executed in response to the trigger.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty
            = DependencyProperty.Register("PropertyName", typeof(string),
            typeof(SetPropertyAction));


        // PropertyValue DependencyProperty.

        /// <summary>
        /// The value to set the property to.
        /// </summary>
        public object PropertyValue
        {
            get { return GetValue(PropertyValueProperty); }
            set { SetValue(PropertyValueProperty, value); }
        }

        public static readonly DependencyProperty PropertyValueProperty
            = DependencyProperty.Register("PropertyValue", typeof(object),
            typeof(SetPropertyAction));


        // TargetObject DependencyProperty.

        /// <summary>
        /// Specifies the object upon which to set the property.
        /// </summary>
        public object TargetObject
        {
            get { return GetValue(TargetObjectProperty); }
            set { SetValue(TargetObjectProperty, value); }
        }

        public static readonly DependencyProperty TargetObjectProperty
            = DependencyProperty.Register("TargetObject", typeof(object),
            typeof(SetPropertyAction));


        // Private Implementation.

        protected override void Invoke(object parameter)
        {
            object target = TargetObject ?? AssociatedObject;
            PropertyInfo propertyInfo = target.GetType().GetProperty(
                PropertyName,
                BindingFlags.Instance|BindingFlags.Public
                |BindingFlags.NonPublic|BindingFlags.InvokeMethod);

            propertyInfo.SetValue(target, PropertyValue);
        }
    }
}

In this case I'm binding to a property called DialogResult on my viewmodel.

<Grid>

    <Button>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
                                       PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        Cancel
    </Button>

</Grid>

How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

You need to open the file in binary mode i.e. wb instead of w. If you don't, the end of line characters are auto-converted to OS specific ones.

Here is an excerpt from Python reference about open().

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

Map over object preserving keys

_x000D_
_x000D_
var mapped = _.reduce({ one: 1, two: 2, three: 3 }, function(obj, val, key) {_x000D_
    obj[key] = val*3;_x000D_
    return obj;_x000D_
}, {});_x000D_
_x000D_
console.log(mapped);
_x000D_
<script src="http://underscorejs.org/underscore-min.js"></script>_x000D_
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
_x000D_
_x000D_
_x000D_

Multiple submit buttons on HTML form – designate one button as default

Quick'n'dirty you could create an hidden duplicate of the submit-button, which should be used, when pressing enter.

Example CSS

input.hidden {
    width: 0px;
    height: 0px;
    margin: 0px;
    padding: 0px;
    outline: none;
    border: 0px;
}

Example HTML

<input type="submit" name="next" value="Next" class="hidden" />
<input type="submit" name="prev" value="Previous" />
<input type="submit" name="next" value="Next" />

If someone now hits enter in your form, the (hidden) next-button will be used as submitter.

Tested on IE9, Firefox, Chrome and Opera

Caesar Cipher Function in Python

according to me this answer is useful for you:

def casear(a,key):
str=""
if key>26:
    key%=26
for i in range(0,len(a)):
    if a[i].isalpha():
        b=ord(a[i])
        b+=key
        #if b>90:                   #if upper case letter ppear in your string
        #    c=b-90                 #if upper case letter ppear in your string
        #    str+=chr(64+c)         #if upper case letter ppear in your string
        if b>122:
            c=b-122
            str+=chr(96+c)
        else:
            str+=chr(b)
    else:
        str+=a[i]
print str

a=raw_input()
key=int(input())
casear(a,key)

This function shifts all letter to right according to given key.

How do you know a variable type in java?

I agree with what Joachim Sauer said, not possible to know (the variable type! not value type!) unless your variable is a class attribute (and you would have to retrieve class fields, get the right field by name...)

Actually for me it's totally impossible that any a.xxx().yyy() method give you the right answer since the answer would be different on the exact same object, according to the context in which you call this method...

As teehoo said, if you know at compile a defined list of types to test you can use instanceof but you will also get subclasses returning true...

One possible solution would also be to inspire yourself from the implementation of java.lang.reflect.Field and create your own Field class, and then declare all your local variables as this custom Field implementation... but you'd better find another solution, i really wonder why you need the variable type, and not just the value type?

Adding custom radio buttons in android

Add a background drawable that references to an image, or a selector (like below), and make the button transparent:

<RadioButton
    android:id="@+id/radio0"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@null"
    android:button="@drawable/yourbuttonbackground"
    android:checked="true"
    android:text="RadioButton1" />

If you would like your radio buttons to have a different resource when checked, create a selector background drawable:

res/drawable/yourbuttonbackground.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:drawable="@drawable/b"
        android:state_checked="true"
        android:state_pressed="true" />
    <item
        android:drawable="@drawable/a"
        android:state_pressed="true" />
    <item
        android:drawable="@drawable/a"
        android:state_checked="true" />
    <item
        android:drawable="@drawable/b" />
</selector>

In the selector above, we reference two drawables, a and b, here's how we create them:

res/drawable/a.xml - Selected State

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <corners
        android:radius="5dp" />
    <solid
        android:color="#fff" />
    <stroke
        android:width="2dp"
        android:color="#53aade" />
</shape>

res/drawable/b.xml - Regular State

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <corners
        android:radius="5dp" />
    <solid
        android:color="#fff" />
    <stroke
        android:width="2dp"
        android:color="#555555" />
</shape>

More on drawables here: http://developer.android.com/guide/topics/resources/drawable-resource.html

How to use global variable in node.js?

Most people advise against using global variables. If you want the same logger class in different modules you can do this

logger.js

  module.exports = new logger(customConfig);

foobar.js

  var logger = require('./logger');
  logger('barfoo');

If you do want a global variable you can do:

global.logger = new logger(customConfig);

how to open .mat file without using MATLAB?

I didn't use it myself but heard of a simple tool (not a text editor) for this so it is definitely possible without setting up a programming environment (by installing octave or python).

A quick search hints that it was possible with total commander. (A lightweight tool with an easy point and click interface)

I would not be surprised if this still works, but I can't guarantee it.

Getting byte array through input type = file

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    (function (document) {_x000D_
  var input = document.getElementById("files"),_x000D_
  output = document.getElementById("result"),_x000D_
  fileData; // We need fileData to be visible to getBuffer._x000D_
_x000D_
  // Eventhandler for file input. _x000D_
  function openfile(evt) {_x000D_
    var files = input.files;_x000D_
    // Pass the file to the blob, not the input[0]._x000D_
    fileData = new Blob([files[0]]);_x000D_
    // Pass getBuffer to promise._x000D_
    var promise = new Promise(getBuffer);_x000D_
    // Wait for promise to be resolved, or log error._x000D_
    promise.then(function(data) {_x000D_
      // Here you can pass the bytes to another function._x000D_
      output.innerHTML = data.toString();_x000D_
      console.log(data);_x000D_
    }).catch(function(err) {_x000D_
      console.log('Error: ',err);_x000D_
    });_x000D_
  }_x000D_
_x000D_
  /* _x000D_
    Create a function which will be passed to the promise_x000D_
    and resolve it when FileReader has finished loading the file._x000D_
  */_x000D_
  function getBuffer(resolve) {_x000D_
    var reader = new FileReader();_x000D_
    reader.readAsArrayBuffer(fileData);_x000D_
    reader.onload = function() {_x000D_
      var arrayBuffer = reader.result_x000D_
      var bytes = new Uint8Array(arrayBuffer);_x000D_
      resolve(bytes);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  // Eventlistener for file input._x000D_
  input.addEventListener('change', openfile, false);_x000D_
}(document));_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<input type="file" id="files"/>_x000D_
<div id="result"></div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

Imagine that we have 3 buttons for example

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // Capture our button from layout
        Button button = (Button)findViewById(R.id.corky);
        Button button2 = (Button)findViewById(R.id.corky2);
        Button button3 = (Button)findViewById(R.id.corky3);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(mCorkyListener);
        button2.setOnClickListener(mCorkyListener);
        button3.setOnClickListener(mCorkyListener);

    }

    // Create an anonymous implementation of OnClickListener
    private View.OnClickListener mCorkyListener = new View.OnClickListener() {
        public void onClick(View v) {
            // do something when the button is clicked 
            // Yes we will handle click here but which button clicked??? We don't know

        }
    };

}

So what we will do?

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // Capture our button from layout
        Button button = (Button)findViewById(R.id.corky);
        Button button2 = (Button)findViewById(R.id.corky2);
        Button button3 = (Button)findViewById(R.id.corky3);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(mCorkyListener);
        button2.setOnClickListener(mCorkyListener);
        button3.setOnClickListener(mCorkyListener);

    }

    // Create an anonymous implementation of OnClickListener
    private View.OnClickListener mCorkyListener = new View.OnClickListener() {
        public void onClick(View v) {
            // do something when the button is clicked
            // Yes we will handle click here but which button clicked??? We don't know

            // So we will make
            switch (v.getId() /*to get clicked view id**/) {
                case R.id.corky:

                    // do something when the corky is clicked

                    break;
                case R.id.corky2:

                    // do something when the corky2 is clicked

                    break;
                case R.id.corky3:

                    // do something when the corky3 is clicked

                    break;
                default:
                    break;
            }
        }
    };

}

Or we can do this:

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // Capture our button from layout
        Button button = (Button)findViewById(R.id.corky);
        Button button2 = (Button)findViewById(R.id.corky2);
        Button button3 = (Button)findViewById(R.id.corky3);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // do something when the corky is clicked
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // do something when the corky2 is clicked
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // do something when the corky3 is clicked
            }
        });

    }

}

Or we can implement View.OnClickListener and i think it's the best way:

public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // Capture our button from layout
        Button button = (Button)findViewById(R.id.corky);
        Button button2 = (Button)findViewById(R.id.corky2);
        Button button3 = (Button)findViewById(R.id.corky3);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // do something when the button is clicked
        // Yes we will handle click here but which button clicked??? We don't know

        // So we will make
        switch (v.getId() /*to get clicked view id**/) {
            case R.id.corky:

                // do something when the corky is clicked

                break;
            case R.id.corky2:

                // do something when the corky2 is clicked

                break;
            case R.id.corky3:

                // do something when the corky3 is clicked

                break;
            default:
                break;
        }
    }
}

Finally there is no real differences here Just "Way better than the other"

fatal: bad default revision 'HEAD'

This happens to me when the branch I'm working in gets deleted from the repository, but the workspace I'm in is not updated. (We have a tool that lets you create multiple git "workspaces" from the same repository using simlinks.)

If git branch does not mark any branch as current, try doing

git reset --hard <<some branch>>

I tried a number of approaches until I worked this one out.

How to split an integer into an array of digits?

Splitting a single number to it's digits (as answered by all):

>>> [int(i) for i in str(12345)]
[1, 2, 3, 4, 5]

But, to get digits from a list of numbers:

>>> [int(d) for d in ''.join(str(x) for x in [12, 34, 5])]
[1, 2, 3, 4, 5]

So like to know, if we can do the above, more efficiently.

How to show a confirm message before delete?

Its very simple

function archiveRemove(any) {
    var click = $(any);
    var id = click.attr("id");
    swal.fire({
        title: 'Are you sure !',
           text: "?????",
           type: 'warning',
           showCancelButton: true,
           confirmButtonColor: '#3085d6',
           cancelButtonColor: '#d33',
           confirmButtonText: 'yes!',
           cancelButtonText: 'no'
    }).then(function (success) {
        if (success) {
            $('a[id="' + id + '"]').parents(".archiveItem").submit();
        }
    })
}

How can I divide two integers stored in variables in Python?

if 'a' is already a decimal; adding '.' would make 3.4/b(for example) into 3.4./b

Try float(a)/b

Send json post using php

Beware that file_get_contents solution doesn't close the connection as it should when a server returns Connection: close in the HTTP header.

CURL solution, on the other hand, terminates the connection so the PHP script is not blocked by waiting for a response.

How can I get a Dialog style activity window to fill the screen?

This would be helpful for someone like me. Create custom dialog style:

<style name="MyDialog" parent="Theme.AppCompat.Light.Dialog">
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowIsFloating">false</item>
</style>

In AndroidManifest.xml file set theme for wanted activity:

<activity
        android:name=".CustomDialog"
        ...
        android:theme="@style/MyDialog"/>

That is all, no need to call methods programaticaly.

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

First of all, it is a waste of an executor slot to wrap the build step in node. Your upstream executor will just be sitting idle for no reason.

Second, from a multibranch project, you can use the environment variable BRANCH_NAME to make logic conditional on the current branch.

Third, the job parameter takes an absolute or relative job name. If you give a name without any path qualification, that would refer to another job in the same folder, which in the case of a multibranch project would mean another branch of the same repository.

Thus what you meant to write is probably

if (env.BRANCH_NAME == 'master') {
    build '../other-repo/master'
}

How to disable Excel's automatic cell reference change after copy/paste?

This simple trick works: Copy and Paste. Do NOT cut and paste. After you paste, then reselect the part you copied and go to EDIT, slide down to CLEAR, and CLEAR CONTENTS.

How to get rid of punctuation using NLTK tokenizer?

I use this code to remove punctuation:

import nltk
def getTerms(sentences):
    tokens = nltk.word_tokenize(sentences)
    words = [w.lower() for w in tokens if w.isalnum()]
    print tokens
    print words

getTerms("hh, hh3h. wo shi 2 4 A . fdffdf. A&&B ")

And If you want to check whether a token is a valid English word or not, you may need PyEnchant

Tutorial:

 import enchant
 d = enchant.Dict("en_US")
 d.check("Hello")
 d.check("Helo")
 d.suggest("Helo")

Show Curl POST Request Headers? Is there a way to do this?

You can make you request headers by yourself using:

// open a socket connection on port 80
$fp = fsockopen($host, 80);

// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);

$result = ''; 
while(!feof($fp)) {
    // receive the results of the request
    $result .= fgets($fp, 128);
}

// close the socket connection:
fclose($fp);

Like writen on how make request

In C can a long printf statement be broken up into multiple lines?

Just some other formatting options:

printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", 
        a,        b,        c,        d);

printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", 
              a,        b,        c,            d);

printf("name: %s\t"      "args: %s\t"      "value %d\t"      "arraysize %d\n", 
        very_long_name_a, very_long_name_b, very_long_name_c, very_long_name_d);

You can add variations on the theme. The idea is that the printf() conversion speficiers and the respective variables are all lined up "nicely" (for some values of "nicely").

How do I debug a stand-alone VBScript script?

Run cscript.exe for full command args, I think

cscript //X scriptfile.vbs MyArg1 MyArg2

will run the script in a debugger.

how to create a Java Date object of midnight today and midnight tomorrow?

java.time

If you are using Java 8 and later, you can try the java.time package (Tutorial):

LocalDate tomorrow = LocalDate.now().plusDays(1);
Date endDate = Date.from(tomorrow.atStartOfDay(ZoneId.systemDefault()).toInstant());

How to remove items from a list while iterating?

You might want to use filter() available as the built-in.

For more details check here

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

With the GnuWin32 tools I found the openssl.cnf under C:\gnuwin32\share

set OPENSSL_CONF=C:\gnuwin32\share\openssl.cnf

@JsonProperty annotation on field as well as getter/setter

My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:

For eg. consider a slight modification of your case:

@JsonProperty("fileName")
private String fileName;

@JsonProperty("fileName")
public String getFileName()
{
    return fileName;
}

@JsonProperty("fileName1")
public void setFileName(String fileName)
{
    this.fileName = fileName;
}

Both fileName field, and method getFileName, have the correct property name of fileName and setFileName has a different one fileName1, in this case Jackson will look for a fileName1 attribute in json at the point of deserialization and will create a attribute called fileName1 at the point of serialization.

Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName, it would just pick one of them as the attribute(FILENAME), and had any on of the three differed, it would have thrown an exception:

java.lang.IllegalStateException: Conflicting property name definitions

Fastest way to extract frames using ffmpeg?

Came across this question, so here's a quick comparison. Compare these two different ways to extract one frame per minute from a video 38m07s long:

time ffmpeg -i input.mp4 -filter:v fps=fps=1/60 ffmpeg_%0d.bmp

1m36.029s

This takes long because ffmpeg parses the entire video file to get the desired frames.

time for i in {0..39} ; do ffmpeg -accurate_seek -ss `echo $i*60.0 | bc` -i input.mp4   -frames:v 1 period_down_$i.bmp ; done

0m4.689s

This is about 20 times faster. We use fast seeking to go to the desired time index and extract a frame, then call ffmpeg several times for every time index. Note that -accurate_seek is the default , and make sure you add -ss before the input video -i option.

Note that it's better to use -filter:v -fps=fps=... instead of -r as the latter may be inaccurate. Although the ticket is marked as fixed, I still did experience some issues, so better play it safe.

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

This is an IDE issue. Change the setting in the PowerShell GUI. Go to the Tools tab and select Options, and then Debugging options. Then check the box Turn off requirement for scripts to be signed. Done.

Which is the correct C# infinite loop, for (;;) or while (true)?

The C# compiler will transform both

for(;;)
{
    // ...
}

and

while (true)
{
    // ...
}

into

{
    :label
    // ...
    goto label;
}

The CIL for both is the same. Most people find while(true) to be easier to read and understand. for(;;) is rather cryptic.

Source:

I messed a little more with .NET Reflector, and I compiled both loops with the "Optimize Code" on in Visual Studio.

Both loops compile into (with .NET Reflector):

Label_0000:
    goto Label_0000;

Raptors should attack soon.

How do I round a float upwards to the nearest int in C#?

Off the top of my head:

float fl = 0.678;
int rounded_f = (int)(fl+0.5f);

PHP is_numeric or preg_match 0-9 validation

If you're only checking if it's a number, is_numeric() is much much better here. It's more readable and a bit quicker than regex.

The issue with your regex here is that it won't allow decimal values, so essentially you've just written is_int() in regex. Regular expressions should only be used when there is a non-standard data format in your input; PHP has plenty of built in validation functions, even an email validator without regex.

disable a hyperlink using jQuery

You can bind a click handler that returns false:

$('.my-link').click(function () {return false;});

To re-enable it again, unbind the handler:

$('.my-link').unbind('click');

Note that disabled doesn't work because it is designed for form inputs only.


jQuery has anticipated this already, providing a shortcut as of jQuery 1.4.3:

$('.my-link').bind('click', false);

And to unbind / re-enable:

$('.my-link').unbind('click', false);

How can I add the new "Floating Action Button" between two widgets/layouts

Here is one aditional free Floating Action Button library for Android. It has many customizations and requires SDK version 9 and higher

enter image description here

Full Demo Video

dependencies {
    compile 'com.scalified:fab:1.1.2'
}

Difference between Node object and Element object?

Best source of information for all of your DOM woes

http://www.w3.org/TR/dom/#nodes

"Objects implementing the Document, DocumentFragment, DocumentType, Element, Text, ProcessingInstruction, or Comment interface (simply called nodes) participate in a tree."

http://www.w3.org/TR/dom/#element

"Element nodes are simply known as elements."

PostgreSQL: Show tables in PostgreSQL

as a quick oneliner

# just list all the postgres tables sorted in the terminal
db='my_db_name'
clear;psql -d $db -t -c '\dt'|cut -c 11-|perl -ne 's/^([a-z_0-9]*)( )(.*)/$1/; print'

or if you prefer much clearer json output multi-liner :

IFS='' read -r -d '' sql_code <<"EOF_CODE"
    select array_to_json(array_agg(row_to_json(t))) from (
        SELECT table_catalog,table_schema,table_name 
        FROM information_schema.tables
        ORDER BY table_schema,table_name ) t
EOF_CODE
psql -d postgres -t -q -c "$sql_code"|jq

Checkout old commit and make it a new commit

The other answers so far create new commits that undo what is in older commits. It is possible to go back and "change history" as it were, but this can be a bit dangerous. You should only do this if the commit you're changing has not been pushed to other repositories.

The command you're looking for is git rebase --interactive

If you want to change HEAD~3, the command you want to issue is git rebase --interactive HEAD~4. This will open a text editor and allow you to specify which commits you want to change.

Practice on a different repository before you try this with something important. The man pages should give you all the rest of the information you need.

Read/Write String from/to a File in Android

the first thing we need is the permissions in AndroidManifest.xml

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

so in an asyncTask Kotlin class, we treat the creation of the file

    import android.os.AsyncTask
    import android.os.Environment
    import android.util.Log
    import java.io.*
    class WriteFile: AsyncTask<String, Int, String>() {
        private val mFolder = "/MainFolder"
        lateinit var folder: File
        internal var writeThis = "string to cacheApp.txt"
        internal var cacheApptxt = "cacheApp.txt"
        override fun doInBackground(vararg writethis: String): String? {
            val received = writethis[0]
            if(received.isNotEmpty()){
                writeThis = received
            }
            folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
            if(!folder.exists()){
                folder.mkdir()
                val readME = File(folder, cacheApptxt)
                val file = File(readME.path)
                val out: BufferedWriter
                try {
                    out = BufferedWriter(FileWriter(file, true), 1024)
                    out.write(writeThis)
                    out.newLine()
                    out.close()
                    Log.d("Output_Success", folder.path)
                } catch (e: Exception) {
                    Log.d("Output_Exception", "$e")
                }
            }
            return folder.path

    }

        override fun onPostExecute(result: String) {
            super.onPostExecute(result)

            if(result.isNotEmpty()){
                //implement an interface or do something
                Log.d("onPostExecuteSuccess", result)
            }else{
                Log.d("onPostExecuteFailure", result)
            }
        }

    }

Of course if you are using Android above Api 23, you must handle the request to allow writing to device memory. Something like this

    import android.Manifest
    import android.content.Context
    import android.content.pm.PackageManager
    import android.os.Build
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat

    class ReadandWrite {
        private val mREAD = 9
        private val mWRITE = 10
        private var readAndWrite: Boolean = false
        fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
            if (Build.VERSION.SDK_INT < 23) {
                readAndWrite = true
            } else {
                val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
                val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)

                if (mRead != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
                } else {
                    readAndWrite = true
                }

                if (mWrite != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
                } else {
                    readAndWrite = true
                }
            }
            return readAndWrite
        }
    }

then in an activity, execute the call.

  var pathToFileCreated = ""
    val anRW = ReadandWrite().readAndwriteStorage(this,this)
    if(anRW){
        pathToFileCreated =  WriteFile().execute("onTaskComplete").get()
        Log.d("pathToFileCreated",pathToFileCreated)
    }

Necessary to add link tag for favicon.ico?

Update Oct 2020:

So if you are on this page scratching your head why my favicon is not working , then read along. I tried all the things (which I supposedly thought I was doing right) yet favicon was not showing up on browser tabs.

Here is one line simple cracker code that worked flawlessly:

<link rel="icon" href="https://abcde.neocities.org/bla123.jpg" size="16x16" type="image/jpg">

enter image description here

Notes:

  1. Put the image in the ROOT folder ( In one of my unsuccessful attempts , I was not using root dir)
  2. Use direct favicon url link ( instead of href="images/bla123.jpg").
  3. I placed this tag just below the <title> tag in the <Header>
  4. I made the favicon size 64x64 px and size was 2.16 KB

I tested it on Firefox, Chrome, Edge, and opera. OS: Win 10, Mac OSX, ios and Android .Also I did not experience any cashing issues, worked pretty much as soon as I refreshed the page.

Why Response.Redirect causes System.Threading.ThreadAbortException?

Here's the official line on the problem (I couldn't find the latest, but I don't think the situation has changed for later versions of .net)

Why boolean in Java takes only true or false? Why not 1 or 0 also?

One thing that other answers haven't pointed out is that one advantage of not treating integers as truth values is that it avoids this C / C++ bug syndrome:

int i = 0;
if (i = 1) {
    print("the sky is falling!\n");
} 

In C / C++, the mistaken use of = rather than == causes the condition to unexpectedly evaluate to "true" and update i as an accidental side-effect.

In Java, that is a compilation error, because the value of the assigment i = 1 has type int and a boolean is required at that point. The only case where you'd get into trouble in Java is if you write lame code like this:

boolean ok = false;
if (ok = true) {  // bug and lame style
    print("the sky is falling!\n");
}

... which anyone with an ounce of "good taste" would write as ...

boolean ok = false;
if (ok) {
    print("the sky is falling!\n");
}

Convert a PHP object to an associative array

You might want to do this when you obtain data as objects from databases:

// Suppose 'result' is the end product from some query $query

$result = $mysqli->query($query);
$result = db_result_to_array($result);

function db_result_to_array($result)
{
    $res_array = array();

    for ($count=0; $row = $result->fetch_assoc(); $count++)
        $res_array[$count] = $row;

    return $res_array;
}

Download and save PDF file with Python requests module

You can use urllib:

import urllib.request
urllib.request.urlretrieve(url, "filename.pdf")

PHP checkbox set to check based on database value

You can read database value in to a variable and then set the variable as follows

$app_container->assign('checked_flag', $db_data=='0'  ? '' : 'checked');

And in html you can just use the checked_flag variable as follows

<input type="checkbox" id="chk_test" name="chk_test" value="1" {checked_flag}>

how can I debug a jar at runtime?

Even though it is a runnable jar, you can still run it from a console -- open a terminal window, navigate to the directory containing the jar, and enter "java -jar yourJar.jar". It will run in that terminal window, and sysout and syserr output will appear there, including stack traces from uncaught exceptions. Be sure to have your debug set to true when you compile. And good luck.


Just thought of something else -- if you're on Win7, it often has permission problems with user applications writing files to specific directories. Make sure the directory to which you are writing your output file is one for which you have permissions.

In a future project, if it's big enough, you can use one of the standard logging facilities for 'debug' output; then it will be easy(ier) to redirect it to a file instead of depending on having a console. But for a smaller job like this, this should be fine.

Where do I find the bashrc file on Mac?

On your Terminal:

  • Type cd ~/ to go to your home folder.

  • Type touch .bash_profile to create your new file.

  • Edit .bash_profile with your code editor (or you can just type open -e .bash_profile to open it in TextEdit).
  • Type . .bash_profile to reload .bash_profile and update any functions you add.

How to call getClass() from a static method in Java?

The Answer

Just use TheClassName.class instead of getClass().

Declaring Loggers

Since this gets so much attention for a specific usecase--to provide an easy way to insert log declarations--I thought I'd add my thoughts on that. Log frameworks often expect the log to be constrained to a certain context, say a fully-qualified class name. So they are not copy-pastable without modification. Suggestions for paste-safe log declarations are provided in other answers, but they have downsides such as inflating bytecode or adding runtime introspection. I don't recommend these. Copy-paste is an editor concern, so an editor solution is most appropriate.

In IntelliJ, I recommend adding a Live Template:

  • Use "log" as the abbreviation
  • Use private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger($CLASS$.class); as the template text.
  • Click Edit Variables and add CLASS using the expression className()
  • Check the boxes to reformat and shorten FQ names.
  • Change the context to Java: declaration.

Now if you type log<tab> it'll automatically expand to

private static final Logger logger = LoggerFactory.getLogger(ClassName.class);

And automatically reformat and optimize the imports for you.

dispatch_after - GCD in Swift?

Swift 3 & 4:

You can create a extension on DispatchQueue and add function delay which uses DispatchQueue asyncAfter function internally

extension DispatchQueue {
    static func delay(_ delay: DispatchTimeInterval, closure: @escaping () -> ()) {
        let timeInterval = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: timeInterval, execute: closure)
    }
}

use:

DispatchQueue.delay(.seconds(1)) {
    print("This is after delay")
}

Convert a String In C++ To Upper Case

#include <string>
#include <locale>

std::string str = "Hello World!";
auto & f = std::use_facet<std::ctype<char>>(std::locale());
f.toupper(str.data(), str.data() + str.size());

This will perform better than all the answers that use the global toupper function, and is presumably what boost::to_upper is doing underneath.

This is because ::toupper has to look up the locale - because it might've been changed by a different thread - for every invocation, whereas here only the call to locale() has this penalty. And looking up the locale generally involves taking a lock.

This also works with C++98 after you replace the auto, use of the new non-const str.data(), and add a space to break the template closing (">>" to "> >") like this:

std::use_facet<std::ctype<char> > & f = 
    std::use_facet<std::ctype<char> >(std::locale());
f.toupper(const_cast<char *>(str.data()), str.data() + str.size());

What does the CSS rule "clear: both" do?

CSS float and clear

Sample Fiddle

Just try to remove clear:both property from the div with class sample and see how it follows floating divs.

Nginx not picking up site in sites-enabled?

I had the same problem. It was because I had accidentally used a relative path with the symbolic link.

Are you sure you used full paths, e.g.:

ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/example.com.conf

How to split a string to 2 strings in C

You can do:

char str[] ="Stackoverflow Serverfault";
char piece1[20] = ""
    ,piece2[20] = "";
char * p;

p = strtok (str," "); // call the strtok with str as 1st arg for the 1st time.
if (p != NULL) // check if we got a token.
{
    strcpy(piece1,p); // save the token.
    p = strtok (NULL, " "); // subsequent call should have NULL as 1st arg.
    if (p != NULL) // check if we got a token.
        strcpy(piece2,p); // save the token.
}
printf("%s :: %s\n",piece1,piece2); // prints Stackoverflow :: Serverfault

If you expect more than one token its better to call the 2nd and subsequent calls to strtok in a while loop until the return value of strtok becomes NULL.

Why am I getting the message, "fatal: This operation must be run in a work tree?"

Just clone the same project in another folder and copy the .git/ folder to your project.

Example

Create temp folder:

mkdir temp

switch to temp folder

cd temp/

clone the same project in the temp folder:

git clone [-b branchName] git@path_to_your_git_repository

copy .git folder to your projet:

cp -R .git/ path/to/your/project/

switch to your project and run git status

delete the temp folder if your are finished.

hope this will help someone

MVC: How to Return a String as JSON

All answers here provide good and working code. But someone would be dissatisfied that they all use ContentType as return type and not JsonResult.

Unfortunately JsonResult is using JavaScriptSerializer without option to disable it. The best way to get around this is to inherit JsonResult.

I copied most of the code from original JsonResult and created JsonStringResult class that returns passed string as application/json. Code for this class is below

public class JsonStringResult : JsonResult
    {
        public JsonStringResult(string data)
        {
            JsonRequestBehavior = JsonRequestBehavior.DenyGet;
            Data = data;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("Get request is not allowed!");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                response.Write(Data);
            }
        }
    }

Example usage:

var json = JsonConvert.SerializeObject(data);
return new JsonStringResult(json);

How to get AM/PM from a datetime in PHP

$dateString = '08/04/2010 22:15:00';
$dateObject = new DateTime($dateString);
echo $dateObject->format('h:i A');

Why doesn't RecyclerView have onItemClickListener()?

Easiest way to do this is as follows:

Declare global variable at start of Adapter class:

// Store out here so we can resuse
private View yourItemView;

Then set the OnClickListener within the onBindViewHolder method:

@Override
public void onBindViewHolder(BusinessAdapter.ViewHolder holder, int position) {

    // Set up the on click listener
    yourItemView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(mContext,Integer.toString(position),Toast.LENGTH_SHORT).show();
        }
    });

}

All other answers are incorrect.

pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

Use the valgrind option --track-origins=yes to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.

Update: Regarding the point at which the uninitialized value is reported, the valgrind manual states:

It is important to understand that your program can copy around junk (uninitialised) data as much as it likes. Memcheck observes this and keeps track of the data, but does not complain. A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.

From the Valgrind FAQ:

As for eager reporting of copies of uninitialised memory values, this has been suggested multiple times. Unfortunately, almost all programs legitimately copy uninitialised memory values around (because compilers pad structs to preserve alignment) and eager checking leads to hundreds of false positives. Therefore Memcheck does not support eager checking at this time.

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

to install bundler that matches with your Gemfile.lock use:

gem install bundler -v "$(grep -A 1 "BUNDLED WITH" Gemfile.lock | tail -n 1)"

How can I loop through a C++ map of maps?

Do something like this:

typedef std::map<std::string, std::string> InnerMap;
typedef std::map<std::string, InnerMap> OuterMap;

Outermap mm;

...//set the initial values

for (OuterMap::iterator i = mm.begin(); i != mm.end(); ++i) {
    InnerMap &im = i->second;
    for (InnerMap::iterator ii = im.begin(); ii != im.end(); ++ii) {
        std::cout << "map[" 
                  << i->first 
                  << "][" 
                  << ii->first 
                  << "] =" 
                  << ii->second 
                  << '\n';
    }
}   

What is the difference between Serializable and Externalizable in Java?

Serialization provides default functionality to store and later recreate the object. It uses verbose format to define the whole graph of objects to be stored e.g. suppose you have a linkedList and you code like below, then the default serialization will discover all the objects which are linked and will serialize. In default serialization the object is constructed entirely from its stored bits, with no constructor calls.

  ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream("/Users/Desktop/files/temp.txt"));
        oos.writeObject(linkedListHead); //writing head of linked list
        oos.close();

But if you want restricted serialization or don't want some portion of your object to be serialized then use Externalizable. The Externalizable interface extends the Serializable interface and adds two methods, writeExternal() and readExternal(). These are automatically called while serialization or deserialization. While working with Externalizable we should remember that the default constructer should be public else the code will throw exception. Please follow the below code:

public class MyExternalizable implements Externalizable
{

private String userName;
private String passWord;
private Integer roll;

public MyExternalizable()
{

}

public MyExternalizable(String userName, String passWord, Integer roll)
{
    this.userName = userName;
    this.passWord = passWord;
    this.roll = roll;
}

@Override
public void writeExternal(ObjectOutput oo) throws IOException 
{
    oo.writeObject(userName);
    oo.writeObject(roll);
}

@Override
public void readExternal(ObjectInput oi) throws IOException, ClassNotFoundException 
{
    userName = (String)oi.readObject();
    roll = (Integer)oi.readObject();
}

public String toString()
{
    StringBuilder b = new StringBuilder();
    b.append("userName: ");
    b.append(userName);
    b.append("  passWord: ");
    b.append(passWord);
    b.append("  roll: ");
    b.append(roll);

    return b.toString();
}
public static void main(String[] args)
{
    try
    {
        MyExternalizable m  = new MyExternalizable("nikki", "student001", 20);
        System.out.println(m.toString());
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/Desktop/files/temp1.txt"));
        oos.writeObject(m);
        oos.close();

        System.out.println("***********************************************************************");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/Desktop/files/temp1.txt"));
        MyExternalizable mm = (MyExternalizable)ois.readObject();
        mm.toString();
        System.out.println(mm.toString());
    } 
    catch (ClassNotFoundException ex) 
    {
        Logger.getLogger(MyExternalizable.class.getName()).log(Level.SEVERE, null, ex);
    }
    catch(IOException ex)
    {
        Logger.getLogger(MyExternalizable.class.getName()).log(Level.SEVERE, null, ex);
    }
}
}

Here if you comment the default constructer then the code will throw below exception:

 java.io.InvalidClassException: javaserialization.MyExternalizable;     
 javaserialization.MyExternalizable; no valid constructor.

We can observe that as password is sensitive information, so i am not serializing it in writeExternal(ObjectOutput oo) method and not setting the value of same in readExternal(ObjectInput oi). That's the flexibility that is provided by Externalizable.

The output of the above code is as per below:

userName: nikki  passWord: student001  roll: 20
***********************************************************************
userName: nikki  passWord: null  roll: 20

We can observe as we are not setting the value of passWord so it's null.

The same can also be achieved by declaring the password field as transient.

private transient String passWord;

Hope it helps. I apologize if i made any mistakes. Thanks.

Selecting a row of pandas series/dataframe by integer index

echoing @HYRY, see the new docs in 0.11

http://pandas.pydata.org/pandas-docs/stable/indexing.html

Here we have new operators, .iloc to explicity support only integer indexing, and .loc to explicity support only label indexing

e.g. imagine this scenario

In [1]: df = pd.DataFrame(np.random.rand(5,2),index=range(0,10,2),columns=list('AB'))

In [2]: df
Out[2]: 
          A         B
0  1.068932 -0.794307
2 -0.470056  1.192211
4 -0.284561  0.756029
6  1.037563 -0.267820
8 -0.538478 -0.800654

In [5]: df.iloc[[2]]
Out[5]: 
          A         B
4 -0.284561  0.756029

In [6]: df.loc[[2]]
Out[6]: 
          A         B
2 -0.470056  1.192211

[] slices the rows (by label location) only

How to save and load numpy.array() data properly?

For a short answer you should use np.save and np.load. The advantages of these is that they are made by developers of the numpy library and they already work (plus are likely already optimized nicely) e.g.

import numpy as np
from pathlib import Path

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

lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2

np.save(path/'x', x)
np.save(path/'y', y)

x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')

print(x is x_loaded) # False
print(x == x_loaded) # [[ True  True  True  True  True]]

Expanded answer:

In the end it really depends in your needs because you can also save it human readable format (see this Dump a NumPy array into a csv file) or even with other libraries if your files are extremely large (see this best way to preserve numpy arrays on disk for an expanded discussion).

However, (making an expansion since you use the word "properly" in your question) I still think using the numpy function out of the box (and most code!) most likely satisfy most user needs. The most important reason is that it already works. Trying to use something else for any other reason might take you on an unexpectedly LONG rabbit hole to figure out why it doesn't work and force it work.

Take for example trying to save it with pickle. I tried that just for fun and it took me at least 30 minutes to realize that pickle wouldn't save my stuff unless I opened & read the file in bytes mode with wb. Took time to google, try thing, understand the error message etc... Small detail but the fact that it already required me to open a file complicated things in unexpected ways. To add that it required me to re-read this (which btw is sort of confusing) Difference between modes a, a+, w, w+, and r+ in built-in open function?.

So if there is an interface that meets your needs use it unless you have a (very) good reason (e.g. compatibility with matlab or for some reason your really want to read the file and printing in python really doesn't meet your needs, which might be questionable). Furthermore, most likely if you need to optimize it you'll find out later down the line (rather than spend ages debugging useless stuff like opening a simple numpy file).

So use the interface/numpy provide. It might not be perfect it's most likely fine, especially for a library that's been around as long as numpy.

I already spent the saving and loading data with numpy in a bunch of way so have fun with it, hope it helps!

import numpy as np
import pickle
from pathlib import Path

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

lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2

# using save (to npy), savez (to npz)
np.save(path/'x', x)
np.save(path/'y', y)
np.savez(path/'db', x=x, y=y)
with open(path/'db.pkl', 'wb') as db_file:
    pickle.dump(obj={'x':x, 'y':y}, file=db_file)

## using loading npy, npz files
x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')
db = np.load(path/'db.npz')
with open(path/'db.pkl', 'rb') as db_file:
    db_pkl = pickle.load(db_file)

print(x is x_loaded)
print(x == x_loaded)
print(x == db['x'])
print(x == db_pkl['x'])
print('done')

Some comments on what I learned:

  • np.save as expected, this already compresses it well (see https://stackoverflow.com/a/55750128/1601580), works out of the box without any file opening. Clean. Easy. Efficient. Use it.
  • np.savez uses a uncompressed format (see docs) Save several arrays into a single file in uncompressed .npz format. If you decide to use this (you were warned to go away from the standard solution so expect bugs!) you might discover that you need to use argument names to save it, unless you want to use the default names. So don't use this if the first already works (or any works use that!)
  • Pickle also allows for arbitrary code execution. Some people might not want to use this for security reasons.
  • human readable files are expensive to make etc. Probably not worth it.
  • there is something called hdf5 for large files. Cool! https://stackoverflow.com/a/9619713/1601580

Note this is not an exhaustive answer. But for other resources check this:

Get folder name from full file path

I think you want to get parent folder name from file path. It is easy to get. One way is to create a FileInfo type object and use its Directory property.

Example:

FileInfo fInfo = new FileInfo("c:\projects\roott\wsdlproj\devlop\beta2\text\abc.txt");

String dirName = fInfo.Directory.Name;

Tainted canvases may not be exported

For security reasons, your local drive is declared to be "other-domain" and will taint the canvas.

(That's because your most sensitive info is likely on your local drive!).

While testing try these workarounds:

  • Put all page related files (.html, .jpg, .js, .css, etc) on your desktop (not in sub-folders).

  • Post your images to a site that supports cross-domain sharing (like dropbox.com). Be sure you put your images in dropbox's public folder and also set the cross origin flag when downloading the image (var img=new Image(); img.crossOrigin="anonymous" ...)

  • Install a webserver on your development computer (IIS and PHP web servers both have free editions that work nicely on a local computer).

Reading a date using DataReader

        /// <summary>
    /// Returns a new conContractorEntity instance filled with the DataReader's current record data
    /// </summary>
    protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
    {
        return new conContractorEntity()
        {
            ConId = reader["conId"].ToString().Length > 0 ? int.Parse(reader["conId"].ToString()) : 0,
            ConEmail = reader["conEmail"].ToString(),
            ConCopyAdr = reader["conCopyAdr"].ToString().Length > 0 ? bool.Parse(reader["conCopyAdr"].ToString()) : true,
            ConCreateTime = reader["conCreateTime"].ToString().Length > 0 ? DateTime.Parse(reader["conCreateTime"].ToString()) : DateTime.MinValue
        };
    }

OR

        /// <summary>
    /// Returns a new conContractorEntity instance filled with the DataReader's current record data
    /// </summary>
    protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
    {
        return new conContractorEntity()
        {
            ConId = GetValue<int>(reader["conId"]),
            ConEmail = reader["conEmail"].ToString(),
            ConCopyAdr = GetValue<bool>(reader["conCopyAdr"], true),
            ConCreateTime = GetValue<DateTime>(reader["conCreateTime"])
        };
    }

// Base methods
        protected T GetValue<T>(object obj)
    {
        if (typeof(DBNull) != obj.GetType())
        {
            return (T)Convert.ChangeType(obj, typeof(T));
        }
        return default(T);
    }

    protected T GetValue<T>(object obj, object defaultValue)
    {
        if (typeof(DBNull) != obj.GetType())
        {
            return (T)Convert.ChangeType(obj, typeof(T));
        }
        return (T)defaultValue;
    }

Best data type for storing currency values in a MySQL database

It is also important to work out how many decimal places maybe required for your calculations.

I worked on a share price application that required the calculation of the price of one million shares. The quoted share price had to be stored to 7 digits of accuracy.

How to add anchor tags dynamically to a div in Javascript?

I recommend that you use jQuery for this, as it makes the process much easier. Here are some examples using jQuery:

$("div#id").append('<a href="' + url + '">' + text + '</a>');

If you need a list though, as in a <ul>, you can do this:

$("div#id").append('<ul>');
var ul = $("div#id > ul");

ul.append('<li><a href="' + url + '">' + text + '</a></li>');

How to unescape HTML character entities in Java?

Incase you want to mimic what php function htmlspecialchars_decode does use php function get_html_translation_table() to dump the table and then use the java code like,

static Map<String,String> html_specialchars_table = new Hashtable<String,String>();
static {
        html_specialchars_table.put("&lt;","<");
        html_specialchars_table.put("&gt;",">");
        html_specialchars_table.put("&amp;","&");
}
static String htmlspecialchars_decode_ENT_NOQUOTES(String s){
        Enumeration en = html_specialchars_table.keys();
        while(en.hasMoreElements()){
                String key = en.nextElement();
                String val = html_specialchars_table.get(key);
                s = s.replaceAll(key, val);
        }
        return s;
}

Cannot execute RUN mkdir in a Dockerfile

You can also simply use

WORKDIR /var/www/app

It will automatically create the folders if they don't exist.

Then switch back to the directory you need to be in.

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

You need to pass your data in the request body as a raw string rather than FormUrlEncodedContent. One way to do so is to serialize it into a JSON string:

var json = JsonConvert.SerializeObject(data); // or JsonSerializer.Serialize if using System.Text.Json

Now all you need to do is pass the string to the post method.

var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); // use MediaTypeNames.Application.Json in Core 3.0+ and Standard 2.1+

var client = new HttpClient();
var response = await client.PostAsync(uri, stringContent);

How to run test methods in specific order in JUnit4?

If the order is important, you should make the order yourself.

@Test public void test1() { ... }
@Test public void test2() { test1(); ... }

In particular, you should list some or all possible order permutations to test, if necessary.

For example,

void test1(); 
void test2(); 
void test3(); 


@Test
public void testOrder1() { test1(); test3(); }

@Test(expected = Exception.class)
public void testOrder2() { test2(); test3(); test1(); }

@Test(expected = NullPointerException.class)
public void testOrder3() { test3(); test1(); test2(); }

Or, a full test of all permutations:

@Test
public void testAllOrders() {
    for (Object[] sample: permute(1, 2, 3)) {
        for (Object index: sample) {
            switch (((Integer) index).intValue()) {
                case 1: test1(); break; 
                case 2: test2(); break; 
                case 3: test3(); break; 
            }
        }
    }
}

Here, permute() is a simple function which iterates all possible permuations into a Collection of array.

Erasing elements from a vector

Depending on why you are doing this, using a std::set might be a better idea than std::vector.

It allows each element to occur only once. If you add it multiple times, there will only be one instance to erase anyway. This will make the erase operation trivial. The erase operation will also have lower time complexity than on the vector, however, adding elements is slower on the set so it might not be much of an advantage.

This of course won't work if you are interested in how many times an element has been added to your vector or the order the elements were added.

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

Actually you can add in your manifest these lines android:hardwareAccelerated="false" , android:largeHeap="true" it is working for some situations, but be aware that the other part of code can be arguing with this.

<application
    android:allowBackup="true"
    android:hardwareAccelerated="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

How to explain callbacks in plain english? How are they different from calling one function from another function?

In plain english a callback is a promise. Joe, Jane, David and Samantha share a carpool to work. Joe is driving today. Jane, David and Samantha have a couple of options:

  1. Check the window every 5 minutes to see if Joe is out
  2. Keep doing their thing until Joe rings the door bell.

Option 1: This is more like a polling example where Jane would be stuck in a "loop" checking if Joe is outside. Jane can't do anything else in the mean time.

Option 2: This is the callback example. Jane tells Joe to ring her doorbell when he's outside. She gives him a "function" to ring the door bell. Joe does not need to know how the door bell works or where it is, he just needs to call that function i.e. ring the door bell when he's there.

Callbacks are driven by "events". In this example the "event" is Joe's arrival. In Ajax for example events can be "success" or "failure" of the asynchronous request and each can have the same or different callbacks.

In terms of JavaScript applications and callbacks. We also need to understand "closures" and application context. What "this" refers to can easily confuse JavaScript developers. In this example within each person's "ring_the_door_bell()" method/callback there might be some other methods that each person need to do based on their morning routine ex. "turn_off_the_tv()". We would want "this" to refer to the "Jane" object or the "David" object so that each can setup whatever else they need done before Joe picks them up. This is where setting up the callback with Joe requires parodying the method so that "this" refers to the right object.

Hope that helps!

How best to include other scripts?

You need to specify the location of the other scripts, there is no other way around it. I'd recommend a configurable variable at the top of your script:

#!/bin/bash
installpath=/where/your/scripts/are

. $installpath/incl.sh

echo "The main script"

Alternatively, you can insist that the user maintain an environment variable indicating where your program home is at, like PROG_HOME or somesuch. This can be supplied for the user automatically by creating a script with that information in /etc/profile.d/, which will be sourced every time a user logs in.

URL encoding in Android

You don't encode the entire URL, only parts of it that come from "unreliable sources".

  • Java:

    String query = URLEncoder.encode("apples oranges", "utf-8");
    String url = "http://stackoverflow.com/search?q=" + query;
    
  • Kotlin:

    val query: String = URLEncoder.encode("apples oranges", "utf-8")
    val url = "http://stackoverflow.com/search?q=$query"
    

Alternatively, you can use Strings.urlEncode(String str) of DroidParts that doesn't throw checked exceptions.

Or use something like

String uri = Uri.parse("http://...")
                .buildUpon()
                .appendQueryParameter("key", "val")
                .build().toString();

How to get single value of List<object>

You can access the fields by indexing the object array:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}

ExpressJS - throw er Unhandled error event

You had run another server use the same port like 8080.

Maybe you had run node app in other shell, Please close it and run again.

You can check PORT no. is available or not using

netstat -tulnp | grep <port no>

Alternatively, you can use lsof:

lsof -i :<port no>

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

I ran into this issue while making REST calls from my app server running in AWS EC2. The following Steps fixed the issue for me.

  1. curl -vs https://your_rest_path
  2. echo | openssl s_client -connect your_domain:443
  3. sudo apt-get install ca-certificates

curl -vs https://your_rest_path will now work!

How to get the first and last date of the current year?

select to_date(substr(sysdate,1, 4) || '01/01'), to_date(substr(sysdate,1, 4) || '12/31') 
from dual

Is __init__.py not required for packages in Python 3.3+

I would say that one should omit the __init__.py only if one wants to have the implicit namespace package. If you don't know what it means, you probably don't want it and therefore you should continue to use the __init__.py even in Python 3.

How to Set Opacity (Alpha) for View in Android

I guess you may have already found the answer, but if not (and for other developers), you can do it like this:

btnMybutton.getBackground().setAlpha(45);

Here I have set the opacity to 45. You can basically set it from anything between 0(fully transparent) to 255 (completely opaque)

How to pass an array to a function in VBA?

Your function worked for me after changing its declaration to this ...

Function processArr(Arr As Variant) As String

You could also consider a ParamArray like this ...

Function processArr(ParamArray Arr() As Variant) As String
    'Dim N As Variant
    Dim N As Long
    Dim finalStr As String
    For N = LBound(Arr) To UBound(Arr)
        finalStr = finalStr & Arr(N)
    Next N
    processArr = finalStr
End Function

And then call the function like this ...

processArr("foo", "bar")

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

Should I use(or both) for signing apk for play store release? An answer is YES.

As per https://source.android.com/security/apksigning/v2.html#verification :

In Android 7.0, APKs can be verified according to the APK Signature Scheme v2 (v2 scheme) or JAR signing (v1 scheme). Older platforms ignore v2 signatures and only verify v1 signatures.

I tried to generate build with checking V2(Full Apk Signature) option. Then when I tried to install a release build in below 7.0 device and I am unable to install build in the device.

After that I tried to build by checking both version checkbox and generate release build. Then able to install build.

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I also have the same problem, and the solution is I didn't bind the event in my onClick. so when it renders for the first time and the data is more, which ends up calling the state setter again, which triggers React to call your function again and so on.

export default function Component(props) {

function clickEvent (event, variable){
    console.log(variable);
}

return (
    <div>
        <IconButton
            key="close"
            aria-label="Close"
            color="inherit"
            onClick={e => clickEvent(e, 10)} // or you can call like this:onClick={() => clickEvent(10)} 
        >
    </div>
)
}

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

Got the same problem, found the following bug report in SQL Server 2012 If still relevant see conditions that cause the issue - there are some workarounds there as well (didn't try though). Failover or Restart Results in Reseed of Identity

What is uintptr_t data type

First thing, at the time the question was asked, uintptr_t was not in C++. It's in C99, in <stdint.h>, as an optional type. Many C++03 compilers do provide that file. It's also in C++11, in <cstdint>, where again it is optional, and which refers to C99 for the definition.

In C99, it is defined as "an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer".

Take this to mean what it says. It doesn't say anything about size.

uintptr_t might be the same size as a void*. It might be larger. It could conceivably be smaller, although such a C++ implementation approaches perverse. For example on some hypothetical platform where void* is 32 bits, but only 24 bits of virtual address space are used, you could have a 24-bit uintptr_t which satisfies the requirement. I don't know why an implementation would do that, but the standard permits it.

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

Websocket onerror - how to read error description?

Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).

you will almost never get these codes in practice so this code is pretty much pointless

var websocket;
if ("WebSocket" in window)
{
    websocket = new WebSocket("ws://yourDomainNameHere.org/");

    websocket.onopen = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
    };
    websocket.onclose = function (event) {
        var reason;
        alert(event.code);
        // See http://tools.ietf.org/html/rfc6455#section-7.4.1
        if (event.code == 1000)
            reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
        else if(event.code == 1001)
            reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
        else if(event.code == 1002)
            reason = "An endpoint is terminating the connection due to a protocol error";
        else if(event.code == 1003)
            reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
        else if(event.code == 1004)
            reason = "Reserved. The specific meaning might be defined in the future.";
        else if(event.code == 1005)
            reason = "No status code was actually present.";
        else if(event.code == 1006)
           reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
        else if(event.code == 1007)
            reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
        else if(event.code == 1008)
            reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
        else if(event.code == 1009)
           reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
        else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
            reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
        else if(event.code == 1011)
            reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
        else if(event.code == 1015)
            reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
        else
            reason = "Unknown reason";

        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
    };
    websocket.onmessage = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
    };
    websocket.onerror = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
    };
}
else
{
    alert("Websocket is not supported by your browser");
    return;
}

websocket.send("Yo wazzup");

websocket.close();

See http://jsfiddle.net/gr0bhrqr/

When to use: Java 8+ interface default method, vs. abstract method

when should interface with default methods be used and when should an abstract class be used?

Backward compatibility: Imagine that your interface is implemented by hundreds of classes, modifying that interface will force all the users to implement the newly added method, even though it could be not essential for many other classes that implements your interface, Plus it allows your interface to be a functional interface

Facts & Restrictions:

1-May only be declared within an interface and not within a class or abstract class.

2-Must provide a body

3-It is not assumed to be abstract as other normal methods used in an interface.

Why am I getting a "401 Unauthorized" error in Maven?

in my case, after encrypting password,I forgot to put settings-security.xml into ~/.m2?

PHPExcel how to set cell value dynamically

I asume you have connected to your database already.

$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);

$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
    $col = 0;
    foreach($row_data as $key=>$value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}

printf a variable in C

As Shafik already wrote you need to use the right format because scanf gets you a char. Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/

Hint: It's faster/nicer to write x=x+1; the shorter way: x++;

Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.

How to get error message when ifstream open fails

Every system call that fails update the errno value.

Thus, you can have more information about what happens when a ifstream open fails by using something like :

cerr << "Error: " << strerror(errno);

However, since every system call updates the global errno value, you may have issues in a multithreaded application, if another system call triggers an error between the execution of the f.open and use of errno.

On system with POSIX standard:

errno is thread-local; setting it in one thread does not affect its value in any other thread.


Edit (thanks to Arne Mertz and other people in the comments):

e.what() seemed at first to be a more C++-idiomatically correct way of implementing this, however the string returned by this function is implementation-dependant and (at least in G++'s libstdc++) this string has no useful information about the reason behind the error...

C compile : collect2: error: ld returned 1 exit status

generally this problem occurred when we have called a function which has not been define in the program file, so to sort out this problem check whether have you called such function which has not been define in the program file.

insert a NOT NULL column to an existing table

As an option you can initially create Null-able column, then update your table column with valid not null values and finally ALTER column to set NOT NULL constraint:

ALTER TABLE MY_TABLE ADD STAGE INT NULL
GO
UPDATE MY_TABLE SET <a valid not null values for your column>
GO
ALTER TABLE MY_TABLE ALTER COLUMN STAGE INT NOT NULL
GO

Another option is to specify correct default value for your column:

ALTER TABLE MY_TABLE ADD STAGE INT NOT NULL DEFAULT '0'

UPD: Please note that answer above contains GO which is a must when you run this code on Microsoft SQL server. If you want to perform the same operation on Oracle or MySQL you need to use semicolon ; like that:

ALTER TABLE MY_TABLE ADD STAGE INT NULL;
UPDATE MY_TABLE SET <a valid not null values for your column>;
ALTER TABLE MY_TABLE ALTER COLUMN STAGE INT NOT NULL;

How do I check if there are duplicates in a flat list?

def check_duplicates(my_list):
    seen = {}
    for item in my_list:
        if seen.get(item):
            return True
        seen[item] = True
    return False

Initialization of all elements of an array to one default value in C++?

Should be a standard feature but for some reason it's not included in standard C nor C++...

#include <stdio.h>

 __asm__
 (
"    .global _arr;      "
"    .section .data;    "
"_arr: .fill 100, 1, 2; "
 );

extern char arr[];

int main() 
{
    int i;

    for(i = 0; i < 100; ++i) {
        printf("arr[%u] = %u.\n", i, arr[i]);
    }
}

In Fortran you could do:

program main
    implicit none

    byte a(100)
    data a /100*2/
    integer i

    do i = 0, 100
        print *, a(i)
    end do
end

but it does not have unsigned numbers...

Why can't C/C++ just implement it. Is it really so hard? It's so silly to have to write this manually to achieve the same result...

#include <stdio.h>
#include <stdint.h>

/* did I count it correctly? I'm not quite sure. */
uint8_t arr = {
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
};    

int main() 
{
    int i;

    for(i = 0; i < 100; ++i) {
        printf("arr[%u] = %u.\n", i, arr[i]);
    }
}

What if it was an array of 1,000,00 bytes? I'd need to write a script to write it for me, or resort to hacks with assembly/etc. This is nonsense.

It's perfectly portable, there's no reason for it not to be in the language.

Just hack it in like:

#include <stdio.h>
#include <stdint.h>

/* a byte array of 100 twos declared at compile time. */
uint8_t twos[] = {100:2};

int main()
{
    uint_fast32_t i;
    for (i = 0; i < 100; ++i) {
        printf("twos[%u] = %u.\n", i, twos[i]);
    }

    return 0;
}

One way to hack it in is via preprocessing... (Code below does not cover edge cases, but is written to quickly demonstrate what could be done.)

#!/usr/bin/perl
use warnings;
use strict;

open my $inf, "<main.c";
open my $ouf, ">out.c";

my @lines = <$inf>;

foreach my $line (@lines) {
    if ($line =~ m/({(\d+):(\d+)})/) {
        printf ("$1, $2, $3");        
        my $lnew = "{" . "$3, "x($2 - 1) . $3 . "}";
        $line =~ s/{(\d+:\d+)}/$lnew/;
        printf $ouf $line;
    } else {
        printf $ouf $line;
    }
}

close($ouf);
close($inf);

How do I convert a file path to a URL in ASP.NET

this is what i use:

private string MapURL(string path)
{
    string appPath = Server.MapPath("/").ToLower();
    return string.Format("/{0}", path.ToLower().Replace(appPath, "").Replace(@"\", "/"));
 }

Pythonic way to find maximum value and its index in a list?

I think the accepted answer is great, but why don't you do it explicitly? I feel more people would understand your code, and that is in agreement with PEP 8:

max_value = max(my_list)
max_index = my_list.index(max_value)

This method is also about three times faster than the accepted answer:

import random
from datetime import datetime
import operator

def explicit(l):
    max_val = max(l)
    max_idx = l.index(max_val)
    return max_idx, max_val

def implicit(l):
    max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1))
    return max_idx, max_val

if __name__ == "__main__":
    from timeit import Timer
    t = Timer("explicit(l)", "from __main__ import explicit, implicit; "
          "import random; import operator;"
          "l = [random.random() for _ in xrange(100)]")
    print "Explicit: %.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)

    t = Timer("implicit(l)", "from __main__ import explicit, implicit; "
          "import random; import operator;"
          "l = [random.random() for _ in xrange(100)]")
    print "Implicit: %.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)

Results as they run in my computer:

Explicit: 8.07 usec/pass
Implicit: 22.86 usec/pass

Other set:

Explicit: 6.80 usec/pass
Implicit: 19.01 usec/pass

How do I get the path to the current script with Node.js?

I know this is pretty old, and the original question I was responding to is marked as duplicate and directed here, but I ran into an issue trying to get jasmine-reporters to work and didn't like the idea that I had to downgrade in order for it to work. I found out that jasmine-reporters wasn't resolving the savePath correctly and was actually putting the reports folder output in jasmine-reporters directory instead of the root directory of where I ran gulp. In order to make this work correctly I ended up using process.env.INIT_CWD to get the initial Current Working Directory which should be the directory where you ran gulp. Hope this helps someone.

var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
  savePath: process.env.INIT_CWD + '/report/e2e/',
  consolidateAll: true,
  captureStdout: true
 });

Run a JAR file from the command line and specify classpath

When you specify -jar then the -cp parameter will be ignored.

From the documentation:

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)

You have two options:

  1. include all jar files from the lib directory into the manifest (you can use relative paths there)
  2. Specify everything (including your jar) on the commandline using -cp:
    java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

Searching a list of objects in Python

Just for completeness, let's not forget the Simplest Thing That Could Possibly Work:

for i in list:
  if i.n == 5:
     # do something with it
     print "YAY! Found one!"

Memcached vs. Redis?

A very simple test to set and get 100k unique keys and values against redis-2.2.2 and memcached. Both are running on linux VM(CentOS) and my client code(pasted below) runs on windows desktop.

Redis

  • Time taken to store 100000 values is = 18954ms

  • Time taken to load 100000 values is = 18328ms

Memcached

  • Time taken to store 100000 values is = 797ms

  • Time taken to retrieve 100000 values is = 38984ms


Jedis jed = new Jedis("localhost", 6379);
int count = 100000;
long startTime = System.currentTimeMillis();
for (int i=0; i<count; i++) {
  jed.set("u112-"+i, "v51"+i);
}
long endTime = System.currentTimeMillis();
System.out.println("Time taken to store "+ count + " values is ="+(endTime-startTime)+"ms");

startTime = System.currentTimeMillis();
for (int i=0; i<count; i++) {
  client.get("u112-"+i);
}
endTime = System.currentTimeMillis();
System.out.println("Time taken to retrieve "+ count + " values is ="+(endTime-startTime)+"ms");

Ruby on Rails: how to render a string as HTML?

The html_safe version works well in Rails 4...

<%= "<center style=\"color: green; font-size: 1.1em\" > Administrators only </center>".html_safe if current_user.admin? %
>

What is a postback?

The term is also used in web application development when interacting with 3rd party web-service APIs

Many APIs require both an interactive and non-interactive integration. Typically the interactive part is done using redirects (site 1 redirects a user to site 2, where they sign in, and are redirected back). The non-interactive part is done using a 'postback', or an HTTP POST from site 2's servers to site 1's servers.

Convert blob URL to normal URL

A URL that was created from a JavaScript Blob can not be converted to a "normal" URL.

A blob: URL does not refer to data the exists on the server, it refers to data that your browser currently has in memory, for the current page. It will not be available on other pages, it will not be available in other browsers, and it will not be available from other computers.

Therefore it does not make sense, in general, to convert a Blob URL to a "normal" URL. If you wanted an ordinary URL, you would have to send the data from the browser to a server and have the server make it available like an ordinary file.

It is possible convert a blob: URL into a data: URL, at least in Chrome. You can use an AJAX request to "fetch" the data from the blob: URL (even though it's really just pulling it out of your browser's memory, not making an HTTP request).

Here's an example:

_x000D_
_x000D_
var blob = new Blob(["Hello, world!"], { type: 'text/plain' });_x000D_
var blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
var xhr = new XMLHttpRequest;_x000D_
xhr.responseType = 'blob';_x000D_
_x000D_
xhr.onload = function() {_x000D_
   var recoveredBlob = xhr.response;_x000D_
_x000D_
   var reader = new FileReader;_x000D_
_x000D_
   reader.onload = function() {_x000D_
     var blobAsDataUrl = reader.result;_x000D_
     window.location = blobAsDataUrl;_x000D_
   };_x000D_
_x000D_
   reader.readAsDataURL(recoveredBlob);_x000D_
};_x000D_
_x000D_
xhr.open('GET', blobUrl);_x000D_
xhr.send();
_x000D_
_x000D_
_x000D_

data: URLs are probably not what you mean by "normal" and can be problematically large. However they do work like normal URLs in that they can be shared; they're not specific to the current browser or session.

Maven: How do I activate a profile from command line?

I have encountered this problem and i solved mentioned problem by adding -DprofileIdEnabled=true parameter while running mvn cli command.

Please run your mvn cli command as : mvn clean install -Pdev1 -DprofileIdEnabled=true.

In addition to this solution, you don't need to remove activeByDefault settings in your POM mentioned as previouses answer.

I hope this answer solve your problem.

how to get last insert id after insert query in codeigniter active record

From the documentation:

$this->db->insert_id()

The insert ID number when performing database inserts.

Therefore, you could use something like this:

$lastid = $this->db->insert_id();

How to secure the ASP.NET_SessionId cookie?

Going with Marcel's solution above to secure Forms Authentication cookie you should also update "authentication" config element to use SSL

<authentication mode="Forms">
   <forms ...  requireSSL="true" />
</authentication>

Other wise authentication cookie will not be https

See: http://msdn.microsoft.com/en-us/library/vstudio/1d3t3c61(v=vs.100).aspx

How do I set GIT_SSL_NO_VERIFY for specific repos only?

This works for me:

git init
git config --global http.sslVerify false
git clone https://myurl/myrepo.git

Python not working in the command line of git bash

I know this is an old post, but I just came across this problem on Windows 10 running Python 3.8.5 and Git 2.28.0.windows.1

Somehow I had several different 2.7x versions of Python installed as well. I removed every version of Python (3x and 2x), downloaded the official installer here, installed 3.8.5 fresh (just used the defaults) which installed Python 3.8.5 at this location:

C:\Users\(my username)\AppData\Local\Programs\Python\Python38

Then to get the command python to work in my git bash shell, I had to manually add the path to Python38 to my path variable following the instructions listed here. This is important to note because on the python installer at the bottom of the first modal that comes up it asks if you want to add the python path to your PATH environment variable. I clicked the checkbox next to this but it didn't actually add the path, hence the need to manually add the path to my PATH environment variable.

Now using my gitbash shell I can browse to a directory with a python script in it and just type python theScriptName.py and it runs no problem.

I wanted to post this because this is all I had to do to get my gitbash shell to allow me to run python scripts. I think there might have been some updates so I didn't need to do any of the other solutions listed here. At any rate, this is another thing to try if you are having issues running python scripts in your gitbash shell on a Windows 10 machine.

Enjoy.

How do I add a auto_increment primary key in SQL Server database?

It can be done in a single command. You need to set the IDENTITY property for "auto number":

ALTER TABLE MyTable ADD mytableID int NOT NULL IDENTITY (1,1) PRIMARY KEY

More precisely, to set a named table level constraint:

ALTER TABLE MyTable
   ADD MytableID int NOT NULL IDENTITY (1,1),
   CONSTRAINT PK_MyTable PRIMARY KEY CLUSTERED (MyTableID)

See ALTER TABLE and IDENTITY on MSDN

How to check if a String contains any letter from a to z?

Use regular expression no need to convert it to char array

if(Regex.IsMatch("yourString",".*?[a-zA-Z].*?"))
{
errorCounter++;
}

Saving numpy array to txt file row wise

I found that the first solution in the accepted answer to be problematic for cases where the newline character is still required. The easiest solution to the problem was doing this:

numpy.savetxt(filename, [a], delimiter='\t')

iOS 6 apps - how to deal with iPhone 5 screen size?

You need to add a 640x1136 pixels PNG image ([email protected]) as a 4 inch default splash image of your project, and it will use extra spaces (without efforts on simple table based applications, games will require more efforts).

I've created a small UIDevice category in order to deal with all screen resolutions. You can get it here, but the code is as follows:

File UIDevice+Resolutions.h:

enum {
    UIDeviceResolution_Unknown           = 0,
    UIDeviceResolution_iPhoneStandard    = 1,    // iPhone 1,3,3GS Standard Display  (320x480px)
    UIDeviceResolution_iPhoneRetina4    = 2,    // iPhone 4,4S Retina Display 3.5"  (640x960px)
    UIDeviceResolution_iPhoneRetina5     = 3,    // iPhone 5 Retina Display 4"       (640x1136px)
    UIDeviceResolution_iPadStandard      = 4,    // iPad 1,2,mini Standard Display   (1024x768px)
    UIDeviceResolution_iPadRetina        = 5     // iPad 3 Retina Display            (2048x1536px)
}; typedef NSUInteger UIDeviceResolution;

@interface UIDevice (Resolutions)

- (UIDeviceResolution)resolution;

NSString *NSStringFromResolution(UIDeviceResolution resolution);

@end

File UIDevice+Resolutions.m:

#import "UIDevice+Resolutions.h"

@implementation UIDevice (Resolutions)

- (UIDeviceResolution)resolution
{
    UIDeviceResolution resolution = UIDeviceResolution_Unknown;
    UIScreen *mainScreen = [UIScreen mainScreen];
    CGFloat scale = ([mainScreen respondsToSelector:@selector(scale)] ? mainScreen.scale : 1.0f);
    CGFloat pixelHeight = (CGRectGetHeight(mainScreen.bounds) * scale);

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){
        if (scale == 2.0f) {
            if (pixelHeight == 960.0f)
                resolution = UIDeviceResolution_iPhoneRetina4;
            else if (pixelHeight == 1136.0f)
                resolution = UIDeviceResolution_iPhoneRetina5;

        } else if (scale == 1.0f && pixelHeight == 480.0f)
            resolution = UIDeviceResolution_iPhoneStandard;

    } else {
        if (scale == 2.0f && pixelHeight == 2048.0f) {
            resolution = UIDeviceResolution_iPadRetina;

        } else if (scale == 1.0f && pixelHeight == 1024.0f) {
            resolution = UIDeviceResolution_iPadStandard;
        }
    }

    return resolution;
 }

 @end

This is how you need to use this code.

1) Add the above UIDevice+Resolutions.h & UIDevice+Resolutions.m files to your project

2) Add the line #import "UIDevice+Resolutions.h" to your ViewController.m

3) Add this code to check what versions of device you are dealing with

int valueDevice = [[UIDevice currentDevice] resolution];

    NSLog(@"valueDevice: %d ...", valueDevice);

    if (valueDevice == 0)
    {
        //unknow device - you got me!
    }
    else if (valueDevice == 1)
    {
        //standard iphone 3GS and lower
    }
    else if (valueDevice == 2)
    {
        //iphone 4 & 4S
    }
    else if (valueDevice == 3)
    {
        //iphone 5
    }
    else if (valueDevice == 4)
    {
        //ipad 2
    }
    else if (valueDevice == 5)
    {
        //ipad 3 - retina display
    }

Using request.setAttribute in a JSP page

You can do it using pageContext attributes, though:

In the JSP:

<form action="Enter.do">
    <button type="SUBMIT" id="btnSubmit" name="btnSubmit">SUBMIT</button>
</form>
<% String s="opportunity";
pageContext.setAttribute("opp", s, PageContext.APPLICATION_SCOPE); %>

In the Servlet (linked to the "Enter.do" url-pattern):

String s=(String) request.getServletContext().getAttribute("opp");

There are other scopes besides APPLICATION_SCOPE like SESSION_SCOPE. APPLICATION_SCOPE is used for ServletContext attributes.

formGroup expects a FormGroup instance

I was using reactive forms and ran into similar problems. What helped me was to make sure that I set up a corresponding FormGroup in the class. Something like this:

myFormGroup: FormGroup = this.builder.group({
    dob: ['', Validators.required]
});

how to dynamically add options to an existing select in vanilla javascript

Try this;

   var data = "";
   data = "<option value = Some value> Some Option </option>";         
   options = [];
   options.push(data);
   select = document.getElementById("drop_down_id");
   select.innerHTML = optionsHTML.join('\n'); 

How can I delete a newline if it is the last character in a file?

You can take advantage of the fact that shell command substitutions remove trailing newline characters:

Simple form that works in bash, ksh, zsh:

printf %s "$(< in.txt)" > out.txt

Portable (POSIX-compliant) alternative (slightly less efficient):

printf %s "$(cat in.txt)" > out.txt

Note:


A guide to the other answers:

  • If Perl is available, go for the accepted answer - it is simple and memory-efficient (doesn't read the whole input file at once).

  • Otherwise, consider ghostdog74's Awk answer - it's obscure, but also memory-efficient; a more readable equivalent (POSIX-compliant) is:

  • awk 'NR > 1 { print prev } { prev=$0 } END { ORS=""; print }' in.txt

  • Printing is delayed by one line so that the final line can be handled in the END block, where it is printed without a trailing \n due to setting the output-record separator (OFS) to an empty string.

  • If you want a verbose, but fast and robust solution that truly edits in-place (as opposed to creating a temp. file that then replaces the original), consider jrockway's Perl script.

How to run C program on Mac OS X using Terminal?

First save your program as program.c.

Now you need the compiler, so you need to go to App Store and install Xcode which is Apple's compiler and development tools. How to find App Store? Do a "Spotlight Search" by typing Space and start typing App Store and hit Enter when it guesses correctly.

App Store looks like this:

enter image description here

Xcode looks like this on App Store:

enter image description here

Then you need to install the command-line tools in Terminal. How to start Terminal? You need to do another "Spotlight Search", which means you type Space and start typing Terminal and hit Enter when it guesses Terminal.

Now install the command-line tools like this:

xcode-select --install

Then you can compile your code with by simply running gcc as in the next line without having to fire up the big, ugly software development GUI called Xcode:

gcc -Wall -o program program.c

Note: On newer versions of OS X, you would use clang instead of gcc, like this:

clang program.c -o program

Then you can run it with:

./program
Hello, world!

If your program is C++, you'll probably want to use one of these commands:

clang++ -o program program.cpp
g++ -std=c++11 -o program program.cpp
g++-7 -std=c++11 -o program program.cpp

Most recent previous business day in Python

Why don't you try something like:

lastBusDay = datetime.datetime.today()
if datetime.date.weekday(lastBusDay) not in range(0,5):
    lastBusDay = 5

ImportError: No module named model_selection

To install scikit-learn version 18.0, I used both commands:

conda update scikit-learn

pip install -U scikit-learn

But it does not work. There was a problem "Cannot install 'scikit-learn'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall".

Finally, i can install it by using following command:

pip install --user --upgrade scikit-learn==0.18.0

how to insert date and time in oracle?

Try this:

...(to_date('2011/04/22 08:30:00', 'yyyy/mm/dd hh24:mi:ss'));

deleted object would be re-saved by cascade (remove deleted object from associations)

Some how all the above solutions did not worked in hibernate 5.2.10.Final.

But setting the map to null as below worked for me:

playlist.setPlaylistadMaps(null);

How to export and import environment variables in windows?

My favorite method for doing this is to write it out as a batch script to combine both user variables and system variables into a single backup file like so, create an environment-backup.bat file and put in it:

@echo off
:: RegEdit can only export into a single file at a time, so create two temporary files.
regedit /e "%CD%\environment-backup1.reg" "HKEY_CURRENT_USER\Environment"
regedit /e "%CD%\environment-backup2.reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

:: Concatenate into a single file and remove temporary files.
type "%CD%\environment-backup1.reg" "%CD%\environment-backup2.reg" > environment-backup.reg
del "%CD%\environment-backup1.reg"
del "%CD%\environment-backup2.reg"

This creates environment-backup.reg which you can use to re-import existing environment variables. This will add & override new variables, but not delete existing ones :)

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

For some reason, even if changing the iOS Deployment Target to 8.0 or higher, the Xib files don't adopt that change and remain with the previous settings in the File inspector

File inspector in the Xib after changing the iOS Deployment target

Therefore, you should change it manually for each Xib Afther the manual change

Once done, the warning will disappear :-)

C error: Expected expression before int

This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570

I guess the counter-intuitive part of the question is: if this is correct C:

if (a == 1) {
  int b = 10;
}

then why is this not also correct C?

if (a == 1)
  int b = 10;

I mean, a one-line conditional if statement should be fine either with or without braces, right?

The answer lies in the grammar of the if statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10 line is a declaration, not a statement, and the grammar for the if statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.

And just for the sake of answering the question completely -- this has nothing to do with scope. The b variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror anyways ;-)

(6.7) declaration:
            declaration-speci?ers init-declarator-listopt ;
            static_assert-declaration

(6.7) init-declarator-list:
            init-declarator
            init-declarator-list , init-declarator

(6.7) init-declarator:
            declarator
            declarator = initializer

(6.8) statement:
            labeled-statement
            compound-statement
            expression-statement
            selection-statement
            iteration-statement
            jump-statement

(6.8.2) compound-statement:
            { block-item-listopt }

(6.8.4) selection-statement:
            if ( expression ) statement
            if ( expression ) statement else statement
            switch ( expression ) statement

Clear the cache in JavaScript

Other than caching every hour, or every week, you may cache according to file data.

Example (in PHP):

<script src="js/my_script.js?v=<?=md5_file('js/my_script.js')?>"></script>

or even use file modification time:

<script src="js/my_script.js?v=<?=filemtime('js/my_script.js')?>"></script>

CSS: how to get scrollbars for div inside container of fixed height

setting the overflow should take care of it, but you need to set the height of Content also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.

See Example: http://jsfiddle.net/ftkbL/1/

Convert a string into an int

I had to do something like this but wanted to use a getter/setter for mine. In particular I wanted to return a long from a textfield. The other answers all worked well also, I just ended up adapting mine a little as my school project evolved.

long ms = [self.textfield.text longLongValue];
return ms;

How to force the browser to reload cached CSS and JavaScript files

Many answers here advocate adding a timestamp to the URL. Unless you are modifying your production files directly, the file's timestamp is not likely to reflect the time when a file was changed. In most cases this will cause the URL to change more frequently than the file itself. This is why you should use a fast hash of the file's contents such as MD5 as levik and others have suggested.

Keep in mind that the value should be calculated once at build or run, rather than each time the file is requested.

As an example, here's a simple bash script that reads a list of filenames from standard input and writes a JSON file containing hashes to standard output:

#!/bin/bash
# Create a JSON map from filenames to MD5 hashes
# Run as hashes.sh < inputfile.list > outputfile.json

echo "{"
delim=""
while read l; do
    echo "$delim\"$l\": \"`md5 -q $l`\""
    delim=","
done
echo "}"

This file could then be loaded at server startup and referenced instead of reading the file system.

Check if a specific value exists at a specific key in any subarray of a multidimensional array

** PHP >= 5.5

simply u can use this

$key = array_search(40489, array_column($userdb, 'uid'));

Let's suppose this multi dimensional array:

$userdb=Array
(
(0) => Array
    (
        (uid) => '100',
        (name) => 'Sandra Shush',
        (url) => 'urlof100'
    ),

(1) => Array
    (
        (uid) => '5465',
        (name) => 'Stefanie Mcmohn',
        (pic_square) => 'urlof100'
    ),

(2) => Array
    (
        (uid) => '40489',
        (name) => 'Michael',
        (pic_square) => 'urlof40489'
    )
);

$key = array_search(40489, array_column($userdb, 'uid'));

How to get keyboard input in pygame?

You should use clock.tick(10) as stated in the docs.

Find the server name for an Oracle database

The query below demonstrates use of the package and some of the information you can get.

select sys_context ( 'USERENV', 'DB_NAME' ) db_name,
sys_context ( 'USERENV', 'SESSION_USER' ) user_name,
sys_context ( 'USERENV', 'SERVER_HOST' ) db_host,
sys_context ( 'USERENV', 'HOST' ) user_host
from dual

NOTE: The parameter ‘SERVER_HOST’ is available in 10G only.

Any Oracle User that can connect to the database can run a query against “dual”. No special permissions are required and SYS_CONTEXT provides a greater range of application-specific information than “sys.v$instance”.

Update GCC on OSX

The following recipe using Homebrew worked for me to update to gcc/g++ 4.7:

$ brew tap SynthiNet/synthinet
$ brew install gcc47

Found it on a post here.

Subprocess check_output returned non-zero exit status 1

The command yum that you launch was executed properly. It returns a non zero status which means that an error occured during the processing of the command. You probably want to add some argument to your yum command to fix that.

Your code could show this error this way:

import subprocess
try:
    subprocess.check_output("dir /f",shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))

Enable vertical scrolling on textarea

You can try adding:

#aboutDescription
{
    height: 100px;
    max-height: 100px;  
}

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

shape is a property of both numpy ndarray's and matrices.

A.shape

will return a tuple (m, n), where m is the number of rows, and n is the number of columns.

In fact, the numpy matrix object is built on top of the ndarray object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray

Xcode warning: "Multiple build commands for output file"

The error seem to appear when u have more than one reference of the same file. I had 2 files of the same name and got this error. When I delete one of them the error disappear..

Android fastboot waiting for devices

In my case (on windows 10), it would connect fine to adb and I could type any adb commands. But as soon as it got to the bootloader using adb reboot bootloader I wasn't able to perform any fastboot commands.

What I did notice that in the device manager that it refreshed when I connected to device. Next thing to do was to check what changed when connecting. Apparently the fastboot device was inside the Kedacom USB Device. Not really sure what that was, but I updated the device to use a different driver, in my case the Fastboot interface (Google USB ID), and that fixed my waiting for device issue

convert base64 to image in javascript/jquery

Have to add this based on @Joseph's answer. If someone want to create image object:

var image = new Image();
image.onload = function(){
   console.log(image.width); // image is loaded and we have image width 
}
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

How do I update/upsert a document in Mongoose?

You were close with

Contact.update({phone:request.phone}, contact, {upsert: true}, function(err){...})

but your second parameter should be an object with a modification operator for example

Contact.update({phone:request.phone}, {$set: { phone: request.phone }}, {upsert: true}, function(err){...})

bootstrap 3 - how do I place the brand in the center of the navbar?

Use these classes: navbar-brand mx-auto

All other solutions overcomplicate the matter.

JQuery addclass to selected div, remove class if another div is selected

**This can be achived easily using two different ways:**

1)We can also do this by using addClass and removeClass of Jquery
2)Toggle class of jQuery

**1)First Way**

$(documnet.ready(function(){
$('#dvId').click(function(){
  $('#dvId').removeClass('active class or your class name which you want to    remove').addClass('active class or your class name which you want to add');     
});
});

**2) Second Way**

i) Here we need to add the class which we want to show while page get loads.
ii)after clicking on div we we will toggle class i.e. the class is added while loading page gets removed and class which we provide in toggleClss gets added :)

<div id="dvId" class="ActiveClassname ">
</div

$(documnet.ready(function(){
$('#dvId').click(function(){
  $('#dvId').toggleClass('ActiveClassname InActiveClassName');     
});
});


Enjoy.....:)

If you any doubt free to ask any time...

Format numbers to strings in Python

str() in python on an integer will not print any decimal places.

If you have a float that you want to ignore the decimal part, then you can use str(int(floatValue)).

Perhaps the following code will demonstrate:

>>> str(5)
'5'
>>> int(8.7)
8

Get gateway ip address in android

I'm using cyanogenmod 7.2 on android 2.3.4, then just open terminal emulator and type:

$ ip addr show
$ ip route show

How to convert decimal to hexadecimal in JavaScript

Here's a trimmed down ECMAScript 6 version:

const convert = {
  bin2dec : s => parseInt(s, 2).toString(10),
  bin2hex : s => parseInt(s, 2).toString(16),
  dec2bin : s => parseInt(s, 10).toString(2),
  dec2hex : s => parseInt(s, 10).toString(16),
  hex2bin : s => parseInt(s, 16).toString(2),
  hex2dec : s => parseInt(s, 16).toString(10)
};

convert.bin2dec('111'); // '7'
convert.dec2hex('42');  // '2a'
convert.hex2bin('f8');  // '11111000'
convert.dec2bin('22');  // '10110'

Python display text with font & color?

I wrote a wrapper, that will cache text surfaces, only re-render when dirty. googlecode/ninmonkey/nin.text/demo/

Why does Date.parse give incorrect results?

There is some method to the madness. As a general rule, if a browser can interpret a date as an ISO-8601, it will. "2005-07-08" falls into this camp, and so it is parsed as UTC. "Jul 8, 2005" cannot, and so it is parsed in the local time.

See JavaScript and Dates, What a Mess! for more.

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

This error happens to me because there is an invalid input in my activity_main.xml file.

When you try to build or clean your project you will see error messages.

I resolved mine by reading those error messages, correct what is wrong in my xml file. then rebuild project.

return query based on date

If you want to get all new things in the past 5 minutes you would have to do some calculations, but its not hard...

First create an index on the property you want to match on (include sort direction -1 for descending and 1 for ascending)

db.things.createIndex({ createdAt: -1 }) // descending order on .createdAt

Then query for documents created in the last 5 minutes (60 seconds * 5 minutes)....because javascript's .getTime() returns milliseconds you need to mulitply by 1000 before you use it as input to the new Date() constructor.

db.things.find({
        createdAt: {
            $gte: new Date(new Date().getTime()-60*5*1000).toISOString()
         }
     })
     .count()

Explanation for new Date(new Date().getTime()-60*5*1000).toISOString() is as follows:

First we calculate "5 minutes ago":

  1. new Date().getTime() gives us current time in milliseconds
  2. We want to subtract 5 minutes (in ms) from that: 5*60*1000 -- I just multiply by 60 seconds so its easy to change. I can just change 5 to 120 if I want 2 hours (120 minutes).
  3. new Date().getTime()-60*5*1000 gives us 1484383878676 (5 minutes ago in ms)

Now we need to feed that into a new Date() constructor to get the ISO string format required by MongoDB timestamps.

  1. { $gte: new Date(resultFromAbove).toISOString() } (mongodb .find() query)
  2. Since we can't have variables we do it all in one shot: new Date(new Date().getTime()-60*5*1000)
  3. ...then convert to ISO string: .toISOString()
  4. new Date(new Date().getTime()-60*5*1000).toISOString() gives us 2017-01-14T08:53:17.586Z

Of course this is a little easier with variables if you're using the node-mongodb-native driver, but this works in the mongo shell which is what I usually use to check things.

Extend contigency table with proportions (percentages)

Here is another example using the lapply and table functions in base R.

freqList = lapply(select_if(tips, is.factor), 
              function(x) {
                  df = data.frame(table(x))

                  df = data.frame(fct = df[, 1], 
                                  n = sapply(df[, 2], function(y) {
                                      round(y / nrow(dat), 2)
                                    }
                                )
                            )
                  return(df) 
                    }
                )

Use print(freqList) to see the proportion tables (percent of frequencies) for each column/feature/variable (depending on your tradecraft) that is labeled as a factor.

System.Data.OracleClient requires Oracle client software version 8.1.7

Update 1: It is possible for different users to have different path. But its not the likely problem here. There is more chance that the user that the iwam user doesn't have permission to the oracle client directory.

Update 0: Its suppose to work. Check for environment variable ( That are needed to find the oracle client and tnsnames.ora ). Also, Maybe you have a 32/64 bit issues. Also, consider using the Oracle Data Provider for .NET ( search for odp.net)

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

In my case, I was missing the setting.gradle file.

How to grant remote access permissions to mysql server for user?

This grants root access with the same password from any machine in *.example.com:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%.example.com' 
    IDENTIFIED BY 'some_characters' 
    WITH GRANT OPTION;
FLUSH PRIVILEGES;

If name resolution is not going to work, you may also grant access by IP or subnet:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.%'
    IDENTIFIED BY 'some_characters'  
    WITH GRANT OPTION;
FLUSH PRIVILEGES;

MySQL GRANT syntax docs.

Can't ignore UserInterfaceState.xcuserstate

Just "git clean -f -d" worked for me!

Can we open pdf file using UIWebView on iOS?

WKWebView: I find this question to be the best place to let people know that they should start using WKWebview as UIWebView is now deprecated.

Objective C

WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame];
webView.navigationDelegate = self;
NSURL *nsurl=[NSURL URLWithString:@"https://www.example.com/document.pdf"];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[webView loadRequest:nsrequest];
[self.view addSubview:webView];

Swift

let myURLString = "https://www.example.com/document.pdf"
let url = NSURL(string: myURLString)
let request = NSURLRequest(URL: url!)  
let webView = WKWebView(frame: self.view.frame)
webView.navigationDelegate = self
webView.loadRequest(request)
view.addSubview(webView)

I haven't copied this code directly from Xcode, so it might, it might contain some syntax error. Please check while using it.

How to refresh a page with jQuery by passing a parameter to URL

if window.location.hash is empty, you cant assign to location.href a new value without using a correct function (at least tested in chrome).

try the window.location.replace:

if (!window.location.hash) 
    {
        window.location.replace(window.location.href + "?single")
    } 

vertical align middle in <div>

_x000D_
_x000D_
.container { 
  height: 200px;
  position: relative;
  border: 3px solid green; 
}

.center {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
_x000D_
<h2>Centering Div inside Div, horizontally and vertically without table</h2>
<p>1. Positioning and the transform property to vertically and horizontally center</p>
<p>2. CSS Layout - Horizontal & Vertical Align</p>

<div class="container">
  <div class="center">
    <p>I am vertically and horizontally centered.</p>
  </div>
</div>
_x000D_
_x000D_
_x000D_

What is the difference between ndarray and array in numpy?

Just a few lines of example code to show the difference between numpy.array and numpy.ndarray

Warm up step: Construct a list

a = [1,2,3]

Check the type

print(type(a))

You will get

<class 'list'>

Construct an array (from a list) using np.array

a = np.array(a)

Or, you can skip the warm up step, directly have

a = np.array([1,2,3])

Check the type

print(type(a))

You will get

<class 'numpy.ndarray'>

which tells you the type of the numpy array is numpy.ndarray

You can also check the type by

isinstance(a, (np.ndarray))

and you will get

True

Either of the following two lines will give you an error message

np.ndarray(a)                # should be np.array(a)
isinstance(a, (np.array))    # should be isinstance(a, (np.ndarray))

How to set opacity in parent div and not affect in child div?

I had the same problem and I fixed by setting transparent png image as background for the parent tag.

This is the 1px x 1px PNG Image that I have created with 60% Opacity of black background !

Disable Proximity Sensor during call

After trying a whole bunch of fixes including:

  • Phone app's menu option (my phone did not have a option to disable)
  • Proximity Screen Off Lite (did not work)
  • Xposed Framework with sensor disabler (works till phone is rebooted or app updates)
  • Macrodroid macro (Macrodroid does not run on my phone for some reason)
  • put some tin foil in front of it?(i don't know what i was thinking)

Here is My fix: I figured you cannot break it more so I opened up my phone and removed the proximity sensor all together from the motherboard. The sensor tester app now shows "no_value" where it use to give "Distance: 0" and my screen no longer goes black after dialing. Please note I can only confirm this working on a Samsung I8190 Galaxy S III mini with CM MOD 5.1.1. Here is a picture of the device i removed: prox sensor I have removed it using a SMD solder station's heat gun at 400 degrees, some tweezers and flux.But a sharp hobby knife might work too.

How do detect Android Tablets in general. Useragent?

While we can't say if some tablets omit "mobile", many including the Samsung Galaxy Tab do have mobile in their user-agent, making it impossible to detect between an android tablet and android phone without resorting to checking model specifics. This IMHO is a waste of time unless you plan on updating and expanding your device list on a monthly basis.

Unfortunately the best solution here is to complain to Google about this and get them to fix Chrome for Android so it adds some text to identify between a mobile device and a tablet. Hell even a single letter M OR T in a specific place in the string would be enough, but I guess that makes too much sense.

How to expand/collapse a diff sections in Vimdiff?

Actually if you do Ctrl+W W, you won't need to add that extra Ctrl. Does the same thing.

"Non-static method cannot be referenced from a static context" error

setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.

You may want to look into some basic object-oriented tutorials to see how static/instance members work.

Add rows to CSV File in powershell

Create a new custom object and add it to the object array that Import-Csv creates.

$fileContent = Import-csv $file -header "Date", "Description"
$newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' }
$fileContent += $newRow

How do I print uint32_t and uint16_t variables value?

The macros defined in <inttypes.h> are the most correct way to print values of types uint32_t, uint16_t, and so forth -- but they're not the only way.

Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)

An alternative is to cast the values to a predefined type and use the format for that type.

Types int and unsigned int are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t or uint16_t, respectively. Similarly, long and unsigned long are at least 32 bits wide, and long long and unsigned long long are at least 64 bits wide.

For example, I might write your program like this (with a few additional tweaks):

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>  

int main(void)
{
    uint32_t a=12, a1;
    uint16_t b=1, b1;
    a1 = htonl(a);
    printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
    b1 = htons(b);
    printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
    return 0;
}

One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>. Such an implementation most likely wouldn't have <stdint.h> either, but the technique is useful for other integer types.

Use a cell value in VBA function with a variable

No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:

Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
    Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng

is producing the same result as Joe's code.

If you need to switch sheets for some reasons, use Application.ScreenUpdating = False at the beginning of your macro (and Application.ScreenUpdating=True at the end). This will remove the screenflickering - and speed up the execution.

How to empty (clear) the logcat buffer in Android

For anyone coming to this question wondering how to do this in Eclipse, You can remove the displayed text from the logCat using the button provided (often has a red X on the icon)

Cannot get to $rootScope

You can not ask for instance during configuration phase - you can ask only for providers.

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

// configure stuff
app.config(function($routeProvider, $locationProvider) {
  // you can inject any provider here
});

// run blocks
app.run(function($rootScope) {
  // you can inject any instance here
});

See http://docs.angularjs.org/guide/module for more info.

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

What does "#include <iostream>" do?

# indicates that the following line is a preprocessor directive and should be processed by the preprocessor before compilation by the compiler.

So, #include is a preprocessor directive that tells the preprocessor to include header files in the program.

< > indicate the start and end of the file name to be included.

iostream is a header file that contains functions for input/output operations (cin and cout).

Now to sum it up C++ to English translation of the command, #include <iostream> is:

Dear preprocessor, please include all the contents of the header file iostream at the very beginning of this program before compiler starts the actual compilation of the code.

Attempted to read or write protected memory

The problem may be due to mixed build platforms DLLs in the project. i.e You build your project to Any CPU but have some DLLs in the project already built for x86 platform. These will cause random crashes because of different memory mapping of 32bit and 64bit architecture. If all the DLLs are built for one platform the problem can be solved. For safety try bulinding for 32bit x86 architecture because it is the most compatible.

How do I undo a checkout in git?

Try this first:

git checkout master

(If you're on a different branch than master, use the branch name there instead.)

If that doesn't work, try...

For a single file:

git checkout HEAD /path/to/file

For the entire repository working copy:

git reset --hard HEAD

And if that doesn't work, then you can look in the reflog to find your old head SHA and reset to that:

git reflog
git reset --hard <sha from reflog>

HEAD is a name that always points to the latest commit in your current branch.

Remove Fragment Page from ViewPager in Android

You could just override the destroyItem method

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    fragmentManager.beginTransaction().remove((Fragment) object).commitNowAllowingStateLoss();
}

How to get cell value from DataGridView in VB.Net?

To get the value of cell, use the following syntax,

datagridviewName(columnFirst, rowSecond).value

But the intellisense and MSDN documentation is wrongly saying rowFirst, colSecond approach...

PHP: HTTP or HTTPS?

If the request was sent with HTTPS you will have a extra parameter in the $_SERVER superglobal - $_SERVER['HTTPS']. You can check if it is set or not

if( isset($_SERVER['HTTPS'] ) ) {

Generating an array of letters in the alphabet

//generate a list of alphabet using csharp
//this recurcive function will return you
//a string with position of passed int
//say if pass 0 will return A ,1-B,2-C,.....,26-AA,27-AB,....,701-ZZ,702-AAA,703-AAB,...

static string CharacterIncrement(int colCount)
{
    int TempCount = 0;
    string returnCharCount = string.Empty;

    if (colCount <= 25)
    {
        TempCount = colCount;
        char CharCount = Convert.ToChar((Convert.ToInt32('A') + TempCount));
        returnCharCount += CharCount;
        return returnCharCount;
    }
    else
    {
        var rev = 0;

        while (colCount >= 26)
        {
            colCount = colCount - 26;
            rev++;
        }

        returnCharCount += CharacterIncrement(rev-1);
        returnCharCount += CharacterIncrement(colCount);
        return returnCharCount;
    }
}

//--------this loop call this function---------//
int i = 0;
while (i <>
    {
        string CharCount = string.Empty;
        CharCount = CharacterIncrement(i);

        i++;
    }

How to make a JFrame Modal in Swing java

just replace JFrame to JDialog in class

public class MyDialog extends JFrame // delete JFrame and write JDialog

and then write setModal(true); in constructor

After that you will be able to construct your Form in netbeans and the form becomes modal

How to declare array of zeros in python (or an array of a certain size)

Just for completeness: To declare a multidimensional list of zeros in python you have to use a list comprehension like this:

buckets = [[0 for col in range(5)] for row in range(10)]

to avoid reference sharing between the rows.

This looks more clumsy than chester1000's code, but is essential if the values are supposed to be changed later. See the Python FAQ for more details.

Count lines in large files

I have a 645GB text file, and none of the earlier exact solutions (e.g. wc -l) returned an answer within 5 minutes.

Instead, here is Python script that computes the approximate number of lines in a huge file. (My text file apparently has about 5.5 billion lines.) The Python script does the following:

A. Counts the number of bytes in the file.

B. Reads the first N lines in the file (as a sample) and computes the average line length.

C. Computes A/B as the approximate number of lines.

It follows along the line of Nico's answer, but instead of taking the length of one line, it computes the average length of the first N lines.

Note: I'm assuming an ASCII text file, so I expect the Python len() function to return the number of chars as the number of bytes.

Put this code into a file line_length.py:

#!/usr/bin/env python

# Usage:
# python line_length.py <filename> <N> 

import os
import sys
import numpy as np

if __name__ == '__main__':

    file_name = sys.argv[1]
    N = int(sys.argv[2]) # Number of first lines to use as sample.
    file_length_in_bytes = os.path.getsize(file_name)
    lengths = [] # Accumulate line lengths.
    num_lines = 0

    with open(file_name) as f:
        for line in f:
            num_lines += 1
            if num_lines > N:
                break
            lengths.append(len(line))

    arr = np.array(lengths)
    lines_count = len(arr)
    line_length_mean = np.mean(arr)
    line_length_std = np.std(arr)

    line_count_mean = file_length_in_bytes / line_length_mean

    print('File has %d bytes.' % (file_length_in_bytes))
    print('%.2f mean bytes per line (%.2f std)' % (line_length_mean, line_length_std))
    print('Approximately %d lines' % (line_count_mean))

Invoke it like this with N=5000.

% python line_length.py big_file.txt 5000

File has 645620992933 bytes.
116.34 mean bytes per line (42.11 std)
Approximately 5549547119 lines

So there are about 5.5 billion lines in the file.

How do I remove a single file from the staging area (undo git add)?

If you want to remove files following a certain pattern and you are using git rm --cached, you can use file-glob patterns too.

See here.

Is there a kind of Firebug or JavaScript console debug for Android?

Try js-mobile-console

MobileConsole can be embedded within any page for debugging. It will catch errors and behave exactly as the native JavaScript console in the browser. It also outputs all the logs you've written via an API of window.console.

How do you round a float to 2 decimal places in JRuby?

Float#round can take a parameter in Ruby 1.9, not in Ruby 1.8. JRuby defaults to 1.8, but it is capable of running in 1.9 mode.

How can I get file extensions with JavaScript?

function getExt(filename)
{
    var ext = filename.split('.').pop();
    if(ext == filename) return "";
    return ext;
}

ImportError: No module named tensorflow

You may need this since first one may not work.

python3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-any.whl

PHP/regex: How to get the string value of HTML tag?

In your pattern, you simply want to match all text between the two tags. Thus, you could use for example a [\w\W] to match all characters.

function getTextBetweenTags($string, $tagname) {
    $pattern = "/<$tagname>([\w\W]*?)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

CSS hover vs. JavaScript mouseover

The CSS one is much more maintainable and readable.

++i or i++ in for loops ??

For integers, there is no difference between pre- and post-increment.

If i is an object of a non-trivial class, then ++i is generally preferred, because the object is modified and then evaluated, whereas i++ modifies after evaluation, so requires a copy to be made.

Testing for empty or nil-value string

The second clause does not need a !variable.nil? check—if evaluation reaches that point, variable.nil is guaranteed to be false (because of short-circuiting).

This should be sufficient:

variable = id if variable.nil? || variable.empty?

If you're working with Ruby on Rails, Object.blank? solves this exact problem:

An object is blank if it’s false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are all blank.