Programs & Examples On #Windows scripting

Windows Scripting refers to any of the various scripting technologies that ship with Microsoft Windows products.

PSEXEC, access denied errors

The following worked, but only after I upgraded PSEXEC to 2.1 from Microsoft.

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System] "LocalAccountTokenFilterPolicy"=dword:00000001 See: http://forum.sysinternals.com/topic10924.html

I had a slightly older version that didn't work. I used it to do some USMT work via Dell kace, worked a treat :)

How to stop a vb script running in windows

Create a Name.bat file that has the following line in it.

taskkill /F /IM wscript.exe /T

Be sure not to overpower your processor. If you're running long scripts, your processor speed changes and script lines will override each other.

How do I execute cmd commands through a batch file?

This fixes some issues with Blorgbeard's answer (but is untested):

@echo off
cd /d "c:\Program files\IIS Express"
start "" iisexpress /path:"C:\FormsAdmin.Site" /port:8088 /clr:v2.0
timeout 10
start http://localhost:8088/default.aspx
pause

Delete specific line number(s) from a text file using sed?

If you want to delete lines 5 through 10 and 12:

sed -e '5,10d;12d' file

This will print the results to the screen. If you want to save the results to the same file:

sed -i.bak -e '5,10d;12d' file

This will back the file up to file.bak, and delete the given lines.

Note: Line numbers start at 1. The first line of the file is 1, not 0.

Reading Email using Pop3 in C#

I wouldn't recommend OpenPOP. I just spent a few hours debugging an issue - OpenPOP's POPClient.GetMessage() was mysteriously returning null. I debugged this and found it was a string index bug - see the patch I submitted here: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778. It was difficult to find the cause since there are empty catch{} blocks that swallow exceptions.

Also, the project is mostly dormant... the last release was in 2004.

For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.

Hibernate: flush() and commit()

flush(); Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory. It will update or insert into your tables in the running transaction, but it may not commit those changes.

You need to flush in batch processing otherwise it may give OutOfMemoryException.

Commit(); Commit will make the database commit. When you have a persisted object and you change a value on it, it becomes dirty and hibernate needs to flush these changes to your persistence layer. So, you should commit but it also ends the unit of work (transaction.commit()).

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Unfortunately, you need to manually construct the query parameters, because as far as I know, there is no built-in bind method for binding a list to an IN clause, similar to Hibernate's setParameterList(). However, you can accomplish the same with the following:

Python 3:

args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)' 
in_p=', '.join(list(map(lambda x: '%s', args)))
sql = sql % in_p
cursor.execute(sql, args)

Python 2:

args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)' 
in_p=', '.join(map(lambda x: '%s', args))
sql = sql % in_p
cursor.execute(sql, args)

Is using 'var' to declare variables optional?

I just found the answer from a forum referred by one of my colleague. If you declare a variable outside a function, it's always global. No matter if you use var keyword or not. But, if you declare the variable inside a function, it has a big difference. Inside a function, if you declare the variable using var keyword, it will be local, but if you declare the variable without var keyword, it will be global. It can overwrite your previously declared variables. - See more at: http://forum.webdeveloperszone.com/question/what-is-the-difference-between-using-var-keyword-or-not-using-var-during-variable-declaration/#sthash.xNnLrwc3.dpuf

Is it possible to use jQuery .on and hover?

$("#MyTableData").on({

 mouseenter: function(){

    //stuff to do on mouse enter
    $(this).css({'color':'red'});

},
mouseleave: function () {
    //stuff to do on mouse leave
    $(this).css({'color':'blue'});

}},'tr');

Kotlin Ternary Conditional Operator

You can do something like this:

val ans = (exp1 == exp2) then "yes" ?: "no"

by using this extension:

infix fun<T> Boolean.then(first: T): T? = if (this) first else null

P.S: Dont modify above infix function to accept first: T?, the expression will become logically incorrect. Eg: If you modify it to accept nullable first: T?, then val ans = (true == true) then null ?: "abcd", ans will be "abcd", which would not be correct.

Is it possible to move/rename files in Git and maintain their history?

git log --follow [file]

will show you the history through renames.

MySQL's now() +1 day

INSERT INTO `table` ( `data` , `date` ) VALUES('".$data."',NOW()+INTERVAL 1 DAY);

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

It was fixed this kind of error after migrate to AndroidX

  • Go to Refactor ---> Migrate to AndroidX

No more data to read from socket error

For errors like this you should involve oracle support. Unfortunately you do not mention what oracle release you are using. The error can be related to optimizer bind peeking. Depending on the oracle version different workarounds apply.

You have two ways to address this:

  • upgrade to 11.2
  • set oracle parameter _optim_peek_user_binds = false

Of course underscore parameters should only be set if advised by oracle support

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

You must check if result returned by mysql_query is false.

$r = mysql_qyery("...");
if ($r) {
  mysql_fetch_assoc($r);
}

You can use @mysql_fetch_assoc($r) to avoid error displaying.

check output from CalledProcessError

I ran into the same problem and found that the documentation has example for this type of scenario (where we write STDERR TO STDOUT and always exit successfully with return code 0) without causing/catching an exception.

output = subprocess.check_output("ping -c 2 -W 2 1.1.1.1; exit 0", stderr=subprocess.STDOUT, shell=True)

Now, you can use standard string function find to check the output string output.

How to make the checkbox unchecked by default always

Well I guess you can use checked="false". That is the html way to leave a checkbox unchecked. You can refer to http://www.w3schools.com/jsref/dom_obj_checkbox.asp.

how to save and read array of array in NSUserdefaults in swift?

Try this.

To get the data from the UserDefaults.

var defaults = NSUserDefaults.standardUserDefaults()
var dict : NSDictionary = ["key":"value"]
var array1: NSArray = dict.allValues // Create a dictionary and assign that to this array
defaults.setObject(array1, forkey : "MyKey")

var myarray : NSArray = defaults.objectForKey("MyKey") as NSArray
println(myarray)

How to move (and overwrite) all files from one directory to another?

If you simply need to answer "y" to all the overwrite prompts, try this:

y | mv srcdir/* targetdir/

How to run Python script on terminal?

First of all, you need to move to the location of the file you are trying to execute, so in a Terminal:

cd ~/Documents/python

Now, you should be able to execute your file:

python gameover.py

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

I had the same problem just with switching the background images with reasonable sizes. I got better results with setting the ImageView to null before putting in a new picture.

ImageView ivBg = (ImageView) findViewById(R.id.main_backgroundImage);
ivBg.setImageDrawable(null);
ivBg.setImageDrawable(getResources().getDrawable(R.drawable.new_picture));

DateTimePicker: pick both date and time

Unfortunately, this is one of the many misnomers in the framework, or at best a violation of SRP.

To use the DateTimePicker for times, set the Format property to either Time or Custom (Use Custom if you want to control the format of the time using the CustomFormat property). Then set the ShowUpDown property to true.

Although a user may set the date and time together manually, they cannot use the GUI to set both.

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

If you are receiving that error even after creating a new user and assigning them the database previledges, then the one last thing to look at is to check if the users have been assigned the preiveledges in the database.

To do this log into to your mysql(This is presumably its the application that has restricted access to the database but you as a root can be ablr to access your database table via mysql -u user -p)

commands to apply

mysql -u root -p 

password: (provide your database credentials)

on successful login

type

use mysql;

from this point check each users priveledges if it is enabled from the db table as follows

select User,Grant_priv,Host from db;

if the values of the Grant_priv col for the created user is N update that value to Y with the following command

UPDATE db SET Grant_priv = "Y" WHERE User= "your user";

with that now try accessing the app and making a transaction with the database.

how to display employee names starting with a and then b in sql

What cfengineers said, except it sounds like you will want to sort it as well.

select columns
  from table
 where (
         column like 'a%' 
      or column like 'b%' )
order by column

Perhaps it would be a good idea for you to check out some tutorials on SQL, it's pretty interesting.

Java: How to get input from System.console()

Try this. hope this will help.

    String cls0;
    String cls1;

    Scanner in = new Scanner(System.in);  
    System.out.println("Enter a string");  
    cls0 = in.nextLine();  

    System.out.println("Enter a string");  
    cls1 = in.nextLine(); 

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

Screenshot sizes for publishing android app on Google Play

You can upload up to 8 screenshots. Those screenshots must be one of the dimensions (sizes) you listed; you can have multiple screenshots of the same dimensions.

How to add a line to a multiline TextBox?

Just put a line break into your text.

You don't add lines as a method. Multiline just supports the use of line breaks.

Facebook Android Generate Key Hash

If you are releasing, use the keystore you used to export your app with and not the debug.keystore.

"NOT IN" clause in LINQ to Entities

If you are using an in-memory collection as your filter, it's probably best to use the negation of Contains(). Note that this can fail if the list is too long, in which case you will need to choose another strategy (see below for using a strategy for a fully DB-oriented query).

   var exceptionList = new List<string> { "exception1", "exception2" };

   var query = myEntities.MyEntity
                         .Select(e => e.Name)
                         .Where(e => !exceptionList.Contains(e.Name));

If you're excluding based on another database query using Except might be a better choice. (Here is a link to the supported Set extensions in LINQ to Entities)

   var exceptionList = myEntities.MyOtherEntity
                                 .Select(e => e.Name);

   var query = myEntities.MyEntity
                         .Select(e => e.Name)
                         .Except(exceptionList);

This assumes a complex entity in which you are excluding certain ones depending some property of another table and want the names of the entities that are not excluded. If you wanted the entire entity, then you'd need to construct the exceptions as instances of the entity class such that they would satisfy the default equality operator (see docs).

jQuery - find child with a specific class

I'm not sure if I understand your question properly, but it shouldn't matter if this div is a child of some other div. You can simply get text from all divs with class bgHeaderH2 by using following code:

$(".bgHeaderH2").text();

C++ Best way to get integer division and remainder

On x86 at least, g++ 4.6.1 just uses IDIVL and gets both from that single instruction.

C++ code:

void foo(int a, int b, int* c, int* d)
{
  *c = a / b;
  *d = a % b;
}

x86 code:

__Z3fooiiPiS_:
LFB4:
    movq    %rdx, %r8
    movl    %edi, %edx
    movl    %edi, %eax
    sarl    $31, %edx
    idivl   %esi
    movl    %eax, (%r8)
    movl    %edx, (%rcx)
    ret

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

In my case, boolean values in my Python dict were the problem. JSON boolean values are in lowercase ("true", "false") whereas in Python they are in Uppercase ("True", "False"). Couldn't find this solution anywhere online but hope it helps.

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

How to finish current activity in Android

I tried using this example but it failed miserably. Every time I use to invoke finish()/ finishactivity() inside a handler, I end up with this menacing java.lang.IllegalAccess Exception. i'm not sure how did it work for the one who posed the question.

Instead the solution I found was that create a method in your activity such as

void kill_activity()
{ 
    finish();
}

Invoke this method from inside the run method of the handler. This worked like a charm for me. Hope this helps anyone struggling with "how to close an activity from a different thread?".

Radio Buttons ng-checked with ng-model

I solved my problem simply using ng-init for default selection instead of ng-checked

<div ng-init="person.billing=FALSE"></div>
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" ng-value="FALSE" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" ng-value="TRUE" />

Change MySQL root password in phpMyAdmin

Explain what video describe to resolve problem

After Changing Password of root (Mysql Account). Accessing to phpmyadmin page will be denied because phpMyAdmin use root/''(blank) as default username/password. To resolve this problem, you need to reconfig phpmyadmin. Edit file config.inc.php in folder %wamp%\apps\phpmyadmin4.1.14 (Not in %wamp%)

$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'changed';
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;

If you have more than 1 DB server, add "i++" to file and continue add new config as above

React Native Change Default iOS Simulator Device

I had an issue with XCode 10.2 specifying the correct iOS simulator version number, so used:

react-native run-ios --simulator='iPhone X (com.apple.CoreSimulator.SimRuntime.iOS-12-1)'

Visual Studio Copy Project

The best way is actually to create a new Project from scratch, then go into the folder with the project files you want to copy over (project, form1, everything except folders). Rename the files (Except for form1 files) for example: I copied Ch4Ex1 files into my Ch4Ex2 project but first renamed the files to Ch4Ex2. Copy and paste those files into the Solution Explorer for the new project in Visual Studio. Then just overwrite the files and you should be good to go!

Old thread but I hope it helps anyone looking for this answer!

How to fix apt-get: command not found on AWS EC2?

Try replacing apt-get with yum as Amazon Linux based AMI uses the yum command instead of apt-get.

Seaborn plots not showing up

To tell from the style of your code snippet, I suppose you were using IPython rather than Jupyter Notebook.

In this issue on GitHub, it was made clear by a member of IPython in 2016 that the display of charts would only work when "only work when it's a Jupyter kernel". Thus, the %matplotlib inline would not work.

I was just having the same issue and suggest you use Jupyter Notebook for the visualization.

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

This will do the work either for Kotlin or Java project.

Step 1 - Locate build.gradle(Module:app) under the Gradle Scripts

Step 2 - add multiDexEnabled true see below:

    compileSdkVersion 29

    defaultConfig {
        applicationId "com.example.appname"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //addded
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

Step 3 - add the multidex dependency

dependencies {
implementation 'com.android.support:multidex:2.0.0' //added
}

Finally, sync your project.. Enjoy!

The openssl extension is required for SSL/TLS protection

I just add this because it worked for me, i install composer with the developer option activate (just check the box in the installer)

https://getcomposer.org/Composer-Setup.exe

I think this problem may occurs when you add a new version of php to your wamp server. If you do this, you have to check if the extension_dir variable is configure to "env".

Then check if the php_openssl.dll exist in your phpx.x/ext folder. If there is not php_openssl.dll, you have to download it here : http://www.telecharger-dll.fr/dll-php_openssl.dll.html

If it still not working, check if your apache server use the good php.ini file by running the following cmd command :

php --ini

Configuration File (php.ini) Path: C:\Windows
Loaded Configuration File:         C:\wamp64\bin\php\php7.4.7x64\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

If the loaded configuration file return (none), you have to check your appache/apache2.4.41/conf/httpd.conf file is configure with the proper phpIniDir and the correct module.

It must be something like this :

PHPIniDir "${APACHE_DIR}/bin"
LoadModule php7_module "${INSTALL_DIR}/bin/php/php7.4.7x64/php7apache2_4.dll"

Then restart apache and check the "apache/apache2.4.41/bin/php.ini" (wich is the one configure above by PHPIniDir) it must me like

enter image description here

Set focus on textbox in WPF

try FocusManager.SetFocusedElement

FocusManager.SetFocusedElement(parentElement, txtCompanyID)

How do I convert a Python program to a runnable .exe Windows program?

I've used py2exe in the past and have been very happy with it. I didn't particularly enjoy using cx-freeze as much, though

How to split a string into a list?

shlex has a .split() function. It differs from str.split() in that it does not preserve quotes and treats a quoted phrase as a single word:

>>> import shlex
>>> shlex.split("sudo echo 'foo && bar'")
['sudo', 'echo', 'foo && bar']

NB: it works well for Unix-like command line strings. It doesn't work for natural-language processing.

Fastest way to convert JavaScript NodeList to Array?

With ES6, we now have a simple way to create an Array from a NodeList: the Array.from() function.

// nl is a NodeList
let myArray = Array.from(nl)

How can I read user input from the console?

Sometime in the future .NET4.6

//for Double
double inputValues = double.Parse(Console.ReadLine());

//for Int
int inputValues = int.Parse(Console.ReadLine());

Inserting created_at data with Laravel

In your User model, add the following line in the User class:

public $timestamps = true;

Now, whenever you save or update a user, Laravel will automatically update the created_at and updated_at fields.


Update:
If you want to set the created at manually you should use the date format Y-m-d H:i:s. The problem is that the format you have used is not the same as Laravel uses for the created_at field.

Update: Nov 2018 Laravel 5.6 "message": "Access level to App\\Note::$timestamps must be public", Make sure you have the proper access level as well. Laravel 5.6 is public.

Getting all types in a namespace via reflection

You won't be able to get all types in a namespace, because a namespace can bridge multiple assemblies, but you can get all classes in an assembly and check to see if they belong to that namespace.

Assembly.GetTypes() works on the local assembly, or you can load an assembly first then call GetTypes() on it.

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

You have to load the url helper to access that function. Either you add

$this->load->helper('url');

somewhere in your controller.

Alternately, to have it be loaded automatically everywhere, make sure the line in application/config/autoload.php that looks like

$autoload['helper'] = array('url');

has 'url' in that array (as shown above).

setState() inside of componentDidUpdate()

The componentDidUpdate signature is void::componentDidUpdate(previousProps, previousState). With this you will be able to test which props/state are dirty and call setState accordingly.

Example:

componentDidUpdate(previousProps, previousState) {
    if (previousProps.data !== this.props.data) {
        this.setState({/*....*/})
    }
}

What is the difference between a field and a property?

Technically, i don't think that there is a difference, because properties are just wrappers around fields created by the user or automatically created by the compiler.The purpose of properties is to enforce encapsuation and to offer a lightweight method-like feature. It's just a bad practice to declare fields as public, but it does not have any issues.

Hide separator line on one UITableViewCell

my develop environment is

  • Xcode 7.0
  • 7A220 Swift 2.0
  • iOS 9.0

above answers not fully work for me

after try, my finally working solution is:

let indent_large_enought_to_hidden:CGFloat = 10000
cell.separatorInset = UIEdgeInsetsMake(0, indent_large_enought_to_hidden, 0, 0) // indent large engough for separator(including cell' content) to hidden separator
cell.indentationWidth = indent_large_enought_to_hidden * -1 // adjust the cell's content to show normally
cell.indentationLevel = 1 // must add this, otherwise default is 0, now actual indentation = indentationWidth * indentationLevel = 10000 * 1 = -10000

and the effect is: enter image description here

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

I had the same problem as you though I have followed a different guide: http://www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/

The strange part is that, in this guide I have used, I should not have any problem with compatibility between versions (1.x against 2.x) because following the guide you use the jersey 1.8.x on pom.xmland in the web.xmlyou refer to a class (com.sun.jersey.spi.container.servlet.ServletContainer) as said before of 1.x version. So as I can infer this should be working.

My guess is because I'm using JDK 1.7 this class does not exist anymore.


After, I tried to resolve with the answers before mine, did not helped, I have made changes on the pom.xmland on the web.xml the error changed to: java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer

Which supposedly should be exist!

As result of this error, I found a "new" solution: http://marek.potociar.net/2013/06/13/jax-rs-2-0-and-jersey-2-0-released/

With Maven (archetypes), generate a jersey project, likes this:

mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.0

And it worked for me! :)

Error in contrasts when defining a linear model in R

If the error happens to be because your data has NAs, then you need to set the glm() function options of how you would like to treat the NA cases. More information on this is found in a relevant post here: https://stats.stackexchange.com/questions/46692/how-the-na-values-are-treated-in-glm-in-r

Setting Remote Webdriver to run tests in a remote computer using Java

This is how I got rid of the error:

WebDriverException: Error forwarding the new session cannot find : {platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=11}

In your nodeconfig.json, the version must be a String, not an integer.

So instead of using "version": 11 use "version": "11" (note the double quotes).

A full example of a working nodecondig.json file for a RemoteWebDriver:

{
  "capabilities":
  [
    {
      "platform": "WIN8_1",
      "browserName": "internet explorer",
      "maxInstances": 1,
      "seleniumProtocol": "WebDriver"
      "version": "11"
    }
    ,{
      "platform": "WIN7",
      "browserName": "chrome",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "40"
    }
    ,{
      "platform": "LINUX",
      "browserName": "firefox",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "33"
    }
  ],
  "configuration":
  {
    "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
    "maxSession": 3,
    "port": 5555,
    "host": ip,
    "register": true,
    "registerCycle": 5000,
    "hubPort": 4444,
    "hubHost": {your-ip-address}
  }
}

Converting JSON to XLS/CSV in Java

you can use commons csv to convert into CSV format. or use POI to convert into xls. if you need helper to convert into xls, you can use jxls, it can convert java bean (or list) into excel with expression language.

Basically, the json doc maybe is a json array, right? so it will be same. the result will be list, and you just write the property that you want to display in excel format that will be read by jxls. See http://jxls.sourceforge.net/reference/collections.html

If the problem is the json can't be read in the jxls excel property, just serialize it into collection of java bean first.

Read text file into string. C++ ifstream

It looks like you are trying to parse each line. You've been shown by another answer how to use getline in a loop to seperate each line. The other tool you are going to want is istringstream, to seperate each token.

std::string line;
while(std::getline(file, line))
{
    std::istringstream iss(line);
    std::string token;
    while (iss >> token)
    {
        // do something with token
    }
}

How to make Apache serve index.php instead of index.html?

PHP will work only on the .php file extension.

If you are on Apache you can also set, in your httpd.conf file, the extensions for PHP. You'll have to find the line:

AddType application/x-httpd-php .php .html
                                     ^^^^^

and add how many extensions, that should be read with the PHP interpreter, as you want.

How to write unit testing for Angular / TypeScript for private methods with Jasmine

Do not write tests for private methods. This defeats the point of unit tests.

  • You should be testing the public API of your class
  • You should NOT be testing the implimentation details of your class

Example

class SomeClass {

  public addNumber(a: number, b: number) {
      return a + b;
  }
}

The test for this method should not need to change if later the implementation changes but the behaviour of the public API remains the same.

class SomeClass {

  public addNumber(a: number, b: number) {
      return this.add(a, b);
  }

  private add(a: number, b: number) {
       return a + b;
  }
}

Don't make methods and properties public just in order to test them. This usually means that either:

  1. You are trying to test implementation rather than API (public interface).
  2. You should move the logic in question into its own class to make testing easier.

Losing scope when using ng-include

I've figured out how to work around this issue without mixing parent and sub scope data. Set a ng-if on the the ng-include element and set it to a scope variable. For example :

<div ng-include="{{ template }}" ng-if="show"/>

In your controller, when you have set all the data you need in your sub scope, then set show to true. The ng-include will copy at this moment the data set in your scope and set it in your sub scope.

The rule of thumb is to reduce scope data deeper the scope are, else you have this situation.

Max

When to use Common Table Expression (CTE)

I use them to break up complex queries, especially complex joins and sub-queries. I find I'm using them more and more as 'pseudo-views' to help me get my head around the intent of the query.

My only complaint about them is they cannot be re-used. For example, I may have a stored proc with two update statements that could use the same CTE. But the 'scope' of the CTE is the first query only.

Trouble is, 'simple examples' probably don't really need CTE's!

Still, very handy.

The differences between initialize, define, declare a variable

For C, at least, per C11 6.7.5:

A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:

  • for an object, causes storage to be reserved for that object;

  • for a function, includes the function body;

  • for an enumeration constant, is the (only) declaration of the identifier;

  • for a typedef name, is the first (or only) declaration of the identifier.

Per C11 6.7.9.8-10:

An initializer specifies the initial value stored in an object ... if an object that has automatic storage is not initialized explicitly, its value is indeterminate.

So, broadly speaking, a declaration introduces an identifier and provides information about it. For a variable, a definition is a declaration which allocates storage for that variable.

Initialization is the specification of the initial value to be stored in an object, which is not necessarily the same as the first time you explicitly assign a value to it. A variable has a value when you define it, whether or not you explicitly give it a value. If you don't explicitly give it a value, and the variable has automatic storage, it will have an initial value, but that value will be indeterminate. If it has static storage, it will be initialized implicitly depending on the type (e.g. pointer types get initialized to null pointers, arithmetic types get initialized to zero, and so on).

So, if you define an automatic variable without specifying an initial value for it, such as:

int myfunc(void) {
    int myvar;
    ...

You are defining it (and therefore also declaring it, since definitions are declarations), but not initializing it. Therefore, definition does not equal declaration plus initialization.

How can I configure Logback to log different levels for a logger to different destinations?

Solution based on configuration only, with a ThresoldFilter and LevelFilters to keep things really simple to understand :

<configuration>
    <appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
        <target>System.err</target>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
          <level>WARN</level>
        </filter>
        <encoder>
            <pattern>%date %level [%thread] %logger %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <target>System.out</target>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
          <level>DEBUG</level>
          <onMatch>ACCEPT</onMatch>
        </filter>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
          <level>INFO</level>
          <onMatch>ACCEPT</onMatch>
        </filter>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
          <level>TRACE</level>
          <onMatch>ACCEPT</onMatch>
        </filter>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
          <level>WARN</level>
          <onMatch>DENY</onMatch>
        </filter>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
          <level>ERROR</level>
          <onMatch>DENY</onMatch>
        </filter>
        <encoder>
            <pattern>%date %level [%thread] %logger %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="STDERR" />
    </root>
</configuration>

Java integer list

Let's use some java 8 feature:

IntStream.iterate(10, x -> x + 10).limit(5)
  .forEach(System.out::println);

If you need to store the numbers you can collect them into a collection eg:

List numbers = IntStream.iterate(10, x -> x + 10).limit(5)
  .boxed()
  .collect(Collectors.toList());

And some delay added:

IntStream.iterate(10, x -> x + 10).limit(5)
  .forEach(x -> {
    System.out.println(x);
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      // Do something with the exception
    }  
  });

VueJS conditionally add an attribute for an element

Try:

<input :required="test ? true : false">

How to set Internet options for Android emulator?

On a slightly different note, I had to make a virtual device without GSM Modem Support so that the internet on my emulator would work.

Compiling/Executing a C# Source File in Command Prompt

You can compile a C# program :

c: > csc Hello.cs

You can run the program

c: > Hello

Attach the Source in Eclipse of a jar

  1. Download JDEclipse from http://java-decompiler.github.io/
  2. Follow the installation steps
  3. If you still didn't find the source, right click on the jar file and select "Attach Library Source" option from the project folder, as you can see below.

Drop down option location

How much data / information can we save / store in a QR code?

See this table.

A 101x101 QR code, with high level error correction, can hold 3248 bits, or 406 bytes. Probably not enough for any meaningful SVG/XML data.

A 177x177 grid, depending on desired level of error correction, can store between 1273 and 2953 bytes. Maybe enough to store something small.

enter image description here

cursor.fetchall() vs list(cursor) in Python

You could use list comprehensions to bring the item in your tuple into a list:

conn = mysql.connector.connect()
cursor = conn.cursor()
sql = "SELECT column_name FROM db.table_name;"
cursor.execute(sql)

results = cursor.fetchall()
# bring the first item of the tuple in your results here
item_0_in_result = [_[0] for _ in results]

How to move a file?

  import os,shutil

  current_path = "" ## source path

  new_path = "" ## destination path

  os.chdir(current_path)

  for files in os.listdir():

        os.rename(files, new_path+'{}'.format(f))
        shutil.move(files, new_path+'{}'.format(f)) ## to move files from 

different disk ex. C: --> D:

How to set timer in android?

If one just want to schedule a countdown until a time in the future with regular notifications on intervals along the way, you can use the CountDownTimer class that is available since API level 1.

new CountDownTimer(30000, 1000) {
    public void onTick(long millisUntilFinished) {
        editText.setText("Seconds remaining: " + millisUntilFinished / 1000);
    }

    public void onFinish() {
        editText.setText("Done");
    }
}.start();

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

You have two records in your json file, and json.loads() is not able to decode more than one. You need to do it record by record.

See Python json.loads shows ValueError: Extra data

OR you need to reformat your json to contain an array:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

would be acceptable again. But there cannot be several top level objects.

HttpURLConnection timeout settings

I could get solution for such a similar problem with addition of a simple line

HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");

My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.

Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.

How to generate an MD5 file hash in JavaScript?

CryptoJS is a crypto library which can generate md5 hash among others:

Usage with Script tag:

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/md5.js"></script>
<script>
   var hash = CryptoJS.MD5("Message");
   alert(hash);
</script>

Alternatively with ES6:

npm install crypto-js

import MD5 from "crypto-js/md5";
console.log(MD5("Message").toString());

You can also use modular imports:

var MD5 = require("crypto-js/md5");
console.log(MD5("Message").toString());

Github: https://github.com/brix/crypto-js

CDN: https://cdnjs.com/libraries/crypto-js

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

I have Samsung Galaxy S3 and it was not showing in the "Remote devices" tab nor in chrome://inspect. The device did show in Windows's Device Manager as GT-I9300, though. What worked for me was:

  1. Plug the mobile phone to the front USB port
  2. On my phone, click the notification about successful connection
  3. Make sure the connection type is Camera (PTP)
  4. On my Windows machine, download installer from https://github.com/koush/UniversalAdbDriver
  5. Run it :)
  6. Open cmd.exe
  7. cd "C:\Program Files (x86)\ClockworkMod\Universal Adb Driver"
  8. adb devices
  9. Open Chrome in both mobile phone and Windows machine
  10. On Windows's machine navigate to chrome://inspect - there, after a while you should see the target phone :)

I'm not sure if it affected the whole flow somehow, but at some point I've installed, and later uninstalled the drivers from Samsung: http://www.samsung.com/us/support/downloads/ > Mobile > Phones > Galaxy S > S III > Unlocked > http://www.samsung.com/us/support/owners/product/galaxy-s-iii-unlocked#downloads

How can I force browsers to print background images in CSS?

Make sure to use the !important attribute. This dramatically increases the likelihood your styles are retained when printed.

#example1 {
    background:url(image.png) no-repeat !important;
}

#example2 {
    background-color: #123456 !important;
}

Counting Line Numbers in Eclipse

I think if you have MyEclipse, it adds a label to the Project Properties page which contains the total number of source code lines. Might not help you as MyEclipse is not free though.

Unfortunately, that wasn't enough in my case so I wrote a source analyzer to gather statistics not gathered by other solutions (for example the metrics mentioned by AlbertoPL).

Call PHP function from jQuery?

AJAX does the magic:

$(document).ready(function(

    $.ajax({ url: 'script.php?argument=value&foo=bar' });

));

Folder is locked and I can't unlock it

I had this problem where I couldn't unlock a file from the client side. I decided to go to the sever side which was much simpler.

On SVN Server:

Locate locks

 svnadmin lslocks /root/of/repo
 (in my case it was var/www/svn/[name of Company])

 You can add a specific path to this by svnadmin lslocks /root/of/repo "path/to/file"

Remove lock

 svnadmin rmlocks /root/of/repo “path/to/file” 

That's it!

pandas get rows which are NOT in other dataframe

This is the best way to do it:

df = df1.drop_duplicates().merge(df2.drop_duplicates(), on=df2.columns.to_list(), 
                   how='left', indicator=True)
df.loc[df._merge=='left_only',df.columns!='_merge']

Note that drop duplicated is used to minimize the comparisons. It would work without them as well. The best way is to compare the row contents themselves and not the index or one/two columns and same code can be used for other filters like 'both' and 'right_only' as well to achieve similar results. For this syntax dataframes can have any number of columns and even different indices. Only the columns should occur in both the dataframes.

Why this is the best way?

  1. index.difference only works for unique index based comparisons
  2. pandas.concat() coupled with drop_duplicated() is not ideal because it will also get rid of the rows which may be only in the dataframe you want to keep and are duplicated for valid reasons.

How to sort a data frame by alphabetic order of a character variable in R?

#sort dataframe by col
sort.df <- with(df,  df[order(sortbythiscolumn) , ])

#can also sort by more than one variable: sort by col1 and then by col2
sort2.df <- with(df, df[order(col1, col2) , ])

#sort in reverse order
sort2.df <- with(df, df[order(col1, -col2) , ])

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

Copy the downloaded DLL file in a custom folder on your dev drive, then add the reference to your project using the Browse button in the Add Reference dialog.
Be sure that the new reference has the Copy Local = True.
The Add Reference dialog could be opened right-clicking on the References item in your project in Solution Explorer

UPDATE AFTER SOME YEARS
At the present time the best way to resolve all those problems is through the
Manage NuGet packages menu command of Visual Studio 2017/2019.
You can right click on the References node of your project and select that command. From the Browse tab search for the library you want to use in the NuGet repository, click on the item if found and then Install it. (Of course you need to have a package for that DLL and this is not guaranteed to exist)

Read about NuGet here

'numpy.float64' object is not iterable

numpy.linspace() gives you a one-dimensional NumPy array. For example:

>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

Therefore:

for index,point in my_array

cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:

>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])

Now you can do this:

>>> for x, y in two_d:
    print(x, y)

1 2
4 5

JavaScript error: "is not a function"

For more generic advice on debugging this kind of problem MDN have a good article TypeError: "x" is not a function:

It was attempted to call a value like a function, but the value is not actually a function. Some code expects you to provide a function, but that didn't happen.

Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript objects have no map function, but JavaScript Array object do.

Basically the object (all functions in js are also objects) does not exist where you think it does. This could be for numerous reasons including(not an extensive list):

  • Missing script library
  • Typo
  • The function is within a scope that you currently do not have access to, e.g.:

_x000D_
_x000D_
var x = function(){_x000D_
   var y = function() {_x000D_
      alert('fired y');_x000D_
   }_x000D_
};_x000D_
    _x000D_
//the global scope can't access y because it is closed over in x and not exposed_x000D_
//y is not a function err triggered_x000D_
x.y();
_x000D_
_x000D_
_x000D_

  • Your object/function does not have the function your calling:

_x000D_
_x000D_
var x = function(){_x000D_
   var y = function() {_x000D_
      alert('fired y');_x000D_
   }_x000D_
};_x000D_
    _x000D_
//z is not a function error (as above) triggered_x000D_
x.z();
_x000D_
_x000D_
_x000D_

How to do a case sensitive search in WHERE clause (I'm using SQL Server)?

use Latin1_General_CS as your collation in your sql db

Where to place $PATH variable assertions in zsh?

Here is the docs from the zsh man pages under STARTUP/SHUTDOWN FILES section.

   Commands  are  first  read from /etc/zshenv this cannot be overridden.
   Subsequent behaviour is modified by the RCS and GLOBAL_RCS options; the
   former  affects all startup files, while the second only affects global
   startup files (those shown here with an path starting with  a  /).   If
   one  of  the  options  is  unset  at  any point, any subsequent startup
   file(s) of the corresponding type will not be read.  It is also  possi-
   ble  for  a  file  in  $ZDOTDIR  to  re-enable GLOBAL_RCS. Both RCS and
   GLOBAL_RCS are set by default.

   Commands are then read from $ZDOTDIR/.zshenv.  If the shell is a  login
   shell,  commands  are  read from /etc/zprofile and then $ZDOTDIR/.zpro-
   file.  Then, if the  shell  is  interactive,  commands  are  read  from
   /etc/zshrc  and then $ZDOTDIR/.zshrc.  Finally, if the shell is a login
   shell, /etc/zlogin and $ZDOTDIR/.zlogin are read.

From this we can see the order files are read is:

/etc/zshenv    # Read for every shell
~/.zshenv      # Read for every shell except ones started with -f
/etc/zprofile  # Global config for login shells, read before zshrc
~/.zprofile    # User config for login shells
/etc/zshrc     # Global config for interactive shells
~/.zshrc       # User config for interactive shells
/etc/zlogin    # Global config for login shells, read after zshrc
~/.zlogin      # User config for login shells
~/.zlogout     # User config for login shells, read upon logout
/etc/zlogout   # Global config for login shells, read after user logout file

You can get more information here.

Break when a value changes using the Visual Studio debugger

Update in 2019:

This is now officially supported in Visual Studio 2019 Preview 2 for .Net Core 3.0 or higher. Of course, you may have to put some thoughts in potential risks of using a Preview version of IDE. I imagine in the near future this will be included in the official Visual Studio.

https://blogs.msdn.microsoft.com/visualstudio/2019/02/12/break-when-value-changes-data-breakpoints-for-net-core-in-visual-studio-2019/

Fortunately, data breakpoints are no longer a C++ exclusive because they are now available for .NET Core (3.0 or higher) in Visual Studio 2019 Preview 2!

Understanding ibeacon distancing

iBeacon uses Bluetooth Low Energy(LE) to keep aware of locations, and the distance/range of Bluetooth LE is 160ft (http://en.wikipedia.org/wiki/Bluetooth_low_energy).

What is the difference between Python and IPython?

IPython is basically the "recommended" Python shell, which provides extra features. There is no language called IPython.

How to convert array into comma separated string in javascript

The method array.toString() actually calls array.join() which result in a string concatenated by commas. ref

_x000D_
_x000D_
var array = ['a','b','c','d','e','f'];_x000D_
document.write(array.toString()); // "a,b,c,d,e,f"
_x000D_
_x000D_
_x000D_

Also, you can implicitly call Array.toString() by making javascript coerce the Array to an string, like:

//will implicitly call array.toString()
str = ""+array;
str = `${array}`;

Array.prototype.join()

The join() method joins all elements of an array into a string.

Arguments:

It accepts a separator as argument, but the default is already a comma ,

str = arr.join([separator = ','])

Examples:

var array = ['A', 'B', 'C'];
var myVar1 = array.join();      // 'A,B,C'
var myVar2 = array.join(', ');  // 'A, B, C'
var myVar3 = array.join(' + '); // 'A + B + C'
var myVar4 = array.join('');    // 'ABC'

Note:

If any element of the array is undefined or null , it is treated as an empty string.

Browser support:

It is available pretty much everywhere today, since IE 5.5 (1999~2000).

References

Regarding Java switch statements - using return and omitting breaks in each case

Assigning a value to a local variable and then returning that at the end is considered a good practice. Methods having multiple exits are harder to debug and can be difficult to read.

That said, thats the only plus point left to this paradigm. It was originated when only low-level procedural languages were around. And it made much more sense at that time.

While we are on the topic you must check this out. Its an interesting read.

gridview data export to excel in asp.net

I don't there there is any DataSource for the gridview
Though you have DataBind in your code as

gvdetails.DataBind(); 

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

A comparison between the different Visual Studio Express editions can be found at Visual Studio Express (archive.org link). The difference between Windows and Windows Desktop is that with the Windows edition you can build Windows Store Apps (using .NET, WPF/XAML) while the Windows Desktop edition allows you to write classic Windows Desktop applications. It is possible to install both products on the same machine.

Visual Studio Express 2010 allows you to build Windows Desktop applications. Writing Windows Store applications is not possible with this product.

For learning I would suggest Notepad and the command line. While an IDE provides significant productivity enhancements to professionals, it can be intimidating to a beginner. If you want to use an IDE nevertheless I would recommend Visual Studio Express 2013 for Windows Desktop.


Update 2015-07-27: In addition to the Express Editions, Microsoft now offers Community Editions. These are still free for individual developers, open source contributors, and small teams. There are no Web, Windows, and Windows Desktop releases anymore either; the Community Edition can be used to develop any app type. In addition, the Community Edition does support (3rd party) Add-ins. The Community Edition offers the same functionality as the commercial Professional Edition.

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

What about casting to Number in Javascript using the Unary (+) Operator

lat: 12.23
lat: +12.23

Depends on the use case. Here is a fullchart what works and what not: parseInt vs unary plus - when to use which

When should I use GC.SuppressFinalize()?

SuppressFinalize should only be called by a class that has a finalizer. It's informing the Garbage Collector (GC) that this object was cleaned up fully.

The recommended IDisposable pattern when you have a finalizer is:

public class MyClass : IDisposable
{
    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // called via myClass.Dispose(). 
                // OK to use any private object references
            }
            // Release unmanaged resources.
            // Set large fields to null.                
            disposed = true;
        }
    }

    public void Dispose() // Implement IDisposable
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~MyClass() // the finalizer
    {
        Dispose(false);
    }
}

Normally, the CLR keeps tabs on objects with a finalizer when they are created (making them more expensive to create). SuppressFinalize tells the GC that the object was cleaned up properly and doesn't need to go onto the finalizer queue. It looks like a C++ destructor, but doesn't act anything like one.

The SuppressFinalize optimization is not trivial, as your objects can live a long time waiting on the finalizer queue. Don't be tempted to call SuppressFinalize on other objects mind you. That's a serious defect waiting to happen.

Design guidelines inform us that a finalizer isn't necessary if your object implements IDisposable, but if you have a finalizer you should implement IDisposable to allow deterministic cleanup of your class.

Most of the time you should be able to get away with IDisposable to clean up resources. You should only need a finalizer when your object holds onto unmanaged resources and you need to guarantee those resources are cleaned up.

Note: Sometimes coders will add a finalizer to debug builds of their own IDisposable classes in order to test that code has disposed their IDisposable object properly.

public void Dispose() // Implement IDisposable
{
    Dispose(true);
#if DEBUG
    GC.SuppressFinalize(this);
#endif
}

#if DEBUG
~MyClass() // the finalizer
{
    Dispose(false);
}
#endif

What is the difference between linear regression and logistic regression?

In case of Linear Regression the outcome is continuous while in case of Logistic Regression outcome is discrete (not continuous)

To perform Linear regression we require a linear relationship between the dependent and independent variables. But to perform Logistic regression we do not require a linear relationship between the dependent and independent variables.

Linear Regression is all about fitting a straight line in the data while Logistic Regression is about fitting a curve to the data.

Linear Regression is a regression algorithm for Machine Learning while Logistic Regression is a classification Algorithm for machine learning.

Linear regression assumes gaussian (or normal) distribution of dependent variable. Logistic regression assumes binomial distribution of dependent variable.

Disable browser cache for entire ASP.NET website

I implemented all the previous answers and still had one view that did not work correctly.

It turned out the name of the view I was having the problem with was named 'Recent'. Apparently this confused the Internet Explorer browser.

After I changed the view name (in the controller) to a different name (I chose to 'Recent5'), the solutions above started to work.

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Something that is now available in maven as well is

mvn goal --no-snapshot-updates

or in short

mvn goal -nsu

HTTPS connection Python

If using httplib.HTTPSConnection:

Please take a look at:

Changed in version 2.7.9:

This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter. You can use:

if hasattr(ssl, '_create_unverified_context'):
  ssl._create_default_https_context = ssl._create_unverified_context

How to specify font attributes for all elements on an html web page?

I can't stress this advice enough: use a reset stylesheet, then set everything explicitly. It'll cut your cross-browser CSS development time in half.

Try Eric Meyer's reset.css.

Make columns of equal width in <table>

Use following property same as table and its fully dynamic:

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed; /* optional, for equal spacing */_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid pink;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz klxjgkldjklg </li>_x000D_
  <li>baz</li>_x000D_
  <li>baz lds.jklklds</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

May be its solve your issue.

How to get my activity context?

If you need the context of A in B, you need to pass it to B, and you can do that by passing the Activity A as parameter as others suggested. I do not see much the problem of having the many instances of A having their own pointers to B, not sure if that would even be that much of an overhead.

But if that is the problem, a possibility is to keep the pointer to A as a sort of global, avariable of the Application class, as @hasanghaforian suggested. In fact, depending on what do you need the context for, you could even use the context of the Application instead.

I'd suggest reading this article about context to better figure it out what context you need.

Left align block of equations

You can use \begin{flalign}, like the example bellow:

\begin{flalign}
    &f(x) = -1.25x^{2} + 1.5x&
\end{flalign}

html table span entire width?

<table border="1"; width=100%>

works for me.

How to do multiple arguments to map function where one remains the same in python?

Sometimes I resolved similar situations (such as using pandas.apply method) using closures

In order to use them, you define a function which dynamically defines and returns a wrapper for your function, effectively making one of the parameters a constant.

Something like this:

def add(x, y):
   return x + y

def add_constant(y):
    def f(x):
        return add(x, y)
    return f

Then, add_constant(y) returns a function which can be used to add y to any given value:

>>> add_constant(2)(3)
5

Which allows you to use it in any situation where parameters are given one at a time:

>>> map(add_constant(2), [1,2,3])
[3, 4, 5]

edit

If you do not want to have to write the closure function somewhere else, you always have the possibility to build it on the fly using a lambda function:

>>> map(lambda x: add(x, 2), [1, 2, 3])
[3, 4, 5]

Correct way to integrate jQuery plugins in AngularJS

Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link function of the directive.

There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls

Using controllers correctly

Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.

EDIT: Rather than using $(element), you can make use of angular.element(element) when using AngularJS with jQuery

Google maps API V3 - multiple markers on exact same spot

This is more of a stopgap 'quick and dirty' solution similar to the one Matthew Fox suggests, this time using JavaScript.

In JavaScript you can just offset the lat and long of all of your locations by adding a small random offset to both e.g.

myLocation[i].Latitude+ = (Math.random() / 25000)

(I found that dividing by 25000 gives enough separation but doesn't move the marker significantly from the exact location e.g. a specific address)

This makes a reasonably good job of offsetting them from one another, but only after you've zoomed in closely. When zoomed out, it still won't be clear that there are multiple options for the location.

An error occurred while signing: SignTool.exe not found

Click "Project" at the top. Then click " Properties" -> Signing -> Unchecked [Sign the ClickOnce manifests] is now working

Is it not possible to stringify an Error using JSON.stringify?

As no one is talking about the why part, I'm gonna answer it.

Why this JSON.stringify returns an empty object?

> JSON.stringify(error);
'{}'

Answer

From the document of JSON.stringify(),

For all the other Object instances (including Map, Set, WeakMap and WeakSet), only their enumerable properties will be serialized.

and Error object doesn't have its enumerable properties, that's why it prints an empty object.

Add directives from directive in AngularJS

I wanted to add my solution since the accepted one didn't quite work for me.

I needed to add a directive but also keep mine on the element.

In this example I am adding a simple ng-style directive to the element. To prevent infinite compile loops and allowing me to keep my directive I added a check to see if what I added was present before recompiling the element.

angular.module('some.directive', [])
.directive('someDirective', ['$compile',function($compile){
    return {
        priority: 1001,
        controller: ['$scope', '$element', '$attrs', '$transclude' ,function($scope, $element, $attrs, $transclude) {

            // controller code here

        }],
        compile: function(element, attributes){
            var compile = false;

            //check to see if the target directive was already added
            if(!element.attr('ng-style')){
                //add the target directive
                element.attr('ng-style', "{'width':'200px'}");
                compile = true;
            }
            return {
                pre: function preLink(scope, iElement, iAttrs, controller) {  },
                post: function postLink(scope, iElement, iAttrs, controller) {
                    if(compile){
                        $compile(iElement)(scope);
                    }
                }
            };
        }
    };
}]);

convert date string to mysql datetime field

First, convert the string into a timestamp:

$timestamp = strtotime($string);

Then do a

date("Y-m-d H:i:s", $timestamp);

PHP Function Comments

That's phpDoc syntax.

Read more here: phpDocumentor

Bash script - variable content as a command to run

Your are probably looking for eval $var.

SQL Server 2008 - Help writing simple INSERT Trigger

You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)

So to insert Employee / Department pairs that do not currently exist you might try something like the following.

CREATE TRIGGER trig_Update_Employee
ON [EmployeeResult]
FOR INSERT
AS
Begin
    Insert into Employee (Name, Department) 
    Select Distinct i.Name, i.Department 
    from Inserted i
    Left Join Employee e
    on i.Name = e.Name and i.Department = e.Department
    where e.Name is null
End

Run cmd commands through Java

Try this:

Process runtime = Runtime.getRuntime().exec("cmd /c start notepad++.exe");

Split varchar into separate columns in Oracle

With REGEXP_SUBSTR is as simple as:

SELECT REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 1) col_one,
       REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 2) col_two
FROM YOUR_TABLE t;

How to find most common elements of a list?

There's two standard library ways to find the most frequent value in a list:

statistics.mode:

from statistics import mode
most_common = mode([3, 2, 2, 2, 1, 1])  # 2
most_common = mode([3, 2])  # StatisticsError: no unique mode
  • Raises an exception if there's no unique most frequent value
  • Only returns single most frequent value

collections.Counter.most_common:

from collections import Counter
most_common, count = Counter([3, 2, 2, 2, 1, 1]).most_common(2)  # 2, 3
(most_common_1, count_1), (most_common_2, count_2) = Counter([3, 2, 2]).most_common(2)  # (2, 2), (3, 1)
  • Can return multiple most frequent values
  • Returns element count as well

So in the case of the question, the second one would be the right choice. As a side note, both are identical in terms of performance.

How do you serve a file for download with AngularJS or Javascript?

I didnt want Static Url. I have AjaxFactory for doing all ajax operations. I am getting url from the factory and binding it as follows.

<a target="_self" href="{{ file.downloadUrl + '/' + order.OrderId + '/' + fileName }}" download="{{fileName}}">{{fileName}}</a>

Thanks @AhlemMustapha

How to remove focus around buttons on click

It is work, I hope help you

.btn:focus, .btn:focus:active {
    outline: none;
}

How to correctly save instance state of Fragments in back stack?

This is the way I am using at this moment... it's very complicated but at least it handles all the possible situations. In case anyone is interested.

public final class MyFragment extends Fragment {
    private TextView vstup;
    private Bundle savedState = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.whatever, null);
        vstup = (TextView)v.findViewById(R.id.whatever);

        /* (...) */

        /* If the Fragment was destroyed inbetween (screen rotation), we need to recover the savedState first */
        /* However, if it was not, it stays in the instance from the last onDestroyView() and we don't want to overwrite it */
        if(savedInstanceState != null && savedState == null) {
            savedState = savedInstanceState.getBundle(App.STAV);
        }
        if(savedState != null) {
            vstup.setText(savedState.getCharSequence(App.VSTUP));
        }
        savedState = null;

        return v;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        savedState = saveState(); /* vstup defined here for sure */
        vstup = null;
    }

    private Bundle saveState() { /* called either from onDestroyView() or onSaveInstanceState() */
        Bundle state = new Bundle();
        state.putCharSequence(App.VSTUP, vstup.getText());
        return state;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        /* If onDestroyView() is called first, we can use the previously savedState but we can't call saveState() anymore */
        /* If onSaveInstanceState() is called first, we don't have savedState, so we need to call saveState() */
        /* => (?:) operator inevitable! */
        outState.putBundle(App.STAV, (savedState != null) ? savedState : saveState());
    }

    /* (...) */

}

Alternatively, it is always a possibility to keep the data displayed in passive Views in variables and using the Views only for displaying them, keeping the two things in sync. I don't consider the last part very clean, though.

How to convert date to string and to date again?

tl;dr

How to convert date to string and to date again?

LocalDate.now().toString()

2017-01-23

…and…

LocalDate.parse( "2017-01-23" )

java.time

The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.

Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.

If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;

ISO 8601

Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.

That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse and LocalDate::toString without specifying a formatting pattern.

String s = ld.toString() ;

To parse:

LocalDate ld = LocalDate.parse( s ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

MatPlotLib: Multiple datasets on the same scatter plot

You can also do this easily in Pandas, if your data is represented in a Dataframe, as described here:

http://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html#scatter-plot

Appending the same string to a list of strings in Python

my_list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
my_new_list = [x + string for x in my_list]
print my_new_list

This will print:

['foobar', 'fobbar', 'fazbar', 'funkbar']

Apply formula to the entire column

You may fill the column by double-clicking on the bottom right hand corner of the cell which you want to copy from (the point on the box that you would otherwise drag) and it will be applied to whole column.

NB: This doesn't work if you have the filter applied, nor if there is already something already in the cells below.

GitHub: How to make a fork of public repository private?

The answers are correct but don't mention how to sync code between the public repo and the fork.

Here is the full workflow (we've done this before open sourcing React Native):


First, duplicate the repo as others said (details here):

Create a new repo (let's call it private-repo) via the Github UI. Then:

git clone --bare https://github.com/exampleuser/public-repo.git
cd public-repo.git
git push --mirror https://github.com/yourname/private-repo.git
cd ..
rm -rf public-repo.git

Clone the private repo so you can work on it:

git clone https://github.com/yourname/private-repo.git
cd private-repo
make some changes
git commit
git push origin master

To pull new hotness from the public repo:

cd private-repo
git remote add public https://github.com/exampleuser/public-repo.git
git pull public master # Creates a merge commit
git push origin master

Awesome, your private repo now has the latest code from the public repo plus your changes.


Finally, to create a pull request private repo -> public repo:

Use the GitHub UI to create a fork of the public repo (the small "Fork" button at the top right of the public repo page). Then:

git clone https://github.com/yourname/the-fork.git
cd the-fork
git remote add private_repo_yourname https://github.com/yourname/private-repo.git
git checkout -b pull_request_yourname
git pull private_repo_yourname master
git push origin pull_request_yourname

Now you can create a pull request via the Github UI for public-repo, as described here.

Once project owners review your pull request, they can merge it.

Of course the whole process can be repeated (just leave out the steps where you add remotes).

"No such file or directory" error when executing a binary

I think you're x86-64 install does not have the i386 runtime linker. The ENOENT is probably due to the OS looking for something like /lib/ld.so.1 or similar. This is typically part of the 32-bit glibc runtime, and while I'm not directly familiar with Ubuntu, I would assume they have some sort of 32-bit compatibility package to install. Fortunately gzip only depends on the C library, so that's probably all you'll need to install.

Invalid self signed SSL cert - "Subject Alternative Name Missing"

The Issue

As others have mentioned, the NET::ERR_CERT_COMMON_NAME_INVALID error is occurring because the generated certificate does not include the SAN (subjectAltName) field.

RFC2818 has deprecated falling back to the commonName field since May of 2000. The use of the subjectAltName field has been enforced in Chrome since version 58 (see Chrome 58 deprecations).

OpenSSL accepts x509v3 configuration files to add extended configurations to certificates (see the subjectAltName field for configuration options).


Bash Script

I created a self-signed-tls bash script with straightforward options to make it easy to generate certificate authorities and sign x509 certificates with OpenSSL (valid in Chrome using the subjectAltName field).

The script will guide you through a series of questions to include the necessary information (including the subjectAltName field). You can reference the README.md for more details and options for automation.

Be sure to restart chrome after installing new certificates.

chrome://restart

Other Resources

  • The Docker documentation has a great straightforward example for creating a self-signed certificate authority and signing certificates with OpenSSL.
  • cfssl is also a very robust tool that is widely used and worth checking out.

How to use Macro argument as string literal?

You want to use the stringizing operator:

#define STRING(s) #s

int main()
{
    const char * cstr = STRING(abc); //cstr == "abc"
}

How to check file MIME type with javascript before upload?

As Drake states this could be done with FileReader. However, what I present here is a functional version. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime type and the magic number):

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

For a complete list of mime types see Wikipedia.

For a complete list of magic number see Wikipedia.

How to create a numpy array of all True or all False?

numpy already allows the creation of arrays of all ones or all zeros very easily:

e.g. numpy.ones((2, 2)) or numpy.zeros((2, 2))

Since True and False are represented in Python as 1 and 0, respectively, we have only to specify this array should be boolean using the optional dtype parameter and we are done.

numpy.ones((2, 2), dtype=bool)

returns:

array([[ True,  True],
       [ True,  True]], dtype=bool)

UPDATE: 30 October 2013

Since numpy version 1.8, we can use full to achieve the same result with syntax that more clearly shows our intent (as fmonegaglia points out):

numpy.full((2, 2), True, dtype=bool)

UPDATE: 16 January 2017

Since at least numpy version 1.12, full automatically casts results to the dtype of the second parameter, so we can just write:

numpy.full((2, 2), True)

UIView Infinite 360 degree rotation animation?

This is how I rotate 360 in right direction.

[UIView animateWithDuration:1.0f delay:0.0f options:UIViewAnimationOptionRepeat|UIViewAnimationOptionCurveLinear
                     animations:^{
                         [imageIndView setTransform:CGAffineTransformRotate([imageIndView transform], M_PI-0.00001f)];
                     } completion:nil];

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

You are using an old version of the date picker js. Upgrade datepicker js with latest one.

Replace your bootstrap-datetimepicker.min.js file with this will work..

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.3/js/bootstrap-datetimepicker.min.js"></script>

How to execute Python code from within Visual Studio Code

  1. First you have install an extension called "Code Runner"
  2. After than look at the right top corner of VS Code, you will see the run button and hit this.
  3. And you can see at the bottom of vs code your code is executed.
  4. You can make your own keyboard shortcut for "Code Runner" to speed up your coding.

If '<selector>' is an Angular component, then verify that it is part of this module

In your components.module.ts you should import IonicModule like this:

import { IonicModule } from '@ionic/angular';

Then import IonicModule like this:

  imports: [
    CommonModule,
    IonicModule
  ],

so your components.module.ts will be like this:

import { CommonModule } from '@angular/common';
import {PostComponent} from './post/post.component'
import { IonicModule } from '@ionic/angular';

@NgModule({
  declarations: [PostComponent],
  imports: [
    CommonModule,
    IonicModule
  ],
  exports: [PostComponent]
})
export class ComponentsModule { }```

How to insert a character in a string at a certain position?

If you are using a system where float is expensive (e.g. no FPU) or not allowed (e.g. in accounting) you could use something like this:

    for (int i = 1; i < 100000; i *= 2) {
        String s = "00" + i;
        System.out.println(s.substring(Math.min(2, s.length() - 2), s.length() - 2) + "." + s.substring(s.length() - 2));
    }

Otherwise the DecimalFormat is the better solution. (the StringBuilder variant above won't work with small numbers (<100)

What is the Auto-Alignment Shortcut Key in Eclipse?

Want to format it automatically when you save the file???

then Goto Window > Preferences > Java > Editor > Save Actions

and configure your save actions.

Along with saving, you can format, Organize imports,add modifier ‘final’ where possible etc

Convert IQueryable<> type object to List<T> type?

Then just Select:

var list = source.Select(s=>new { ID = s.ID, Name = s.Name }).ToList();

(edit) Actually - the names could be inferred in this case, so you could use:

var list = source.Select(s=>new { s.ID, s.Name }).ToList();

which saves a few electrons...

How to restrict the selectable date ranges in Bootstrap Datepicker?

With selectable date ranges you might want to use something like this. My solution prevents selecting #from_date bigger than #to_date and changes #to_date startDate every time when user selects new date in #from_date box:

http://bootply.com/74352

JS file:

var startDate = new Date('01/01/2012');
var FromEndDate = new Date();
var ToEndDate = new Date();

ToEndDate.setDate(ToEndDate.getDate()+365);

$('.from_date').datepicker({

    weekStart: 1,
    startDate: '01/01/2012',
    endDate: FromEndDate, 
    autoclose: true
})
    .on('changeDate', function(selected){
        startDate = new Date(selected.date.valueOf());
        startDate.setDate(startDate.getDate(new Date(selected.date.valueOf())));
        $('.to_date').datepicker('setStartDate', startDate);
    }); 
$('.to_date')
    .datepicker({

        weekStart: 1,
        startDate: startDate,
        endDate: ToEndDate,
        autoclose: true
    })
    .on('changeDate', function(selected){
        FromEndDate = new Date(selected.date.valueOf());
        FromEndDate.setDate(FromEndDate.getDate(new Date(selected.date.valueOf())));
        $('.from_date').datepicker('setEndDate', FromEndDate);
    });

HTML:

<input class="from_date" placeholder="Select start date" contenteditable="false" type="text">
<input class="to_date" placeholder="Select end date" contenteditable="false" type="text" 

And do not forget to include bootstrap datepicker.js and .css files aswell.

How do I access an access array item by index in handlebars?

While you are looping in an array with each and if you want to access another array in the context of the current item you do it like this.

Here is the example data.


[
  {
    name: 'foo',
    attr: [ 'boo', 'zoo' ]
  },
  {
    name: 'bar',
    attr: [ 'far', 'zar' ]
  }
]

Here is the handlebars to get the first item in attr array.

{{#each player}}
  <p> {{this.name}} </p>

  {{#with this.attr}}
    <p> {{this.[0]}} </p>
  {{/with}}

{{/each}}

This will output

<p> foo </p>
<p> boo </p>

<p> bar </p>
<p> far </p>

Evaluating a mathematical expression in a string

The reason eval and exec are so dangerous is that the default compile function will generate bytecode for any valid python expression, and the default eval or exec will execute any valid python bytecode. All the answers to date have focused on restricting the bytecode that can be generated (by sanitizing input) or building your own domain-specific-language using the AST.

Instead, you can easily create a simple eval function that is incapable of doing anything nefarious and can easily have runtime checks on memory or time used. Of course, if it is simple math, than there is a shortcut.

c = compile(stringExp, 'userinput', 'eval')
if c.co_code[0]==b'd' and c.co_code[3]==b'S':
    return c.co_consts[ord(c.co_code[1])+ord(c.co_code[2])*256]

The way this works is simple, any constant mathematic expression is safely evaluated during compilation and stored as a constant. The code object returned by compile consists of d, which is the bytecode for LOAD_CONST, followed by the number of the constant to load (usually the last one in the list), followed by S, which is the bytecode for RETURN_VALUE. If this shortcut doesn't work, it means that the user input isn't a constant expression (contains a variable or function call or similar).

This also opens the door to some more sophisticated input formats. For example:

stringExp = "1 + cos(2)"

This requires actually evaluating the bytecode, which is still quite simple. Python bytecode is a stack oriented language, so everything is a simple matter of TOS=stack.pop(); op(TOS); stack.put(TOS) or similar. The key is to only implement the opcodes that are safe (loading/storing values, math operations, returning values) and not unsafe ones (attribute lookup). If you want the user to be able to call functions (the whole reason not to use the shortcut above), simple make your implementation of CALL_FUNCTION only allow functions in a 'safe' list.

from dis import opmap
from Queue import LifoQueue
from math import sin,cos
import operator

globs = {'sin':sin, 'cos':cos}
safe = globs.values()

stack = LifoQueue()

class BINARY(object):
    def __init__(self, operator):
        self.op=operator
    def __call__(self, context):
        stack.put(self.op(stack.get(),stack.get()))

class UNARY(object):
    def __init__(self, operator):
        self.op=operator
    def __call__(self, context):
        stack.put(self.op(stack.get()))


def CALL_FUNCTION(context, arg):
    argc = arg[0]+arg[1]*256
    args = [stack.get() for i in range(argc)]
    func = stack.get()
    if func not in safe:
        raise TypeError("Function %r now allowed"%func)
    stack.put(func(*args))

def LOAD_CONST(context, arg):
    cons = arg[0]+arg[1]*256
    stack.put(context['code'].co_consts[cons])

def LOAD_NAME(context, arg):
    name_num = arg[0]+arg[1]*256
    name = context['code'].co_names[name_num]
    if name in context['locals']:
        stack.put(context['locals'][name])
    else:
        stack.put(context['globals'][name])

def RETURN_VALUE(context):
    return stack.get()

opfuncs = {
    opmap['BINARY_ADD']: BINARY(operator.add),
    opmap['UNARY_INVERT']: UNARY(operator.invert),
    opmap['CALL_FUNCTION']: CALL_FUNCTION,
    opmap['LOAD_CONST']: LOAD_CONST,
    opmap['LOAD_NAME']: LOAD_NAME
    opmap['RETURN_VALUE']: RETURN_VALUE,
}

def VMeval(c):
    context = dict(locals={}, globals=globs, code=c)
    bci = iter(c.co_code)
    for bytecode in bci:
        func = opfuncs[ord(bytecode)]
        if func.func_code.co_argcount==1:
            ret = func(context)
        else:
            args = ord(bci.next()), ord(bci.next())
            ret = func(context, args)
        if ret:
            return ret

def evaluate(expr):
    return VMeval(compile(expr, 'userinput', 'eval'))

Obviously, the real version of this would be a bit longer (there are 119 opcodes, 24 of which are math related). Adding STORE_FAST and a couple others would allow for input like 'x=5;return x+x or similar, trivially easily. It can even be used to execute user-created functions, so long as the user created functions are themselves executed via VMeval (don't make them callable!!! or they could get used as a callback somewhere). Handling loops requires support for the goto bytecodes, which means changing from a for iterator to while and maintaining a pointer to the current instruction, but isn't too hard. For resistance to DOS, the main loop should check how much time has passed since the start of the calculation, and certain operators should deny input over some reasonable limit (BINARY_POWER being the most obvious).

While this approach is somewhat longer than a simple grammar parser for simple expressions (see above about just grabbing the compiled constant), it extends easily to more complicated input, and doesn't require dealing with grammar (compile take anything arbitrarily complicated and reduces it to a sequence of simple instructions).

Converting JavaScript object with numeric keys into array

var json = '{"0":"1","1":"2","2":"3","3":"4"}';

var parsed = JSON.parse(json);

var arr = [];

for(var x in parsed){
  arr.push(parsed[x]);
}

Hope this is what you're after!

Best practice for storing and protecting private API keys in applications

This example has a number of different aspects to it. I will mention a couple of points that I don't think have been explicitly covered elsewhere.

Protecting the secret in transit

The first thing to note is that accessing the dropbox API using their app authentication mechanism requires you to transmit your key and secret. The connection is HTTPS which means that you can't intercept the traffic without knowing the TLS certificate. This is to prevent a person intercepting and reading the packets on their journey from the mobile device to the server. For normal users it is a really good way of ensuring the privacy of their traffic.

What it is not good at, is preventing a malicious person downloading the app and inspecting the traffic. It is really easy to use a man-in-the-middle proxy for all traffic into and out of a mobile device. It would require no disassembly or reverse engineering of code to extract the app key and secret in this case due to the nature of the Dropbox API.

You could do pinning which checks that the TLS certificate you receive from the server is the one you expect. This adds a check to the client and makes it more difficult to intercept the traffic. This would make it harder to inspect the traffic in flight, but the pinning check happens in the client, so it would likely still be possible to disable the pinning test. It does make it harder though.

Protecting the secret at rest

As a first step, using something like proguard will help to make it less obvious where any secrets are held. You could also use the NDK to store the key and secret and send requests directly, which would greatly reduce the number of people with the appropriate skills to extract the information. Further obfuscation can be achieved by not storing the values directly in memory for any length of time, you can encrypt them and decrypt them just before use as suggested by another answer.

More advanced options

If you are now paranoid about putting the secret anywhere in your app, and you have time and money to invest in more comprehensive solutions, then you might consider storing the credentials on your servers (presuming you have any). This would increase the latency of any calls to the API, as it will have to communicate via your server, and might increase the costs of running your service due to increased data throughput.

You then have to decide how best to communicate with your servers to ensure they are protected. This is important to prevent all of the same problems coming up again with your internal API. The best rule of thumb I can give is to not transmit any secret directly because of the man-in-the-middle threat. Instead you can sign the traffic using your secret and verify the integrity of any requests that come to your server. One standard way of doing this is to compute an HMAC of the message keyed on a secret. I work at a company that has a security product that also operates in this field which is why this sort of stuff interests me. In fact, here is a blog article from one of my colleagues that goes over most of this.

How much should I do?

With any security advice like this you need to make a cost/benefit decision about how hard you want to make it for someone to break in. If you are a bank protecting millions of customers your budget is totally different to someone supporting an app in their spare time. It is virtually impossible to prevent someone from breaking your security, but in practice few people need all of the bells and whistles and with some basic precautions you can get a long way.

Where is the php.ini file on a Linux/CentOS PC?

In your terminal/console (only Linux, in windows you need Putty)

ssh user@ip
php -i | grep "Loaded Configuration File"

And it will show you something like this Loaded Configuration File => /etc/php.ini.

ALTERNATIVE METHOD

You can make a php file on your website, which run: <?php phpinfo(); ?>, and you can see the php.ini location on the line with: "Loaded Configuration File".

Update This command gives the path right away

cli_php_ini=php -i | grep /.+/php.ini -oE  #ref. https://stackoverflow.com/a/15763333/248616
    php_ini="${cli_php_ini/cli/apache2}"   #replace cli by apache2 ref. https://stackoverflow.com/a/13210909/248616

ImportError: DLL load failed: The specified module could not be found

I had the same issue with importing matplotlib.pylab with Python 3.5.1 on Win 64. Installing the Visual C++ Redistributable für Visual Studio 2015 from this links: https://www.microsoft.com/en-us/download/details.aspx?id=48145 fixed the missing DLLs.

I find it better and easier than downloading and pasting DLLs.

Generate war file from tomcat webapp folder

Its just like creating a WAR file of your project, you can do it in several ways (from Eclipse, command line, maven).

If you want to do from command line, the command is

jar -cvf my_web_app.war * 

Which means, "compress everything in this directory into a file named my_web_app.war" (c=create, v=verbose, f=file)

multiple packages in context:component-scan, spring config

<context:component-scan base-package="x.y.z"/>

will work since the rest of the packages are sub packages of "x.y.z". Thus, you dont need to mention each package individually.

Countdown timer using Moment js

Timezones. You have to deal with them, by using getTimezoneOffset() if you want your visitors from around the wolrd to get the same time.

Try this http://jsfiddle.net/cxyms/2/, it works for me, but I'm not sure will it work with other timezones.

var eventTimeStamp = '1366549200'; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTimeStamp = '1366547400'; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT

var eventTime = new Date();
eventTime.setTime(366549200);

var Offset = new Date(eventTime.getTimezoneOffset()*60000)

var Diff = eventTimeStamp - currentTimeStamp + (Offset.getTime() / 2);
var duration = moment.duration(Diff, 'milliseconds');
var interval = 1000;

setInterval(function(){
  duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
  $('.countdown').text(moment(duration.asMilliseconds()).format('H[h]:mm[m]:ss[s]'));
}, interval);

Best way in asp.net to force https for an entire site?

I spent sometime looking for best practice that make sense and found the following which worked perfected for me. I hope this will save you sometime.

Using Config file (for example an asp.net website) https://blogs.msdn.microsoft.com/kaushal/2013/05/22/http-to-https-redirects-on-iis-7-x-and-higher/

or on your own server https://www.sslshopper.com/iis7-redirect-http-to-https.html

[SHORT ANSWER] Simply The code below goes inside

<system.webServer> 
 <rewrite>
     <rules>
       <rule name="HTTP/S to HTTPS Redirect" enabled="true" 
           stopProcessing="true">
       <match url="(.*)" />
        <conditions logicalGrouping="MatchAny">
        <add input="{SERVER_PORT_SECURE}" pattern="^0$" />
       </conditions>
       <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" 
        redirectType="Permanent" />
        </rule>
       </rules>
 </rewrite>

Make a table fill the entire window

you can see the solution on http://jsfiddle.net/CBQCA/1/

OR

<table style="height:100%;width:100%; position: absolute; top: 0; bottom: 0; left: 0; right: 0;border:1px solid">
     <tr style="height: 25%;">
        <td>Region</td>
    </tr>
    <tr style="height: 75%;">
        <td>100.00%</td>
    </tr>
</table>?

I removed the font size, to show that columns are expanded. I added border:1px solid just to make sure table is expanded. you can remove it.

How to implement a custom AlertDialog View

After changing the ID it android.R.id.custom, I needed to add the following to get the View to display:

((View) f1.getParent()).setVisibility(View.VISIBLE);

However, this caused the new View to render in a big parent view with no background, breaking the dialog box in two parts (text and buttons, with the new View in between). I finally got the effect that I wanted by inserting my View next to the message:

LinearLayout f1 = (LinearLayout)findViewById(android.R.id.message).getParent().getParent();

I found this solution by exploring the View tree with View.getParent() and View.getChildAt(int). Not really happy about either, though. None of this is in the Android docs and if they ever change the structure of the AlertDialog, this might break.

Smooth scroll to specific div on click

You can use basic css to achieve smooth scroll

html {
  scroll-behavior: smooth;
}

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

Linux / Bash, using ps -o to get process by specific name?

This is a bit old, but I guess what you want is: ps -o pid -C PROCESS_NAME, for example:

ps -o pid -C bash

EDIT: Dependening on the sort of output you expect, pgrep would be more elegant. This, in my knowledge, is Linux specific and result in similar output as above. For example:

pgrep bash

Delete element in a slice

... is syntax for variadic arguments.

I think it is implemented by the complier using slice ([]Type), just like the function append :

func append(slice []Type, elems ...Type) []Type

when you use "elems" in "append", actually it is a slice([]type). So "a = append(a[:0], a[1:]...)" means "a = append(a[0:0], a[1:])"

a[0:0] is a slice which has nothing

a[1:] is "Hello2 Hello3"

This is how it works

Why do you need to put #!/bin/bash at the beginning of a script file?

It's a convention so the *nix shell knows what kind of interpreter to run.

For example, older flavors of ATT defaulted to sh (the Bourne shell), while older versions of BSD defaulted to csh (the C shell).

Even today (where most systems run bash, the "Bourne Again Shell"), scripts can be in bash, python, perl, ruby, PHP, etc, etc. For example, you might see #!/bin/perl or #!/bin/perl5.

PS: The exclamation mark (!) is affectionately called "bang". The shell comment symbol (#) is sometimes called "hash".

PPS: Remember - under *nix, associating a suffix with a file type is merely a convention, not a "rule". An executable can be a binary program, any one of a million script types and other things as well. Hence the need for #!/bin/bash.

Django ManyToMany filter()

Just restating what Tomasz said.

There are many examples of FOO__in=... style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:

users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])

# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])

The double underscore (__) syntax is used all over the place when working with querysets.

CSS: create white glow around image

Works like a charm!

.imageClass {
  -webkit-filter: drop-shadow(12px 12px 7px rgba(0,0,0,0.5));
}

Voila! That's it! Obviously this won't work in ie, but who cares...

Java Spring Boot: How to map my app root (“/”) to index.html?

@Configuration  
@EnableWebMvc  
public class WebAppConfig extends WebMvcConfigurerAdapter {  

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/", "index.html");
    }

}

How to delete rows from a pandas DataFrame based on a conditional expression

You can assign the DataFrame to a filtered version of itself:

df = df[df.score > 50]

This is faster than drop:

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test[test.x < 0]
# 54.5 ms ± 2.02 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test.drop(test[test.x > 0].index, inplace=True)
# 201 ms ± 17.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test.drop(test[test.x > 0].index)
# 194 ms ± 7.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Where is the application.properties file in a Spring Boot project?

In the your first journey in spring boot project I recommend you to start with Spring Starter Try this link here.

enter image description here

It will auto generate the project structure for you like this.application.perperties it will be under /resources.

application.properties important change,

server.port = Your PORT(XXXX) by default=8080
server.servlet.context-path=/api (SpringBoot version 2.x.)
server.contextPath-path=/api (SpringBoot version < 2.x.)

Any way you can use application.yml in case you don't want to make redundancy properties setting.

Example
application.yml

server:
   port: 8080 
   contextPath: /api

application.properties

server.port = 8080
server.contextPath = /api

Backbone.js fetch with parameters

try {
    // THIS for POST+JSON
    options.contentType = 'application/json';
    options.type = 'POST';
    options.data = JSON.stringify(options.data);

    // OR THIS for GET+URL-encoded
    //options.data = $.param(_.clone(options.data));

    console.log('.fetch options = ', options);
    collection.fetch(options);
} catch (excp) {
    alert(excp);
}

Push commits to another branch

when you pushing code to another branch just follow the below git command. Remember demo is my other branch name you can replace with your branch name.

git push origin master:demo

Change User Agent in UIWebView

The only problem I have found was change user agent only

- (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSDictionary *dictionary = [NSDictionary 
        dictionaryWithObjectsAndKeys:
        @"Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; ja-jp) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5", 
        @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}

How to change font size in a textbox in html

Here are some ways to edit the text and the size of the box:

rows="insertNumber"
cols="insertNumber"
style="font-size:12pt"

Example:

<textarea rows="5" cols="30" style="font-size: 12pt" id="myText">Enter 
Text Here</textarea>

How do I query using fields inside the new PostgreSQL JSON datatype?

With Postgres 9.3+, just use the -> operator. For example,

SELECT data->'images'->'thumbnail'->'url' AS thumb FROM instagram;

see http://clarkdave.net/2013/06/what-can-you-do-with-postgresql-and-json/ for some nice examples and a tutorial.

Python-Requests close http connection

please use response.close() to close to avoid "too many open files" error

for example:

r = requests.post("https://stream.twitter.com/1/statuses/filter.json", data={'track':toTrack}, auth=('username', 'passwd'))
....
r.close()

How to get multiple select box values using jQuery?

var selected=[];
 $('#multipleSelect :selected').each(function(){
     selected[$(this).val()]=$(this).text();
    });
console.log(selected);

Yet another approch to this problem. The selected array will have the indexes as the option values and the each array item will have the text as its value.

for example

<select id="multipleSelect" multiple="multiple">
    <option value="abc">Text 1</option>
    <option value="def">Text 2</option>
    <option value="ghi">Text 3</option>
</select>

if say option 1 and 2 are selected.

the selected array will be :

selected['abc']=1; 
selected['def']=2.

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

You can use this for the Width of your DataTemplate:

Width="{Binding ActualWidth,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ScrollContentPresenter}}}"

Make sure your DataTemplate root has Margin="0" (you can use some panel as the root and set the Margin to the children of that root)

Importing a CSV file into a sqlite3 database table using Python

import csv, sqlite3

def _get_col_datatypes(fin):
    dr = csv.DictReader(fin) # comma is default delimiter
    fieldTypes = {}
    for entry in dr:
        feildslLeft = [f for f in dr.fieldnames if f not in fieldTypes.keys()]        
        if not feildslLeft: break # We're done
        for field in feildslLeft:
            data = entry[field]

        # Need data to decide
        if len(data) == 0:
            continue

        if data.isdigit():
            fieldTypes[field] = "INTEGER"
        else:
            fieldTypes[field] = "TEXT"
    # TODO: Currently there's no support for DATE in sqllite

if len(feildslLeft) > 0:
    raise Exception("Failed to find all the columns data types - Maybe some are empty?")

return fieldTypes


def escapingGenerator(f):
    for line in f:
        yield line.encode("ascii", "xmlcharrefreplace").decode("ascii")


def csvToDb(csvFile,dbFile,tablename, outputToFile = False):

    # TODO: implement output to file

    with open(csvFile,mode='r', encoding="ISO-8859-1") as fin:
        dt = _get_col_datatypes(fin)

        fin.seek(0)

        reader = csv.DictReader(fin)

        # Keep the order of the columns name just as in the CSV
        fields = reader.fieldnames
        cols = []

        # Set field and type
        for f in fields:
            cols.append("\"%s\" %s" % (f, dt[f]))

        # Generate create table statement:
        stmt = "create table if not exists \"" + tablename + "\" (%s)" % ",".join(cols)
        print(stmt)
        con = sqlite3.connect(dbFile)
        cur = con.cursor()
        cur.execute(stmt)

        fin.seek(0)


        reader = csv.reader(escapingGenerator(fin))

        # Generate insert statement:
        stmt = "INSERT INTO \"" + tablename + "\" VALUES(%s);" % ','.join('?' * len(cols))

        cur.executemany(stmt, reader)
        con.commit()
        con.close()

Append text to file from command line without using io redirection

If you just want to tack something on by hand, then the sed answer will work for you. If instead the text is in file(s) (say file1.txt and file2.txt):

Using Perl:

perl -e 'open(OUT, ">>", "outfile.txt"); print OUT while (<>);' file*.txt

N.B. while the >> may look like an indication of redirection, it is just the file open mode, in this case "append".

How to stop asynctask thread in android?

You may also have to use it in onPause or onDestroy of Activity Life Cycle:

//you may call the cancel() method but if it is not handled in doInBackground() method
if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
    loginTask.cancel(true);

where loginTask is object of your AsyncTask

Thank you.

Jquery select change not firing

You can fire chnage event by these methods:

First

$('#selectid').change(function () {
    alert('This works');
}); 

Second

$(document).on('change', '#selectid', function() {
    alert('This Works');
});

Third

$(document.body).on('change','#selectid',function(){
    alert('This Works');
});

If this methods not working, check your jQuery working or not:

$(document).ready(function($) {
   alert('Jquery Working');
});

Programmatically Check an Item in Checkboxlist where text is equal to what I want

Assuming that the items in your CheckedListBox are strings:

  for (int i = 0; i < checkedListBox1.Items.Count; i++)
  {
    if ((string)checkedListBox1.Items[i] == value)
    {
      checkedListBox1.SetItemChecked(i, true);
    }
  }

Or

  int index = checkedListBox1.Items.IndexOf(value);

  if (index >= 0)
  {
    checkedListBox1.SetItemChecked(index, true);
  }

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

How do I execute .js files locally in my browser?

If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor

Oracle PL/SQL string compare issue

I've created a stored function for this text comparison purpose:

CREATE OR REPLACE FUNCTION TextCompare(vOperand1 IN VARCHAR2, vOperator IN VARCHAR2, vOperand2 IN VARCHAR2) RETURN NUMBER DETERMINISTIC AS
BEGIN
  IF vOperator = '=' THEN
    RETURN CASE WHEN vOperand1 = vOperand2 OR vOperand1 IS NULL AND vOperand2 IS NULL THEN 1 ELSE 0 END;
  ELSIF vOperator = '<>' THEN
    RETURN CASE WHEN vOperand1 <> vOperand2 OR (vOperand1 IS NULL) <> (vOperand2 IS NULL) THEN 1 ELSE 0 END;
  ELSIF vOperator = '<=' THEN
    RETURN CASE WHEN vOperand1 <= vOperand2 OR vOperand1 IS NULL THEN 1 ELSE 0 END;
  ELSIF vOperator = '>=' THEN
    RETURN CASE WHEN vOperand1 >= vOperand2 OR vOperand2 IS NULL THEN 1 ELSE 0 END;
  ELSIF vOperator = '<' THEN
    RETURN CASE WHEN vOperand1 < vOperand2 OR vOperand1 IS NULL AND vOperand2 IS NOT NULL THEN 1 ELSE 0 END;
  ELSIF vOperator = '>' THEN
    RETURN CASE WHEN vOperand1 > vOperand2 OR vOperand1 IS NOT NULL AND vOperand2 IS NULL THEN 1 ELSE 0 END;
  ELSIF vOperator = 'LIKE' THEN
    RETURN CASE WHEN vOperand1 LIKE vOperand2 OR vOperand1 IS NULL AND vOperand2 IS NULL THEN 1 ELSE 0 END;
  ELSIF vOperator = 'NOT LIKE' THEN
    RETURN CASE WHEN vOperand1 NOT LIKE vOperand2 OR (vOperand1 IS NULL) <> (vOperand2 IS NULL) THEN 1 ELSE 0 END;
  ELSE
    RAISE VALUE_ERROR;
  END IF;
END;

In example:

SELECT * FROM MyTable WHERE TextCompare(MyTable.a, '>=', MyTable.b) = 1;

Custom fonts and XML layouts (Android)

This might be a little late, but you need to create a singleton class that returns the custom typeface to avoid memory leaks.

TypeFace class:

public class OpenSans {

private static OpenSans instance;
private static Typeface typeface;

public static OpenSans getInstance(Context context) {
    synchronized (OpenSans.class) {
        if (instance == null) {
            instance = new OpenSans();
            typeface = Typeface.createFromAsset(context.getResources().getAssets(), "open_sans.ttf");
        }
        return instance;
    }
}

public Typeface getTypeFace() {
    return typeface;
}
}

Custom TextView:

public class NativelyCustomTextView extends TextView {

    public NativelyCustomTextView(Context context) {
        super(context);
        setTypeface(OpenSans.getInstance(context).getTypeFace());
    }

    public NativelyCustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setTypeface(OpenSans.getInstance(context).getTypeFace());
    }

    public NativelyCustomTextView(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
        setTypeface(OpenSans.getInstance(context).getTypeFace());
    }

}

By xml:

<com.yourpackage.views.NativelyCustomTextView
            android:id="@+id/natively_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_margin="20dp"
            android:text="@string/natively"
            android:textSize="30sp" /> 

Programmatically:

TextView programmaticallyTextView = (TextView) 
       findViewById(R.id.programmatically_text_view);

programmaticallyTextView.setTypeface(OpenSans.getInstance(this)
                .getTypeFace());

How to center and crop an image to always appear in square shape with CSS?

object-fit property does the magic. On JsFiddle.

CSS

.image {
  width: 160px;
  height: 160px;
}

.object-fit_fill {
  object-fit: fill
}

.object-fit_contain {
  object-fit: contain
}

.object-fit_cover {
  object-fit: cover
}

.object-fit_none {
  object-fit: none
}

.object-fit_scale-down {
  object-fit: scale-down
}

HTML

<div class="original-image">
  <p>original image</p>
  <img src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: fill</p>
  <img class="object-fit_fill" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: contain</p>
  <img class="object-fit_contain" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: cover</p>
  <img class="object-fit_cover" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: none</p>
  <img class="object-fit_none" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: scale-down</p>
  <img class="object-fit_scale-down" src="http://lorempixel.com/500/200">
</div>

Result

How the rendered images look (in a browser that supports <code>object-fit</code>)

How to access the correct `this` inside a callback?

First, you need to have a clear understanding of scope and behaviour of this keyword in the context of scope.

this & scope :


there are two types of scope in javascript. They are :

   1) Global Scope

   2) Function Scope

in short, global scope refers to the window object.Variables declared in a global scope are accessible from anywhere.On the other hand function scope resides inside of a function.variable declared inside a function cannot be accessed from outside world normally.this keyword in global scope refers to the window object.this inside function also refers to the window object.So this will always refer to the window until we find a way to manipulate this to indicate a context of our own choosing.

--------------------------------------------------------------------------------
-                                                                              -
-   Global Scope                                                               -
-   ( globally "this" refers to window object)                                 -     
-                                                                              -
-         function outer_function(callback){                                   -
-                                                                              -
-               // outer function scope                                        -
-               // inside outer function"this" keyword refers to window object -                                                                              -
-              callback() // "this" inside callback also refers window object  -

-         }                                                                    -
-                                                                              -
-         function callback_function(){                                        -
-                                                                              -
-                //  function to be passed as callback                         -
-                                                                              -
-                // here "THIS" refers to window object also                   -
-                                                                              -
-         }                                                                    -
-                                                                              -
-         outer_function(callback_function)                                    -
-         // invoke with callback                                              -
--------------------------------------------------------------------------------

Different ways to manipulate this inside callback functions:

Here I have a constructor function called Person. It has a property called name and four method called sayNameVersion1,sayNameVersion2,sayNameVersion3,sayNameVersion4. All four of them has one specific task.Accept a callback and invoke it.The callback has a specific task which is to log the name property of an instance of Person constructor function.

function Person(name){

    this.name = name

    this.sayNameVersion1 = function(callback){
        callback.bind(this)()
    }
    this.sayNameVersion2 = function(callback){
        callback()
    }

    this.sayNameVersion3 = function(callback){
        callback.call(this)
    }

    this.sayNameVersion4 = function(callback){
        callback.apply(this)
    }

}

function niceCallback(){

    // function to be used as callback

    var parentObject = this

    console.log(parentObject)

}

Now let's create an instance from person constructor and invoke different versions of sayNameVersionX ( X refers to 1,2,3,4 ) method with niceCallback to see how many ways we can manipulate the this inside callback to refer to the person instance.

var p1 = new Person('zami') // create an instance of Person constructor

bind :

What bind do is to create a new function with the this keyword set to the provided value.

sayNameVersion1 and sayNameVersion2 use bind to manipulate this of the callback function.

this.sayNameVersion1 = function(callback){
    callback.bind(this)()
}
this.sayNameVersion2 = function(callback){
    callback()
}

first one bind this with callback inside the method itself.And for the second one callback is passed with the object bound to it.

p1.sayNameVersion1(niceCallback) // pass simply the callback and bind happens inside the sayNameVersion1 method

p1.sayNameVersion2(niceCallback.bind(p1)) // uses bind before passing callback

call :

The first argument of the call method is used as this inside the function that is invoked with call attached to it.

sayNameVersion3 uses call to manipulate the this to refer to the person object that we created, instead of the window object.

this.sayNameVersion3 = function(callback){
    callback.call(this)
}

and it is called like the following :

p1.sayNameVersion3(niceCallback)

apply :

Similar to call, first argument of apply refers to the object that will be indicated by this keyword.

sayNameVersion4 uses apply to manipulate this to refer to person object

this.sayNameVersion4 = function(callback){
    callback.apply(this)
}

and it is called like the following.Simply the callback is passed,

p1.sayNameVersion4(niceCallback)

How to randomly select an item from a list?

This may already be an answer but you could use random.shuffle. Example:

import random
foo = ['a', 'b', 'c', 'd', 'e']
random.shuffle(foo)

How to get id from URL in codeigniter?

I think you're using the CodeIgniter URI routing wrong: http://ellislab.com/codeigniter%20/user-guide/general/routing.html

Basically if you had a Products_controller with a method called delete($id) and the url you created was of the form http://localhost/designs2/index.php/products_controller/delete/4, the delete function would receive the $id as a parameter.

Using what you have there I think you can get the id by using $this->input->get('product_id);

Get Application Name/ Label via ADB Shell or Terminal

adb shell pm list packages will give you a list of all installed package names.

You can then use dumpsys | grep -A18 "Package \[my.package\]" to grab the package information such as version identifiers etc

How do I fix a merge conflict due to removal of a file in a branch?

I normally just run git mergetool and it will prompt me if I want to keep the modified file or keep it deleted. This is the quickest way IMHO since it's one command instead of several per file.

If you have a bunch of deleted files in a specific subdirectory and you want all of them to be resolved by deleting the files, you can do this:

yes d | git mergetool -- the/subdirectory

The d is provided to choose deleting each file. You can also use m to keep the modified file. Taken from the prompt you see when you run mergetool:

Use (m)odified or (d)eleted file, or (a)bort?

iPhone SDK on Windows (alternative solutions)

There are two ways:

  1. If you are patient (requires Ubuntu corral pc and Android SDK and some heavy terminal work to get it all set up). See Using the 3.0 SDK without paying for the priviledge.

  2. If you are immoral (requires Mac OS X Leopard and virtualization, both only obtainable through great expense or pirating) - remove space from the following link. htt p://iphonewo rld. codinghut.com /2009/07/using-the-3-0-sdk-without-paying-for-the-priviledge/

I use the Ubuntu method myself.

Validate fields after user has left a field

You can dynamically set the has-error css class (assuming you're using bootstrap) using ng-class and a property on the scope of the associated controller:

plunkr: http://plnkr.co/edit/HYDlaTNThZE02VqXrUCH?p=info

HTML:

<div ng-class="{'has-error': badEmailAddress}">
    <input type="email" class="form-control" id="email" name="email"
        ng-model="email" 
        ng-blur="emailBlurred(email.$valid)">
</div>

Controller:

$scope.badEmailAddress = false;

$scope.emailBlurred = function (isValid) {
    $scope.badEmailAddress = !isValid;
};

Append data frames together in a for loop

For me, it worked very simply. At first, I made an empty data.frame, then in each iteration I added one column to it. Here is my code:

df <- data.frame(modelForOneIteration)
for(i in 1:10){
  model <- # some processing
  df[,i] = model
}

Eclipse Problems View not showing Errors anymore

This is not totally an answer to your question, but is related. I thought eclipse stopped showing red/yellow flags next to files in my project. The solution was very simple - I was looking at the Navigator tab (which doesn't show error/warning flags) instead of the Package Explorer tab.

enter image description here

Adding text to ImageView in Android

You can use the TextView for the same purpose, But if you want to use the same with the ImageView then you have to create a class and extends the ImageView then use onDraw() method to paint the text on to the canvas. for more details visit to http://developer.android.com/reference/android/graphics/Canvas.html

CSS transition between left -> right and top -> bottom positions

This worked for me on Chromium. The % for translate is in reference to the size of the bounding box of the element it is applied to so it perfectly gets the element to the lower right edge while not having to switch which property is used to specify it's location.

topleft {
  top: 0%;
  left: 0%;
}
bottomright {
  top: 100%;
  left: 100%;
  -webkit-transform: translate(-100%,-100%);
}

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

1: Go to the gradle enable multiDexEnabled and add the multidex library in the dependencies.

android {
   ...
   defaultConfig {
      multiDexEnabled true
      ...
   }
}

dependencies {
  // add dependency 
  implementation 'com.android.support:multidex:1.0.1'
}

2: Go to the Manifest file and write android:name=".MyApplication" (Class name(MyApplication) is optional you can write whatever you want ).

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        .
        .
        .
        .
        .
    </application>

3: As you wrote android:name=".MyApplication" Inside Application at Manifest file. it will give you an error because you didn't create MyApplication class. Create MyApplication Class extend it by "application" class or Simply click on.MyApplication, a small red balloon appear on the left side of a syntax click on it, you will see (create MyApplication class) in the menu, click on it and Include below Method Inside that class.

    public class MyApplication extends Application {

    @Override 
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    } 

If you want to get more information then Click on this Link:[https://developer.android.com/studio/build/multidex.html]

Hopefully, It works for you.

Redirect to external URL with return in laravel

For Laravel 8 you can also use

Route::redirect('/here', '/there');
//or
Route::permanentRedirect('/here', '/there');

This also works with external URLs

See: https://austencam.com/posts/setting-up-an-m1-mac-for-laravel-development-with-homebrew-php-mysql-valet-and-redis

Understanding MongoDB BSON Document size limit

Nested Depth for BSON Documents: MongoDB supports no more than 100 levels of nesting for BSON documents.

More more info vist

Http Post request with content type application/x-www-form-urlencoded not working in Spring

you should replace @RequestBody with @RequestParam, and do not accept parameters with a java entity.

Then you controller is probably like this:

@RequestMapping(value = "/patientdetails", method = RequestMethod.POST, 
consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public @ResponseBody List<PatientProfileDto> getPatientDetails(
    @RequestParam Map<String, String> name) {
   List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
   ...
   PatientProfileDto patientProfileDto = mapToPatientProfileDto(mame);
   ...
   list = service.getPatient(patientProfileDto);
   return list;
}

#1214 - The used table type doesn't support FULLTEXT indexes

The problem occurred because of wrong table type.MyISAM is the only type of table that Mysql supports for Full-text indexes.

To correct this error run following sql.

 CREATE TABLE gamemech_chat (
  id bigint(20) unsigned NOT NULL auto_increment,
  from_userid varchar(50) NOT NULL default '0',
  to_userid varchar(50) NOT NULL default '0',
  text text NOT NULL,
  systemtext text NOT NULL,
  timestamp datetime NOT NULL default '0000-00-00 00:00:00',
  chatroom bigint(20) NOT NULL default '0',
  PRIMARY KEY  (id),
  KEY from_userid (from_userid),
  FULLTEXT KEY from_userid_2 (from_userid),
  KEY chatroom (chatroom),
  KEY timestamp (timestamp)
) ENGINE=MyISAM;

Mysql adding user for remote access

An alternative way is to use MySql Workbench. Go to Administration -> Users and privileges -> and change 'localhost' with '%' in 'Limit to Host Matching' (From host) attribute for users you wont to give remote access Or create new user ( Add account button ) with '%' on this attribute instead localhost.