Programs & Examples On #.net micro framework

.NET Micro Framework is a CLR and set of libraries that runs on tiny low-cost microcontrollers with limited resources. It brings the genuine .NET developing experience (Visual Studio, managed high level coding & garbage collection, the VS debugger) to the embedded world.

How to subtract days from a plain Date?

split your date into parts, then return a new Date with the adjusted values

function DateAdd(date, type, amount){
    var y = date.getFullYear(),
        m = date.getMonth(),
        d = date.getDate();
    if(type === 'y'){
        y += amount;
    };
    if(type === 'm'){
        m += amount;
    };
    if(type === 'd'){
        d += amount;
    };
    return new Date(y, m, d);
}

Remember that the months are zero based, but the days are not. ie new Date(2009, 1, 1) == 01 February 2009, new Date(2009, 1, 0) == 31 January 2009;

Node.js Hostname/IP doesn't match certificate's altnames

I was getting this when streaming to ElasticSearch from a Lambda function in AWS. Smashed my head a against a wall trying to figure it out. In the end when setting the request.headers['Host'] I was adding in the https:// to the domain for ES - changing this to [es-domain-name].eu-west-1.es.amazonaws.com (without https://) worked straight away. Below is the code I used to get it working, hopefully save anyone else smashing their head against a wall...

import path from 'path';
import AWS from 'aws-sdk';

const { region, esEndpoint } = process.env;
const endpoint = new AWS.Endpoint(esEndpoint);
const httpClient = new AWS.HttpClient();
const credentials = new AWS.EnvironmentCredentials('AWS');

/**
 * Sends a request to Elasticsearch
 *
 * @param {string} httpMethod - The HTTP method, e.g. 'GET', 'PUT', 'DELETE', etc
 * @param {string} requestPath - The HTTP path (relative to the Elasticsearch domain), e.g. '.kibana'
 * @param {string} [payload] - An optional JavaScript object that will be serialized to the HTTP request body
 * @returns {Promise} Promise - object with the result of the HTTP response
 */
export function sendRequest ({ httpMethod, requestPath, payload }) {
    const request = new AWS.HttpRequest(endpoint, region);

    request.method = httpMethod;
    request.path = path.join(request.path, requestPath);
    request.body = payload;
    request.headers['Content-Type'] = 'application/json';
    request.headers['Host'] = '[es-domain-name].eu-west-1.es.amazonaws.com';
    request.headers['Content-Length'] = Buffer.byteLength(request.body);
    const signer = new AWS.Signers.V4(request, 'es');
    signer.addAuthorization(credentials, new Date());

    return new Promise((resolve, reject) => {
        httpClient.handleRequest(
            request,
            null,
            response => {
                const { statusCode, statusMessage, headers } = response;
                let body = '';
                response.on('data', chunk => {
                    body += chunk;
                });
                response.on('end', () => {
                    const data = {
                        statusCode,
                        statusMessage,
                        headers
                    };
                    if (body) {
                        data.body = JSON.parse(body);
                    }
                    resolve(data);
                });
            },
            err => {
                reject(err);
            }
        );
    });
}

How do I correctly upgrade angular 2 (npm) to the latest version?

npm uninstall --save-dev angular-cli

npm install --save-dev @angular/cli@latest

ng update @angular/cli

ng update @angular/core --force

ng update @angular/material or npm i @angular/cdk@6 @angular/material@6 --save

npm install typescript@'>=2.7.0 <2.8.0'

OS X Bash, 'watch' command

To prevent flickering when your main command takes perceivable time to complete, you can capture the output and only clear screen when it's done.

function watch {while :; do a=$($@); clear; echo "$(date)\n\n$a"; sleep 1;  done}

Then use it by:

watch istats

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

If you were using DropDownListFor like this:

@Html.DropDownListFor(m => m.SelectedItemId, Model.MySelectList)

where MySelectList in the model was a property of type SelectList, this error could be thrown if the property was null.

Avoid this by simple initializing it in constructor, like this:

public MyModel()
{
    MySelectList = new SelectList(new List<string>()); // empty list of anything...
}

I know it's not the OP's case, but this might help someone like me which had the same error due to this.

Convert .pfx to .cer

PFX files are PKCS#12 Personal Information Exchange Syntax Standard bundles. They can include arbitrary number of private keys with accompanying X.509 certificates and a certificate authority chain (set certificates).

If you want to extract client certificates, you can use OpenSSL's PKCS12 tool.

openssl pkcs12 -in input.pfx -out mycerts.crt -nokeys -clcerts

The command above will output certificate(s) in PEM format. The ".crt" file extension is handled by both macOS and Window.

You mention ".cer" extension in the question which is conventionally used for the DER encoded files. A binary encoding. Try the ".crt" file first and if it's not accepted, easy to convert from PEM to DER:

openssl x509 -inform pem -in mycerts.crt -outform der -out mycerts.cer

Loop through Map in Groovy?

When using the for loop, the value of s is a Map.Entry element, meaning that you can get the key from s.key and the value from s.value

Jquery function return value

The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:

function getMachine(color, qty) {
    var returnValue = null;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            returnValue = thisArray[3];
            return false; // this breaks out of the each
        }
    });
    return returnValue;
}

var retval = getMachine(color, qty);

What is the facade design pattern?

Facade Design Pattern comes under Structural Design Pattern. In short Facade means the exterior appearance. It means in Facade design pattern we hide something and show only what actually client requires. Read more at below blog: http://www.sharepointcafe.net/2017/03/facade-design-pattern-in-aspdotnet.html

Use the auto keyword in C++ STL

It's additional information, and isn't an answer.

In C++11 you can write:

for (auto& it : s) {
    cout << it << endl;
}

instead of

for (auto it = s.begin(); it != s.end(); it++) {
    cout << *it << endl;
}

It has the same meaning.

Update: See the @Alnitak's comment also.

Elegant way to create empty pandas DataFrame with NaN of type float

Simply pass the desired value as first argument, like 0, math.inf or, here, np.nan. The constructor then initializes and fills the value array to the size specified by arguments index and columns:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame(np.nan, index=[0, 1, 2, 3], columns=['A', 'B'])

>>> df.dtypes
A    float64
B    float64
dtype: object

>>> df.values
array([[nan, nan],
       [nan, nan],
       [nan, nan],
       [nan, nan]])

Using multiple .cpp files in c++ program?

You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.

other.h

void MyFunc();

main.cpp

#include "other.h"
int main() {
    MyFunc();
}

other.cpp

#include "other.h"
#include <iostream>
void MyFunc() {
    std::cout << "Ohai from another .cpp file!";
    std::cin.get();
}

Best way to select random rows PostgreSQL

You can examine and compare the execution plan of both by using

EXPLAIN select * from table where random() < 0.01;
EXPLAIN select * from table order by random() limit 1000;

A quick test on a large table1 shows, that the ORDER BY first sorts the complete table and then picks the first 1000 items. Sorting a large table not only reads that table but also involves reading and writing temporary files. The where random() < 0.1 only scans the complete table once.

For large tables this might not what you want as even one complete table scan might take to long.

A third proposal would be

select * from table where random() < 0.01 limit 1000;

This one stops the table scan as soon as 1000 rows have been found and therefore returns sooner. Of course this bogs down the randomness a bit, but perhaps this is good enough in your case.

Edit: Besides of this considerations, you might check out the already asked questions for this. Using the query [postgresql] random returns quite a few hits.

And a linked article of depez outlining several more approaches:


1 "large" as in "the complete table will not fit into the memory".

Sound alarm when code finishes

It can be done by code as follows:

import time
time.sleep(10)   #Set the time
for x in range(60):  
    time.sleep(1)
    print('\a')

How do I pass named parameters with Invoke-Command?

I needed something to call scripts with named parameters. We have a policy of not using ordinal positioning of parameters and requiring the parameter name.

My approach is similar to the ones above but gets the content of the script file that you want to call and sends a parameter block containing the parameters and values.

One of the advantages of this is that you can optionally choose which parameters to send to the script file allowing for non-mandatory parameters with defaults.

Assuming there is a script called "MyScript.ps1" in the temporary path that has the following parameter block:

[CmdletBinding(PositionalBinding = $False)]
param
(
    [Parameter(Mandatory = $True)] [String] $MyNamedParameter1,
    [Parameter(Mandatory = $True)] [String] $MyNamedParameter2,
    [Parameter(Mandatory = $False)] [String] $MyNamedParameter3 = "some default value"
)

This is how I would call this script from another script:

$params = @{
    MyNamedParameter1 = $SomeValue
    MyNamedParameter2 = $SomeOtherValue
}

If ($SomeCondition)
{
    $params['MyNamedParameter3'] = $YetAnotherValue
}

$pathToScript = Join-Path -Path $env:Temp -ChildPath MyScript.ps1

$sb = [scriptblock]::create(".{$(Get-Content -Path $pathToScript -Raw)} $(&{
        $args
} @params)")
Invoke-Command -ScriptBlock $sb

I have used this in lots of scenarios and it works really well. One thing that you occasionally need to do is put quotes around the parameter value assignment block. This is always the case when there are spaces in the value.

e.g. This param block is used to call a script that copies various modules into the standard location used by PowerShell C:\Program Files\WindowsPowerShell\Modules which contains a space character.

$params = @{
        SourcePath      = "$WorkingDirectory\Modules"
        DestinationPath = "'$(Join-Path -Path $([System.Environment]::GetFolderPath('ProgramFiles')) -ChildPath 'WindowsPowershell\Modules')'"
    }

Hope this helps!

How to check Oracle database for long running queries

v$session_longops

If you look for sofar != totalwork you'll see ones that haven't completed, but the entries aren't removed when the operation completes so you can see a lot of history there too.

How to read an external properties file in Maven

This answer to a similar question describes how to extend the properties plugin so it can use a remote descriptor for the properties file. The descriptor is basically a jar artifact containing a properties file (the properties file is included under src/main/resources).

The descriptor is added as a dependency to the extended properties plugin so it is on the plugin's classpath. The plugin will search the classpath for the properties file, read the file''s contents into a Properties instance, and apply those properties to the project's configuration so they can be used elsewhere.

How to determine the Schemas inside an Oracle Data Pump Export file

The running the impdp command to produce an sqlfile, you will need to run it as a user which has the DATAPUMP_IMP_FULL_DATABASE role.

Or... run it as a low privileged user and use the MASTER_ONLY=YES option, then inspect the master table. e.g.

select value_t 
from SYS_IMPORT_TABLE_01 
where name = 'CLIENT_COMMAND' 
and process_order = -59;

col object_name for a30
col processing_status head STATUS for a6
col processing_state head STATE for a5
select distinct
  object_schema,
  object_name,
  object_type,
  object_tablespace,
  process_order,
  duplicate,
  processing_status,
  processing_state
from sys_import_table_01
where process_order > 0
and object_name is not null
order by object_schema, object_name
/

http://download.oracle.com/otndocs/products/database/enterprise_edition/utilities/pdf/oow2011_dp_mastering.pdf

explicit casting from super class to subclass

As explained, it is not possible. If you want to use a method of the subclass, evaluate the possibility to add the method to the superclass (may be empty) and call from the subclasses getting the behaviour you want (subclass) thanks to polymorphism. So when you call d.method() the call will succeed withoug casting, but in case the object will be not a dog, there will not be a problem

javax.naming.NameNotFoundException

I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound

This means that nothing is bound to the jndi name greetJndi, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.

Is there any specific directory structure to deploy in JBoss?

The internal structure of the ejb-jar is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):

.
+-- greetBean.java
+-- greetHome.java
+-- greetRemote.java
+-- META-INF
    +-- ejb-jar.xml
    +-- jboss.xml

But as already mentioned, this tutorial is full of mistakes:

  • there is an extra character (<enterprise-beans>] <-- HERE) in the ejb-jar.xml (!)
  • a space is missing after PUBLIC in the ejb-jar.xml and jboss.xml (!!)
  • the jboss.xml is incorrect, it should contain a session element instead of entity (!!!)

Here is a "fixed" version of the ejb-jar.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <home>greetHome</home>
      <remote>greetRemote</remote>
      <ejb-class>greetBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>
</ejb-jar>

And of the jboss.xml:

<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <jndi-name>greetJndi</jndi-name>
    </session>
  </enterprise-beans>
</jboss>

After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:

21:48:06,512 INFO  [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/}
21:48:06,534 INFO  [EjbDeployer] installing bean: ejb/#greetBean,uid19981448
21:48:06,534 INFO  [EjbDeployer]   with dependencies:
21:48:06,534 INFO  [EjbDeployer]   and supplies:
21:48:06,534 INFO  [EjbDeployer]    jndi:greetJndi
21:48:06,624 INFO  [EjbModule] Deploying greetBean
21:48:06,661 WARN  [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/
21:48:06,805 INFO  [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'

That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.

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

Javascript: The prettiest way to compare one value against multiple values

Don't try to be too sneaky, especially when it needlessly affects performance. If you really have a whole heap of comparisons to do, just format it nicely.

if (foobar === foo ||
    foobar === bar ||
    foobar === baz ||
    foobar === pew) {
     //do something
}

How to do a JUnit assert on a message in a logger

Wow. I'm unsure why this was so hard. I found I was unable to use any of the code samples above because I was using log4j2 over slf4j. This is my solution:

public class SpecialLogServiceTest {

  @Mock
  private Appender appender;

  @Captor
  private ArgumentCaptor<LogEvent> captor;

  @InjectMocks
  private SpecialLogService specialLogService;

  private LoggerConfig loggerConfig;

  @Before
  public void setUp() {
    // prepare the appender so Log4j likes it
    when(appender.getName()).thenReturn("MockAppender");
    when(appender.isStarted()).thenReturn(true);
    when(appender.isStopped()).thenReturn(false);

    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    loggerConfig = config.getLoggerConfig("org.example.SpecialLogService");
    loggerConfig.addAppender(appender, AuditLogCRUDService.LEVEL_AUDIT, null);
  }

  @After
  public void tearDown() {
    loggerConfig.removeAppender("MockAppender");
  }

  @Test
  public void writeLog_shouldCreateCorrectLogMessage() throws Exception {
    SpecialLog specialLog = new SpecialLogBuilder().build();
    String expectedLog = "this is my log message";

    specialLogService.writeLog(specialLog);

    verify(appender).append(captor.capture());
    assertThat(captor.getAllValues().size(), is(1));
    assertThat(captor.getAllValues().get(0).getMessage().toString(), is(expectedLog));
  }
}

How to use PHP string in mySQL LIKE query?

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

Can I run multiple programs in a Docker container?

Docker provides a couple of examples on how to do it. The lightweight option is to:

Put all of your commands in a wrapper script, complete with testing and debugging information. Run the wrapper script as your CMD. This is a very naive example. First, the wrapper script:

#!/bin/bash

# Start the first process
./my_first_process -D
status=$?
if [ $status -ne 0 ]; then
  echo "Failed to start my_first_process: $status"
  exit $status
fi

# Start the second process
./my_second_process -D
status=$?
if [ $status -ne 0 ]; then
  echo "Failed to start my_second_process: $status"
  exit $status
fi

# Naive check runs checks once a minute to see if either of the processes exited.
# This illustrates part of the heavy lifting you need to do if you want to run
# more than one service in a container. The container will exit with an error
# if it detects that either of the processes has exited.
# Otherwise it will loop forever, waking up every 60 seconds

while /bin/true; do
  ps aux |grep my_first_process |grep -q -v grep
  PROCESS_1_STATUS=$?
  ps aux |grep my_second_process |grep -q -v grep
  PROCESS_2_STATUS=$?
  # If the greps above find anything, they will exit with 0 status
  # If they are not both 0, then something is wrong
  if [ $PROCESS_1_STATUS -ne 0 -o $PROCESS_2_STATUS -ne 0 ]; then
    echo "One of the processes has already exited."
    exit -1
  fi
  sleep 60
done

Next, the Dockerfile:

FROM ubuntu:latest
COPY my_first_process my_first_process
COPY my_second_process my_second_process
COPY my_wrapper_script.sh my_wrapper_script.sh
CMD ./my_wrapper_script.sh

What does "all" stand for in a makefile?

Not sure it stands for anything special. It's just a convention that you supply an 'all' rule, and generally it's used to list all the sub-targets needed to build the entire project, hence the name 'all'. The only thing special about it is that often times people will put it in as the first target in the makefile, which means that just typing 'make' alone will do the same thing as 'make all'.

Reporting Services Remove Time from DateTime in Expression

    FormatDateTime(Parameter.StartDate.Value)

error: Your local changes to the following files would be overwritten by checkout

You can commit in the current branch, checkout to another branch, and finally cherry-pick that commit (in lieu of merge).

Print number of keys in Redis

WARNING: Do not run this on a production machine.

On a Linux box:

redis-cli KEYS "*" | wc -l

Note: As mentioned in comments below, this is an O(N) operation, so on a large DB with many keys you should not use this. For smaller deployments, it should be fine.

How to modify STYLE attribute of element with known ID using JQuery

Not sure I completely understand the question but:

$(":button.brown").click(function() {
  $(":button.brown.selected").removeClass("selected");
  $(this).addClass("selected");
});

seems to be along the lines of what you want.

I would certainly recommend using classes instead of directly setting CSS, which is problematic for several reasons (eg removing styles is non-trivial, removing classes is easy) but if you do want to go that way:

$("...").css("background", "brown");

But when you want to reverse that change, what do you set it to?

How to delete a folder and all contents using a bat file in windows?

  1. del /s /q c:\where ever the file is\*
  2. rmdir /s /q c:\where ever the file is\
  3. mkdir c:\where ever the file is\

How do I use 'git reset --hard HEAD' to revert to a previous commit?

WARNING: git clean -f will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.


Try this and see git clean -f.

git reset --hard will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under Git tracking.

Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)

  • git clean -df
  • git clean -xdf CAUTION! This will also delete ignored files

Java path..Error of jvm.cfg

I had this issue when installing 201, somehow it didn't uninstall my 191 properly. I had to go to the Program Files/Java folder, rename the old 201 directory, then install a fresh copy of 201. When doing so, it prompted me to uninstall 191, which I did. Now it's working fine.

How to extract .war files in java? ZIP vs JAR

If you using Linux or Ubuntu than you can directly extract data from .war file.

A war file is just a jar file, to extract it, just issue following command using the jar program:

jar -xvf yourWARfileName.war

jQuery autocomplete with callback ajax json

I used the construction of $.each (data [i], function (key, value) But you must pre-match the names of the selection fields with the names of the form elements. Then, in the loop after "success", autocomplete elements from the "data" array. Did this: autocomplete form with ajax success

error: Unable to find vcvarsall.bat

Below steps fixed this issue for me, I was trying to create setup with cython extension.

  1. Install Microsoft Visual C++ Compiler for Python 2.7
  2. The default install location would be @ C:\Users\PC-user\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python This might actually fix the issue, test once before proceeding.
  3. If it fails, Check where in VC++ for python vcvarsall.bat file is located
  4. Open the msvc9compiler.py file of distutils package in notepad.
  5. In my box this was @ C:\Anaconda2\Lib\distutils\msvc9compiler.py find_vcvarsall function in this file, determine the version of VC by printing out version argument. For Python 2.7 it's likely to be 9.0
  6. Now create an environment variable VS90COMNTOOLS, Pointing to C:\Users\PC-user\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\bin
  7. For some reason distutils expects the vcvarsall.bat file to be within VC dir, but VC++ for python tools has it in the root of 9.0 To fix this, remove "VC" from the path.join (roughly around line 247)

    #productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC") productdir = os.path.join(toolsdir, os.pardir, os.pardir)

The above steps fixed the issue for me.

Find nginx version?

Make sure that you have permissions to run the following commands.

If you check the man page of nginx from a terminal

man nginx

you can find this:

-V             Print the nginx version, compiler version, and configure script parameters.

-v             Print the nginx version.

Then type in terminal

nginx -v
nginx version: nginx/1.14.0

nginx -V
nginx version: nginx/1.14.0
built with OpenSSL 1.1.0g  2 Nov 2017
TLS SNI support enabled

If nginx is not installed in your system man nginx command can not find man page, so make sure you have installed nginx.

You can also find the version using this command:

Use one of the command to find the path of nginx

ps aux | grep nginx
ps -ef | grep nginx

root       883  0.0  0.3  44524  3388 ?        Ss   Dec07   0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on

Then run from terminal:

/usr/sbin/nginx -v

nginx version: nginx/1.14.0

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

I found the InvokeRequired not reliable, so I simply use

if (!this.IsHandleCreated)
{
    this.CreateHandle();
}

How does += (plus equal) work?

x += 1 is just shorthand for x = x + 1 It can also be used for strings:

var string = "foo"
string += "bar"

Change Title of Javascript Alert

It's not possible, sorry. If really needed, you could use a jQuery plugin to have a custom alert.

Faster way to zero memory than with memset?

x86 is rather broad range of devices.

For totally generic x86 target, an assembly block with "rep movsd" could blast out zeros to memory 32-bits at time. Try to make sure the bulk of this work is DWORD aligned.

For chips with mmx, an assembly loop with movq could hit 64bits at a time.

You might be able to get a C/C++ compiler to use a 64-bit write with a pointer to a long long or _m64. Target must be 8 byte aligned for the best performance.

for chips with sse, movaps is fast, but only if the address is 16 byte aligned, so use a movsb until aligned, and then complete your clear with a loop of movaps

Win32 has "ZeroMemory()", but I forget if thats a macro to memset, or an actual 'good' implementation.

Match all elements having class name starting with a specific string

You can easily add multiple classes to divs... So:

<div class="myclass myclass-one"></div>
<div class="myclass myclass-two"></div>
<div class="myclass myclass-three"></div>

Then in the CSS call to the share class to apply the same styles:

.myclass {...}

And you can still use your other classes like this:

.myclass-three {...}

Or if you want to be more specific in the CSS like this:

.myclass.myclass-three {...}

How to enable PHP's openssl extension to install Composer?

If you are using xampp .Go back to where you choose which command-line php you want to use at the beginning of your installation and select the path where your xampp folder is included.After that if your installer says youve got duplicate 'extension=php_openssl.dll' comment one ssl file in your php ini with a ';'and your installation should run smoothly.

Arithmetic overflow error converting numeric to data type numeric

If you want to reduce the size to decimal(7,2) from decimal(9,2) you will have to account for the existing data with values greater to fit into decimal(7,2). Either you will have to delete those numbers are truncate it down to fit into your new size. If there was no data for the field you are trying to update it will do it automatically without issues

Define variable to use with IN operator (T-SQL)

There are two ways to tackle dynamic csv lists for TSQL queries:

1) Using an inner select

SELECT * FROM myTable WHERE myColumn in (SELECT id FROM myIdTable WHERE id > 10)

2) Using dynamically concatenated TSQL

DECLARE @sql varchar(max)  
declare @list varchar(256)  
select @list = '1,2,3'  
SELECT @sql = 'SELECT * FROM myTable WHERE myColumn in (' + @list + ')'

exec sp_executeSQL @sql

3) A possible third option is table variables. If you have SQl Server 2005 you can use a table variable. If your on Sql Server 2008 you can even pass whole table variables in as a parameter to stored procedures and use it in a join or as a subselect in the IN clause.

DECLARE @list TABLE (Id INT)

INSERT INTO @list(Id)
SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4


SELECT
    * 
FROM 
    myTable
    JOIN @list l ON myTable.myColumn = l.Id

SELECT
    * 
FROM 
    myTable
WHERE
    myColumn IN (SELECT Id FROM @list)

Best implementation for hashCode method for a collection

about8.blogspot.com, you said

if equals() returns true for two objects, then hashCode() should return the same value. If equals() returns false, then hashCode() should return different values

I cannot agree with you. If two objects have the same hashcode it doesn't have to mean that they are equal.

If A equals B then A.hashcode must be equal to B.hascode

but

if A.hashcode equals B.hascode it does not mean that A must equals B

Is there a way to get a collection of all the Models in your Rails app?

This seems to work for me:

  Dir.glob(RAILS_ROOT + '/app/models/*.rb').each { |file| require file }
  @models = Object.subclasses_of(ActiveRecord::Base)

Rails only loads models when they are used, so the Dir.glob line "requires" all the files in the models directory.

Once you have the models in an array, you can do what you were thinking (e.g. in view code):

<% @models.each do |v| %>
  <li><%= h v.to_s %></li>
<% end %>

Duplicate Entire MySQL Database

Here's a windows bat file I wrote which combines Vincent and Pauls suggestions. It prompts the user for source and destination names.

Just modify the variables at the top to set the proper paths to your executables / database ports.

:: Creates a copy of a database with a different name.
:: User is prompted for Src and destination name.
:: Fair Warning: passwords are passed in on the cmd line, modify the script with -p instead if security is an issue.
:: Uncomment the rem'd out lines if you want script to prompt for database username, password, etc.

:: See also: http://stackoverflow.com/questions/1887964/duplicate-entire-mysql-database

@set MYSQL_HOME="C:\sugarcrm\mysql\bin"
@set mysqldump_exec=%MYSQL_HOME%\mysqldump
@set mysql_exec=%MYSQL_HOME%\mysql
@set SRC_PORT=3306
@set DEST_PORT=3306
@set USERNAME=TODO_USERNAME
@set PASSWORD=TODO_PASSWORD

:: COMMENT any of the 4 lines below if you don't want to be prompted for these each time and use defaults above.
@SET /p USERNAME=Enter database username: 
@SET /p PASSWORD=Enter database password: 
@SET /p SRC_PORT=Enter SRC database port (usually 3306): 
@SET /p DEST_PORT=Enter DEST database port: 

%MYSQL_HOME%\mysql --user=%USERNAME% --password=%PASSWORD% --port=%DEST_PORT% --execute="show databases;"
@IF NOT "%ERRORLEVEL%" == "0" GOTO ExitScript

@SET /p SRC_DB=What is the name of the SRC Database:  
@SET /p DEST_DB=What is the name for the destination database (that will be created):  

%mysql_exec% --user=%USERNAME% --password=%PASSWORD% --port=%DEST_PORT% --execute="create database %DEST_DB%;"
%mysqldump_exec% --add-drop-table --user=%USERNAME% --password=%PASSWORD% --port=%SRC_PORT% %SRC_DB% | %mysql_exec% --user=%USERNAME% --password=%PASSWORD% --port=%DEST_PORT% %DEST_DB%
@echo SUCCESSFUL!!!
@GOTO ExitSuccess

:ExitScript
@echo "Failed to copy database"
:ExitSuccess

Sample output:

C:\sugarcrm_backups\SCRIPTS>copy_db.bat
Enter database username: root
Enter database password: MyPassword
Enter SRC database port (usually 3306): 3308
Enter DEST database port: 3308

C:\sugarcrm_backups\SCRIPTS>"C:\sugarcrm\mysql\bin"\mysql --user=root --password=MyPassword --port=3308 --execute="show databases;"
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sugarcrm_550_pro   |
| sugarcrm_550_ce    |
| sugarcrm_640_pro   |
| sugarcrm_640_ce    |
+--------------------+
What is the name of the SRC Database:  sugarcrm
What is the name for the destination database (that will be created):  sugarcrm_640_ce

C:\sugarcrm_backups\SCRIPTS>"C:\sugarcrm\mysql\bin"\mysql --user=root --password=MyPassword --port=3308 --execute="create database sugarcrm_640_ce;"

C:\sugarcrm_backups\SCRIPTS>"C:\sugarcrm\mysql\bin"\mysqldump --add-drop-table --user=root --password=MyPassword --port=3308 sugarcrm   | "C:\sugarcrm\mysql\bin"\mysql --user=root --password=MyPassword --port=3308 sugarcrm_640_ce
SUCCESSFUL!!!

How do you develop Java Servlets using Eclipse?

Alternatively you can use Jetty which is (now) part of the Eclipe Platform (the Help system is running Jetty). Besides Jetty is used by Android, Windows Mobile..

To get started check the Eclipse Wiki or if you prefer a Video And check out this related Post!

How can I reorder a list?

>>> import random
>>> x = [1,2,3,4,5]
>>> random.shuffle(x)
>>> x
[5, 2, 4, 3, 1]

What command shows all of the topics and offsets of partitions in Kafka?

We're using Kafka 2.11 and make use of this tool - kafka-consumer-groups.

$ rpm -qf /bin/kafka-consumer-groups
confluent-kafka-2.11-1.1.1-1.noarch

For example:

$ kafka-consumer-groups --describe --group logstash | grep -E "TOPIC|filebeat"
Note: This will not show information about old Zookeeper-based consumers.
TOPIC            PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                     HOST             CLIENT-ID
beats_filebeat   0          20003914484     20003914888     404             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   1          19992522286     19992522709     423             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   2          19990597254     19990597637     383             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   7          19991718707     19991719268     561             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   8          20015611981     20015612509     528             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   5          19990536340     19990541331     4991            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   6          19990728038     19990733086     5048            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   3          19994613945     19994616297     2352            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0
beats_filebeat   4          19990681602     19990684038     2436            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0

Random Tip

NOTE: We use an alias that overloads kafka-consumer-groups like so in our /etc/profile.d/kafka.sh:

alias kafka-consumer-groups="KAFKA_JVM_PERFORMANCE_OPTS=\"-Djava.security.auth.login.config=$HOME/.kafka_client_jaas.conf\"  kafka-consumer-groups --bootstrap-server ${KAFKA_HOSTS} --command-config /etc/kafka/security-enabler.properties"

Print range of numbers on same line

for i in range(1,11):
    print(i)

i know this is an old question but i think this works now

How to programmatically get iOS status bar height

Try this:

CGFloat statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;

Updating state on props change in React Form

I think use ref is safe for me, dont need care about some method above.

class Company extends XComponent {
    constructor(props) {
        super(props);
        this.data = {};
    }
    fetchData(data) {
        this.resetState(data);
    }
    render() {
        return (
            <Input ref={c => this.data['name'] = c} type="text" className="form-control" />
        );
    }
}
class XComponent extends Component {
    resetState(obj) {
        for (var property in obj) {
            if (obj.hasOwnProperty(property) && typeof this.data[property] !== 'undefined') {
                if ( obj[property] !== this.data[property].state.value )
                    this.data[property].setState({value: obj[property]});
                else continue;
            }
            continue;
        }
    }
}

'Operation is not valid due to the current state of the object' error during postback

If your stack trace looks like following then you are sending a huge load of json objects to server

Operation is not valid due to the current state of the object. 
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
    at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
    at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
    at Failing.Page_Load(Object sender, EventArgs e) 
    at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
    at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
    at System.Web.UI.Control.OnLoad(EventArgs e)
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

For resolution, please update your web config with following key. If you are not able to get the stack trace then please use fiddler. If it still does not help then please try increasing the number to 10000 or something

<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>

For more details, please read this Microsoft kb article

Jquery select this + class

Use find()

$(this).find(".subclass").css("visibility","visible");

Git push error: Unable to unlink old (Permission denied)

Some files are write-protected that even git cannot over write it. Change the folder permission to allow writing e.g. sudo chmod 775 foldername

And then execute

git pull 

again

Check to see if cURL is installed locally?

cURL is disabled for most hosting control panels for security reasons, but it's required for a lot of php applications. It's not unusual for a client to request it. Since the risk of enabling cURL is minimal, you are probably better off enabling it than losing a customer. It's simply a utility that helps php scripts fetch things using standard Internet URLs.

To enable cURL, you will remove curl_exec from the "disabled list" in the control panel php advanced settings. You will also find a disabled list in the various php.ini files; look in /etc/php.ini and other paths that might exist for your control panel. You will need to restart Apache to make the change take effect.

service httpd restart

To confirm whether cURL is enabled or disabled, create a file somewhere in your system and paste the following contents.

<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>

Save the file as testcurl.php and then run it as a php script.

php testcurl.php

If cURL is disabled you will see this error.

Fatal error: Call to undefined function curl_version() in testcurl.php on line 2

If cURL is enabled you will see a long list of attributes, like this.

array(9) {
["version_number"]=>
int(461570)
["age"]=>
int(1)
["features"]=>
int(540)
["ssl_version_number"]=>
int(9465919)
["version"]=>
string(6) "7.11.2"
["host"]=>
string(13) "i386-pc-win32"
["ssl_version"]=>
string(15) " OpenSSL/0.9.7c"
["libz_version"]=>
string(5) "1.1.4"
["protocols"]=>
array(9) {
[0]=>
string(3) "ftp"
[1]=>
string(6) "gopher"
[2]=>
string(6) "telnet"
[3]=>
string(4) "dict"
[4]=>
string(4) "ldap"
[5]=>
string(4) "http"
[6]=>
string(4) "file"
[7]=>
string(5) "https"
[8]=>
string(4) "ftps"
}
}

Bash: Echoing a echo command with a variable in bash

The immediate problem is you have is with quoting: by using double quotes ("..."), your variable references are instantly expanded, which is probably not what you want.

Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.

(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $ of references you do not want expanded with \; e.g., \$var).

However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<, and the closing one on a line by itself - starting at the very first column; search for Here Documents in man bash or at http://www.gnu.org/software/bash/manual/html_node/Redirections.html.

If you quote the here-doc delimiter (EOF in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \:

echo "creating new script file."

cat <<'EOF'  > "$servfile"
#!/bin/bash
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}` 
if [ $servicetest > /dev/null ]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi
EOF

As @BruceK notes, you can prefix your here-doc delimiter with - (applied to this example: <<-"EOF") in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern. Note, however, that this only works with actual tab characters, not leading spaces.

Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):

cat <<-'EOF' > "$servfile"
    #!/bin/bash
    read -p "Please enter a service name: " ser
    if [[ -n $(getsebool -a | grep "${ser}") ]]; then 
      echo "We are now going to work with ${ser}."
    else
      exit 1
    fi
EOF

Finally, note that in bash even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.

Thus, note how in the following #!/bin/bash has to follow the opening ' immediately in order to become the first line of output:

echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi' > "$servfile"

Afterthoughts regarding the contents of your script:

  • The syntax $(...) is preferred over `...` for command substitution nowadays.
  • You should double-quote ${ser} in the grep command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).
  • Use [[ -n $servicetest ]] to test whether $servicetest is empty (or perform the command substitution directly inside the conditional) - [[ ... ]] - the preferred form in bash - protects you from breaking the conditional if the $servicetest happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ] or [[ ... ]], as no stdout output is passed through; thus, the > /dev/null is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).

Clicking at coordinates without identifying element

I used AutoIt to do it.

using AutoIt;
AutoItX.MouseClick("LEFT",150,150,1,0);//1: click once, 0: Move instantaneous
  1. Pro:
    • simple
    • regardless of mouse movement
  2. Con:
    • since coordinate is screen-based, there should be some caution if the app scales.
    • the drive won't know when the app finish with clicking consequence actions. There should be a waiting period.

int to unsigned int conversion

You can convert an int to an unsigned int. The conversion is valid and well-defined.

Since the value is negative, UINT_MAX + 1 is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)

In this case, since int on your platform has a width of 32 bits, 62 is subtracted from 232, yielding 4,294,967,234.

Import Python Script Into Another?

Hope this work

def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

def sort_words(words):
    """Sorts the words."""
    return sorted(words)

def print_first_word(words):
    """Prints the first word after popping it off."""
    word = words.pop(0)
    print (word)

def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1)
    print(word)

def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)
    return sort_words(words)

def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)


print ("Let's practice everything.")
print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explantion
\n\t\twhere there is none.
"""


print ("--------------")
print (poem)
print ("--------------")

five = 10 - 2 + 3 - 5
print ("This should be five: %s" % five)

def secret_formula(start_point):
    jelly_beans = start_point * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates


start_point = 10000
jelly_beans, jars, crates = secret_formula(start_point)

print ("With a starting point of: %d" % start_point)
print ("We'd have %d jeans, %d jars, and %d crates." % (jelly_beans, jars, crates))

start_point = start_point / 10

print ("We can also do that this way:")
print ("We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point))


sentence = "All god\tthings come to those who weight."

words =  break_words(sentence)
sorted_words =  sort_words(words)

print_first_word(words)
print_last_word(words)
print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words =  sort_sentence(sentence)
print (sorted_words)

print_first_and_last(sentence)
print_first_and_last_sorted(sentence)

How to compare two vectors for equality element by element in C++?

If they really absolutely have to remain unsorted (which they really don't.. and if you're dealing with hundreds of thousands of elements then I have to ask why you would be comparing vectors like this), you can hack together a compare method which works with unsorted arrays.

The only way I though of to do that was to create a temporary vector3 and pretend to do a set_intersection by adding all elements of vector1 to it, then doing a search for each individual element of vector2 in vector3 and removing it if found. I know that sounds terrible, but that's why I'm not writing any C++ standard libraries anytime soon.

Really, though, just sort them first.

How to install Anaconda on RaspBerry Pi 3 Model B

Installing Miniconda on Raspberry Pi and adding Python 3.5 / 3.6

Skip the first section if you have already installed Miniconda successfully.

Installation of Miniconda on Raspberry Pi

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
sudo md5sum Miniconda3-latest-Linux-armv7l.sh
sudo /bin/bash Miniconda3-latest-Linux-armv7l.sh

Accept the license agreement with yes

When asked, change the install location: /home/pi/miniconda3

Do you wish the installer to prepend the Miniconda3 install location to PATH in your /root/.bashrc ? yes

Now add the install path to the PATH variable:

sudo nano /home/pi/.bashrc

Go to the end of the file .bashrc and add the following line:

export PATH="/home/pi/miniconda3/bin:$PATH"

Save the file and exit.

To test if the installation was successful, open a new terminal and enter

conda

If you see a list with commands you are ready to go.

But how can you use Python versions greater than 3.4 ?


Adding Python 3.5 / 3.6 to Miniconda on Raspberry Pi

After the installation of Miniconda I could not yet install Python versions higher than Python 3.4, but i needed Python 3.5. Here is the solution which worked for me on my Raspberry Pi 4:

First i added the Berryconda package manager by jjhelmus (kind of an up-to-date version of the armv7l version of Miniconda):

conda config --add channels rpi

Only now I was able to install Python 3.5 or 3.6 without the need for compiling it myself:

conda install python=3.5
conda install python=3.6

Afterwards I was able to create environments with the added Python version, e.g. with Python 3.5:

conda create --name py35 python=3.5

The new environment "py35" can now be activated:

source activate py35

Using Python 3.7 on Raspberry Pi

Currently Jonathan Helmus, who is the developer of berryconda, is working on adding Python 3.7 support, if you want to see if there is an update or if you want to support him, have a look at this pull request. (update 20200623) berryconda is now inactive, This project is no longer active, no recipe will be updated and no packages will be added to the rpi channel. If you need to run Python 3.7 on your Pi right now, you can do so without Miniconda. Check if you are running the latest version of Raspbian OS called Buster. Buster ships with Python 3.7 preinstalled (source), so simply run your program with the following command:

Python3.7 app-that-needs-python37.py

I hope this solution will work for you too!

Can I set subject/content of email using mailto:?

The mailto: URL scheme is defined in RFC 2368. Also, the convention for encoding information into URLs and URIs is defined in RFC 1738 and then RFC 3986. These prescribe how to include the body and subject headers into a URL (URI):

mailto:[email protected]?subject=current-issue&body=send%20current-issue

Specifically, you must percent-encode the email address, subject, and body and put them into the format above. Percent-encoded text is legal for use in HTML, however this URL must be entity encoded for use in an href attribute, according to the HTML4 standard:

<a href="mailto:[email protected]?subject=current-issue&amp;body=send%20current-issue">Send email</a>

And most generally, here is a simple PHP script that encodes per the above.

<?php
$encodedTo = rawurlencode($message->to);
$encodedSubject = rawurlencode($message->subject);
$encodedBody = rawurlencode($message->body);
$uri = "mailto:$encodedTo?subject=$encodedSubject&body=$encodedBody";
$encodedUri = htmlspecialchars($uri);
echo "<a href=\"$encodedUri\">Send email</a>";
?>

Why does overflow:hidden not work in a <td>?

Well here is a solution for you but I don't really understand why it works:

<html><body>
  <div style="width: 200px; border: 1px solid red;">Test</div>
  <div style="width: 200px; border: 1px solid blue; overflow: hidden; height: 1.5em;">My hovercraft is full of eels.  These pretzels are making me thirsty.</div>
  <div style="width: 200px; border: 1px solid yellow; overflow: hidden; height: 1.5em;">
  This_is_a_terrible_example_of_thinking_outside_the_box.
  </div>
  <table style="border: 2px solid black; border-collapse: collapse; width: 200px;"><tr>
   <td style="width:200px; border: 1px solid green; overflow: hidden; height: 1.5em;"><div style="width: 200px; border: 1px solid yellow; overflow: hidden;">
    This_is_a_terrible_example_of_thinking_outside_the_box.
   </div></td>
  </tr></table>
</body></html>

Namely, wrapping the cell contents in a div.

Windows Batch Files: if else

if not %1 == "" (

must be

if not "%1" == "" (

If an argument isn't given, it's completely empty, not even "" (which represents an empty string in most programming languages). So we use the surrounding quotes to detect an empty argument.

Can't install APK from browser downloads

It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.

A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?

Settings > Applications > Unknown sources...

Edit

Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive

Laravel eloquent update record without loading from database

Use property exists:

$post = new Post();
$post->exists = true;
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();

Here is the API documentation: http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

Using scanner.nextLine()

I think your problem is that

int selection = scanner.nextInt();

reads just the number, not the end of line or anything after the number. When you declare

String sentence = scanner.nextLine();

This reads the remainder of the line with the number on it (with nothing after the number I suspect)

Try placing a scanner.nextLine(); after each nextInt() if you intend to ignore the rest of the line.

How can I determine if a variable is 'undefined' or 'null'?

The shortest and easiest:

if(!EmpName ){
 // DO SOMETHING
}

this will evaluate true if EmpName is:

  • null
  • undefined
  • NaN
  • empty
  • string ("")
  • 0
  • false

comma separated string of selected values in mysql

Just so for people doing it in SQL server: use STRING_AGG to get similar results.

Set Radiobuttonlist Selected from Codebehind

We can change the item by value, here is the trick:

radio1.ClearSelection();
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2

jQuery .live() vs .on() method for adding a click event after loading dynamic html

.on() is for jQuery version 1.7 and above. If you have an older version, use this:

$("#SomeId").live("click",function(){
    //do stuff;
});

How can I tell what edition of SQL Server runs on the machine?

You can get just the edition name by using the following steps.

  • Open "SQL Server Configuration Manager"
  • From the List of SQL Server Services, Right Click on "SQL Server (Instance_name)" and Select Properties.
  • Select "Advanced" Tab from the Properties window.
  • Verify Edition Name from the "Stock Keeping Unit Name"
  • Verify Edition Id from the "Stock Keeping Unit Id"
  • Verify Service Pack from the "Service Pack Level"
  • Verify Version from the "Version"

screen shot

nodemon not working: -bash: nodemon: command not found

npx nodemon filename.js

This will work on macOS BigSur

What is EOF in the C programming language?

EOF means end of file. It's a sign that the end of a file is reached, and that there will be no data anymore.

Edit:

I stand corrected. In this case it's not an end of file. As mentioned, it is passed when CTRL+d (linux) or CTRL+z (windows) is passed.

Center div on the middle of screen

2018: CSS3

div{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%);
}

This is even shorter. For more information see this: CSS: Centering Things

Reading NFC Tags with iPhone 6 / iOS 8

The iPhone6/6s/6+ are NOT designed to read passive NFC tags (aka Discovery Mode). There's a lot of misinformation on this topic, so I thought to provide some tangible info for developers to consider. The lack of NFC tag read support is not because of software but because of hardware. To understand why, you need to understand how NFC works. NFC works by way of Load Modulation. That means that the interrogator (PCD) emits a carrier magnetic field that energizes the passive target (PICC). With the potential generated by this carrier field, the target then is able to demodulate data coming from the interrogator and respond by modulating data over top of this very same field. The key here is that the target never creates a field of its own.

If you look at the iPhone6 teardown and parts list you will see the presence of a very small NFC loop antenna as well as the use of the AS3923 booster IC. This design was intended for custom microSD or SIM cards to enable mobile phones of old to do payments. This is the type of application where the mobile phone presents a Card Emulated credential to a high power contactless POS terminal. The POS terminal acts as the reader, energizing the iPhone6 with help from the AS3923 chip. The AS3923 block diagram clearly shows how the RX and TX modulation is boosted from a signal presented by a reader device. In other words the iPhone6 is not meant to provide a field, only to react to one. That's why it's design is only meant for NFC Card Emulation and perhaps Peer-2-Peer, but definitely not tag Discovery.

AS3923 booster IC

There are some alternatives to achieving tag Discovery with an iPhone6 using HW accessories. I talk about these integrations and how developers can architect solutions in this blog post. Our low power reader designs open interesting opportunities for mobile engagement that few developers are thinking about.

Disclosure: I'm the founder of Flomio, Inc., a TechStars company that delivers proximity ID hardware, software, and services for applications ranging from access control to payments.

Update: This rumor, if true, would open up the possibility for the iPhone to practically support NFC tag Discovery mode. An all glass design would not interfere with the NFC antenna as does the metal back of the current iPhone. We've attempted this design approach --albeit with cheaper materials-- on some of our custom reader designs with success so looking forward to this improvement.

Update: iOS11 has announced support for "NFC reader mode" for iPhone7/7+. Details here. API only supports reading NDEF messages (no ISO7816 APDUs) while an app is in the foreground (no background detection). Due out in the Fall, 2017... check the screenshot from WWDC keynote:

enter image description here

How to give credentials in a batch script that copies files to a network location?

You can also map the share to a local drive as follows:

net use X: "\\servername\share" /user:morgan password

Detect Windows version in .net

This is a relatively old question but I've recently had to solve this problem and didn't see my solution posted anywhere.

The easiest (and simplest way in my opinion) is to just use a pinvoke call to RtlGetVersion

[DllImport("ntdll.dll", SetLastError = true)]
internal static extern uint RtlGetVersion(out Structures.OsVersionInfo versionInformation); // return type should be the NtStatus enum

[StructLayout(LayoutKind.Sequential)]
internal struct OsVersionInfo
{
    private readonly uint OsVersionInfoSize;

    internal readonly uint MajorVersion;
    internal readonly uint MinorVersion;

    private readonly uint BuildNumber;

    private readonly uint PlatformId;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
    private readonly string CSDVersion;
}

Where Major and Minor version numbers in this struct correspond to the values in the table of the accepted answer.

This returns the correct Windows version number unlike the deprecated GetVersion & GetVersionEx functions from kernel32

Get current language in CultureInfo

I think something like this would give you the current CultureInfo:

CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;

Is that what you're looking for?

Binding an Image in WPF MVVM

If you have a process that already generates and returns an Image type, you can alter the bind and not have to modify any additional image creation code.

Refer to the ".Source" of the image in the binding statement.

XAML

<Image Name="imgOpenClose" Source="{Binding ImageOpenClose.Source}"/>

View Model Field

private Image _imageOpenClose;
public Image ImageOpenClose
{
    get
    {
        return _imageOpenClose;
    }
    set
    {
        _imageOpenClose = value;
        OnPropertyChanged();
    }
}

key_load_public: invalid format

It seems that ssh cannot read your public key. But that doesn't matter.

You upload your public key to github, but you authenticate using your private key. See e.g. the FILES section in ssh(1).

Bootstrap control with multiple "data-toggle"

HTML (ejs dianmic web page): this is a table list of all users and from nodejs generate the table. NodeJS provide dinamic "<%= user.id %>". simply change for any value like "54"

<span type="button" data-href='/admin/user/del/<%= user.id %>' class="item" 
 data-toggle="modal" data-target="#confirm_delete">
    <div data-toggle="tooltip" data-placement="top" title="Delete" data- 
     toggle="modal">
       <i class="zmdi zmdi-delete"></i> 
    </div>
</span>
<div class="modal fade" id="confirm_delete" tabindex="-1" role="dialog" aria-labelledby="staticModalLabel" aria-hidden="true"
         data-backdrop="static">
  <div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="staticModalLabel">Static Modal</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button>
      </div>
      <div class="modal-body">
        <p> This is a static modal, backdrop click will not close it. </p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
          <form method="POST" class="btn-ok">
            <input  type="submit" class="btn btn-danger" value="Confirm"></input>
        </form>
      </div>
    </div>
  </div>
</div>
<!-- end modal static --> 

JS:

    $(document).ready(function(){
        $('#confirm_delete').on('show.bs.modal', function(e) {
            $(this).find('.btn-ok').attr('action', $(e.relatedTarget).data('href'));
        });
    });

jQuery Datepicker onchange event issue

On jQueryUi 1.9 I've managed to get it to work through an additional data value and a combination of beforeShow and onSelect functions:

$( ".datepicker" ).datepicker({
    beforeShow: function( el ){
        // set the current value before showing the widget
        $(this).data('previous', $(el).val() );
    },

    onSelect: function( newText ){
        // compare the new value to the previous one
        if( $(this).data('previous') != newText ){
            // do whatever has to be done, e.g. log it to console
            console.log( 'changed to: ' + newText );
        }
    }
});

Works for me :)

PHP max_input_vars

It's 2018 now.And I just got stuck on this problem when I must send a request that exceeds the max_input_vars. And I came up with a solution that newie like me forgot to restart php fpm service after changing the max_input_vars param. because I only tried to restart apache2 service, but not php fpm

  1. uncomment code at /etc/php/7.0/fpm/php.ini and set number as you wish
    max_input_vars = 4000
  2. restart php fpm service, as I use php 7. Therefore,
    sudo service php7.0-fpm restart

Hope it helps
Tested on Debian Stretch, php7.0

How to change app default theme to a different app theme?

To change your application to a different built-in theme, just add this line under application tag in your app's manifest.xml file.

Example:

<application 
    android:theme="@android:style/Theme.Holo"/>

<application 
    android:theme="@android:style/Theme.Holo.Light"/>

<application 
    android:theme="@android:style/Theme.Black"/>

<application 
    android:theme="@android:style/Theme.DeviceDefault"/>

If you set style to DeviceDefault it will require min SDK version 14, but if you won't add a style, it will set to the device default anyway.

<uses-sdk
    android:minSdkVersion="14"/>

AngularJs: How to set radio button checked based on model

Just do something like this,<input type="radio" ng-disabled="loading" name="dateRange" ng-model="filter.DateRange" value="1" ng-checked="(filter.DateRange == 1)"/>

How to execute VBA Access module?

You're not running a module -- you're running subroutines/functions that happen to be stored in modules.

If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).

Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:

  SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
  FROM MyTable;

That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.

Subroutines (i.e., code that returns no value) are not callable from within SQL statements.

How to center a navigation bar with CSS or HTML?

#nav ul {
    display: inline-block;
    list-style-type: none;
}

It should work, I tested it in your site.

enter image description here

Determine which element the mouse pointer is on top of in JavaScript

The following code will help you to get the element of the mouse pointer. The resulted elements will display in the console.

document.addEventListener('mousemove', function(e) {
    console.log(document.elementFromPoint(e.pageX, e.pageY)); 
})

What is the cleanest way to get the progress of JQuery ajax request?

http://www.htmlgoodies.com/beyond/php/show-progress-report-for-long-running-php-scripts.html

I was searching for a similar solution and found this one use full.

var es;

function startTask() {
    es = new EventSource('yourphpfile.php');

//a message is received
es.addEventListener('message', function(e) {
    var result = JSON.parse( e.data );

    console.log(result.message);       

    if(e.lastEventId == 'CLOSE') {
        console.log('closed');
        es.close();
        var pBar = document.getElementById('progressor');
        pBar.value = pBar.max; //max out the progress bar
    }
    else {

        console.log(response); //your progress bar action
    }
});

es.addEventListener('error', function(e) {
    console.log('error');
    es.close();
});

}

and your server outputs

header('Content-Type: text/event-stream');
// recommended to prevent caching of event data.
header('Cache-Control: no-cache'); 

function send_message($id, $message, $progress) {
    $d = array('message' => $message , 'progress' => $progress); //prepare json

    echo "id: $id" . PHP_EOL;
    echo "data: " . json_encode($d) . PHP_EOL;
    echo PHP_EOL;

   ob_flush();
   flush();
}


//LONG RUNNING TASK
 for($i = 1; $i <= 10; $i++) {
    send_message($i, 'on iteration ' . $i . ' of 10' , $i*10); 

    sleep(1);
 }

send_message('CLOSE', 'Process complete');

Limiting the output of PHP's echo to 200 characters

this is most easy way for doing that

//substr(string,start,length)
substr("Hello Word", 0, 5);
substr($text, 0, 5);
substr($row['style-info'], 0, 5);

for more detail

https://www.w3schools.com/php/func_string_substr.asp

http://php.net/manual/en/function.substr.php

How to read string from keyboard using C?

#include<stdio.h>

int main()
{
    char str[100];
    scanf("%[^\n]s",str);
    printf("%s",str);
    return 0;
}

input: read the string
ouput: print the string

This code prints the string with gaps as shown above.

How to print / echo environment variables?

These need to go as different commands e.g.:

NAME=sam; echo "$NAME"
NAME=sam && echo "$NAME"

The expansion $NAME to empty string is done by the shell earlier, before running echo, so at the time the NAME variable is passed to the echo command's environment, the expansion is already done (to null string).

To get the same result in one command:

NAME=sam printenv NAME

Using Notepad++ to validate XML against an XSD

  1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

    enter image description here

  2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
    Following dialog will open: enter image description here

  3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

Hope this saves you some time.

EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

enter image description here

Input widths on Bootstrap 3

Current docs say to use .col-xs-x , no lg. Then I try in fiddle and it's seem to work :

http://jsfiddle.net/tX3ae/225/

to keep the layout maybe you can change where you put the class "row" like this :

<div class="container">
  <h1>My form</h1>
  <p>How to make these input fields small and retain the layout.</p>
  <div class="row">
    <form role="form" class="col-xs-3">

      <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="name" name="name" >
      </div>

      <div class="form-group">
        <label for="email">Email</label>
        <input type="text" class="form-control" id="email" name="email">
      </div>

      <button type="submit" class="btn btn-default">Submit</button>
    </form>
  </div>
</div>

http://jsfiddle.net/tX3ae/226/

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

None of the answers so far explains how to download the various variants of that font so that you can serve them from your own website (WWW server).

While this might seem like a minor issue from the technical perspective, it is a big issue from the legal perspective, at least if you intend to present your pages to any EU citizen (or even, if you do that by accident). This is even true for companies which reside in the US (or any country outside the EU).

If anybody is interested why this is, I'll update this answer and give some more details here, but at the moment, I don't want to waste too much space off-topic.

Having said this:

I've downloaded all versions (regular, outlined, rounded, sharp, two-tone) of that font following two very easy steps (it was @Aj334's answer to his own question which put me on the right track) (example: "outlined" variant):

  1. Get the CSS from the Google CDN by directly letting your browser fetch the CSS URL, i.e. copy the following URL into your browser's location bar:

    https://fonts.googleapis.com/css?family=Material+Icons+Outlined
    

    This will return a page which looks like this (at least in Firefox 70.0.1 at the time of writing this):

    /* fallback */
    @font-face {
      font-family: 'Material Icons Outlined';
      font-style: normal;
      font-weight: 400;
      src: url(https://fonts.gstatic.com/s/materialiconsoutlined/v14/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUce.woff2) format('woff2');
    }
    
    .material-icons-outlined {
      font-family: 'Material Icons Outlined';
      font-weight: normal;
      font-style: normal;
      font-size: 24px;
      line-height: 1;
      letter-spacing: normal;
      text-transform: none;
      display: inline-block;
      white-space: nowrap;
      word-wrap: normal;
      direction: ltr;
      -moz-font-feature-settings: 'liga';
      -moz-osx-font-smoothing: grayscale;
    }
    
  2. Find the line starting with src: in the above code, and let your browser fetch the URL contained in that line, i.e. copy the following URL into your browser's location bar:

    https://fonts.gstatic.com/s/materialiconsoutlined/v14/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUce.woff2
    

    Now the browser will download that .woff2 file and offer to save it locally (at least, Firefox did).

Two final remarks:

Of course, you can download the other variants of that font using the same method. In the first step, just replace the character sequence Outlined in the URL by the character sequences Round (yes, really, although here it's called "Rounded" in the left navigation menu), Sharp or Two+Tone, respectively. The result page will look nearly the same each time, but the URL in the src: line of course is different for each variant.

Finally, in step 1, you even can use that URL:

https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp

This will return the CSS for all variants in one page, which then contains five src: lines, each one with another URL designating where the respective font is located.

Syntax for creating a two-dimensional array in Java

Actually Java doesn't have multi-dimensional array in mathematical sense. What Java has is just array of arrays, an array where each element is also an array. That is why the absolute requirement to initialize it is the size of the first dimension. If the rest are specified then it will create an array populated with default value.

int[][]   ar  = new int[2][];
int[][][] ar  = new int[2][][];
int[][]   ar  = new int[2][2]; // 2x2 array with zeros

It also gives us a quirk. The size of the sub-array cannot be changed by adding more elements, but we can do so by assigning a new array of arbitrary size.

int[][]   ar  = new int[2][2];
ar[1][3] = 10; // index out of bound
ar[1]    = new int[] {1,2,3,4,5,6}; // works

How do you get the path to the Laravel Storage folder?

You can use the storage_path(); function to get storage folder path.

storage_path(); // Return path like: laravel_app\storage

Suppose you want to save your logfile mylog.log inside Log folder of storage folder. You have to write something like

storage_path() . '/LogFolder/mylog.log'

checking for typeof error in JS

Or use this for different types of errors

function isError(val) {
  return (!!val && typeof val === 'object')
    && ((Object.prototype.toString.call(val) === '[object Error]')
      || (typeof val.message === 'string' && typeof val.name === 'string'))
}

How to set a single, main title above all the subplots with Pyplot?

If your subplots also have titles, you may need to adjust the main title size:

plt.suptitle("Main Title", size=16)

How to make inline functions in C#

Yes, C# supports that. There are several syntaxes available.

  • Anonymous methods were added in C# 2.0:

    Func<int, int, int> add = delegate(int x, int y)
    {
        return x + y;
    };
    Action<int> print = delegate(int x)
    {
        Console.WriteLine(x);
    }
    Action<int> helloWorld = delegate // parameters can be elided if ignored
    {
        Console.WriteLine("Hello world!");
    }
    
  • Lambdas are new in C# 3.0 and come in two flavours.

    • Expression lambdas:

      Func<int, int, int> add = (int x, int y) => x + y; // or...
      Func<int, int, int> add = (x, y) => x + y; // types are inferred by the compiler
      
    • Statement lambdas:

      Action<int> print = (int x) => { Console.WriteLine(x); };
      Action<int> print = x => { Console.WriteLine(x); }; // inferred types
      Func<int, int, int> add = (x, y) => { return x + y; };
      
  • Local functions have been introduced with C# 7.0:

    int add(int x, int y) => x + y;
    void print(int x) { Console.WriteLine(x); }
    

There are basically two different types for these: Func and Action. Funcs return values but Actions don't. The last type parameter of a Func is the return type; all the others are the parameter types.

There are similar types with different names, but the syntax for declaring them inline is the same. An example of this is Comparison<T>, which is roughly equivalent to Func<T, T, int>.

Func<string, string, int> compare1 = (l,r) => 1;
Comparison<string> compare2 = (l, r) => 1;
Comparison<string> compare3 = compare1; // this one only works from C# 4.0 onwards

These can be invoked directly as if they were regular methods:

int x = add(23, 17); // x == 40
print(x); // outputs 40
helloWorld(x); // helloWorld has one int parameter declared: Action<int>
               // even though it does not make any use of it.

In C# check that filename is *possibly* valid (not that it exists)

Several of the System.IO.Path methods will throw exceptions if the path or filename is invalid:

  • Path.IsPathRooted()
  • Path.GetFileName()

http://msdn.microsoft.com/en-us/library/system.io.path_methods.aspx

"git checkout <commit id>" is changing branch to "no branch"

If you are branch master and you do a git checkout <SHA>

I'm fairly certain that this causes git to load that commit in a detached state, changing you out of the current branch.

If you want to make changes you can and then you can do a git checkout -b <mynewbranch> to create a new branch based off that commit and any changes you have made.

IBOutlet and IBAction

IBAction and IBOutlets are used to hook up your interface made in Interface Builder with your controller. If you wouldn't use Interface Builder and build your interface completely in code, you could make a program without using them. But in reality most of us use Interface Builder, once you want to get some interactivity going in your interface, you will have to use IBActions and IBoutlets.

Is it possible to select the last n items with nth-child?

If you are using jQuery in your project, or are willing to include it you can call nth-last-child through its selector API (this is this simulated it will cross browser). Here is a link to an nth-last-child plugin. If you took this method of targeting the elements you were interested in:

$('ul li:nth-last-child(1)').addClass('last');

And then style again the last class instead of the nth-child or nth-last-child pseudo selectors, you will have a much more consistent cross browser experience.

Where are static methods and static variables stored in Java?

In addition to the Thomas's answer , static variable are stored in non heap area which is called Method Area.

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

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

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

This should work in Java6, not sure about Java5

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

Can you display HTML5 <video> as a full screen background?

I might be a bit late to answer this but this will be useful for new people looking for this answer.

The answers above are good, but to have a perfect video background you have to check at the aspect ratio as the video might cut or the canvas around get deformed when resizing the screen or using it on different screen sizes.

I got into this issue not long ago and I found the solution using media queries.

Here is a tutorial that I wrote on how to create a Fullscreen Video Background with only CSS

I will add the code here as well:

HTML:

<div class="videoBgWrapper">
    <video loop muted autoplay poster="img/videoframe.jpg" class="videoBg">
        <source src="videosfolder/video.webm" type="video/webm">
        <source src="videosfolder/video.mp4" type="video/mp4">
        <source src="videosfolder/video.ogv" type="video/ogg">
    </video>
</div>

CSS:

.videoBgWrapper {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    z-index: -100;
}
.videoBg{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

@media (min-aspect-ratio: 16/9) {
  .videoBg{
    width: 100%;
    height: auto;
  }
}
@media (max-aspect-ratio: 16/9) {
  .videoBg {
    width: auto;
    height: 100%;
  }
}

I hope you find it useful.

When using SASS how can I import a file from a different directory?

Using webpack with sass-loader I can use ~ to refer to the project root path. E.g assuming OPs folder structure and that you're in a file inside sub_directory_b:

@import "~sub_directory_a/_common";

Documentation: https://github.com/webpack-contrib/sass-loader#resolving-import-at-rules

get current date and time in groovy?

Date has the time part, so we only need to extract it from Date

I personally prefer the default format parameter of the Date when date and time needs to be separated instead of using the extra SimpleDateFormat

Date date = new Date()
String datePart = date.format("dd/MM/yyyy")
String timePart = date.format("HH:mm:ss")

println "datePart : " + datePart + "\ttimePart : " + timePart

Determine .NET Framework version for dll

Just simply

var tar = (TargetFrameworkAttribute)Assembly
          .LoadFrom("yoursAssembly.dll")
          .GetCustomAttributes(typeof(TargetFrameworkAttribute)).First();

Get Selected value of a Combobox

If you're dealing with Data Validation lists, you can use the Worksheet_Change event. Right click on the sheet with the data validation and choose View Code. Then type in this:

Private Sub Worksheet_Change(ByVal Target As Range)

    MsgBox Target.Value

End Sub

If you're dealing with ActiveX comboboxes, it's a little more complicated. You need to create a custom class module to hook up the events. First, create a class module named CComboEvent and put this code in it.

Public WithEvents Cbx As MSForms.ComboBox

Private Sub Cbx_Change()

    MsgBox Cbx.Value

End Sub

Next, create another class module named CComboEvents. This will hold all of our CComboEvent instances and keep them in scope. Put this code in CComboEvents.

Private mcolComboEvents As Collection

Private Sub Class_Initialize()
    Set mcolComboEvents = New Collection
End Sub

Private Sub Class_Terminate()
    Set mcolComboEvents = Nothing
End Sub

Public Sub Add(clsComboEvent As CComboEvent)

    mcolComboEvents.Add clsComboEvent, clsComboEvent.Cbx.Name

End Sub

Finally, create a standard module (not a class module). You'll need code to put all of your comboboxes into the class modules. You might put this in an Auto_Open procedure so it happens whenever the workbook is opened, but that's up to you.

You'll need a Public variable to hold an instance of CComboEvents. Making it Public will kepp it, and all of its children, in scope. You need them in scope so that the events are triggered. In the procedure, loop through all of the comboboxes, creating a new CComboEvent instance for each one, and adding that to CComboEvents.

Public gclsComboEvents As CComboEvents

Public Sub AddCombox()

    Dim oleo As OLEObject
    Dim clsComboEvent As CComboEvent

    Set gclsComboEvents = New CComboEvents

    For Each oleo In Sheet1.OLEObjects
        If TypeName(oleo.Object) = "ComboBox" Then
            Set clsComboEvent = New CComboEvent
            Set clsComboEvent.Cbx = oleo.Object
            gclsComboEvents.Add clsComboEvent
        End If
    Next oleo

End Sub

Now, whenever a combobox is changed, the event will fire and, in this example, a message box will show.

You can see an example at https://www.dropbox.com/s/sfj4kyzolfy03qe/ComboboxEvents.xlsm

jQuery SVG, why can't I addClass?

There is element.classList in the DOM API that works for both HTML and SVG elements. No need for jQuery SVG plugin or even jQuery.

$(".jimmy").click(function() {
    this.classList.add("clicked");
});

Detect URLs in text with JavaScript

tmp.innerText is undefined. You should use tmp.innerHTML

function strip(html) 
    {  
        var tmp = document.createElement("DIV"); 
        tmp.innerHTML = html; 
        var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;   
        return tmp.innerHTML .replace(urlRegex, function(url) {     
        return '\n' + url 
    })

What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do

I would use liquibase for updating your db. hibernate's schema update feature is really only o.k. for a developer while they are developing new features. In a production situation, the db upgrade needs to be handled more carefully.

Right way to write JSON deserializer in Spring or extend it

With Spring MVC 4.2.1.RELEASE, you need to use the new Jackson2 dependencies as below for the Deserializer to work.

Dont use this

<dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.12</version>  
        </dependency>  

Use this instead.

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.2</version>
        </dependency>  

Also use com.fasterxml.jackson.databind.JsonDeserializer and com.fasterxml.jackson.databind.annotation.JsonDeserialize for the deserialization and not the classes from org.codehaus.jackson

How do I convert a number to a letter in Java?

This isn't exactly an answer, but some useful/related code I made. When you run it and enter any character in the command line it returns getNumericValue(char) ... which doesn't seem to be the same as the ASCII table so be aware. Anyways, not a direct answer to your question but hopefully helpful:

import java.lang.*;
import java.util.*;
/* charVal.java
         */

//infinite loops. whenever you type in a character gives you value of 
//getNumericValue(char)
//
//ctrl+c to exit



public class charVal {
   public static void main(String[] args) {
     Scanner inPut = new Scanner(System.in);
     for(;;){
       char c = inPut.next().charAt(0);
       System.out.printf("\n %s = %d \n", c, Character.getNumericValue(c));
     }
    }
}

How to compile a Perl script to a Windows executable with Strawberry Perl?

There are three packagers, and two compilers:

free packager: PAR
commercial packagers: perl2exe, perlapp
compilers: B::C, B::CC

http://search.cpan.org/dist/B-C/perlcompile.pod

(Note: perlfaq3 is still wrong)

For strawberry you need perl-5.16 and B-C from git master (1.43), as B-C-1.42 does not support 5.16.

Add Expires headers

You can add them in your htaccess file or vhost configuration.

See here : http://httpd.apache.org/docs/2.2/mod/mod_expires.html

But unless you own those domains .. they are our of your control.

VBoxManage: error: Failed to create the host-only adapter

My solution:

Make sure you have the following files under System32:

vboxnetadp.sys

vboxnetflt.sys

You can download them from here:

http://www.sysfilesdownload.com/V/VBoxNetFltsys.html

http://www.sysfilesdownload.com/U/VBoxNetAdp.sys.html

Fastest way to check if a string matches a regexp in ruby?

Depending on how complicated your regular expression is, you could possibly just use simple string slicing. I'm not sure about the practicality of this for your application or whether or not it would actually offer any speed improvements.

'testsentence'['stsen']
=> 'stsen' # evaluates to true
'testsentence'['koala']
=> nil # evaluates to false

Observable Finally on Subscribe

The only thing which worked for me is this

fetchData()
  .subscribe(
    (data) => {
       //Called when success
     },
    (error) => {
       //Called when error
    }
  ).add(() => {
       //Called when operation is complete (both success and error)
  });

PHP convert string to hex and hex to string

Using @bill-shirley answer with a little addition

function str_to_hex($string) {
$hexstr = unpack('H*', $string);
return array_shift($hexstr);
}
function hex_to_str($string) {
return hex2bin("$string");
}

Usage:

  $str = "Go placidly amidst the noise";
  $hexstr = str_to_hex($str);// 476f20706c616369646c7920616d6964737420746865206e6f697365
  $strstr = hex_to_str($str);// Go placidly amidst the noise

Select from one table matching criteria in another?

The simplest solution would be a correlated sub select:

select
    A.*
from
    table_A A
where
    A.id in (
        select B.id from table_B B where B.tag = 'chair'
)

Alternatively you could join the tables and filter the rows you want:

select
    A.*
from
    table_A A
inner join table_B B
    on A.id = B.id
where
    B.tag = 'chair'

You should profile both and see which is faster on your dataset.

How do I force a favicon refresh?

Ok, after 10 minutes of trying, the easy way to fix it is close to that of the line of birds

  1. Type in www.yoursite.com/favicon.ico (or www.yoursite.com/apple-touch-icon.png, etc.)
  2. Push enter
  3. ctrl+f5
  4. Restart Browser (IE, Firefox)

How to start anonymous thread class

Just call start()

new Thread()
{
    public void run() {
        System.out.println("blah");
    }
}.start();

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

Of course there is a best way.Objects in javascript have enumerable and nonenumerable properties.

var empty = {};
console.log(empty.toString);
// . function toString(){...}
console.log(empty.toString());
// . [object Object]

In the example above you can see that an empty object actually has properties.

Ok first let's see which is the best way:

var new_object = Object.create(null)

new_object.name = 'Roland'
new_object.last_name = 'Doda'
//etc

console.log("toString" in new_object) //=> false

In the example above the log will output false.

Now let's see why the other object creation ways are incorrect.

//Object constructor
var object = new Object();

console.log("toString" in object); //=> true

//Literal constructor
var person = { 
  name : "Anand",
  getName : function (){
   return this.name
  } 
} 

console.log("toString" in person); //=> true

//function Constructor
function Person(name){
  this.name = name
  this.getName = function(){
    return this.name
  } 
}

var person = new Person ('landi')

console.log("toString" in person); //=> true

//Prototype
function Person(){};

Person.prototype.name = "Anand";

console.log("toString" in person); //=> true

//Function/Prototype combination
function Person2(name){
  this.name = name;
} 

Person2.prototype.getName = function(){
  return this.name
}

var person2 = new Person2('Roland')

console.log("toString" in person2) //=> true

As you can see above,all examples log true.Which means if you have a case that you have a for in loop to see if the object has a property will lead you to wrong results probably.

Note that the best way it is not easy.You have to define all properties of object line by line.The other ways are more easier and will have less code to create an object but you have to be aware in some cases. I always use the "other ways" by the way and one solution to above warning if you don't use the best way is:

 for (var property in new_object) {
  if (new_object.hasOwnProperty(property)) {
    // ... this is an own property
  }
 }

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Plenty of responses already, but you can use this:

Sub runQry(qDefName)
    Dim db As DAO.Database, qd As QueryDef, par As Parameter

    Set db = CurrentDb
    Set qd = db.QueryDefs(qDefName)

    On Error Resume Next
    For Each par In qd.Parameters
        Err.Clear
        par.Value = Eval(par.Name)          'try evaluating param
        If Err.Number <> 0 Then             'failed ?
            par.Value = InputBox(par.Name)  'ask for value
        End If
    Next par
    On Error GoTo 0

    qd.Execute dbFailOnError
End Sub

Sub runQry_test()
    runQry "test"  'qryDef name
End Sub

How can I get nth element from a list?

I'm not saying that there's anything wrong with your question or the answer given, but maybe you'd like to know about the wonderful tool that is Hoogle to save yourself time in the future: With Hoogle, you can search for standard library functions that match a given signature. So, not knowing anything about !!, in your case you might search for "something that takes an Int and a list of whatevers and returns a single such whatever", namely

Int -> [a] -> a

Lo and behold, with !! as the first result (although the type signature actually has the two arguments in reverse compared to what we searched for). Neat, huh?

Also, if your code relies on indexing (instead of consuming from the front of the list), lists may in fact not be the proper data structure. For O(1) index-based access there are more efficient alternatives, such as arrays or vectors.

Clean out Eclipse workspace metadata

In my case eclipse is not showing parent class function on $this, so I perform below mention points and it starts works:-

I go to my /var/www/ folder and check for .metadata folder (Here check the .log file and it shows) Resource is out of sync with the file system: 1. Go to Eclipse --> Project --> Clean 2. Windows -- preferences --> General --> Workspace --> And set it to "Refresh Automatically"

After that boom - things gets start working :)

If you want to load variables from other files too then ado this :- Eclipse-->Windows-->Preferences-->Php-->Editor-->Content Assist --> and check "show variable from other files"

Then it will show element , variables and other functions also.

Using R to list all files with a specified extension

Peg the pattern to find "\\.dbf" at the end of the string using the $ character:

list.files(pattern = "\\.dbf$")

WPF loading spinner

In WPF, you can now simply do:

Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; // set the cursor to loading spinner

Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow; // set the cursor back to arrow

Swap two variables without using a temporary variable

For the sake of future learners, and humanity, I submit this correction to the currently selected answer.

If you want to avoid using temp variables, there are only two sensible options that take first performance and then readability into consideration.

  • Use a temp variable in a generic Swap method. (Absolute best performance, next to inline temp variable)
  • Use Interlocked.Exchange. (5.9 times slower on my machine, but this is your only option if multiple threads will be swapping these variables simultaneously.)

Things you should never do:

  • Never use floating point arithmetic. (slow, rounding and overflow errors, hard to understand)
  • Never use non-primitive arithmetic. (slow, overflow errors, hard to understand) Decimal is not a CPU primitive and results in far more code than you realize.
  • Never use arithmetic period. Or bit hacks. (slow, hard to understand) That's the compiler's job. It can optimize for many different platforms.

Because everyone loves hard numbers, here's a program that compares your options. Run it in release mode from outside Visual Studio so that Swap is inlined. Results on my machine (Windows 7 64-bit i5-3470):

Inline:      00:00:00.7351931
Call:        00:00:00.7483503
Interlocked: 00:00:04.4076651

Code:

class Program
{
    static void Swap<T>(ref T obj1, ref T obj2)
    {
        var temp = obj1;
        obj1 = obj2;
        obj2 = temp;
    }

    static void Main(string[] args)
    {
        var a = new object();
        var b = new object();

        var s = new Stopwatch();

        Swap(ref a, ref b); // JIT the swap method outside the stopwatch

        s.Restart();
        for (var i = 0; i < 500000000; i++)
        {
            var temp = a;
            a = b;
            b = temp;
        }
        s.Stop();
        Console.WriteLine("Inline temp: " + s.Elapsed);


        s.Restart();
        for (var i = 0; i < 500000000; i++)
        {
            Swap(ref a, ref b);
        }
        s.Stop();
        Console.WriteLine("Call:        " + s.Elapsed);

        s.Restart();
        for (var i = 0; i < 500000000; i++)
        {
            b = Interlocked.Exchange(ref a, b);
        }
        s.Stop();
        Console.WriteLine("Interlocked: " + s.Elapsed);

        Console.ReadKey();
    }
}

Java: Reading a file into an array

Here is some example code to help you get started:

package com.acme;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileArrayProvider {

    public String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
}

And an example unit test:

package com.acme;

import java.io.IOException;

import org.junit.Test;

public class FileArrayProviderTest {

    @Test
    public void testFileArrayProvider() throws IOException {
        FileArrayProvider fap = new FileArrayProvider();
        String[] lines = fap
                .readLines("src/main/java/com/acme/FileArrayProvider.java");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Hope this helps.

Reading a file character by character in C

Either of the two should do the trick -

char *readFile(char *fileName)
{
  FILE *file;
  char *code = malloc(1000 * sizeof(char));
  char *p = code;
  file = fopen(fileName, "r");
  do 
  {
    *p++ = (char)fgetc(file);
  } while(*p != EOF);
  *p = '\0';
  return code;
}

char *readFile(char *fileName)
{
  FILE *file;
  int i = 0;
  char *code = malloc(1000 * sizeof(char));
  file = fopen(fileName, "r");
  do 
  {
    code[i++] = (char)fgetc(file);
  } while(code[i-1] != EOF);
  code[i] = '\0'
  return code;
}

Like the other posters have pointed out, you need to ensure that the file size does not exceed 1000 characters. Also, remember to free the memory when you're done using it.

How do I convert a string to a number in PHP?

Different approach:

  1. Push it all into an array / associative array.
  2. json_encode($your_array, JSON_NUMERIC_CHECK); optionally decode it back
  3. ?
  4. Profit!

Possible to change where Android Virtual Devices are saved?

Add a new user environment variable (Windows 7):

  1. Start Menu > Control Panel > System > Advanced System Settings (on the left) > Environment Variables

  2. Add a new user variable (at the top) that points your home user directory:

    Variable name: ANDROID_SDK_HOME
    Variable value: a path to a directory of your choice

AVD Manager will use this directory to save its .android directory into it.

For those who may be interested, I blogged about my first foray into Android development...
Android "Hello World": a Tale of Woe

Alternatively, you can use the Rapid Environment Editor to set the environment variables.

How to copy a row from one SQL Server table to another

INSERT INTO DestTable
SELECT * FROM SourceTable
WHERE ... 

works in SQL Server

Angular 2 filter/search list

You have to manually filter result based on change of input each time by keeping listener over input event. While doing manually filtering make sure you should maintain two copy of variable, one would be original collection copy & second would be filteredCollection copy. The advantage for going this way could save your couple of unnecessary filtering on change detection cycle. You may see a more code, but this would be more performance friendly.

Markup - HTML Template

<md-input #myInput placeholder="Item name..." [(ngModel)]="name" (input)="filterItem(myInput.value)"></md-input>

<div *ngFor="let item of filteredItems">
   {{item.name}}
</div>

Code

assignCopy(){
   this.filteredItems = Object.assign([], this.items);
}
filterItem(value){
   if(!value){
       this.assignCopy();
   } // when nothing has typed
   this.filteredItems = Object.assign([], this.items).filter(
      item => item.name.toLowerCase().indexOf(value.toLowerCase()) > -1
   )
}
this.assignCopy();//when you fetch collection from server.

JavaScript Array splice vs slice

The difference between Slice() and Splice() javascript build-in functions is, Slice returns removed item but did not change the original array ; like,

        // (original Array)
        let array=[1,2,3,4,5] 
        let index= array.indexOf(4)
         // index=3
        let result=array.slice(index)
        // result=4  
        // after slicing=>  array =[1,2,3,4,5]  (same as original array)

but in splice() case it affects original array; like,

         // (original Array)
        let array=[1,2,3,4,5] 
        let index= array.indexOf(4)
         // index=3
        let result=array.splice(index)
        // result=4  
        // after splicing array =[1,2,3,5]  (splicing affects original array)

What is Activity.finish() method doing exactly?

Also notice if you call finish() after an intent you can't go back to the previous activity with the "back" button

startActivity(intent);
finish();

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

There's a very simple way to do on/off flags without parsing the arguments. gulpfile.js is just a file that's executed like any other, so you can do:

var flags = {
  production: false
};

gulp.task('production', function () {
  flags.production = true;
});

And use something like gulp-if to conditionally execute a step

gulp.task('build', function () {
  gulp.src('*.html')
    .pipe(gulp_if(flags.production, minify_html()))
    .pipe(gulp.dest('build/'));
});

Executing gulp build will produce a nice html, while gulp production build will minify it.

How do I wait for a promise to finish before returning the variable of a function?

What do I need to do to make this function wait for the result of the promise?

Use async/await (NOT Part of ECMA6, but available for Chrome, Edge, Firefox and Safari since end of 2017, see canIuse)
MDN

    async function waitForPromise() {
        // let result = await any Promise, like:
        let result = await Promise.resolve('this is a sample promise');
    }

Added due to comment: An async function always returns a Promise, and in TypeScript it would look like:

    async function waitForPromise(): Promise<string> {
        // let result = await any Promise, like:
        let result = await Promise.resolve('this is a sample promise');
    }

java.text.ParseException: Unparseable date

String date="Sat Jun 01 12:53:10 IST 2013";

SimpleDateFormat sdf=new SimpleDateFormat("MMM d, yyyy HH:mm:ss");

This patterns does not tally with your input String which occurs the exception.

You need to use following pattern to get the work done.

E MMM dd HH:mm:ss z yyyy

Following code will help you to skip the exception.

SimpleDateFormat is used.

    String date="Sat Jun 01 12:53:10 IST 2013"; // Input String

    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy"); // Existing Pattern

    Date currentdate=simpleDateFormat.parse(date); // Returns Date Format,

    SimpleDateFormat simpleDateFormat1=new SimpleDateFormat("MMM dd,yyyy HH:mm:ss"); // New Pattern

    System.out.println(simpleDateFormat1.format(currentdate)); // Format given String to new pattern

    // outputs: Jun 01,2013 12:53:10

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

You need to add the following line:

using FootballLeagueSystem;

into your all your classes (MainMenu.cs, programme.cs, etc.) that use Login.

At the moment the compiler can't find the Login class.

PHP expects T_PAAMAYIM_NEKUDOTAYIM?

This can happen on foreachs when using:

foreach( $array as $key = $value )

instead of

foreach( $array as $key => $value )

CSS Outside Border

Try the outline property W3Schools - CSS Outline

Outline will not interfere with widths and lenghts of the elements/divs!

Please click the link I provided at the bottom to see working demos of the the different ways you can make borders, and inner/inline borders, even ones that do not disrupt the dimensions of the element! No need to add extra divs every time, as mentioned in another answer!

You can also combine borders with outlines, and if you like, box-shadows (also shown via link)

<head>
   <style type="text/css" ref="stylesheet">
      div {
        width:22px;
        height:22px;
        outline:1px solid black;
      }
   </style>
</head>
<div>
    outlined
</div>

Usually by default, 'border:' puts the border on the outside of the width, measurement, adding to the overall dimensions, unless you use the 'inset' value:

div {border: inset solid 1px black};

But 'outline:' is an extra border outside of the border, and of course still adds extra width/length to the element.

Hope this helps

PS: I also was inspired to make this for you : Using borders, outlines, and box-shadows

How do I turn off Unicode in a VC++ project?

For whatever reason, I noticed that setting to unicode for "All Configurations" did not actually apply to all configurations.

Picture: Setting Configuragion In IDE

To confirm this, I would open the .vcxproj and confirm the correct token is in all 4 locations. In this photo, I am using unicode. So the string I am looking for is "Unicode". For you, you likely want it to say "MultiByte".

Picture: Confirming changes in configuration file

How do I set log4j level on the command line?

With Log4j2, this can be achieved using the following utility method added to your code.

private static void setLogLevel() {
  if (Boolean.getBoolean("log4j.debug")) {
    Configurator.setLevel(System.getProperty("log4j.logger"), Level.DEBUG);
  }
}

You need these imports

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.config.Configurator;

Now invoke the setLogLevel method in your main() or whereever appropriate and pass command line params -Dlog4j.logger=com.mypackage.Thingie and -Dlog4j.debug=true.

Copy Files from Windows to the Ubuntu Subsystem

You should only access Linux files system (those located in lxss folder) from inside WSL; DO NOT create/modify any files in lxss folder in Windows - it's dangerous and WSL will not see these files.

Files can be shared between WSL and Windows, though; put the file outside of lxss folder. You can access them via drvFS (/mnt) such as /mnt/c/Users/yourusername/files within WSL. These files stay synced between WSL and Windows.

For details and why, see: https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/

What is the difference between onBlur and onChange attribute in HTML?

The onBlur event is fired when you have moved away from an object without necessarily having changed its value.

The onChange event is only called when you have changed the value of the field and it loses focus.

You might want to take a look at quirksmode's intro to events. This is a great place to get info on what's going on in your browser when you interact with it. His book is good too.

CSS content property: is it possible to insert HTML instead of Text?

Unfortunately, this is not possible. Per the spec:

Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).

In other words, for string values this means the value is always treated literally. It is never interpreted as markup, regardless of the document language in use.

As an example, using the given CSS with the following HTML:

<h1 class="header">Title</h1>

... will result in the following output:

<a href="#top">Back</a>Title

Best practices for styling HTML emails

The resource I always end up going back to about HTML emails is CampaignMonitor's CSS guide.

As their business is geared solely around email delivery, they know their stuff as well as anyone is going to

Android splash screen image sizes to fit all devices

Using PNG is not such a good idea. Actually it's costly as far as performance is concerned. You can use drawable XML files, for example, Facebook's background.

This will help you to smooth and speed up your performance, and for the logo use .9 patch images.

keyCode values for numeric keypad?

You can use the key code page in order to find the:

event.code

to diference the number keyboard.

https://keycode.info/

function getNumberFromKeyEvent(event) {
   if (event.code.indexOf('Numpad') === 0) {
      var number = parseInt(event.code.replace('Numpad', ''), 10);
      if (number >= 0 && number <= 9) {
           // numbers from numeric keyboard
      }
   }
}

"Gradle Version 2.10 is required." Error

File - setting - Build Execution Deployment - Gradle - Select 'Use default gradle wrapper(recommended)'

What is the naming convention in Python for variable and function names?

As the Style Guide for Python Code admits,

The naming conventions of Python's library are a bit of a mess, so we'll never get this completely consistent

Note that this refers just to Python's standard library. If they can't get that consistent, then there hardly is much hope of having a generally-adhered-to convention for all Python code, is there?

From that, and the discussion here, I would deduce that it's not a horrible sin if one keeps using e.g. Java's or C#'s (clear and well-established) naming conventions for variables and functions when crossing over to Python. Keeping in mind, of course, that it is best to abide with whatever the prevailing style for a codebase / project / team happens to be. As the Python Style Guide points out, internal consistency matters most.

Feel free to dismiss me as a heretic. :-) Like the OP, I'm not a "Pythonista", not yet anyway.

How to determine if a type implements an interface with C# reflection

Note that if you have a generic interface IMyInterface<T> then this will always return false:

  typeof(IMyInterface<>).IsAssignableFrom(typeof(MyType)) /* ALWAYS FALSE */

This doesn't work either:

  typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface<>))  /* ALWAYS FALSE */

However, if MyType implements IMyInterface<MyType> this works and returns true:

  typeof(IMyInterface<MyType>).IsAssignableFrom(typeof(MyType))

However, you likely will not know the type parameter T at runtime. A somewhat hacky solution is:

  typeof(MyType).GetInterfaces()
                .Any(x=>x.Name == typeof(IMyInterface<>).Name)

Jeff's solution is a bit less hacky:

  typeof(MyType).GetInterfaces()
         .Any(i => i.IsGenericType 
             && i.GetGenericTypeDefinition() == typeof(IMyInterface<>));

Here's a extension method on Type that works for any case:

public static class TypeExtensions
{
    public static bool IsImplementing(this Type type, Type someInterface)
    {
        return type.GetInterfaces()
             .Any(i => i == someInterface 
                 || i.IsGenericType 
                    && i.GetGenericTypeDefinition() == someInterface);
    }
}

(Note that the above uses linq, which is probably slower than a loop.)

You can then do:

   typeof(MyType).IsImplementing(IMyInterface<>)

How do I compare two DateTime objects in PHP 5.2.8?

If you want to compare dates and not time, you could use this:

$d1->format("Y-m-d") == $d2->format("Y-m-d")

Format SQL in SQL Server Management Studio

Azure Data Studio - free and from Microsoft - offers automatic formatting (ctrl + shift + p while editing -> format document). More information about Azure Data Studio here.

While this is not SSMS, it's great for writing queries, free and an official product from Microsoft. It's even cross-platform. Short story: Just switch to Azure Data Studio to write your queries!

Update: Actually Azure Data Studio is in some way the recommended tool for writing queries (source)

Use Azure Data Studio if you: [..] Are mostly editing or executing queries.

I get exception when using Thread.sleep(x) or wait()

As other users have said you should surround your call with a try{...} catch{...} block. But since Java 1.5 was released, there is TimeUnit class which do the same as Thread.sleep(millis) but is more convenient. You can pick time unit for sleep operation.

try {
    TimeUnit.NANOSECONDS.sleep(100);
    TimeUnit.MICROSECONDS.sleep(100);
    TimeUnit.MILLISECONDS.sleep(100);
    TimeUnit.SECONDS.sleep(100);
    TimeUnit.MINUTES.sleep(100);
    TimeUnit.HOURS.sleep(100);
    TimeUnit.DAYS.sleep(100);
} catch (InterruptedException e) {
    //Handle exception
}

Also it has additional methods: TimeUnit Oracle Documentation

Java - Writing strings to a CSV file

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class CsvFile {

    public static void main(String[]args){
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new File("NewData.csv"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        StringBuilder builder = new StringBuilder();
        String columnNamesList = "Id,Name";
        // No need give the headers Like: id, Name on builder.append
        builder.append(columnNamesList +"\n");
        builder.append("1"+",");
        builder.append("Chola");
        builder.append('\n');
        pw.write(builder.toString());
        pw.close();
        System.out.println("done!");
    }
}

Which exception should I raise on bad/illegal argument combinations in Python?

I would inherit from ValueError

class IllegalArgumentError(ValueError):
    pass

It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible.

If you need to catch that specific error, it is helpful to have a name.

Generating statistics from Git repository

git-bars can show you "commits per day/week/year/etc".

You can install it with pip install git-bars (cf. https://github.com/knadh/git-bars)

The output looks like this:

$ git-bars -p month
370 commits over 19 month(s)
2019-10  7    ¯¯¯¯¯¯
2019-09  36   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2019-08  7    ¯¯¯¯¯¯
2019-07  10   ¯¯¯¯¯¯¯¯
2019-05  4    ¯¯¯
2019-04  2    ¯
2019-03  28   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2019-02  32   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2019-01  16   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-12  41   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-11  52   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-10  57   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-09  37   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-08  17   ¯¯¯¯¯¯¯¯¯¯¯¯¯¯
2018-07  1    
2018-04  7    ¯¯¯¯¯¯
2018-03  12   ¯¯¯¯¯¯¯¯¯¯
2018-02  2    ¯
2016-01  2    ¯

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

This is showing some path issue:

pip install graphviz

So this worked for me:

sudo apt-get install graphviz

adding to window.onload event?

If you are using jQuery, you don't have to do anything special. Handlers added via $(document).ready() don't overwrite each other, but rather execute in turn:

$(document).ready(func1)
...
$(document).ready(func2)

If you are not using jQuery, you could use addEventListener, as demonstrated by Karaxuna, plus attachEvent for IE<9.

Note that onload is not equivalent to $(document).ready() - the former waits for CSS, images... as well, while the latter waits for the DOM tree only. Modern browsers (and IE since IE9) support the DOMContentLoaded event on the document, which corresponds to the jQuery ready event, but IE<9 does not.

if(window.addEventListener){
  window.addEventListener('load', func1)
}else{
  window.attachEvent('onload', func1)
}
...
if(window.addEventListener){
  window.addEventListener('load', func2)
}else{
  window.attachEvent('onload', func2)
}

If neither option is available (for example, you are not dealing with DOM nodes), you can still do this (I am using onload as an example, but other options are available for onload):

var oldOnload1=window.onload;
window.onload=function(){
  oldOnload1 && oldOnload1();
  func1();
}
...
var oldOnload2=window.onload;
window.onload=function(){
  oldOnload2 && oldOnload2();
  func2();
}

or, to avoid polluting the global namespace (and likely encountering namespace collisions), using the import/export IIFE pattern:

window.onload=(function(oldLoad){
  return function(){
    oldLoad && oldLoad();
    func1();
  }
})(window.onload)
...
window.onload=(function(oldLoad){
  return function(){
    oldLoad && oldLoad();
    func2();
  }
})(window.onload)

How to remove RVM (Ruby Version Manager) from my system

A lot of people do a common mistake of thinking that 'rvm implode' does it . You need to delete all traces of any .rm files . Also , it will take some manual deletions from root . Make sure , it gets deleted and also all the ruby versions u installed using it .

Send private messages to friends

You can use Facebook Chat API to send private messages, here is an example in Ruby using xmpp4r_facebook gem:

sender_chat_id = "-#{sender_uid}@chat.facebook.com"
receiver_chat_id = "-#{receiver_uid}@chat.facebook.com"
message_body = "message body"
message_subject = "message subject"

jabber_message = Jabber::Message.new(receiver_chat_id, message_body)
jabber_message.subject = message_subject

client = Jabber::Client.new(Jabber::JID.new(sender_chat_id))
client.connect
client.auth_sasl(Jabber::SASL::XFacebookPlatform.new(client,
   ENV.fetch('FACEBOOK_APP_ID'), facebook_auth.token,
   ENV.fetch('FACEBOOK_APP_SECRET')), nil)
client.send(jabber_message)
client.close

How can I define an array of objects?

 var xxxx : { [key:number]: MyType };

How to print the array?

There is no .length property in C. The .length property can only be applied to arrays in object oriented programming (OOP) languages. The .length property is inherited from the object class; the class all other classes & objects inherit from in an OOP language. Also, one would use .length-1 to return the number of the last index in an array; using just the .length will return the total length of the array.

I would suggest something like this:

int index;
int jdex;
for( index = 0; index < (sizeof( my_array ) / sizeof( my_array[0] )); index++){
   for( jdex = 0; jdex < (sizeof( my_array ) / sizeof( my_array[0] )); jdex++){
        printf( "%d", my_array[index][jdex] );
        printf( "\n" );
   }
}

The line (sizeof( my_array ) / sizeof( my_array[0] )) will give you the size of the array in question. The sizeof property will return the length in bytes, so one must divide the total size of the array in bytes by how many bytes make up each element, each element takes up 4 bytes because each element is of type int, respectively. The array is of total size 16 bytes and each element is of 4 bytes so 16/4 yields 4 the total number of elements in your array because indexing starts at 0 and not 1.

Why can't non-default arguments follow default arguments?

Required arguments (the ones without defaults), must be at the start to allow client code to only supply two. If the optional arguments were at the start, it would be confusing:

fun1("who is who", 3, "jack")

What would that do in your first example? In the last, x is "who is who", y is 3 and a = "jack".

Class is not abstract and does not override abstract method

Both classes Rectangle and Ellipse need to override both of the abstract methods.

To work around this, you have 3 options:

  • Add the two methods
  • Make each class that extends Shape abstract
  • Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:

    abstract class Shape {
        // ...
        void draw(Graphics g);
    }
    

And

    class Rectangle extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

Finally

    class Ellipse extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

And you can switch in between them, like so:

    Shape shape = new Ellipse();
    shape.draw(/* ... */);

    shape = new Rectangle();
    shape.draw(/* ... */);

Again, just an example.

relative path to CSS file

if the file containing that link tag is in the root dir of the project, then the correct path would be "css/styles.css"

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

Actually, the solutions is to open the php.ini file edit the include_path line and either completely change it to

include_path='.:/usr/share/php:/usr/share/pear' 

or append the

'.:/usr/share/php:/usr/share/pear' 

to the current value of include_path.

It is further explained in : http://pear.php.net/manual/en/installation.checking.php#installation.checking.cli.phpdir

how to use javascript Object.defineProperty

Defines a new property directly on an object, or modifies an existing property on an object, and return the object.

Note: You call this method directly on the Object constructor rather than on an instance of type Object.

   const object1 = {};
   Object.defineProperty(object1, 'property1', {
      value: 42,
      writable: false, //If its false can't modify value using equal symbol
      enumerable: false, // If its false can't able to get value in Object.keys and for in loop
      configurable: false //if its false, can't able to modify value using defineproperty while writable in false
   });

enter image description here

Simple explanation about define Property.

Example code: https://jsfiddle.net/manoj_antony32/pu5n61fs/

What is the main difference between Collection and Collections in Java?

Are you asking about the Collections class versus the classes which implement the Collection interface?

If so, the Collections class is a utility class having static methods for doing operations on objects of classes which implement the Collection interface. For example, Collections has methods for finding the max element in a Collection.

The Collection interface defines methods common to structures which hold other objects. List and Set are subinterfaces of Collection, and ArrayList and HashSet are examples of concrete collections.

How to search for a string in an arraylist

Loop through your list and do a contains or startswith.

ArrayList<String> resList = new ArrayList<String>();
String searchString = "bea";

for (String curVal : list){
  if (curVal.contains(searchString)){
    resList.add(curVal);
  }
}

You can wrap that in a method. The contains checks if its in the list. You could also go for startswith.

Time part of a DateTime Field in SQL

This should strip away the date part:

select convert(datetime,convert(float, getdate()) - convert(int,getdate())), getdate()

and return a datetime with a default date of 1900-01-01.

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

Here's the answer that I found for my question:

urlList1.FocusedItem.Index

And I am getting selected item value by:

urlList1.Items(urlList1.FocusedItem.Index).SubItems(0).Text

The right way of setting <a href=""> when it's a local file

By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)

So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).

If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,

TypeError: Converting circular structure to JSON in nodejs

Came across this issue in my Node Api call when I missed to use await keyword in a async method in front of call returning Promise. I solved it by adding await keyword.

How to get all child inputs of a div element (jQuery)

If you are using a framework like Ruby on Rails or Spring MVC you may need to use divs with square braces or other chars, that are not allowed you can use document.getElementById and this solution still works if you have multiple inputs with the same type.

var div = document.getElementById(divID);
$(div).find('input:text, input:password, input:file, select, textarea')
        .each(function() {
            $(this).val('');
        });
$(div).find('input:radio, input:checkbox').each(function() {
    $(this).removeAttr('checked');
    $(this).removeAttr('selected');
});

This examples shows how to clear the inputs, for you example you'll need to change it.

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

I'm not sure how efficient this is but you can use range() to slice in both axis

 x=np.arange(16).reshape((4,4))
 x[range(1,3), :][:,range(1,3)] 

How can I get the current PowerShell executing file?

I've tried to summarize the various answers here, updated for PowerShell 5:

  • If you're only using PowerShell 3 or higher, use $PSCommandPath

  • If want compatibility with older versions, insert the shim:

    if ($PSCommandPath -eq $null) { function GetPSCommandPath() { return $MyInvocation.PSCommandPath; } $PSCommandPath = GetPSCommandPath; }

    This adds $PSCommandPath if it doesn't already exist.

    The shim code can be executed anywhere (top-level or inside a function), though $PSCommandPath variable is subject to normal scoping rules (eg, if you put the shim in a function, the variable is scoped to that function only).

Details

There's 4 different methods used in various answers, so I wrote this script to demonstrate each (plus $PSCommandPath):

function PSCommandPath() { return $PSCommandPath; }
function ScriptName() { return $MyInvocation.ScriptName; }
function MyCommandName() { return $MyInvocation.MyCommand.Name; }
function MyCommandDefinition() {
    # Begin of MyCommandDefinition()
    # Note: ouput of this script shows the contents of this function, not the execution result
    return $MyInvocation.MyCommand.Definition;
    # End of MyCommandDefinition()
}
function MyInvocationPSCommandPath() { return $MyInvocation.PSCommandPath; }

Write-Host "";
Write-Host "PSVersion: $($PSVersionTable.PSVersion)";
Write-Host "";
Write-Host "`$PSCommandPath:";
Write-Host " *   Direct: $PSCommandPath";
Write-Host " * Function: $(PSCommandPath)";
Write-Host "";
Write-Host "`$MyInvocation.ScriptName:";
Write-Host " *   Direct: $($MyInvocation.ScriptName)";
Write-Host " * Function: $(ScriptName)";
Write-Host "";
Write-Host "`$MyInvocation.MyCommand.Name:";
Write-Host " *   Direct: $($MyInvocation.MyCommand.Name)";
Write-Host " * Function: $(MyCommandName)";
Write-Host "";
Write-Host "`$MyInvocation.MyCommand.Definition:";
Write-Host " *   Direct: $($MyInvocation.MyCommand.Definition)";
Write-Host " * Function: $(MyCommandDefinition)";
Write-Host "";
Write-Host "`$MyInvocation.PSCommandPath:";
Write-Host " *   Direct: $($MyInvocation.PSCommandPath)";
Write-Host " * Function: $(MyInvocationPSCommandPath)";
Write-Host "";

Output:

PS C:\> .\Test\test.ps1

PSVersion: 5.1.19035.1

$PSCommandPath:
 *   Direct: C:\Test\test.ps1
 * Function: C:\Test\test.ps1

$MyInvocation.ScriptName:
 *   Direct:
 * Function: C:\Test\test.ps1

$MyInvocation.MyCommand.Name:
 *   Direct: test.ps1
 * Function: MyCommandName

$MyInvocation.MyCommand.Definition:
 *   Direct: C:\Test\test.ps1
 * Function:
    # Begin of MyCommandDefinition()
    # Note this is the contents of the MyCommandDefinition() function, not the execution results
    return $MyInvocation.MyCommand.Definition;
    # End of MyCommandDefinition()


$MyInvocation.PSCommandPath:
 *   Direct:
 * Function: C:\Test\test.ps1

Notes:

  • Executed from C:\, but actual script is C:\Test\test.ps1.
  • No method tells you the passed invocation path (.\Test\test.ps1)
  • $PSCommandPath is the only reliable way, but was introduced in PowerShell 3
  • For versions prior to 3, no single method works both inside and outside of a function

IIS AppPoolIdentity and file system write access permissions

I tried this to fix access issues to an IIS website, which manifested as something like the following in the Event Logs ? Windows ? Application:

Log Name:      Application
Source:        ASP.NET 4.0.30319.0
Date:          1/5/2012 4:12:33 PM
Event ID:      1314
Task Category: Web Event
Level:         Information
Keywords:      Classic
User:          N/A
Computer:      SALTIIS01

Description:
Event code: 4008 
Event message: File authorization failed for the request. 
Event time: 1/5/2012 4:12:33 PM 
Event time (UTC): 1/6/2012 12:12:33 AM 
Event ID: 349fcb2ec3c24b16a862f6eb9b23dd6c 
Event sequence: 7 
Event occurrence: 3 
Event detail code: 0 

Application information: 
    Application domain: /LM/W3SVC/2/ROOT/Application/SNCDW-19-129702818025409890 
    Trust level: Full 
    Application Virtual Path: /Application/SNCDW 
    Application Path: D:\Sites\WCF\Application\SNCDW\ 
    Machine name: SALTIIS01 

Process information: 
    Process ID: 1896 
    Process name: w3wp.exe 
    Account name: iisservice 

Request information: 
    Request URL: http://webservicestest/Application/SNCDW/PC.svc 
    Request path: /Application/SNCDW/PC.svc 
    User host address: 10.60.16.79 
    User: js3228 
    Is authenticated: True 
    Authentication Type: Negotiate 
    Thread account name: iisservice 

In the end I had to give the Windows Everyone group read access to that folder to get it to work properly.

Android: How to get a custom View's height and width?

Just got a solution to get height and width of a custom view:

@Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
    super.onSizeChanged(xNew, yNew, xOld, yOld);

    viewWidth = xNew;
    viewHeight = yNew;
}

Its working in my case.

Installing Python packages from local file system folder to virtualenv with pip

I am installing pyfuzzybut is is not in PyPI; it returns the message: No matching distribution found for pyfuzzy.

I tried the accepted answer

pip install  --no-index --find-links=file:///Users/victor/Downloads/pyfuzzy-0.1.0 pyfuzzy

But it does not work either and returns the following error:

Ignoring indexes: https://pypi.python.org/simple Collecting pyfuzzy Could not find a version that satisfies the requirement pyfuzzy (from versions: ) No matching distribution found for pyfuzzy

At last , I have found a simple good way there: https://pip.pypa.io/en/latest/reference/pip_install.html

Install a particular source archive file.
$ pip install ./downloads/SomePackage-1.0.4.tar.gz
$ pip install http://my.package.repo/SomePackage-1.0.4.zip

So the following command worked for me:

pip install ../pyfuzzy-0.1.0.tar.gz.

Hope it can help you.

How do I tell Gradle to use specific JDK version?

Android Studio

File > Project Structure > SDK Location > JDK Location >

/usr/lib/jvm/java-8-openjdk-amd64

GL

Install JDK

Web scraping with Python

Python has good options to scrape the web. The best one with a framework is scrapy. It can be a little tricky for beginners, so here is a little help.
1. Install python above 3.5 (lower ones till 2.7 will work).
2. Create a environment in conda ( I did this).
3. Install scrapy at a location and run in from there.
4. Scrapy shell will give you an interactive interface to test you code.
5. Scrapy startproject projectname will create a framework.
6. Scrapy genspider spidername will create a spider. You can create as many spiders as you want. While doing this make sure you are inside the project directory.


The easier one is to use requests and beautiful soup. Before starting give one hour of time to go through the documentation, it will solve most of your doubts. BS4 offer wide range of parsers that you can opt for. Use user-agent and sleep to make scraping easier. BS4 returns a bs.tag so use variable[0]. If there is js running, you wont be able to scrape using requests and bs4 directly. You could get the api link then parse the JSON to get the information you need or try selenium.