Programs & Examples On #Opendir

Open directory using C

Some feedback on the segment of code, though for the most part, it should work...

void main(int c,char **args)
  • int main - the standard defines main as returning an int.
  • c and args are typically named argc and argv, respectfully, but you are allowed to name them anything

...

{
DIR *dir;
struct dirent *dent;
char buffer[50];
strcpy(buffer,args[1]);
  • You have a buffer overflow here: If args[1] is longer than 50 bytes, buffer will not be able to hold it, and you will write to memory that you shouldn't. There's no reason I can see to copy the buffer here, so you can sidestep these issues by just not using strcpy...

...

dir=opendir(buffer);   //this part

If this returning NULL, it can be for a few reasons:

  • The directory didn't exist. (Did you type it right? Did it have a space in it, and you typed ./your_program my directory, which will fail, because it tries to opendir("my"))
  • You lack permissions to the directory
  • There's insufficient memory. (This is unlikely.)

MySQL - Operand should contain 1 column(s)

Your subquery is selecting two columns, while you are using it to project one column (as part of the outer SELECT clause). You can only select one column from such a query in this context.

Consider joining to the users table instead; this will give you more flexibility when selecting what columns you want from users.

SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
users.username AS posted_by,
users.id AS posted_by_id

FROM topics

LEFT OUTER JOIN posts ON posts.topic_id = topics.id
LEFT OUTER JOIN users ON users.id = posts.posted_by

WHERE topics.cat_id = :cat
GROUP BY topics.id

How to place div in top right hand corner of page

<style type="text/css">
 .topcorner{
  position:absolute;
  top:10;
  right:15;
  }
</style>

You ca also use this in CSS external file.

text flowing out of div

It's due to the fact that you have one long word without spaces. You can use the word-wrap property to cause the text to break:

#w74 { word-wrap: break-word; }

It has fairly good browser support, too. See documentation about it here.

What is the default Jenkins password?

The password is present in the log generated by docker run image as shown in the example below.

Jenkins Docker run log

Additionally you can check the directory /var/jenkins_home/secrets/ Its in the file name initialAdminPassword

You can use cat /var/jenkins_home/secrets/initialAdminPassword to read it.

How to split an integer into an array of digits?

[int(i) for i in str(number)]

or, if do not want to use a list comprehension or you want to use a base different from 10

from __future__ import division # for compatibility of // between Python 2 and 3
def digits(number, base=10):
    assert number >= 0
    if number == 0:
        return [0]
    l = []
    while number > 0:
        l.append(number % base)
        number = number // base
    return l

Block Comments in a Shell Script

You can use:

if [ 1 -eq 0 ]; then
  echo "The code that you want commented out goes here."
  echo "This echo statement will not be called."
fi

How to keep a git branch in sync with master

concept47's approach is the right way to do it, but I'd advise to merge with the --no-ff option in order to keep your commit history clear.

git checkout develop
git pull --rebase
git checkout NewFeatureBranch
git merge --no-ff master

Detect Android phone via Javascript / jQuery

Take a look at that : http://davidwalsh.name/detect-android

JavaScript:

var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
  // Do something!
  // Redirect to Android-site?
  window.location = 'http://android.davidwalsh.name';
}

PHP:

$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') !== false) { // && stripos($ua,'mobile') !== false) {
  header('Location: http://android.davidwalsh.name');
  exit();
}

Edit : As pointed out in some comments, this will work in 99% of the cases, but some edge cases are not covered. If you need a much more advanced and bulletproofed solution in JS, you should use platform.js : https://github.com/bestiejs/platform.js

SQL ORDER BY multiple columns

yes,the sorting proceed differently. in first scenario, orders based on column1 and in addition to that process further by sorting colmun2 based on column1 .. in second scenario ,it orders completely based on column 1 only... please proceed with a simple example...u will get quickly..

curl posting with header application/x-www-form-urlencoded

Try something like:

$post_data="dispnumber=567567567&extension=6";
$url="http://xxxxxxxx.xxx/xx/xx";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));   
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$result = curl_exec($ch);

echo $result;

AttributeError: 'str' object has no attribute 'strftime'

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'

Spring: How to get parameters from POST body?

You can try using @RequestBodyParam

@RequestMapping(value = "/saveData", headers="Content-Type=application/json", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(@RequestBodyParam String source,@RequestBodyParam JsonDto json) throws MyException {
    ...
}

https://github.com/LambdaExpression/RequestBodyParam

Create table (structure) from existing table

Its probably also worth mentioning that you can do the following:

Right click the table you want to duplicate > Script Table As > Create To > New Query Editor Window

Then, where is says the name of the table you just right clicked in the script that has been generated, change the name to what ever you want your new table to be called and click Execute

Sort ArrayList of custom Objects by property

With Java 8 you can use a method reference for your comparator:

import static java.util.Comparator.comparing;

Collections.sort(list, comparing(MyObject::getStartDate));

WCF gives an unsecured or incorrectly secured fault error

You have obviously a problem with the WCF security subsystem. What binding are you using? What authentication? Encryption? Signing? Do you have to cross domain boundaries?

A bit of goggling further reveals that others are experiencing this error if the clocks of client and server are out of sync (more than about five minutes) because some security schemata rely on synchronized clocks.

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

If you want to test if an object is strictly or extends a Hash, use:

value = {}
value.is_a?(Hash) || value.is_a?(Array) #=> true

But to make value of Ruby's duck typing, you could do something like:

value = {}
value.respond_to?(:[]) #=> true

It is useful when you only want to access some value using the value[:key] syntax.

Please note that Array.new["key"] will raise a TypeError.

Does JavaScript pass by reference?

"Global" JavaScript variables are members of the window object. You could access the reference as a member of the window object.

var v = "initialized";

function byref(ref) {
  window[ref] = "changed by ref";
}

byref((function(){for(r in window){if(window[r]===v){return(r);}}})());
// It could also be called like... byref('v');
console.log(v); // outputs changed by ref

Note, the above example will not work for variables declared within a function.

Changing the tmp folder of mysql

You can also set the TMPDIR environment variable.

In some situations (Docker in my case) it's more convenient to set an environment variable than to update a config file.

How to detect my browser version and operating system using JavaScript?

Code to detect the operating system of an user

let os = navigator.userAgent.slice(13).split(';')
os = os[0]
console.log(os)
Windows NT 10.0

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

It seems that many other posts are concerned about speed (i.e best = fastest). What about simplicity? Consider:

char ReverseBits(char character) {
    char reversed_character = 0;
    for (int i = 0; i < 8; i++) {
        char ith_bit = (c >> i) & 1;
        reversed_character |= (ith_bit << (sizeof(char) - 1 - i));
    }
    return reversed_character;
}

and hope that clever compiler will optimise for you.

If you want to reverse a longer list of bits (containing sizeof(char) * n bits), you can use this function to get:

void ReverseNumber(char* number, int bit_count_in_number) {
    int bytes_occupied = bit_count_in_number / sizeof(char);      

    // first reverse bytes
    for (int i = 0; i <= (bytes_occupied / 2); i++) {
        swap(long_number[i], long_number[n - i]);
    }

    // then reverse bits of each individual byte
    for (int i = 0; i < bytes_occupied; i++) {
         long_number[i] = ReverseBits(long_number[i]);
    }
}

This would reverse [10000000, 10101010] into [01010101, 00000001].

How to turn a String into a JavaScript function call?

I wanted to be able to take a function name as a string, call it, AND pass an argument to the function. I couldn't get the selected answer for this question to do that, but this answer explained it exactly, and here is a short demo.

function test_function(argument)    {
    alert('This function ' + argument); 
}

functionName = 'test_function';

window[functionName]('works!');

This also works with multiple arguments.

Match at every second occurrence

There's no "direct" way of doing so but you can specify the pattern twice as in: a[^a]*a that match up to the second "a".

The alternative is to use your programming language (perl? C#? ...) to match the first occurence and then the second one.

EDIT: I've seen other responded using the "non-greedy" operators which might be a good way to go, assuming you have them in your regex library!

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

Actually the minimum amount of Angular to be used (as requested in the original question) is just adding a class to the DOM element when show variable is true, and perform the animation/transition via CSS.

So your minimum Angular code is this:

<div class="box-opener" (click)="show = !show">
    Open/close the box
</div>

<div class="box" [class.opened]="show">
    <!-- Content -->
</div>

With this solution, you need to create CSS rules for the transition, something like this:

.box {
    background-color: #FFCC55;
    max-height: 0px;
    overflow-y: hidden;
    transition: ease-in-out 400ms max-height;
}

.box.opened {
    max-height: 500px;
    transition: ease-in-out 600ms max-height;
}

If you have retro-browser-compatibility issues, just remember to add the vendor prefixes in the transitions.

See the example here

How to focus on a form input text field on page load using jQuery?

The line $('#myTextBox').focus() alone won't put the cursor in the text box, instead use:

$('#myTextBox:text:visible:first').focus();

How do I force files to open in the browser instead of downloading (PDF)?

To indicate to the browser that the file should be viewed in the browser, the HTTP response should include these headers:

Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"

To have the file downloaded rather than viewed:

Content-Type: application/pdf
Content-Disposition: attachment; filename="filename.pdf"

The quotes around the filename are required if the filename contains special characters such as filename[1].pdf which may otherwise break the browser's ability to handle the response.

How you set the HTTP response headers will depend on your HTTP server (or, if you are generating the PDF response from server-side code: your server-side programming language).

How to detect a docker daemon port

By default, the docker daemon will use the unix socket unix:///var/run/docker.sock (you can check this is the case for you by doing a sudo netstat -tunlp and note that there is no docker daemon process listening on any ports). It's recommended to keep this setting for security reasons but it sounds like Riak requires the daemon to be running on a TCP socket.

To start the docker daemon with a TCP socket that anybody can connect to, use the -H option:

sudo docker -H 0.0.0.0:2375 -d &

Warning: This means machines that can talk to the daemon through that TCP socket can get root access to your host machine.

Related docs:

http://basho.com/posts/technical/running-riak-in-docker/

https://docs.docker.com/install/linux/linux-postinstall/#configure-where-the-docker-daemon-listens-for-connections

How to check if a variable is set in Bash?

You want to exit if it's unset

This worked for me. I wanted my script to exit with an error message if a parameter wasn't set.

#!/usr/bin/env bash

set -o errexit

# Get the value and empty validation check all in one
VER="${1:?You must pass a version of the format 0.0.0 as the only argument}"

This returns with an error when it's run

peek@peek:~$ ./setver.sh
./setver.sh: line 13: 1: You must pass a version of the format 0.0.0 as the only argument

Check only, no exit - Empty and Unset are INVALID

Try this option if you just want to check if the value set=VALID or unset/empty=INVALID.

TSET="good val"
TEMPTY=""
unset TUNSET

if [ "${TSET:-}" ]; then echo "VALID"; else echo "INVALID";fi
# VALID
if [ "${TEMPTY:-}" ]; then echo "VALID"; else echo "INVALID";fi
# INVALID
if [ "${TUNSET:-}" ]; then echo "VALID"; else echo "INVALID";fi
# INVALID

Or, Even short tests ;-)

[ "${TSET:-}"   ] && echo "VALID" || echo "INVALID"
[ "${TEMPTY:-}" ] && echo "VALID" || echo "INVALID"
[ "${TUNSET:-}" ] && echo "VALID" || echo "INVALID"

Check only, no exit - Only empty is INVALID

And this is the answer to the question. Use this if you just want to check if the value set/empty=VALID or unset=INVALID.

NOTE, the "1" in "..-1}" is insignificant, it can be anything (like x)

TSET="good val"
TEMPTY=""
unset TUNSET

if [ "${TSET+1}" ]; then echo "VALID"; else echo "INVALID";fi
# VALID
if [ "${TEMPTY+1}" ]; then echo "VALID"; else echo "INVALID";fi
# VALID
if [ "${TUNSET+1}" ]; then echo "VALID"; else echo "INVALID";fi
# INVALID

Short tests

[ "${TSET+1}"   ] && echo "VALID" || echo "INVALID"
[ "${TEMPTY+1}" ] && echo "VALID" || echo "INVALID"
[ "${TUNSET+1}" ] && echo "VALID" || echo "INVALID"

I dedicate this answer to @mklement0 (comments) who challenged me to answer the question accurately.

Reference http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02

How to open VMDK File of the Google-Chrome-OS bundle 2012?

WinMount provides an easiest way to mount VMDK as a virtual disk. You can read or write to the vmdk file without loading the virtual system. Here shows you how to do: http://www.winmount.com/mount_vmdk.html

Using group by and having clause

What type of sql database are using (MSSQL, Oracle etc)? I believe what you have written is correct.

You could also write the first query like this:

SELECT s.sid, s.name
FROM Supplier s
WHERE (SELECT COUNT(DISTINCT pr.jid)
       FROM Supplies su, Projects pr
       WHERE su.sid = s.sid 
           AND pr.jid = su.jid) >= 2

It's a little more readable, and less mind-bending than trying to do it with GROUP BY. Performance may differ though.

Is it possible to have empty RequestParam values use the defaultValue?

You can keep primitive type by setting default value, in the your case just add "required = false" property:

@RequestParam(value = "i", required = false, defaultValue = "10") int i

P.S. This page from Spring documentation might be useful: Annotation Type RequestParam

Matplotlib figure facecolor (background color)

If you want to change background color, try this:

plt.rcParams['figure.facecolor'] = 'white'

UIImage: Resize, then Crop

An older post contains code for a method to resize your UIImage. The relevant portion is as follows:

+ (UIImage*)imageWithImage:(UIImage*)image 
               scaledToSize:(CGSize)newSize;
{
   UIGraphicsBeginImageContext( newSize );
   [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
   UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   return newImage;
}

As far as cropping goes, I believe that if you alter the method to use a different size for the scaling than for the context, your resulting image should be clipped to the bounds of the context.

How to print to console using swift playground?

As of Xcode 7.0.1 println is change to print. Look at the image. there are lot more we can print out. enter image description here

django templates: include and extends

From Django docs:

The include tag should be considered as an implementation of "render this subtemplate and include the HTML", not as "parse this subtemplate and include its contents as if it were part of the parent". This means that there is no shared state between included templates -- each include is a completely independent rendering process.

So Django doesn't grab any blocks from your commondata.html and it doesn't know what to do with rendered html outside blocks.

Failed to load ApplicationContext from Unit Test: FileNotFound

If you are using intellij, then try restarting intellij cache

  1. File-> Invalidate cache/restart
  2. clean and build project

See if it works, it worked for me.

Android Push Notifications: Icon not displaying in notification, white square shown instead

For SDK >= 23, please add setLargeIcon

notification = new Notification.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setLargeIcon(context.getResources(), R.drawable.lg_logo))
            .setContentTitle(title)
            .setStyle(new Notification.BigTextStyle().bigText(msg))
            .setAutoCancel(true)
            .setContentText(msg)
            .setContentIntent(contentIntent)
            .setSound(sound)
            .build();

basic authorization command for curl

Background

You can use the base64 CLI tool to generate the base64 encoded version of your username + password like this:

$ echo -n "joeuser:secretpass" | base64
am9ldXNlcjpzZWNyZXRwYXNz

-or-

$ base64 <<<"joeuser:secretpass"
am9ldXNlcjpzZWNyZXRwYXNzCg==

Base64 is reversible so you can also decode it to confirm like this:

$ echo -n "joeuser:secretpass" | base64 | base64 -D
joeuser:secretpass

-or-

$ base64 <<<"joeuser:secretpass" | base64 -D
joeuser:secretpass

NOTE: username = joeuser, password = secretpass

Example #1 - using -H

You can put this together into curl like this:

$ curl -H "Authorization: Basic $(base64 <<<"joeuser:secretpass")" http://example.com

Example #2 - using -u

Most will likely agree that if you're going to bother doing this, then you might as well just use curl's -u option.

$ curl --help |grep -- "--user "
 -u, --user USER[:PASSWORD]  Server user and password

For example:

$ curl -u someuser:secretpass http://example.com

But you can do this in a semi-safer manner if you keep your credentials in a encrypted vault service such as LastPass or Pass.

For example, here I'm using the LastPass' CLI tool, lpass, to retrieve my credentials:

$ curl -u $(lpass show --username example.com):$(lpass show --password example.com) \
     http://example.com

Example #3 - using curl config

There's an even safer way to hand your credentials off to curl though. This method makes use of the -K switch.

$ curl -X GET -K \
    <(cat <<<"user = \"$(lpass show --username example.com):$(lpass show --password example.com)\"") \
    http://example.com

When used, your details remain hidden, since they're passed to curl via a temporary file descriptor, for example:

+ curl -skK /dev/fd/63 -XGET -H 'Content-Type: application/json' https://es-data-01a.example.com:9200/_cat/health
++ cat
+++ lpass show --username example.com
+++ lpass show --password example.com
1561075296 00:01:36 rdu-es-01 green 9 6 2171 1085 0 0 0 0 - 100.0%       

NOTE: Above I'm communicating with one of our Elasticsearch nodes, inquiring about the cluster's health.

This method is dynamically creating a file with the contents user = "<username>:<password>" and giving that to curl.

HTTP Basic Authorization

The methods shown above are facilitating a feature known as Basic Authorization that's part of the HTTP standard.

When the user agent wants to send authentication credentials to the server, it may use the Authorization field.

The Authorization field is constructed as follows:

  1. The username and password are combined with a single colon (:). This means that the username itself cannot contain a colon.
  2. The resulting string is encoded into an octet sequence. The character set to use for this encoding is by default unspecified, as long as it is compatible with US-ASCII, but the server may suggest use of UTF-8 by sending the charset parameter.
  3. The resulting string is encoded using a variant of Base64.
  4. The authorization method and a space (e.g. "Basic ") is then prepended to the encoded string.

For example, if the browser uses Aladdin as the username and OpenSesame as the password, then the field's value is the base64-encoding of Aladdin:OpenSesame, or QWxhZGRpbjpPcGVuU2VzYW1l. Then the Authorization header will appear as:

Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l

Source: Basic access authentication

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

As this post gets a bit of popularity I edited it a bit. Spring Boot 2.x.x changed default JDBC connection pool from Tomcat to faster and better HikariCP. Here comes incompatibility, because HikariCP uses different property of jdbc url. There are two ways how to handle it:

OPTION ONE

There is very good explanation and workaround in spring docs:

Also, if you happen to have Hikari on the classpath, this basic setup does not work, because Hikari has no url property (but does have a jdbcUrl property). In that case, you must rewrite your configuration as follows:

app.datasource.jdbc-url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass

OPTION TWO

There is also how-to in the docs how to get it working from "both worlds". It would look like below. ConfigurationProperties bean would do "conversion" for jdbcUrl from app.datasource.url

@Configuration
public class DatabaseConfig {
    @Bean
    @ConfigurationProperties("app.datasource")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("app.datasource")
    public HikariDataSource dataSource(DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
                .build();
    }
}

Disable ONLY_FULL_GROUP_BY

    mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
    mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
    mysql> exit;

How can I convert uppercase letters to lowercase in Notepad++

First select the text
To convert lowercase to uppercase, press Ctrl+Shift+U
To convert uppercase to lowercase, press Ctrl+U

Partly JSON unmarshal into a map in Go

Further to Stephen Weinberg's answer, I have since implemented a handy tool called iojson, which helps to populate data to an existing object easily as well as encoding the existing object to a JSON string. A iojson middleware is also provided to work with other middlewares. More examples can be found at https://github.com/junhsieh/iojson

Example:

func main() {
    jsonStr := `{"Status":true,"ErrArr":[],"ObjArr":[{"Name":"My luxury car","ItemArr":[{"Name":"Bag"},{"Name":"Pen"}]}],"ObjMap":{}}`

    car := NewCar()

    i := iojson.NewIOJSON()

    if err := i.Decode(strings.NewReader(jsonStr)); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    }

    // populating data to a live car object.
    if v, err := i.GetObjFromArr(0, car); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    } else {
        fmt.Printf("car (original): %s\n", car.GetName())
        fmt.Printf("car (returned): %s\n", v.(*Car).GetName())

        for k, item := range car.ItemArr {
            fmt.Printf("ItemArr[%d] of car (original): %s\n", k, item.GetName())
        }

        for k, item := range v.(*Car).ItemArr {
            fmt.Printf("ItemArr[%d] of car (returned): %s\n", k, item.GetName())
        }
    }
}

Sample output:

car (original): My luxury car
car (returned): My luxury car
ItemArr[0] of car (original): Bag
ItemArr[1] of car (original): Pen
ItemArr[0] of car (returned): Bag
ItemArr[1] of car (returned): Pen

Location of the mongodb database on mac

I had the same problem, with version 3.4.2

to run it (if you installed it with homebrew) run the process like this:

$ mongod --dbpath /usr/local/var/mongodb

Replace text in HTML page with jQuery

Like others mentioned in this thread, replacing the entire body HTML is a bad idea because it reinserts the entire DOM and can potentially break any other javascript that was acting on those elements.

Instead, replace just the text on your page and not the DOM elements themselves using jQuery filter:

  $('body :not(script)').contents().filter(function() {
    return this.nodeType === 3;
  }).replaceWith(function() {
      return this.nodeValue.replace('-9o0-9909','The new string');
  });

this.nodeType is the type of node we are looking to replace the contents of. nodeType 3 is text. See the full list here.

How can I resolve the error: "The command [...] exited with code 1"?

This builds on the answer from JaredPar... and is for VS2017. The same "Build and Run" options are present in Visual Studio 2017.

I was getting, The command "chmod +x """ exited with code 1

In the build output window, I searched for "Error" and found a few errors in the same general area. I was able to click on a link in the build output, and found that the error involved this entry in the .targets file:

  <Target Name="ChmodChromeDriver" BeforeTargets="BeforeBuild" Condition="'$(WebDriverPlatform)' != 'win32'">
    <Exec Command="chmod +x &quot;$(ChromeDriverSrcPath)&quot;" />
  </Target>

In the build output, I also found a more detailed error message that essentially stated that it couldn't find Selenium.WebDriver.ChromeDriver v2.36 in the packages folder it was looking in. I checked the project's NuGet packages, and version 2.36 was indeed in the list of installed packages. I did find the package files for 2.36, and changed the attributes on the folder, subfolders and files from "Read Only" to "Read/Write". Built, but same failure. Sometimes "updating" to a different version of the package and then updating back to the original can fix this type of error. So I "updated" the reference in Manage NuGet packages to 2.37, built, failed, then "updated" back to 2.36, built, and the build succeeded without the "chmod +x" error message.

The project I was building was based on a Visual Studio Project template for Appium test tooling, template name "Develop_Automated_Test".

Laravel form html with PUT method for PUT routes

Is very easy, you just need to use method_field('PUT') like this:

HTML:

<form action="{{ route('route_name') }}" method="post">
    {{ method_field('PUT') }}
    {{ csrf_field() }}
</form>

or

<form action="{{ route('route_name') }}" method="post">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

Regards!

How to read data from java properties file using Spring Boot

I have created following class

ConfigUtility.java

@Configuration
public class ConfigUtility {

    @Autowired
    private Environment env;

    public String getProperty(String pPropertyKey) {
        return env.getProperty(pPropertyKey);
    }
} 

and called as follow to get application.properties value

myclass.java

@Autowired
private ConfigUtility configUtil;

public AppResponse getDetails() {

  AppResponse response = new AppResponse();
    String email = configUtil.getProperty("emailid");
    return response;        
}

application.properties

[email protected]

unit tested, working as expected...

The program can't start because libgcc_s_dw2-1.dll is missing

Find that dll on your PC, and copy it into the same directory your executable is in.

Is it possible to cast a Stream in Java 8?

I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:

Stream.of(objects)
    .filter(c -> c instanceof Client)
    .map(c -> (Client) c)
    .map(Client::getID)
    .forEach(System.out::println);

or, as suggested in the comments, you could use the cast method - the former may be easier to read though:

Stream.of(objects)
    .filter(Client.class::isInstance)
    .map(Client.class::cast)
    .map(Client::getID)
    .forEach(System.out::println);

Python list iterator behavior and next(iterator)

I find the existing answers a little confusing, because they only indirectly indicate the essential mystifying thing in the code example: both* the "print i" and the "next(a)" are causing their results to be printed.

Since they're printing alternating elements of the original sequence, and it's unexpected that the "next(a)" statement is printing, it appears as if the "print i" statement is printing all the values.

In that light, it becomes more clear that assigning the result of "next(a)" to a variable inhibits the printing of its' result, so that just the alternate values that the "i" loop variable are printed. Similarly, making the "print" statement emit something more distinctive disambiguates it, as well.

(One of the existing answers refutes the others because that answer is having the example code evaluated as a block, so that the interpreter is not reporting the intermediate values for "next(a)".)

The beguiling thing in answering questions, in general, is being explicit about what is obvious once you know the answer. It can be elusive. Likewise critiquing answers once you understand them. It's interesting...

Making a WinForms TextBox behave like your browser's address bar

'Inside the Enter event
TextBox1.SelectAll();

Ok, after trying it here is what you want:

  • On the Enter event start a flag that states that you have been in the enter event
  • On the Click event, if you set the flag, call .SelectAll() and reset the flag.
  • On the MouseMove event, set the entered flag to false, which will allow you to click highlight without having to enter the textbox first.

This selected all the text on entry, but allowed me to highlight part of the text afterwards, or allow you to highlight on the first click.

By request:

    bool entered = false;
    private void textBox1_Enter(object sender, EventArgs e)
    {
        entered = true;
        textBox1.SelectAll();   //From Jakub's answer.
    }

    private void textBox1_Click(object sender, EventArgs e)
    {
        if (entered) textBox1.SelectAll();
        entered = false;
    }

    private void textBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (entered) entered = false;
    }

For me, the tabbing into the control selects all the text.

What does ON [PRIMARY] mean?

ON [PRIMARY] will create the structures on the "Primary" filegroup. In this case the primary key index and the table will be placed on the "Primary" filegroup within the database.

init-param and context-param

What is the difference between <init-param> and <context-param> !?

Single servlet versus multiple servlets.

Other Answers give details, but here is the summary:

A web app, that is, a “context”, is made up of one or more servlets.

  • <init-param> defines a value available to a single specific servlet within a context.
  • <context-param> defines a value available to all the servlets within a context.

How can I write output from a unit test?

Are you sure you're running your unit tests in Debug? Debug.WriteLine won't be called in Release builds.

Two options to try are:

  • Trace.WriteLine(), which is built into release builds as well as debug

  • Undefine DEBUG in your build settings for the unit test

Pure Javascript listen to input value change

instead of id use title to identify your element and write the code as below.

$(document).ready(()=>{

 $("input[title='MyObject']").change(()=>{
        console.log("Field has been changed...")
    })  
});

How to fill the whole canvas with specific color?

_x000D_
_x000D_
let canvas = document.getElementById('canvas');_x000D_
canvas.setAttribute('width', window.innerWidth);_x000D_
canvas.setAttribute('height', window.innerHeight);_x000D_
let ctx = canvas.getContext('2d');_x000D_
_x000D_
//Draw Canvas Fill mode_x000D_
ctx.fillStyle = 'blue';_x000D_
ctx.fillRect(0,0,canvas.width, canvas.height);
_x000D_
* { margin: 0; padding: 0; box-sizing: border-box; }_x000D_
body { overflow: hidden; }
_x000D_
<canvas id='canvas'></canvas>
_x000D_
_x000D_
_x000D_

Remove first Item of the array (like popping from stack)

const a = [1, 2, 3]; // -> [2, 3]

// Mutable solutions: update array 'a', 'c' will contain the removed item
const c = a.shift(); // prefered mutable way
const [c] = a.splice(0, 1);

// Immutable solutions: create new array 'b' and leave array 'a' untouched
const b = a.slice(1); // prefered immutable way
const b = a.filter((_, i) => i > 0);
const [c, ...b] = a; // c: the removed item

Odd behavior when Java converts int to byte?

In Java, an int is 32 bits. A byte is 8 bits .

Most primitive types in Java are signed, and byte, short, int, and long are encoded in two's complement. (The char type is unsigned, and the concept of a sign is not applicable to boolean.)

In this number scheme the most significant bit specifies the sign of the number. If more bits are needed, the most significant bit ("MSB") is simply copied to the new MSB.

So if you have byte 255: 11111111 and you want to represent it as an int (32 bits) you simply copy the 1 to the left 24 times.

Now, one way to read a negative two's complement number is to start with the least significant bit, move left until you find the first 1, then invert every bit afterwards. The resulting number is the positive version of that number

For example: 11111111 goes to 00000001 = -1. This is what Java will display as the value.

What you probably want to do is know the unsigned value of the byte.

You can accomplish this with a bitmask that deletes everything but the least significant 8 bits. (0xff)

So:

byte signedByte = -1;
int unsignedByte = signedByte & (0xff);

System.out.println("Signed: " + signedByte + " Unsigned: " + unsignedByte);

Would print out: "Signed: -1 Unsigned: 255"

What's actually happening here?

We are using bitwise AND to mask all of the extraneous sign bits (the 1's to the left of the least significant 8 bits.) When an int is converted into a byte, Java chops-off the left-most 24 bits

1111111111111111111111111010101
&
0000000000000000000000001111111
=
0000000000000000000000001010101

Since the 32nd bit is now the sign bit instead of the 8th bit (and we set the sign bit to 0 which is positive), the original 8 bits from the byte are read by Java as a positive value.

Npm Please try using this command again as root/administrator

This is the flow often happens in this case. You run a command with no admin rights, you get message npm ERR! Please try running this command again as root/Administrator.. Then you open one more CLI(cmd, powershell, bash or whatever) and don't close the previous CLI. It appears you have 2 prompts opened in the same directory. And until you close CLI which runs with no admin rights you will be continuously getting npm ERR! Please try running this command again as root/Administrator. So close CLI which runs with no admins rights before running a new one.

NOTE: a lot of IDE has embedded CLI(Visual Studio, VS Code etc) so please close the instance of IDE as well

(Deep) copying an array using jQuery

$.extend(true, [], [['a', ['c']], 'b'])

That should do it for you.

Simulating Button click in javascript

try this

document.getElementById("datapicker").addEventListener("submit", function())

IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler

The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ). Let's replace it in its context:

  • x is an array equal to [x0 * n], so its length is 1
  • you're iterating from 0 to n-2 (n doesn't matter here), and i is the index. In the beginning, everything is ok (here there's no beginning apparently... :( ), but as soon as i + 1 >= len(x) <=> i >= 0, the element x[i+1] doesn't exist. Here, this element doesn't exist since the beginning of the for loop.

To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ) by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )).

trying to animate a constraint in swift

You need to first change the constraint and then animate the update.
This should be in the superview.

self.nameInputConstraint.constant = 8

Swift 2

UIView.animateWithDuration(0.5) {
    self.view.layoutIfNeeded()
}

Swift 3, 4, 5

UIView.animate(withDuration: 0.5) {
    self.view.layoutIfNeeded()
}

Remove decimal values using SQL query

Here column name must be decimal.

select CAST(columnname AS decimal(38,0)) from table

Fast way to concatenate strings in nodeJS/JavaScript

You asked about performance. See this perf test comparing 'concat', '+' and 'join' - in short the + operator wins by far.

int to unsigned int conversion

This conversion is well defined and will yield the value UINT_MAX - 61. On a platform where unsigned int is a 32-bit type (most common platforms, these days), this is precisely the value that others are reporting. Other values are possible, however.

The actual language in the standard is

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type).

How do I setup the dotenv file in Node.js?

This is how i fix my issue

Intially had this in .env of the root of my project

const db_port = 90101
const db_host="localhost"
const db_username="name"
const db_password="pwd"
const db_name="db"

And all my env variables where undefined.

I fixed it by removing all the const and using just key=value insted of const key="value"

db_port = 90101
db_host=localhost
db_username=name
db_password=pws
db_name=db

How to execute raw queries with Laravel 5.1?

I found the solution in this topic and I code this:

$cards = DB::select("SELECT
        cards.id_card,
        cards.hash_card,
        cards.`table`,
        users.name,
        0 as total,
        cards.card_status,
        cards.created_at as last_update
    FROM cards
    LEFT JOIN users
    ON users.id_user = cards.id_user
    WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
    UNION
    SELECT
        cards.id_card,
        orders.hash_card,
        cards.`table`,
        users.name,
        sum(orders.quantity*orders.product_price) as total, 
        cards.card_status, 
        max(orders.created_at) last_update 
    FROM menu.orders
    LEFT JOIN cards
    ON cards.hash_card = orders.hash_card
    LEFT JOIN users
    ON users.id_user = cards.id_user
    GROUP BY hash_card
    ORDER BY id_card ASC");

Passing arguments to angularjs filters

Extending on pkozlowski.opensource's answer and using javascript array's builtin filter method a prettified solution could be this:

.filter('weDontLike', function(){
    return function(items, name){
        return items.filter(function(item) {
            return item.name != name;
        });
    };
});

Here's the jsfiddle link.

More on Array filter here.

Password masking console application

If I understand this correctly, you're trying to make backspace delete both the visible * character on screen and the cached character in your pass variable?

If so, then just change your else block to this:

            else
            {
                Console.Write("\b");
                pass = pass.Remove(pass.Length -1);
            }

Time part of a DateTime Field in SQL

I know this is an old question, but since the other answers all

  • return strings (rather than datetimes),
  • rely on the internal representation of dates (conversion to float, int, and back) or
  • require SQL Server 2008 or beyond,

I thought I'd add a "pure" option which only requires datetime operations and works with SQL Server 2005+:

SELECT DATEADD(dd, -DATEDIFF(dd, 0, mydatetime), mydatetime)

This calculates the difference (in whole days) between date zero (1900-01-01) and the given date and then subtracts that number of days from the given date, thereby setting its date component to zero.

How to get request url in a jQuery $.get/ajax request

I can't get it to work on $.get() because it has no complete event.

I suggest to use $.ajax() like this,

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

craz demo

Finding the index of elements based on a condition using python list comprehension

  • In Python, you wouldn't use indexes for this at all, but just deal with the values—[value for value in a if value > 2]. Usually dealing with indexes means you're not doing something the best way.

  • If you do need an API similar to Matlab's, you would use numpy, a package for multidimensional arrays and numerical math in Python which is heavily inspired by Matlab. You would be using a numpy array instead of a list.

    >>> import numpy
    >>> a = numpy.array([1, 2, 3, 1, 2, 3])
    >>> a
    array([1, 2, 3, 1, 2, 3])
    >>> numpy.where(a > 2)
    (array([2, 5]),)
    >>> a > 2
    array([False, False,  True, False, False,  True], dtype=bool)
    >>> a[numpy.where(a > 2)]
    array([3, 3])
    >>> a[a > 2]
    array([3, 3])
    

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

Rails find_or_create_by more than one attribute?

In Rails 4 you could do:

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

And use where is different:

GroupMember.where(member_id: 4, group_id: 7).first_or_create

This will call create on GroupMember.where(member_id: 4, group_id: 7):

GroupMember.where(member_id: 4, group_id: 7).create

On the contrary, the find_or_create_by(member_id: 4, group_id: 7) will call create on GroupMember:

GroupMember.create(member_id: 4, group_id: 7)

Please see this relevant commit on rails/rails.

How to get time difference in minutes in PHP

I found so many solution but I never got correct solution. But i have created some code to find minutes please check it.

<?php

  $time1 = "23:58";
  $time2 = "01:00";
  $time1 = explode(':',$time1);
  $time2 = explode(':',$time2);
  $hours1 = $time1[0];
  $hours2 = $time2[0];
  $mins1 = $time1[1];
  $mins2 = $time2[1];
  $hours = $hours2 - $hours1;
  $mins = 0;
  if($hours < 0)
  {
    $hours = 24 + $hours;
  }
  if($mins2 >= $mins1) {
        $mins = $mins2 - $mins1;
    }
    else {
      $mins = ($mins2 + 60) - $mins1;
      $hours--;
    }
    if($mins < 9)
    {
      $mins = str_pad($mins, 2, '0', STR_PAD_LEFT);
    }
    if($hours < 9)
    {
      $hours =str_pad($hours, 2, '0', STR_PAD_LEFT);
    }
echo $hours.':'.$mins;
?>

It gives output in hours and minutes for example 01 hour 02 minutes like 01:02

The import org.apache.commons cannot be resolved in eclipse juno

If you got a Apache Maven project, it's easy to use this package in your project. Just specify it in your pom.xml:

<project>
...

    <properties>
        <version.commons-io>2.4</version.commons-io>
    </properties>

    <dependencies>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${version.commons-io}</version>
        </dependency>
    </dependencies>

...
</project>

Why am I not getting a java.util.ConcurrentModificationException in this example?

Here's why: As it is says in the Javadoc:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

This check is done in the next() method of the iterator (as you can see by the stacktrace). But we will reach the next() method only if hasNext() delivered true, which is what is called by the for each to check if the boundary is met. In your remove method, when hasNext() checks if it needs to return another element, it will see that it returned two elements, and now after one element was removed the list only contains two elements. So all is peachy and we are done with iterating. The check for concurrent modifications does not occur, as this is done in the next() method which is never called.

Next we get to the second loop. After we remove the second number the hasNext method will check again if can return more values. It has returned two values already, but the list now only contains one. But the code here is:

public boolean hasNext() {
        return cursor != size();
}

1 != 2, so we continue to the next() method, which now realizes that someone has been messing with the list and fires the exception.

Hope that clears your question up.

Summary

List.remove() will not throw ConcurrentModificationException when it removes the second last element from the list.

What's the meaning of exception code "EXC_I386_GPFLT"?

EXC_I386_GPFLT is surely referring to "General Protection fault", which is the x86's way to tell you that "you did something that you are not allowed to do". It typically DOESN'T mean that you access out of memory bounds, but it could be that your code is going out of bounds and causing bad code/data to be used in a way that makes for an protection violation of some sort.

Unfortunately it can be hard to figure out exactly what the problem is without more context, there are 27 different causes listed in my AMD64 Programmer's Manual, Vol 2 from 2005 - by all accounts, it is likely that 8 years later would have added a few more.

If it is a 64-bit system, a plausible scenario is that your code is using a "non-canonical pointer" - meaning that a 64-bit address is formed in such a way that the upper 16 bits of the address aren't all copies of the top of the lower 48 bits (in other words, the top 16 bits of an address should all be 0 or all 1, based on the bit just below 16 bits). This rule is in place to guarantee that the architecture can "safely expand the number of valid bits in the address range". This would indicate that the code is either overwriting some pointer data with other stuff, or going out of bounds when reading some pointer value.

Another likely causes is unaligned access with an SSE register - in other word, reading a 16-byte SSE register from an address that isn't 16-byte aligned.

There are, as I said, many other possible reasons, but most of those involve things that "normal" code wouldn't be doing in a 32- or 64-bit OS (such as loading segment registers with invalid selector index or writing to MSR's (model specific registers)).

PivotTable to show values, not sum of values

I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.

Assuming your data is in ColumnA:C and has column labels in Row 1, also that Month is formatted mmm(this last for ease of sorting):

  1. Sort the data by Name then Month
  2. Enter in D2 =IF(AND(A2=A1,C2=C1),D1+1,1) (One way to deal with what is the tricky issue of multiple entries for the same person for the same month).
  3. Create a pivot table from A1:D(last occupied row no.)
  4. Say insert in F1.
  5. Layout as in screenshot.

SO12803305 example

I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.

  1. Copy pivot table and Paste Special/Values to, say, L1.
  2. Delete top row of copied range with shift cells up.
  3. Insert new cell at L1 and shift down.
  4. Key 'Name' into L1.
  5. Filter copied range and for ColumnL, select Row Labels and numeric values.
  6. Delete contents of L2:L(last selected cell)
  7. Delete blank rows in copied range with shift cells up (may best via adding a column that counts all 12 months). Hopefully result should be as highlighted in yellow.

Happy to explain further/try again (I've not really tested this) if does not suit.

EDIT (To avoid second block of steps above and facilitate updating for source data changes)

.0. Before first step 2. add a blank row at the very top and move A2:D2 up.
.2. Adjust cell references accordingly (in D3 =IF(AND(A3=A2,C3=C2),D2+1,1).
.3. Create pivot table from A:D

.6. Overwrite Row Labels with Name.
.7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
.8. Hide Row1, ColumnG and rows and columns that show (blank).

additional example

Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).

Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank) into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.

Return current date plus 7 days

$now = date('Y-m-d');
$start_date = strtotime($now);
$end_date = strtotime("+7 day", $start_date);
echo date('Y-m-d', $start_date) . '  + 7 days =  ' . date('Y-m-d', $end_date);

Recyclerview inside ScrollView not scrolling smoothly

Summary of all answers (Advantages & Disadvantages)

For single recyclerview

you can use it inside Coordinator layout.

Advantage - it will not load entire recyclerview items. So smooth loading.

Disadvantage - you can't load two recyclerview inside Coordinator layout - it produce scrolling problems

reference - https://stackoverflow.com/a/33143512/3879847

For multiple recylerview with minimum rows

you can load inside NestedScrollView

Advantage - it will scroll smoothly

Disadvantage - It load all rows of recyclerview so your activity open with delay

reference - https://stackoverflow.com/a/33143512/3879847

For multiple recylerview with large rows(more than 100)

You must go with recyclerview.

Advantage - Scroll smoothly, load smoothly

Disadvantage - You need to write more code and logic

Load each recylerview inside main recyclerview with help of multi-viewholders

ex:

MainRecyclerview

-ChildRecyclerview1 (ViewHolder1)

-ChildRecyclerview2 (ViewHolder2)

-ChildRecyclerview3 (ViewHolder3) 

-Any other layout   (ViewHolder4)

Reference for multi-viewHolder - https://stackoverflow.com/a/26245463/3879847

/usr/bin/ld: cannot find

Add -L/opt/lib to your compiler parameters, this makes the compiler and linker search that path for libcalc.so in that folder.

unary operator expected in shell script when comparing null value with string

Since the value of $var is the empty string, this:

if [ $var == $var1 ]; then

expands to this:

if [ == abcd ]; then

which is a syntax error.

You need to quote the arguments:

if [ "$var" == "$var1" ]; then

You can also use = rather than ==; that's the original syntax, and it's a bit more portable.

If you're using bash, you can use the [[ syntax, which doesn't require the quotes:

if [[ $var = $var1 ]]; then

Even then, it doesn't hurt to quote the variable reference, and adding quotes:

if [[ "$var" = "$var1" ]]; then

might save a future reader a moment trying to remember whether [[ ... ]] requires them.

Playing MP4 files in Firefox using HTML5 video

This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.

Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:

http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/

Get index of a key in json

Try this

var json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
json = $.parseJSON(json);

var i = 0, req_index = "";
$.each(json, function(index, value){
    if(index == 'key2'){
        req_index = i;
    }
    i++;
});
alert(req_index);

How to enable GZIP compression in IIS 7.5

Sometimes no matter what you do or follow whole internet posts. Try on the MIMETYPES of applicationhost.config of the server.

https://docs.microsoft.com/en-us/iis/configuration/system.webserver/httpcompression/#configuration-sample

Calculating bits required to store decimal number

The largest number that can be represented by an n digit number in base b is bn - 1. Hence, the largest number that can be represented in N binary digits is 2N - 1. We need the smallest integer N such that:

2N - 1 = bn - 1
? 2N = bn

Taking the base 2 logarithm of both sides of the last expression gives:

log2 2N = log2 bn
? N = log2 bn
? N = log bn / log 2

Since we want the smallest integer N that satisfies the last relation, to find N, find log bn / log 2 and take the ceiling.

In the last expression, any base is fine for the logarithms, so long as both bases are the same. It is convenient here, since we are interested in the case where b = 10, to use base 10 logarithms taking advantage of log1010n == n.

For n = 3:

N = ?3 / log10 2? = 10

For n = 4:

N = ?4 / log10 2? = 14

For n = 6:

N = ?6 / log10 2? = 20

And in general, for n decimal digits:

N = ?n / log10 2?

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

I tried Ricardo Stuven's way but it didn't work for me. What worked in the end was adding "compact": false to my .babelrc file:

{
    "compact": false,
    "presets": ["latest", "react", "stage-0"]
}

Check if a varchar is a number (TSQL)

ISNUMERIC will not do - it tells you that the string can be converted to any of the numeric types, which is almost always a pointless piece of information to know. For example, all of the following are numeric, according to ISNUMERIC:

£, $, 0d0

If you want to check for digits and only digits, a negative LIKE expression is what you want:

not Value like '%[^0-9]%'

SQL Server datetime LIKE select?

The LIKE operator does not work with date parts like month or date but the DATEPART operator does.

Command to find out all accounts whose Open Date was on the 1st:

SELECT * 
  FROM Account 
 WHERE DATEPART(DAY, CAST(OpenDt AS DATE)) = 1`

*CASTING OpenDt because it's value is in DATETIME and not just DATE.

How to concatenate two strings to build a complete path

The following script catenates several (relative/absolute) paths (BASEPATH) with a relative path (SUBDIR):

shopt -s extglob
SUBDIR="subdir"
for BASEPATH in '' / base base/ base// /base /base/ /base//; do
  echo "BASEPATH = \"$BASEPATH\" --> ${BASEPATH%%+(/)}${BASEPATH:+/}$SUBDIR"
done

The output of which is:

BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base/subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base/subdir

The shopt -s extglob is only necessary to allow BASEPATH to end on multiple slashes (which is probably nonsense). Without extended globing you can just use:

echo ${BASEPATH%%/}${BASEPATH:+/}$SUBDIR

which would result in the less neat but still working:

BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base//subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base//subdir

SSLHandshakeException: No subject alternative names present

Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.

But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.

static {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {
            public boolean verify(String hostname, SSLSession session)
            {
                // ip address of the service URL(like.23.28.244.244)
                if (hostname.equals("23.28.244.244"))
                    return true;
                return false;
            }
        });
}

If you happen to be using Java 8, there is a much slicker way of achieving the same result:

static {
    HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}

How to make a TextBox accept only alphabetic characters?

This works fine as far as characters restriction, Any suggestions on error msg prompt with my code if it's not C OR L

Private Sub TXTBOX_TextChanged(sender As System.Object, e As System.EventArgs) Handles TXTBOX.TextChanged

        Dim allowed As String = "C,L"
        For Each C As Char In TXTBOX.Text
            If allowed.Contains(C) = False Then

                TXTBOX.Text = TXTBOX.Text.Remove(TXTBOX.SelectionStart - 1, 1)
                TXTBOX.Select(TXTBOX.Text.Count, 0)

            End If

        Next
      
    End Sub

.NET Format a string with fixed spaces

Here's a VB.NET version I created, inspired by Joel Coehoorn's answer, Oliver's edit, and shaunmartin's comment:

    <Extension()>
Public Function PadCenter(ByVal [string] As String, ByVal width As Integer, ByVal c As Char) As String

    If [string] Is Nothing Then [string] = String.Empty
    If (width <= [string].Length) Then Return [string]

    Dim padding = width - [string].Length
    Return [string].PadLeft([string].Length + (padding \ 2), c).PadRight(width, c)

End Function

<Extension()>
Public Function PadCenter(ByVal [string] As String, ByVal width As Integer) As String

    If [string] Is Nothing Then [string] = String.Empty
    If (width <= [string].Length) Then Return [string]

    Dim padding = width - [string].Length
    Return [string].PadLeft([string].Length + (padding \ 2)).PadRight(width)

End Function

This is set up as a string extension, inside a Public Module (the way you do Extensions in VB.NET, a bit different than C#). My slight change is that it treats a null string as an empty string, and it pads an empty string with the width value (meets my particular needs). Hopefully this will convert easily to C# for anyone who needs it. If there's a better way to reference the answers, edits, and comments I mentioned above, which inspired my post, please let me know and I'll do it - I'm relatively new to posting, and I couldn't figure out to leave a comment (might not have enough rep yet).

Why Java Calendar set(int year, int month, int date) not returning correct date?

Months in Calendar object start from 0

0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY

How can I invert color using CSS?

I think the only way to handle this is to use JavaScript

Try this Invert text color of a specific element

If you do this with css3 it's only compatible with the newest browser versions.

VB.net: Date without time

Either use one of the standard date and time format strings which only specifies the date (e.g. "D" or "d"), or a custom date and time format string which only uses the date parts (e.g. "yyyy/MM/dd").

initializing a Guava ImmutableMap

"put" has been deprecated, refrain from using it, use .of instead

ImmutableMap<String, String> myMap = ImmutableMap.of(
    "city1", "Seattle",
    "city2", "Delhi"
);

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

If by chance this error happens when working with SharePoint 2010: Rename your .json file extensions and be sure to update your restService path. No additional "track by $index" was required.

Luckily I was forwarded this link to this rationale:

.json becomes an important file type in SP2010. SP2010 includes certains webservice endpoints. The location of these files is 14hive\isapi folder. The extension of these files are .json. That is the reason it gives such a error.

"cares only that the contents of a json file is json - not its file extension"

Once the file extensions are changed, should be all set.

Drawing Isometric game worlds

Coobird's answer is the correct, complete one. However, I combined his hints with those from another site to create code that works in my app (iOS/Objective-C), which I wanted to share with anyone who comes here looking for such a thing. Please, if you like/up-vote this answer, do the same for the originals; all I did was "stand on the shoulders of giants."

As for sort-order, my technique is a modified painter's algorithm: each object has (a) an altitude of the base (I call "level") and (b) an X/Y for the "base" or "foot" of the image (examples: avatar's base is at his feet; tree's base is at it's roots; airplane's base is center-image, etc.) Then I just sort lowest to highest level, then lowest (highest on-screen) to highest base-Y, then lowest (left-most) to highest base-X. This renders the tiles the way one would expect.

Code to convert screen (point) to tile (cell) and back:

typedef struct ASIntCell {  // like CGPoint, but with int-s vice float-s
    int x;
    int y;
} ASIntCell;

// Cell-math helper here:
//      http://gamedevelopment.tutsplus.com/tutorials/creating-isometric-worlds-a-primer-for-game-developers--gamedev-6511
// Although we had to rotate the coordinates because...
// X increases NE (not SE)
// Y increases SE (not SW)
+ (ASIntCell) cellForPoint: (CGPoint) point
{
    const float halfHeight = rfcRowHeight / 2.;

    ASIntCell cell;
    cell.x = ((point.x / rfcColWidth) - ((point.y - halfHeight) / rfcRowHeight));
    cell.y = ((point.x / rfcColWidth) + ((point.y + halfHeight) / rfcRowHeight));

    return cell;
}


// Cell-math helper here:
//      http://stackoverflow.com/questions/892811/drawing-isometric-game-worlds/893063
// X increases NE,
// Y increases SE
+ (CGPoint) centerForCell: (ASIntCell) cell
{
    CGPoint result;

    result.x = (cell.x * rfcColWidth  / 2) + (cell.y * rfcColWidth  / 2);
    result.y = (cell.y * rfcRowHeight / 2) - (cell.x * rfcRowHeight / 2);

    return result;
}

Image library for Python 3

As of March 30, 2012, I have tried and failed to get the sloonz fork on GitHub to open images. I got it to compile ok, but it didn't actually work. I also tried building gohlke's library, and it compiled also but failed to open any images. Someone mentioned PythonMagick above, but it only compiles on Windows. See PythonMagick on the wxPython wiki.

PIL was last updated in 2009, and while it's website says they are working on a Python 3 port, it's been 3 years, and the mailing list has gone cold.

To solve my Python 3 image manipulation problem, I am using subprocess.call() to execute ImageMagick shell commands. This method works.

See the subprocess module documentation.

How to put php inside JavaScript?

As others have pointed out you need the quotes, but I just want to point out that there's a shorthand method of writing this same line of code

var htmlString="<?=$htmlString?>";

See you can leave out the "php echo" stuff and replace it with a simple "=".

Better way to find last used row

You should use a with statement to qualify both your Rows and Columns counts. This will prevent any errors while working with older pre 2007 and newer 2007 Excel Workbooks.

Last Column

With Sheets("Sheet2")
    .Cells(1, .Columns.Count).End(xlToLeft).Column
End With 

Last Row

With Sheets("Sheet2")
    .Range("A" & .Rows.Count).End(xlUp).Row
End With 

Or

With Sheets("Sheet2")
    .Cells(.Rows.Count, 1).End(xlUp).Row
End With 

How to check Django version

For Python:

import sys
sys.version

For Django (as mentioned by others here):

import django
django.get_version()

The potential problem with simply checking the version, is that versions get upgraded and so the code can go out of date. You want to make sure that '1.7' < '1.7.1' < '1.7.5' < '1.7.10'. A normal string comparison would fail in the last comparison:

>>> '1.7.5' < '1.7.10'
False

The solution is to use StrictVersion from distutils.

>>> from distutils.version import StrictVersion
>>> StrictVersion('1.7.5') < StrictVersion('1.7.10')
True

How can I rollback a git repository to a specific commit?

Another way:

Checkout the branch you want to revert, then reset your local working copy back to the commit that you want to be the latest one on the remote server (everything after it will go bye-bye). To do this, in SourceTree, I right-clicked on the and selected "Reset BRANCHNAME to this commit".

Then navigate to your repository's local directory and run this command:

git -c diff.mnemonicprefix=false -c core.quotepath=false push -v -f -- tags REPOSITORY_NAME BRANCHNAME:BRANCHNAME 

This will erase all commits after the current one in your local repository but only for that one branch.

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


Specify an SSH key for git push for a given domain

From git 2.10 upwards it is also possible to use the gitconfig sshCommand setting. Docs state :

If this variable is set, git fetch and git push will use the specified command instead of ssh when they need to connect to a remote system. The command is in the same form as the GIT_SSH_COMMAND environment variable and is overridden when the environment variable is set.

An usage example would be: git config core.sshCommand "ssh -i ~/.ssh/[insert_your_keyname]

In some cases this doesn't work because ssh_config overriding the command, in this case try ssh -i ~/.ssh/[insert_your_keyname] -F /dev/null to not use the ssh_config.

Clear text field value in JQuery

$('#[element id]').val(null);

or

$('.[element class]').val(null);

Eclipse copy/paste entire line keyboard shortcut

If Your Window pc, you may try this, it's also for STS:

Ctrl + win + Alt + Down :: Copy current line or selected line to below

Ctrl + win + Alt + Up :: Copy current line or selected line to above

What exactly are iterator, iterable, and iteration?

The above answers are great, but as most of what I've seen, don't stress the distinction enough for people like me.

Also, people tend to get "too Pythonic" by putting definitions like "X is an object that has __foo__() method" before. Such definitions are correct--they are based on duck-typing philosophy, but the focus on methods tends to get between when trying to understand the concept in its simplicity.

So I add my version.


In natural language,

  • iteration is the process of taking one element at a time in a row of elements.

In Python,

  • iterable is an object that is, well, iterable, which simply put, means that it can be used in iteration, e.g. with a for loop. How? By using iterator. I'll explain below.

  • ... while iterator is an object that defines how to actually do the iteration--specifically what is the next element. That's why it must have next() method.

Iterators are themselves also iterable, with the distinction that their __iter__() method returns the same object (self), regardless of whether or not its items have been consumed by previous calls to next().


So what does Python interpreter think when it sees for x in obj: statement?

Look, a for loop. Looks like a job for an iterator... Let's get one. ... There's this obj guy, so let's ask him.

"Mr. obj, do you have your iterator?" (... calls iter(obj), which calls obj.__iter__(), which happily hands out a shiny new iterator _i.)

OK, that was easy... Let's start iterating then. (x = _i.next() ... x = _i.next()...)

Since Mr. obj succeeded in this test (by having certain method returning a valid iterator), we reward him with adjective: you can now call him "iterable Mr. obj".

However, in simple cases, you don't normally benefit from having iterator and iterable separately. So you define only one object, which is also its own iterator. (Python does not really care that _i handed out by obj wasn't all that shiny, but just the obj itself.)

This is why in most examples I've seen (and what had been confusing me over and over), you can see:

class IterableExample(object):

    def __iter__(self):
        return self

    def next(self):
        pass

instead of

class Iterator(object):
    def next(self):
        pass

class Iterable(object):
    def __iter__(self):
        return Iterator()

There are cases, though, when you can benefit from having iterator separated from the iterable, such as when you want to have one row of items, but more "cursors". For example when you want to work with "current" and "forthcoming" elements, you can have separate iterators for both. Or multiple threads pulling from a huge list: each can have its own iterator to traverse over all items. See @Raymond's and @glglgl's answers above.

Imagine what you could do:

class SmartIterableExample(object):

    def create_iterator(self):
        # An amazingly powerful yet simple way to create arbitrary
        # iterator, utilizing object state (or not, if you are fan
        # of functional), magic and nuclear waste--no kittens hurt.
        pass    # don't forget to add the next() method

    def __iter__(self):
        return self.create_iterator()

Notes:

  • I'll repeat again: iterator is not iterable. Iterator cannot be used as a "source" in for loop. What for loop primarily needs is __iter__() (that returns something with next()).

  • Of course, for is not the only iteration loop, so above applies to some other constructs as well (while...).

  • Iterator's next() can throw StopIteration to stop iteration. Does not have to, though, it can iterate forever or use other means.

  • In the above "thought process", _i does not really exist. I've made up that name.

  • There's a small change in Python 3.x: next() method (not the built-in) now must be called __next__(). Yes, it should have been like that all along.

  • You can also think of it like this: iterable has the data, iterator pulls the next item

Disclaimer: I'm not a developer of any Python interpreter, so I don't really know what the interpreter "thinks". The musings above are solely demonstration of how I understand the topic from other explanations, experiments and real-life experience of a Python newbie.

Ansible: How to delete files and folders inside a directory?

Using shell module (idempotent too):

- shell: /bin/rm -rf /home/mydata/web/*

If there are dot/hidden files:

- shell: /bin/rm -rf /home/mydata/web/* /home/mydata/web/.*

Cleanest solution if you don't care about creation date and owner/permissions:

- file: path=/home/mydata/web state=absent
- file: path=/home/mydata/web state=directory

What is an instance variable in Java?

Instance variable is the variable declared inside a class, but outside a method: something like:

class IronMan {

    /** These are all instance variables **/
    public String realName;
    public String[] superPowers;
    public int age;

    /** Getters and setters here **/
}

Now this IronMan Class can be instantiated in another class to use these variables. Something like:

class Avengers {

    public static void main(String[] a) {
        IronMan ironman = new IronMan();
        ironman.realName = "Tony Stark";
        // or
        ironman.setAge(30);
    }

}

This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.

MySQL WHERE: how to write "!=" or "not equals"?

DELETE FROM konta WHERE taken <> '';

How to add MVC5 to Visual Studio 2013?

Go File -> New Project.

Select Web under Visual C#.

Select ASP.NET Web Application

Click OK.

New Project Dialog

Select MVC.

Click OK.

ASP.Net Dialog

How to discard all changes made to a branch?

In the source root: git reset ./ HEAD <--un-stage any staged changes git checkout ./ <--discard any unstaged changes

How to add an empty column to a dataframe?

Sorry for I did not explain my answer really well at beginning. There is another way to add an new column to an existing dataframe. 1st step, make a new empty data frame (with all the columns in your data frame, plus a new or few columns you want to add) called df_temp 2nd step, combine the df_temp and your data frame.

df_temp = pd.DataFrame(columns=(df_null.columns.tolist() + ['empty']))
df = pd.concat([df_temp, df])

It might be the best solution, but it is another way to think about this question.

the reason of I am using this method is because I am get this warning all the time:

: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df["empty1"], df["empty2"] = [np.nan, ""]

great I found the way to disable the Warning

pd.options.mode.chained_assignment = None 

Fullscreen Activity in Android?

You can do it programatically:

public class ActivityName extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // remove title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
    }
}

Or you can do it via your AndroidManifest.xml file:

<activity android:name=".ActivityName"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen"/>

Edit:

If you are using AppCompatActivity then you need to add new theme

<style name="Theme.AppCompat.Light.NoActionBar.FullScreen" parent="@style/Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

and then use it.

<activity android:name=".ActivityName"
    android:label="@string/app_name"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen"/>

Thanks to https://stackoverflow.com/a/25365193/1646479

how to find array size in angularjs

Just use the length property of a JavaScript array like so:

$scope.names.length

Also, I don't see a starting <script> tag in your code.

If you want the length inside your view, do it like so:

{{ names.length }}

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

The following worked for Laravel 7.x (and should probably work for any other version as well given the nature of the issue).

npm uninstall --save-dev cross-env
npm install -g cross-env

Just moving cross-env from being a local devDependency to a globally available package.

How can I get the height of an element using css only

You could use the CSS calc parameter to calculate the height dynamically like so:

_x000D_
_x000D_
.dynamic-height {_x000D_
   color: #000;_x000D_
   font-size: 12px;_x000D_
   margin-top: calc(100% - 10px);_x000D_
   text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

php $_POST array empty upon form submission

If you are posting to a index.php file in a directory for example /api/index.php make sure in your form you specify the full directory to the file e.g

This

<form method="post" action="/api/index.php"> 
</form>

OR

<form method="post" action="/api/"> 
</form>

works.

But this fails

<form method="post" action="/api"> 
</form>

System.MissingMethodException: Method not found?

Ran into this error after updating a variety of Nuget packages. Check your Visual Studio Error List (or build output) for a warning similar to the following:

Found conflicts between different versions of the same dependent assembly. In Visual Studio, double-click this warning (or select it and press Enter) to fix the conflicts; otherwise, add the following binding redirects to the "runtime" node in the application configuration file:
...

Double-clicking this warning in Visual Studio automatically adjusted a variety of bindingRedirect package versions in my web.config and resolved the error.

How to convert string to double with proper cultureinfo

Use InvariantCulture. The decimal separator is always "." eventually you can replace "," by "." When you display the result , use your local culture. But internally use always invariant culture

TryParse does not allway work as we would expect There are change request in .net in this area:

https://github.com/dotnet/runtime/issues/25868

Laravel 5 – Remove Public from URL

I found the most working solution to this problem.

Just edit your .htaccess in the root folder and write the following code. Nothing else required

RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]

<IfModule php7_module>
   php_flag display_errors Off
   php_value max_execution_time 30
   php_value max_input_time 60
   php_value max_input_vars 1000
   php_value memory_limit -1
   php_value post_max_size 8M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php71"
   php_value upload_max_filesize 2M
   php_flag zlib.output_compression Off
</IfModule>

node.js execute system command synchronously

Native Node.js solution is:

const {execSync} = require('child_process');

const result = execSync('node -v'); //  this do the trick 

Just be aware that some commands returns Buffer instead of string. And if you need string just add encoding to execSync options:

const result = execSync('git rev-parse HEAD', {encoding: 'utf8'});

... and it is also good to have timeout on sync exec:

const result = execSync('git rev-parse HEAD', {encoding: 'utf8', timeout: 10000});

Write to UTF-8 file in Python

@S-Lott gives the right procedure, but expanding on the Unicode issues, the Python interpreter can provide more insights.

Jon Skeet is right (unusual) about the codecs module - it contains byte strings:

>>> import codecs
>>> codecs.BOM
'\xff\xfe'
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'
>>> 

Picking another nit, the BOM has a standard Unicode name, and it can be entered as:

>>> bom= u"\N{ZERO WIDTH NO-BREAK SPACE}"
>>> bom
u'\ufeff'

It is also accessible via unicodedata:

>>> import unicodedata
>>> unicodedata.lookup('ZERO WIDTH NO-BREAK SPACE')
u'\ufeff'
>>> 

Removing spaces from a variable input using PowerShell 4.0

The Replace operator means Replace something with something else; do not be confused with removal functionality.

Also you should send the result processed by the operator to a variable or to another operator. Neither .Replace(), nor -replace modifies the original variable.

To remove all spaces, use 'Replace any space symbol with empty string'

$string = $string -replace '\s',''

To remove all spaces at the beginning and end of the line, and replace all double-and-more-spaces or tab symbols to spacebar symbol, use

$string = $string -replace '(^\s+|\s+$)','' -replace '\s+',' '

or the more native System.String method

$string = $string.Trim()

Regexp is preferred, because ' ' means only 'spacebar' symbol, and '\s' means 'spacebar, tab and other space symbols'. Note that $string.Replace() does 'Normal' replace, and $string -replace does RegEx replace, which is more heavy but more functional.

Note that RegEx have some special symbols like dot (.), braces ([]()), slashes (\), hats (^), mathematical signs (+-) or dollar signs ($) that need do be escaped. ( 'my.space.com' -replace '\.','-' => 'my-space-com'. A dollar sign with a number (ex $1) must be used on a right part with care

'2033' -replace '(\d+)',$( 'Data: $1')
Data: 2033

UPDATE: You can also use $str = $str.Trim(), along with TrimEnd() and TrimStart(). Read more at System.String MSDN page.

Php artisan make:auth command is not defined

If you using >5 version of laravel then you will use.

composer require laravel/ui --dev **or** composer require laravel/ui

And then

php artisan ui:auth

Updating a date in Oracle SQL table

Just to add to Alex Poole's answer, here is how you do the date and time:

    TO_DATE('31/DEC/2017 12:59:59', 'dd/mm/yyyy hh24:mi:ss')

How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?

If you have Cygwin installed (which I strongly recommend for a variety of reasons), you could use the 'file' utility on the DLL

file <filename>

which would give an output like this:

icuuc36.dll: MS-DOS executable PE  for MS Windows (DLL) (GUI) Intel 80386 32-bit

Cross domain POST request is not sending cookie Ajax Jquery

You cannot set or read cookies on CORS requests through JavaScript. Although CORS allows cross-origin requests, the cookies are still subject to the browser's same-origin policy, which means only pages from the same origin can read/write the cookie. withCredentials only means that any cookies set by the remote host are sent to that remote host. You will have to set the cookie from the remote server by using the Set-Cookie header.

FileNotFoundError: [Errno 2] No such file or directory

with open(fpath, 'rb') as myfile:
    fstr = myfile.read()

I encounter this error because the file is empty. This answer may not a correct answer for this question but should give developers a hint like me.

How do I send a POST request as a JSON?

for python 3.4.2 I found the following will work:

import urllib.request
import json      

body = {'ids': [12, 14, 50]}  
myurl = "http://www.testmycode.com"

req = urllib.request.Request(myurl)
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8')   # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
response = urllib.request.urlopen(req, jsondataasbytes)

How to use Select2 with JSON via Ajax request?

My ajax never gets fired until I wrapped the whole thing in

setTimeout(function(){ .... }, 3000);

I was using it in mounted section of Vue. it needs more time.

Download pdf file using jquery ajax

I am newbie and most of the code is from google search. I got my pdf download working with the code below (trial and error play). Thank you for code tips (xhrFields) above.

$.ajax({
            cache: false,
            type: 'POST',
            url: 'yourURL',
            contentType: false,
            processData: false,
            data: yourdata,
             //xhrFields is what did the trick to read the blob to pdf
            xhrFields: {
                responseType: 'blob'
            },
            success: function (response, status, xhr) {

                var filename = "";                   
                var disposition = xhr.getResponseHeader('Content-Disposition');

                 if (disposition) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches !== null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                } 
                var linkelem = document.createElement('a');
                try {
                                           var blob = new Blob([response], { type: 'application/octet-stream' });                        

                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        //   IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                        window.navigator.msSaveBlob(blob, filename);
                    } else {
                        var URL = window.URL || window.webkitURL;
                        var downloadUrl = URL.createObjectURL(blob);

                        if (filename) { 
                            // use HTML5 a[download] attribute to specify filename
                            var a = document.createElement("a");

                            // safari doesn't support this yet
                            if (typeof a.download === 'undefined') {
                                window.location = downloadUrl;
                            } else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.target = "_blank";
                                a.click();
                            }
                        } else {
                            window.location = downloadUrl;
                        }
                    }   

                } catch (ex) {
                    console.log(ex);
                } 
            }
        });

What is external linkage and internal linkage?

Linkage determines whether identifiers that have identical names refer to the same object, function, or other entity, even if those identifiers appear in different translation units. The linkage of an identifier depends on how it was declared. There are three types of linkages:

  1. Internal linkage : identifiers can only be seen within a translation unit.
  2. External linkage : identifiers can be seen (and referred to) in other translation units.
  3. No linkage : identifiers can only be seen in the scope in which they are defined. Linkage does not affect scoping

C++ only : You can also have linkage between C++ and non-C++ code fragments, which is called language linkage.

Source :IBM Program Linkage

Where do I find old versions of Android NDK?

Looks like simply putting the link like this

http://dl.google.com/android/ndk/android-ndk-r7c-windows.zip

on the address bar of your browser

The revision names (r7c, r8c etc.) could be found from the ndk download page

How do I set log4j level on the command line?

Based on @lijat, here is a simplified implementation. In my spring-based application I simply load this as a bean.

public static void configureLog4jFromSystemProperties()
{
  final String LOGGER_PREFIX = "log4j.logger.";

  for(String propertyName : System.getProperties().stringPropertyNames())
  {
    if (propertyName.startsWith(LOGGER_PREFIX)) {
      String loggerName = propertyName.substring(LOGGER_PREFIX.length());
      String levelName = System.getProperty(propertyName, "");
      Level level = Level.toLevel(levelName); // defaults to DEBUG
      if (!"".equals(levelName) && !levelName.toUpperCase().equals(level.toString())) {
        logger.error("Skipping unrecognized log4j log level " + levelName + ": -D" + propertyName + "=" + levelName);
        continue;
      }
      logger.info("Setting " + loggerName + " => " + level.toString());
      Logger.getLogger(loggerName).setLevel(level);
    }
  }
}

Encode URL in JavaScript?

Encode URL String

    var url = $(location).attr('href'); //get current url
    //OR
    var url = 'folder/index.html?param=#23dd&noob=yes'; //or specify one

var encodedUrl = encodeURIComponent(url); console.log(encodedUrl); //outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes for more info go http://www.sitepoint.com/jquery-decode-url-string

When to use HashMap over LinkedList or ArrayList and vice-versa

Lists and Maps are different data structures. Maps are used for when you want to associate a key with a value and Lists are an ordered collection.

Map is an interface in the Java Collection Framework and a HashMap is one implementation of the Map interface. HashMap are efficient for locating a value based on a key and inserting and deleting values based on a key. The entries of a HashMap are not ordered.

ArrayList and LinkedList are an implementation of the List interface. LinkedList provides sequential access and is generally more efficient at inserting and deleting elements in the list, however, it is it less efficient at accessing elements in a list. ArrayList provides random access and is more efficient at accessing elements but is generally slower at inserting and deleting elements.

Multiple Inheritance in C#

Since the question of multiple inheritance (MI) pops up from time to time, I'd like to add an approach which addresses some problems with the composition pattern.

I build upon the IFirst, ISecond,First, Second, FirstAndSecond approach, as it was presented in the question. I reduce sample code to IFirst, since the pattern stays the same regardless of the number of interfaces / MI base classes.

Lets assume, that with MI First and Second would both derive from the same base class BaseClass, using only public interface elements from BaseClass

This can be expressed, by adding a container reference to BaseClass in the First and Second implementation:

class First : IFirst {
  private BaseClass ContainerInstance;
  First(BaseClass container) { ContainerInstance = container; }
  public void FirstMethod() { Console.WriteLine("First"); ContainerInstance.DoStuff(); } 
}
...

Things become more complicated, when protected interface elements from BaseClass are referenced or when First and Second would be abstract classes in MI, requiring their subclasses to implement some abstract parts.

class BaseClass {
  protected void DoStuff();
}

abstract class First : IFirst {
  public void FirstMethod() { DoStuff(); DoSubClassStuff(); }
  protected abstract void DoStuff(); // base class reference in MI
  protected abstract void DoSubClassStuff(); // sub class responsibility
}

C# allows nested classes to access protected/private elements of their containing classes, so this can be used to link the abstract bits from the First implementation.

class FirstAndSecond : BaseClass, IFirst, ISecond {
  // link interface
  private class PartFirst : First {
    private FirstAndSecond ContainerInstance;
    public PartFirst(FirstAndSecond container) {
      ContainerInstance = container;
    }
    // forwarded references to emulate access as it would be with MI
    protected override void DoStuff() { ContainerInstance.DoStuff(); }
    protected override void DoSubClassStuff() { ContainerInstance.DoSubClassStuff(); }
  }
  private IFirst partFirstInstance; // composition object
  public FirstMethod() { partFirstInstance.FirstMethod(); } // forwarded implementation
  public FirstAndSecond() {
    partFirstInstance = new PartFirst(this); // composition in constructor
  }
  // same stuff for Second
  //...
  // implementation of DoSubClassStuff
  private void DoSubClassStuff() { Console.WriteLine("Private method accessed"); }
}

There is quite some boilerplate involved, but if the actual implementation of FirstMethod and SecondMethod are sufficiently complex and the amount of accessed private/protected methods is moderate, then this pattern may help to overcome lacking multiple inheritance.

Java check if boolean is null

In Java, null only applies to object references; since boolean is a primitive type, it cannot be assigned null.

It's hard to get context from your example, but I'm guessing that if hideInNav is not in the object returned by getProperties(), the (default value?) you've indicated will be false. I suspect this is the bug that you're seeing, as false is not equal to null, so hideNavigation is getting the empty string?

You might get some better answers with a bit more context to your code sample.

Visual c++ can't open include file 'iostream'

I got this error when I created an 'Empty' console application in Visual Studio 2015. I re-created the application, leaving the 'Empty' box unchecked, it added all of the necessary libraries.

how to set mongod --dbpath

First you will have a config file in /etc/mongodb.conf, therefore this sounds like a homebrew install which will use some more standardized paths. The whole /data/db/ thing is referenced in a lot of manual install documentation.

So basically from your log the server is not running, it's shutting down, so there is nothing for the shell to connect to. Seems like you have had some unclean shutdowns/restarts which has led to the inconsistency.

Clear the files in the journal /usr/local/var/mongodb/journal/ on your config.

Also:

sudo rm /var/lib/mongodb/mongod.lock

Just in case, even though that part looks clean. And then restart.

Convert a python 'type' object to a string

In case you want to use str() and a custom str method. This also works for repr.

class TypeProxy:
    def __init__(self, _type):
        self._type = _type

    def __call__(self, *args, **kwargs):
        return self._type(*args, **kwargs)

    def __str__(self):
        return self._type.__name__

    def __repr__(self):
        return "TypeProxy(%s)" % (repr(self._type),)

>>> str(TypeProxy(str))
'str'
>>> str(TypeProxy(type("")))
'str'

Determine a user's timezone

You could do it on the client with moment-timezone and send the value to server; sample usage:

> moment.tz.guess()
"America/Asuncion"

How do I count a JavaScript object's attributes?

You can iterate over the object to get the keys or values:

function numKeys(obj)
{
    var count = 0;
    for(var prop in obj)
    {
        count++;
    }
    return count;
}

It looks like a "spelling mistake" but just want to point out that your example is invalid syntax, should be

var object = {"key1":"value1","key2":"value2","key3":"value3"};

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

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

Getting the names of all files in a directory with PHP

It's due to operator precidence. Try changing it to:

while(($file = readdir($handle)) !== FALSE)
{
    $results_array[] = $file;
}
closedir($handle);

How to check if an user is logged in Symfony2 inside a controller?

Try this:

if( $this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') ){
    // authenticated (NON anonymous)
}

Further information:

"Anonymous users are technically authenticated, meaning that the isAuthenticated() method of an anonymous user object will return true. To check if your user is actually authenticated, check for the IS_AUTHENTICATED_FULLY role."

Source: http://symfony.com/doc/current/book/security.html

How do I get the full path of the current file's directory?

I found the following commands will all return the full path of the parent directory of a Python 3.6 script.

Python 3.6 Script:

#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-

from pathlib import Path

#Get the absolute path of a Python3.6 script
dir1 = Path().resolve()  #Make the path absolute, resolving any symlinks.
dir2 = Path().absolute() #See @RonKalian answer 
dir3 = Path(__file__).parent.absolute() #See @Arminius answer 

print(f'dir1={dir1}\ndir2={dir2}\ndir3={dir3}')

Explanation links: .resolve(), .absolute(), Path(file).parent().absolute()

Leader Not Available Kafka in Console Producer

In my case, it was working fine at home, but it was failing in office, the moment I connect to office network.

So modified the config/server.properties listeners=PLAINTEXT://:9092 to listeners=PLAINTEXT://localhost:9092

In my case, I was getting while describing the Consumer Group

Foreign Key naming scheme

A note from Microsoft concerning SQL Server:

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.

so, I'll use terms describing dependency instead of the conventional primary/foreign relationship terms.

When referencing the PRIMARY KEY of the independent (parent) table by the similarly named column(s) in the dependent (child) table, I omit the column name(s):

FK_ChildTable_ParentTable

When referencing other columns, or the column names vary between the two tables, or just to be explicit:

FK_ChildTable_childColumn_ParentTable_parentColumn

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

/**
 * @param filePath
 * @param fs
 * @return list of absolute file path present in given path
 * @throws FileNotFoundException
 * @throws IOException
 */
public static List<String> getAllFilePath(Path filePath, FileSystem fs) throws FileNotFoundException, IOException {
    List<String> fileList = new ArrayList<String>();
    FileStatus[] fileStatus = fs.listStatus(filePath);
    for (FileStatus fileStat : fileStatus) {
        if (fileStat.isDirectory()) {
            fileList.addAll(getAllFilePath(fileStat.getPath(), fs));
        } else {
            fileList.add(fileStat.getPath().toString());
        }
    }
    return fileList;
}

Quick Example : Suppose you have the following file structure:

a  ->  b
   ->  c  -> d
          -> e 
   ->  d  -> f

Using the code above, you get:

a/b
a/c/d
a/c/e
a/d/f

If you want only the leaf (i.e. fileNames), use the following code in else block :

 ...
    } else {
        String fileName = fileStat.getPath().toString(); 
        fileList.add(fileName.substring(fileName.lastIndexOf("/") + 1));
    }

This will give:

b
d
e
f

What is the difference between Views and Materialized Views in Oracle?

Materialized views are disk based and are updated periodically based upon the query definition.

Views are virtual only and run the query definition each time they are accessed.

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

Plot a bar using matplotlib using a dictionary

You can do it in two lines by first plotting the bar chart and then setting the appropriate ticks:

import matplotlib.pyplot as plt

D = {u'Label1':26, u'Label2': 17, u'Label3':30}

plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
# # for python 2.x:
# plt.bar(range(len(D)), D.values(), align='center')  # python 2.x
# plt.xticks(range(len(D)), D.keys())  # in python 2.x

plt.show()

Note that the penultimate line should read plt.xticks(range(len(D)), list(D.keys())) in python3, because D.keys() returns a generator, which matplotlib cannot use directly.

java.util.Date and getYear()

The java documentation suggests to make use of Calendar class instead of this deprecated way Here is the sample code to set up the calendar object

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());

Here is the sample code to get the year, month, etc.

System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.MONTH));

Calendar also has support for many other useful information like, TIME, DAY_OF_MONTH, etc. Here the documentation listing all of them Please note that the month are 0 based. January is 0th month.

Why can a function modify some arguments as perceived by the caller, but not others?

If the functions are re-written with completely different variables and we call id on them, it then illustrates the point well. I didn't get this at first and read jfs' post with the great explanation, so I tried to understand/convince myself:

def f(y, z):
    y = 2
    z.append(4)
    print ('In f():             ', id(y), id(z))

def main():
    n = 1
    x = [0,1,2,3]
    print ('Before in main:', n, x,id(n),id(x))
    f(n, x)
    print ('After in main:', n, x,id(n),id(x))

main()
Before in main: 1 [0, 1, 2, 3]   94635800628352 139808499830024
In f():                          94635800628384 139808499830024
After in main: 1 [0, 1, 2, 3, 4] 94635800628352 139808499830024

z and x have the same id. Just different tags for the same underlying structure as the article says.

How to use filter, map, and reduce in Python 3

One of the advantages of map, filter and reduce is how legible they become when you "chain" them together to do something complex. However, the built-in syntax isn't legible and is all "backwards". So, I suggest using the PyFunctional package (https://pypi.org/project/PyFunctional/). Here's a comparison of the two:

flight_destinations_dict = {'NY': {'London', 'Rome'}, 'Berlin': {'NY'}}

PyFunctional version

Very legible syntax. You can say:

"I have a sequence of flight destinations. Out of which I want to get the dict key if city is in the dict values. Finally, filter out the empty lists I created in the process."

from functional import seq  # PyFunctional package to allow easier syntax

def find_return_flights_PYFUNCTIONAL_SYNTAX(city, flight_destinations_dict):
    return seq(flight_destinations_dict.items()) \
        .map(lambda x: x[0] if city in x[1] else []) \
        .filter(lambda x: x != []) \

Default Python version

It's all backwards. You need to say:

"OK, so, there's a list. I want to filter empty lists out of it. Why? Because I first got the dict key if the city was in the dict values. Oh, the list I'm doing this to is flight_destinations_dict."

def find_return_flights_DEFAULT_SYNTAX(city, flight_destinations_dict):
    return list(
        filter(lambda x: x != [],
               map(lambda x: x[0] if city in x[1] else [], flight_destinations_dict.items())
               )
    )

iOS download and save image inside app

You cannot save anything inside the app's bundle, but you can use +[NSData dataWithContentsOfURL:] to store the image in your app's documents directory, e.g.:

NSData *imageData = [NSData dataWithContentsOfURL:myImageURL];
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];
[imageData writeToFile:imagePath atomically:YES];

Not exactly permanent, but it stays there at least until the user deletes the app.

How to call Makefile from another Makefile?

http://www.gnu.org/software/make/manual/make.html#Recursion

 subsystem:
         cd subdir && $(MAKE)

or, equivalently, this :

 subsystem:
         $(MAKE) -C subdir

taking input of a string word by word

Put the line in a stringstream and extract word by word back:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string t;
    getline(cin,t);

    istringstream iss(t);
    string word;
    while(iss >> word) {
        /* do stuff with word */
    }
}

Of course, you can just skip the getline part and read word by word from cin directly.

And here you can read why is using namespace std considered bad practice.

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

Problem solved!

I was having all my website set up first in XAMMP, then I had to transfer it to LAMP, in a SUSE installation of LAMP, where I got this error.

The problem is that these parameters in the database.php file should not be initialised. Just leave username and password blank. That's just it.

(My first and lame guess would be that's because of old version of mysql, as built-in installations come with older versions.

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

If none of the answers worked out for you, try this,

Hyper-V might not be disabled If you have windows 10 features such as Device Guard and Credential Guard is enabled, it can prevent Hyper-V from being completely disabled.

The Device Guard and Credential Guard hardware readiness tool released by Microsoft can disable the said Windows 10 features along with Hyper-V:

Download it here, https://www.microsoft.com/en-us/download/details.aspx?id=53337

Download the latest version of the Device Guard and Credential Guard hardware readiness tool. Unzip Open the Command Prompt using Run as administrator @powershell -ExecutionPolicy RemoteSigned -Command "X:\path\to\dgreadiness_v3.6\DG_Readiness_Tool_v3.6.ps1 -Disable" Reboot.

Eclipse error: R cannot be resolved to a variable

In addition to install the build tools and restart the update manager I also had to restart Eclipse to make this work.

How to increase the vertical split window size in Vim

In case you need HORIZONTAL SPLIT resize as well:
The command is the same for all splits, just the parameter changes:

- + instead of < >

Examples:
Decrease horizontal size by 10 columns

:10winc -

Increase horizontal size by 30 columns

:30winc +

or within normal mode:

Horizontal splits

10 CTRL+w -

30 CTRL+w +

Vertical splits

10 CTRL+w < (decrease)

30 CTRL+w > (increase)

How do I change the figure size for a seaborn plot?

You can set the context to be poster or manually set fig_size.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

np.random.seed(0)
n, p = 40, 8
d = np.random.normal(0, 2, (n, p))
d += np.log(np.arange(1, p + 1)) * -5 + 10


# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(11.7, 8.27)
sns.violinplot(data=d, inner="points", ax=ax)    
sns.despine()

fig.savefig('example.png')

enter image description here

Volley - POST/GET parameters

This helper class manages parameters for GET and POST requests:

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;    

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

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject> {
    private int mMethod;
    private String mUrl;
    private Map<String, String> mParams;
    private Listener<JSONObject> mListener;

    public CustomRequest(int method, String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.mMethod = method;
        this.mUrl = url;
        this.mParams = params;
        this.mListener = reponseListener;
    }

@Override
public String getUrl() {
    if(mMethod == Request.Method.GET) {
        if(mParams != null) {
            StringBuilder stringBuilder = new StringBuilder(mUrl);
            Iterator<Map.Entry<String, String>> iterator = mParams.entrySet().iterator();
            int i = 1;
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                if (i == 1) {
                    stringBuilder.append("?" + entry.getKey() + "=" + entry.getValue());
                } else {
                    stringBuilder.append("&" + entry.getKey() + "=" + entry.getValue());
                }
                iterator.remove(); // avoids a ConcurrentModificationException
                i++;
            }
            mUrl = stringBuilder.toString();
        }
    }
    return mUrl;
}

    @Override
    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return mParams;
    };

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        mListener.onResponse(response);
    }
}

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

Even easier is just to add the following annotations to the top of your class:

[Serializable, XmlRoot("user")]
public partial class User
{
}

How do you remove duplicates from a list whilst preserving order?

MizardX's answer gives a good collection of multiple approaches.

This is what I came up with while thinking aloud:

mylist = [x for i,x in enumerate(mylist) if x not in mylist[i+1:]]

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Avoiding "resource is out of sync with the filesystem"

If this occurs trying to delete a folder (on *nix) and Refresh does not help, open a terminal and look for a symlink below the folder you are trying to delete and remove this manually. This solved my issues.

JavaScript module pattern with example

I would really recommend anyone entering this subject to read Addy Osmani's free book:

"Learning JavaScript Design Patterns".

http://addyosmani.com/resources/essentialjsdesignpatterns/book/

This book helped me out immensely when I was starting into writing more maintainable JavaScript and I still use it as a reference. Have a look at his different module pattern implementations, he explains them really well.

dll missing in JDBC

Alright guys, I found it out! I didn't really need to change the java.library.path but the "Native library location" of sqljdbc.jar

This is the best answer I could find: https://stackoverflow.com/a/958074/2000342

It works now, thanks for the support!

How can I format date by locale in Java?

SimpleDateFormat has a constructor which takes the locale, have you tried that?

http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Something like new SimpleDateFormat("your-pattern-here", Locale.getDefault());

ERROR: Error 1005: Can't create table (errno: 121)

Something I noticed was that I had "other_database" and "Other_Database" in my databases. That caused this problem as I actually had same reference in other database which caused this mysterious error!

Difference between "while" loop and "do while" loop

The difference between do while (exit check) and while (entry check) is that while entering in do while it will not check but in while it will first check

The example is as such:

Program 1:

int a=10;
do{
System.out.println(a);
}
while(a<10);

//here the a is not less than 10 then also it will execute once as it will execute do while exiting it checks that a is not less than 10 so it will exit the loop

Program 2:

int b=0;
while(b<10)
{
System.out.println(b);
}
//here nothing will be printed as the value of b is not less than 10 and it will not let enter the loop and will exit

output Program 1:

10

output Program 2:

[nothing is printed]

note:

output of the program 1 and program 2 will be same if we assign a=0 and b=0 and also put a++; and b++; in the respective body of the program.

A Generic error occurred in GDI+ in Bitmap.Save method

This error message is displayed if the path you pass to Bitmap.Save() is invalid (folder doesn't exist etc).

Convert object string to JSON

If the string is from a trusted source, you could use eval then JSON.stringify the result. Like this:

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
var json = JSON.stringify(eval("(" + str + ")"));

Note that when you eval an object literal, it has to be wrapped in parentheses, otherwise the braces are parsed as a block instead of an object.

I also agree with the comments under the question that it would be much better to just encode the object in valid JSON to begin with and avoid having to parse, encode, then presumably parse it again. HTML supports single-quoted attributes (just be sure to HTML-encode any single quotes inside strings).

Are loops really faster in reverse?

Wouldn't the compiler cache .length, and therefore it makes no difference if you are comparing 0 or .length? I guess this is very specific to the compiler or interpreter you are dealing with.

I would say if you are using a well optimised compiler or interpreter then you shouldn't worry about this, it is for the language developers to worry about.

How to get .app file of a xcode application

You can find the .app file here:

~/Library/Developer/Xcode/DerivedData/{app name}/Build/Products/Deployment/ 

credit for path goes to this answer

SIDENOTE: I had a lot of fun trying to get this into my iPad after that. It worked however. Using Snow Leopard + Xcode 4.2 + iPad with IOS 5.1.1 :) - I used the iPhone configuration utility to get the app into the ipad (you have to add the app, then click on the device, then click "install" behind the app you just added in the "application library" of iphone configuration utility) and had to create a Distribution Provisioning Profile and get the WWDR certificate and finally change the build settings in Xcode after all the certificates were in place. See here

But after much fun I am now looking at my first app on my iPad :) - btw, for getting apps into the app store you need to create a app store Distribution Provisioning Profile, while for ad hoc installs like these you create an ad hoc one. There is a bit more to it, but I think these are the most important and tricky steps. Enjoy.

PS. Just remembered that you also have to set the build type (top left of Xcode) to "iOS device", otherwise it will never sign your application. So the path name above only has limited value: yes, it will have the .app file in it, but no you can't upload it (at least not using the iPhone configuration utility) since it is not code signed - you will get an "Could not copy validate signature" error. So change it to "iOS device" and build (remember to select the right certificates in the build section of Xcode as per the url info above). In that same build section, you can also set the "Installation Build Products Location" to a different path, so that you can determine where the .app (the one that is properly code signed) ends up.

How to get the title of HTML page with JavaScript?

Can use getElementsByTagName

var x = document.getElementsByTagName("title")[0];

alert(x.innerHTML)

// or

alert(x.textContent)

// or

document.querySelector('title')

Edits as suggested by Paul

Push method in React Hooks (useState)?

Most recommended method is using wrapper function and spread operator together. For example, if you have initialized a state called name like this,

const [names, setNames] = useState([])

You can push to this array like this,

setNames(names => [...names, newName])

Hope that helps.

How to give ASP.NET access to a private key in a certificate in the certificate store?

  1. Create / Purchase certificate. Make sure it has a private key.
  2. Import the certificate into the "Local Computer" account. Best to use Certificates MMC. Make sure to check "Allow private key to be exported"
  3. Based upon which, IIS 7.5 Application Pool's identity use one of the following.

    • IIS 7.5 Website is running under ApplicationPoolIdentity. Open MMC => Add Certificates (Local computer) snap-in => Certificates (Local Computer) => Personal => Certificates => Right click the certificate of interest => All tasks => Manage private key => Add IIS AppPool\AppPoolName and grant it Full control. Replace "AppPoolName" with the name of your application pool (sometimes IIS_IUSRS)
    • IIS 7.5 Website is running under NETWORK SERVICE. Using Certificates MMC, added "NETWORK SERVICE" to Full Trust on certificate in "Local Computer\Personal".
    • IIS 7.5 Website is running under "MyIISUser" local computer user account. Using Certificates MMC, added "MyIISUser" (a new local computer user account) to Full Trust on certificate in "Local Computer\Personal".

Update based upon @Phil Hale comment:

Beware, if you're on a domain, your domain will be selected by default in the 'from location box'. Make sure to change that to "Local Computer". Change the location to "Local Computer" to view the app pool identities.

Good beginners tutorial to socket.io?

A 'fun' way to learn socket.io is to play BrowserQuest by mozilla and look at its source code :-)

http://browserquest.mozilla.org/

https://github.com/mozilla/BrowserQuest

How can I copy columns from one sheet to another with VBA in Excel?

Selecting is often unnecessary. Try this

Sub OneCell()
    Sheets("Sheet2").range("B1:B3").value = Sheets("Sheet1").range("A1:A3").value
End Sub

How do I pipe or redirect the output of curl -v?

add the -s (silent) option to remove the progress meter, then redirect stderr to stdout to get verbose output on the same fd as the response body

curl -vs google.com 2>&1 | less

Dependent DLL is not getting copied to the build output folder in Visual Studio

If you right Click the referenced assembly, you will see a property called Copy Local. If Copy Local is set to true, then the assembly should be included in the bin. However, there seams to be a problem with Visual studio, that sometimes it does not include the referenced dll in the bin folder... this is the workaround that worked for me:

enter image description here

HTTP Status 405 - Method Not Allowed Error for Rest API

I also had this problem and was able to solve it by enabling CORS support on the server. In my case it was an Azure server and it was easy: Enable CORS on Azure

So check for your server how it works and enable CORS. I didn't even need a browser plugin or proxy :)

Allow Access-Control-Allow-Origin header using HTML5 fetch API

Look at https://expressjs.com/en/resources/middleware/cors.html You have to use cors.

Install:

$ npm install cors
const cors = require('cors');
app.use(cors());

You have to put this code in your node server.

How to get label text value form a html page?

Use innerText/textContent:

  var el = document.getElementById('*spaM4');
  console.log(el.innerText || el.textContent);

Fiddle: http://jsfiddle.net/NeTgC/2/

How to call an element in a numpy array?

Also, you could try to use ndarray.item(), for example, arr.item((0, 0))(rowid+colid to index) or arr.item(0)(flatten index), its doc https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.item.html

Broadcast Receiver within a Service

The better pattern is to create a standalone BroadcastReceiver. This insures that your app can respond to the broadcast, whether or not the Service is running. In fact, using this pattern may remove the need for a constant-running Service altogether.

Register the BroadcastReceiver in your Manifest, and create a separate class/file for it.

Eg:

<receiver android:name=".FooReceiver" >
    <intent-filter >
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

When the receiver runs, you simply pass an Intent (Bundle) to the Service, and respond to it in onStartCommand().

Eg:

public class FooReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do your work quickly!
        // then call context.startService();
    }   
}