Programs & Examples On #Mod php

PHP installed as an Apache module

Install pip in docker

You might want to change the DNS settings of the Docker daemon. You can edit (or create) the configuration file at /etc/docker/daemon.json with the dns key, as

{
    "dns": ["your_dns_address", "8.8.8.8"]
}

In the example above, the first element of the list is the address of your DNS server. The second item is the Google’s DNS which can be used when the first one is not available.

Before proceeding, save daemon.json and restart the docker service.

sudo service docker restart

Once fixed, retry to run the build command.

How can I enable the MySQLi extension in PHP 7?

The problem is that the package that used to connect PHP to MySQL is deprecated (php5-mysql). If you install the new package,

sudo apt-get install php-mysql

this will automatically update Apache and PHP 7.

Why is php not running?

When installing Apache and PHP under Ubuntu 14.04, I needed to specifically enable php configs by issuing a2enmod php5-cgi

Can't execute jar- file: "no main manifest attribute"

Any executable jar file Should run either by clicking or running using command prompt like java -jar app.jar (use "if path of jar contains space" - i.e. java -jar "C:\folder name\app.jar"). If your executable jar is not running, which means it is not created properly.

For better understanding, extract the jar file (or view using any tool, for windows 7-Zip is nice one) and check the file under /META-INF/MANIFEST.MF. If you find any entry like

Main-Class: your.package.name.ClaaswithMain - then it's fine, otherwise you have to provide it.

Be aware of appending Main-Class entry on MANIFEST.MF file, check where you are saving it!

How to get the list of all database users

Go for this:

 SELECT name,type_desc FROM sys.sql_logins

Setting the correct encoding when piping stdout in Python

I had a similar issue last week. It was easy to fix in my IDE (PyCharm).

Here was my fix:

Starting from PyCharm menu bar: File -> Settings... -> Editor -> File Encodings, then set: "IDE Encoding", "Project Encoding" and "Default encoding for properties files" ALL to UTF-8 and she now works like a charm.

Hope this helps!

How do I empty an array in JavaScript?

If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:

A.length = 0;

How can I test that a variable is more than eight characters in PowerShell?

Use the length property of the [String] type:

if ($dbUserName.length -gt 8) {
    Write-Output "Please enter more than 8 characters."
    $dbUserName = Read-Host "Re-enter database username"
}

Please note that you have to use -gt instead of > in your if condition. PowerShell uses the following comparison operators to compare values and test conditions:

  • -eq = equals
  • -ne = not equals
  • -lt = less than
  • -gt = greater than
  • -le = less than or equals
  • -ge = greater than or equals

How to create a sticky left sidebar menu using bootstrap 3?

I used this way in my code

$(function(){
    $('.block').affix();
})

Getting Java version at runtime

Don't know another way of checking this, but this: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#getProperties()" implies "java.version" is a standard system property so I'd expect it to work with other JVMs.

How can I scan barcodes on iOS?

For a native iOS 7 bar code scanner take a look at my project on GitHub:

https://github.com/werner77/WECodeScanner

Java Swing revalidate() vs repaint()

revalidate is called on a container once new components are added or old ones removed. this call is an instruction to tell the layout manager to reset based on the new component list. revalidate will trigger a call to repaint what the component thinks are 'dirty regions.' Obviously not all of the regions on your JPanel are considered dirty by the RepaintManager.

repaint is used to tell a component to repaint itself. It is often the case that you need to call this in order to cleanup conditions such as yours.

Rank function in MySQL

select id,first_name,gender,age,
rank() over(partition by gender order by age) rank_g
from person

CREATE TABLE person (id int, first_name varchar(20), age int, gender char(1));

INSERT INTO person VALUES (1, 'Bob', 25, 'M');
INSERT INTO person VALUES (2, 'Jane', 20, 'F');
INSERT INTO person VALUES (3, 'Jack', 30, 'M');
INSERT INTO person VALUES (4, 'Bill', 32, 'M');
INSERT INTO person VALUES (5, 'Nick', 22, 'M');
INSERT INTO person VALUES (6, 'Kathy', 18, 'F');
INSERT INTO person VALUES (7, 'Steve', 36, 'M');
INSERT INTO person VALUES (8, 'Anne', 25, 'F');
INSERT INTO person VALUES (9,'AKSH',32,'M');

Circle drawing with SVG's arc path

Same for XAML's arc. Just close the 99.99% arc with a Z and you've got a circle!

How do I compile a .c file on my Mac?

You'll need to get a compiler. The easiest way is probably to install XCode development environment from the CDs/DVDs you got with your Mac, which will give you gcc. Then you should be able compile it like

gcc -o mybinaryfile mysourcefile.c

limit text length in php and provide 'Read more' link

I have combine two different answers:

  1. Limit the characters
  2. Complete HTML missing tags

    $string = strip_tags($strHTML);
    $yourText = $strHTML;
    if (strlen($string) > 350) {
        $stringCut = substr($post->body, 0, 350);
        $doc = new DOMDocument();
        $doc->loadHTML($stringCut);
        $yourText = $doc->saveHTML();
    }
    $yourText."...<a href=''>View More</a>"
    

CURL and HTTPS, "Cannot resolve host"

After tried all above, still can't resolved my issue yet. But got new solution for my problem.

At server where you are going to make a request, there should be a entry of your virtual host.

sudo vim /etc/hosts

and insert

192.xxx.x.xx www.domain.com

The reason if you are making request from server to itself then, to resolve your virtual host or to identify it, server would need above stuff, otherwise server won't understand your requesting(origin) host.

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

This issue seems to like the following.

How to resolve repository certificate error in Gradle build

Below steps may help:

1. Add certificate to keystore-

Import some certifications into Android Studio JDK cacerts from Android Studio’s cacerts.

Android Studio’s cacerts may be located in

{your-home-directory}/.AndroidStudio3.0/system/tasks/cacerts

I used the following import command.

$ keytool -importkeystore -v -srckeystore {src cacerts} -destkeystore {dest cacerts}

2. Add modified cacert path to gradle.properties-

systemProp.javax.net.ssl.trustStore={your-android-studio-directory}\\jre\\jre\\lib\\security\\cacerts
systemProp.javax.net.ssl.trustStorePassword=changeit

Ref : https://www.cresco.co.jp/blog/entry/2014//

Using a remote repository with non-standard port

SSH doesn't use the : syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config file and add:

Host git.host.de
  Port 4019

Then specify just git.host.de without a port number.

What's the -practical- difference between a Bare and non-Bare repository?

Another difference between a bare and non-bare repository is that a bare repository does not have a default remote origin repository:

~/Projects$ git clone --bare test bare
Initialized empty Git repository in /home/derek/Projects/bare/
~/Projects$ cd bare
~/Projects/bare$ git branch -a
* master
~/Projects/bare$ cd ..
~/Projects$ git clone test non-bare
Initialized empty Git repository in /home/derek/Projects/non-bare/.git/
~/Projects$ cd non-bare
~/Projects/non-bare$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master

From the manual page for git clone --bare:

Also the branch heads at the remote are copied directly to corresponding local branch heads, without mapping them to refs/remotes/origin/. When this option is used, neither remote-tracking branches nor the related configuration variables are created.

Presumably, when it creates a bare repository, Git assumes that the bare repository will serve as the origin repository for several remote users, so it does not create the default remote origin. What this means is that basic git pull and git push operations won't work since Git assumes that without a workspace, you don't intend to commit any changes to the bare repository:

~/Projects/bare$ git push
fatal: No destination configured to push to.
~/Projects/bare$ git pull
fatal: /usr/lib/git-core/git-pull cannot be used without a working tree.
~/Projects/bare$ 

Is there a way to change the spacing between legend items in ggplot2?

I think the best option is to use guide_legend within guides:

p + guides(fill=guide_legend(
                 keywidth=0.1,
                 keyheight=0.1,
                 default.unit="inch")
      )

Note the use of default.unit , no need to load grid package.

Java LinkedHashMap get first or last entry

Yea I came across the same problem, but luckily I only need the first element... - This is what I did for it.

private String getDefaultPlayerType()
{
    String defaultPlayerType = "";
    for(LinkedHashMap.Entry<String,Integer> entry : getLeagueByName(currentLeague).getStatisticsOrder().entrySet())
    {
        defaultPlayerType = entry.getKey();
        break;
    }
    return defaultPlayerType;
}

If you need the last element as well - I'd look into how to reverse the order of your map - store it in a temp variable, access the first element in the reversed map(therefore it would be your last element), kill the temp variable.

Here's some good answers on how to reverse order a hashmap:

How to iterate hashmap in reverse order in Java

If you use help from the above link, please give them up-votes :) Hope this can help someone.

Two values from one input in python?

Two inputs separated by space:

x,y=input().split()

C++ [Error] no matching function for call to

You are trying to call DeckOfCards::shuffle with a deckOfCards parameter:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck

But the method takes a vector<Card>&:

void deckOfCards::shuffle(vector<Card>& deck)

The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.

Error:

[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'

Paraphrased:

Hey, pal. You're trying to call a function called shuffle which apparently takes a single parameter of type reference-to-deckOfCards, but there is no such function.

Error:

[Note] candidate is:

In file included from main.cpp

[Note] void deckOfCards::shuffle(std::vector&)

Paraphrased:

I mean, maybe you meant this other function called shuffle, but that one takes a reference-tovector<something>.

Error:

[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'

Which I'd be happy to call if I knew how to convert from a deckOfCards to a vector; but I don't. So I won't.

How to select following sibling/xml tag using xpath

Try the following-sibling axis (following-sibling::td).

maxlength ignored for input type="number" in Chrome

I once got into the same problem and found this solution with respect to my needs. It may help Some one.

<input type="number" placeholder="Enter 4 Digits" max="9999" min="0" 
onKeyDown="if(this.value.length==4 && event.keyCode>47 && event.keyCode < 58)return false;"
/>

Happy Coding :)

How do I export html table data as .csv file?

The following solution can do it.

_x000D_
_x000D_
$(function() {_x000D_
  $("button").on('click', function() {_x000D_
    var data = "";_x000D_
    var tableData = [];_x000D_
    var rows = $("table tr");_x000D_
    rows.each(function(index, row) {_x000D_
      var rowData = [];_x000D_
      $(row).find("th, td").each(function(index, column) {_x000D_
        rowData.push(column.innerText);_x000D_
      });_x000D_
      tableData.push(rowData.join(","));_x000D_
    });_x000D_
    data += tableData.join("\n");_x000D_
    $(document.body).append('<a id="download-link" download="data.csv" href=' + URL.createObjectURL(new Blob([data], {_x000D_
      type: "text/csv"_x000D_
    })) + '/>');_x000D_
_x000D_
_x000D_
    $('#download-link')[0].click();_x000D_
    $('#download-link').remove();_x000D_
  });_x000D_
});
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
  border: 1px solid #aaa;_x000D_
  padding: 0.5rem;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
td {_x000D_
  font-size: 0.875rem;_x000D_
}_x000D_
_x000D_
.btn-group {_x000D_
  padding: 1rem 0;_x000D_
}_x000D_
_x000D_
button {_x000D_
  background-color: #fff;_x000D_
  border: 1px solid #000;_x000D_
  margin-top: 0.5rem;_x000D_
  border-radius: 3px;_x000D_
  padding: 0.5rem 1rem;_x000D_
  font-size: 1rem;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
  cursor: pointer;_x000D_
  background-color: #000;_x000D_
  color: #fff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Name</th>_x000D_
      <th>Author</th>_x000D_
      <th>Description</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>jQuery</td>_x000D_
      <td>John Resig</td>_x000D_
      <td>The Write Less, Do More, JavaScript Library.</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>React</td>_x000D_
      <td>Jordan Walke</td>_x000D_
      <td>React makes it painless to create interactive UIs.</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Vue.js</td>_x000D_
      <td>Yuxi You</td>_x000D_
      <td>The Progressive JavaScript Framework.</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
<div class="btn-group">_x000D_
  <button>csv</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to add image in Flutter

I think the error is caused by the redundant ,

flutter:
  uses-material-design: true, # <<< redundant , at the end of the line
  assets:
    - images/lake.jpg

I'd also suggest to create an assets folder in the directory that contains the pubspec.yaml file and move images there and use

flutter:
  uses-material-design: true
  assets:
    - assets/images/lake.jpg

The assets directory will get some additional IDE support that you won't have if you put assets somewhere else.

How to stop process from .BAT file?

To terminate a process you know the name of, try:

taskkill /IM notepad.exe

This will ask it to close, but it may refuse, offer to "save changes", etc. If you want to forcibly kill it, try:

taskkill /F /IM notepad.exe

StringBuilder vs String concatenation in toString() in Java

The key is whether you are writing a single concatenation all in one place or accumulating it over time.

For the example you gave, there's no point in explicitly using StringBuilder. (Look at the compiled code for your first case.)

But if you are building a string e.g. inside a loop, use StringBuilder.

To clarify, assuming that hugeArray contains thousands of strings, code like this:

...
String result = "";
for (String s : hugeArray) {
    result = result + s;
}

is very time- and memory-wasteful compared with:

...
StringBuilder sb = new StringBuilder();
for (String s : hugeArray) {
    sb.append(s);
}
String result = sb.toString();

Newtonsoft JSON Deserialize

You can implement a class that holds the fields you have in your JSON

class MyData
{
    public string t;
    public bool a;
    public object[] data;
    public string[][] type;
}

and then use the generic version of DeserializeObject:

MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
    // Do something with typeStr
}

Documentation: Serializing and Deserializing JSON

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

When you get this vague error message, you can find out the more specific error by running

SHOW ENGINE INNODB STATUS;

The most common reasons are that when creating a foreign key, both the referenced field and the foreign key field need to match:

  • Engine should be the same e.g. InnoDB
  • Datatype should be the same, and with same length.
    e.g. VARCHAR(20) or INT(10) UNSIGNED
  • Collation should be the same. e.g. utf8
  • Unique - Foreign key should refer to field that is unique (usually private) in the reference table.

Another cause of this error is:
You have defined a SET NULL condition though some of the columns are defined as NOT NULL.

Formatting Decimal places in R

Looks to me like to would be something like

library(tutoR)
format(1.128347132904321674821, 2)

Per a little online help.

How to add a line break in an Android TextView?

I found another method: Is necessary to add the "android:maxWidth="40dp"" attribute. Of course, it may not work perfectly, but it gives a line break.

What is the difference between vmalloc and kmalloc?

What are the advantages of having a contiguous block of memory? Specifically, why would I need to have a contiguous physical block of memory in a system call? Is there any reason I couldn't just use vmalloc?

From Google's "I'm Feeling Lucky" on vmalloc:

kmalloc is the preferred way, as long as you don't need very big areas. The trouble is, if you want to do DMA from/to some hardware device, you'll need to use kmalloc, and you'll probably need bigger chunk. The solution is to allocate memory as soon as possible, before memory gets fragmented.

Rails 4: before_filter vs. before_action

As we can see in ActionController::Base, before_action is just a new syntax for before_filter.

However all before_filters syntax are deprecated in Rails 5.0 and will be removed in Rails 5.1

Install windows service without InstallUtil.exe

Topshelf is an OSS project which was started after this question was answered and it makes Windows service much, MUCH easier.I highly recommend looking into it.

http://topshelf-project.com/

Javascript require() function giving ReferenceError: require is not defined

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

IE 6+ .......... compatible ?
Firefox 2+ ..... compatible ?
Safari 3.2+ .... compatible ?
Chrome 3+ ...... compatible ?
Opera 10+ ...... compatible ?

http://requirejs.org/docs/download.html

Add this to your project: https://requirejs.org/docs/release/2.3.5/minified/require.js

and take a look at this http://requirejs.org/docs/api.html

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

#php -i | grep php.ini also will work too!

can't start MySql in Mac OS 10.6 Snow Leopard

snow leopard is different to the "old" leopard therefore its not surprising that the sources won' work... you should probably wait till the official release on friday and oracle might be releasing a properly working sql version soon.

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

Python try-else

An else block can often exist to complement functionality that occurs in every except block.

try:
    test_consistency(valuable_data)
except Except1:
    inconsistency_type = 1
except Except2:
    inconsistency_type = 2
except:
    # Something else is wrong
    raise
else:
    inconsistency_type = 0

"""
Process each individual inconsistency down here instead of
inside the except blocks. Use 0 to mean no inconsistency.
"""

In this case, inconsistency_type is set in each except block, so that behaviour is complemented in the no-error case in else.

Of course, I'm describing this as a pattern that may turn up in your own code someday. In this specific case, you just set inconsistency_type to 0 before the try block anyway.

Convert base-2 binary number string to int

You use the built-in int function, and pass it the base of the input number, i.e. 2 for a binary number:

>>> int('11111111', 2)
255

Here is documentation for python2, and for python3.

Concrete Javascript Regex for Accented Characters (Diacritics)

How about this?

/^[a-zA-ZÀ-ÖØ-öø-ÿ]+$/

Compare given date with today

Compare date time objects:

(I picked 10 days - Anything older than 10 days is "OLD", else "NEW")

$now   = new DateTime();
$diff=date_diff($yourdate,$now);
$diff_days = $diff->format("%a");
if($diff_days > 10){
    echo "OLD! " . $yourdate->format('m/d/Y');
}else{
    echo "NEW! " . $yourdate->format('m/d/Y');
}

How do I pass a variable by reference?

In this case the variable titled var in the method Change is assigned a reference to self.variable, and you immediately assign a string to var. It's no longer pointing to self.variable. The following code snippet shows what would happen if you modify the data structure pointed to by var and self.variable, in this case a list:

>>> class PassByReference:
...     def __init__(self):
...         self.variable = ['Original']
...         self.change(self.variable)
...         print self.variable
...         
...     def change(self, var):
...         var.append('Changed')
... 
>>> q = PassByReference()
['Original', 'Changed']
>>> 

I'm sure someone else could clarify this further.

pip install: Please check the permissions and owner of that directory

What is the problem here is that you somehow installed into virtualenv using sudo. Probably by accident. This means root user will rewrite Python package data, making all file owned by root and your normal user cannot write those files anymore. Usually virtualenv should be used and owned by your normal UNIX user only.

You can fix the issue by changing UNIX file permissions pack to your user. Try:

$ sudo chown -R USERNAME /Users/USERNAME/Library/Logs/pip
$ sudo chown -R USERNAME /Users/USERNAME/Library/Caches/pip

then pip should be able to write those files again.

More information about UNIX file permission management

XMLHttpRequest cannot load an URL with jQuery

I am using WebAPI 3 and was facing the same issue. The issue has resolve as @Rytis added his solution. And I think in WebAPI 3, we don't need to define method RegisterWebApi.

My change was only in web.config file and is working.

<httpProtocol>
 <customHeaders>
 <add name="Access-Control-Allow-Origin" value="*" />
 <add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol> 

Thanks for you solution @Rytis!

Create an array with same element repeated multiple times

you can try:

Array(6).join('a').split(''); // returns ['a','a','a','a','a'] (5 times)

Update (01/06/2018):

Now you can have a set of characters repeating.

new Array(5).fill('a'); // give the same result as above;
// or
Array.from({ length: 5 }).fill('a')

Note: Check more about fill(...) and from(...) for compatibility and browser support.

Update (05/11/2019):

Another way, without using fill or from, that works for string of any length:

Array.apply(null, Array(3)).map(_ => 'abc') // ['abc', 'abc', 'abc']

Same as above answer. Adding for sake of completeness.

How to change permissions for a folder and its subfolders/files in one step?

I think Adam was asking how to change umask value for all processes that tying to operate on /opt/lampp/htdocs directory.

The user file-creation mode mask (umask) is use to determine the file permission for newly created files. It can be used to control the default file permission for new files.

so if you will use some kind of ftp program to upload files into /opt/lampp/htdocs you need to configure your ftp server to use umask you want.

If files / directories be created for example by php, you need to modify php code

<?php
umask(0022);
// other code
?>

if you will create new files / folders from your bash session, you can set umask value in your shell profile ~/.bashrc Or you can set up umask in /etc/bashrc or /etc/profile file for all users. add the following to file: umask 022

Sample umask Values and File Creation Permissions
If umask value set to   User permission     Group permission     Others permission
000                         all              all                   all
007                         all              all                   none
027                         all          read / execute            none

And to change permissions for already created files you can use find. Hope this helps.

Permission denied (publickey) when SSH Access to Amazon EC2 instance

i had same error but different situation. to me it happened out of the blue after a lot of time i could ssh successfully to my remote computer out there. after a lot of searching the solution to my problem were file permissions. it is strange of course because i didn't change any permissions in my computer or the remote one belonging to the ssh's files/directories. so from the good archlinux wiki here it is:

For the local machine do this:

$ chmod 700 ~/
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/id_ecdsa

For the remote machine do that:

$ chmod 700 ~/
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys

after that my ssh started to working again without the permission denied (publickey) thing.

Python variables as keys to dict

Based on the answer by mouad, here's a more pythonic way to select the variables based on a prefix:

# All the vars that I want to get start with fruit_
fruit_apple = 1
fruit_carrot = 'f'
rotten = 666

prefix = 'fruit_'
sourcedict = locals()
fruitdict = { v[len(prefix):] : sourcedict[v]
              for v in sourcedict
              if v.startswith(prefix) }
# fruitdict = {'carrot': 'f', 'apple': 1}

You can even put that in a function with prefix and sourcedict as arguments.

What is the proper #include for the function 'sleep()'?

The sleep man page says it is declared in <unistd.h>.

Synopsis:

#include <unistd.h>

unsigned int sleep(unsigned int seconds);

How to select a CRAN mirror in R

I'm a fan of:

chooseCRANmirror()

Which will print the list of mirrors in the output (no worrying a popup window since you are running it from the terminal) and then you enter the number you want.

pycharm running way slow

It is super easy by changing the heap size as it was mentioned. Just easily by going to Pycharm HELP -> Edit custom VM option ... and change it to:

-Xms2048m
-Xmx2048m

How to concatenate two strings in SQL Server 2005

so if you have a table with a row like:

firstname lastname
Bill      smith

you can do something like

select firstname + ' ' + lastname from thetable

and you will get "Bill Smith"

make an html svg object also a clickable link

To accomplish this in all browsers you need to use a combination of @energee, @Richard and @Feuermurmel methods.

<a href="" style="display: block; z-index: 1;">
    <object data="" style="z-index: -1; pointer-events: none;" />
</a>

Adding:

  • pointer-events: none; makes it work in Firefox.
  • display: block; gets it working in Chrome, and Safari.
  • z-index: 1; z-index: -1; makes it work in IE as well.

Serializing an object to JSON

Just to keep it backward compatible I load Crockfords JSON-library from cloudflare CDN if no native JSON support is given (for simplicity using jQuery):

function winHasJSON(){
  json_data = JSON.stringify(obj);
  // ... (do stuff with json_data)
}
if(typeof JSON === 'object' && typeof JSON.stringify === 'function'){
  winHasJSON();
} else {
  $.getScript('//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.min.js', winHasJSON)
}

PLS-00103: Encountered the symbol when expecting one of the following:

begin
    var_number := 10;

    if var_number > 100 then
        dbms_output.put_line(var_number||' is greater than 100');
    else if var_number < 100 then
        dbms_output.put_line(var_number||' is less than 100');
    else
        dbms_output.put_line(var_number||' is equal to 100');
    end if;
end if;

OSError - Errno 13 Permission denied

This may also happen if you have a slash before the folder name:

path = '/folder1/folder2'

OSError: [Errno 13] Permission denied: '/folder1'

comes up with an error but this one works fine:

path = 'folder1/folder2'

Bootstrap 3 - set height of modal window according to screen size

I am using jquery for this. I mad a function to set desired height to the modal(You can change that according to your requirement). Then I used Modal Shown event to call this function. Remember not to use $("#modal").show() rather use $("#modal").modal('show') otherwise shown.bs.modal will not be fired.

That all I have for this scenario.

_x000D_
_x000D_
var offset=250; //You can set offset accordingly based on your UI_x000D_
function AdjustPopup() _x000D_
{_x000D_
    $(".modal-body").css("height","auto");_x000D_
    if ($(".modal-body:visible").height() > ($(window).height() - offset)) _x000D_
    {_x000D_
        $(".modal-body:visible").css("height", ($(window).height() - offset));_x000D_
    }_x000D_
}_x000D_
//Execute the function on every trigger on show() event._x000D_
$(document).ready(function(){_x000D_
$('.modal').on('shown.bs.modal', function (e) {_x000D_
        AdjustPopup();_x000D_
    });_x000D_
});_x000D_
//Remember to show modal like this_x000D_
$("#MyModal").modal('show');
_x000D_
_x000D_
_x000D_

How to get box-shadow on left & right sides only

In some situations you can hide the shadow by another container. Eg, if there is a DIV above and below the DIV with the shadow, you can use position: relative; z-index: 1; on the surrounding DIVs.

How to get Current Timestamp from Carbon in Laravel 5

You can try this if you want date time string:

use Carbon\Carbon;
$current_date_time = Carbon::now()->toDateTimeString(); // Produces something like "2019-03-11 12:25:00"

If you want timestamp, you can try:

use Carbon\Carbon;
$current_timestamp = Carbon::now()->timestamp; // Produces something like 1552296328

See the official Carbon documentation here.

Prevent form submission on Enter key press

<form id="form1" runat="server" onkeypress="return event.keyCode != 13;">

Add this Code In Your HTML Page...it will disable ...Enter Button..

How to open Atom editor from command line in OS X?

With the Atom editor open, in the menu bar:

Click Atom >> Install Shell Commands

atom-add-shell-commands

You should expect to see:

atom-commands-installed

Potentially restart your terminal. (I did just out of habit, not sure if you need to)

CURL to pass SSL certifcate and password

Should be:

curl --cert certificate_file.pem:password https://www.example.com/some_protected_page

Does Notepad++ show all hidden characters?

For non-printing characters, you can do the following:

  • if you could identify the character, where cursor takes 2 arrow keys to move, just select that character.
  • do Ctrl-F
  • now you can count or replace or even mark all such characters

What is sharding and why is it important?

Sharding is horizontal(row wise) database partitioning as opposed to vertical(column wise) partitioning which is Normalization. It separates very large databases into smaller, faster and more easily managed parts called data shards. It is a mechanism to achieve distributed systems.

Why do we need distributed systems?

  • Increased availablity.
  • Easier expansion.
  • Economics: It costs less to create a network of smaller computers with the power of single large computer.

You can read more here: Advantages of Distributed database

How sharding help achieve distributed system?

You can partition a search index into N partitions and load each index on a separate server. If you query one server, you will get 1/Nth of the results. So to get complete result set, a typical distributed search system use an aggregator that will accumulate results from each server and combine them. An aggregator also distribute query onto each server. This aggregator program is called MapReduce in big data terminology. In other words, Distributed Systems = Sharding + MapReduce (Although there are other things too).

A visual representation below. Distributed System

How to make Visual Studio copy a DLL file to the output directory?

Use a post-build action in your project, and add the commands to copy the offending DLL. The post-build action are written as a batch script.

The output directory can be referenced as $(OutDir). The project directory is available as $(ProjDir). Try to use relative pathes where applicable, so that you can copy or move your project folder without breaking the post-build action.

prevent property from being serialized in web API

I'm late to the game, but an anonymous objects would do the trick:

[HttpGet]
public HttpResponseMessage Me(string hash)
{
    HttpResponseMessage httpResponseMessage;
    List<Something> somethings = ...

    var returnObjects = somethings.Select(x => new {
        Id = x.Id,
        OtherField = x.OtherField
    });

    httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, 
                                 new { result = true, somethings = returnObjects });

    return httpResponseMessage;
}

"Eliminate render-blocking CSS in above-the-fold content"

Few tips that may help:

  • I came across this article in CSS optimization yesterday: CSS profiling for ... optimization
    A lot of useful info on CSS and what CSS causes the most performance drains.

  • I saw the following presentation on jQueryUK on "hidden secrets" in Googe Chrome (Canary) Dev Tools: DevTools Can do that. Check out the sections on Time to First Paint, repaints and costly CSS.

  • Also, if you are using a loader like requireJS you could have a look at one of the CSS loader plugins, called require-CSS, which uses CSSO - a optimzer that also does structural optimization, eg. merging blocks with identical properties. I used it a few times and it can save quite a lot of CSS from case to case.

Off the question: I second @Enzino in creating a sprite for all the small icons you are loading. The file sizes are so small it does not really warrant a server roundtrip for each icon. Also keep in mind the total number of concurrent http requests are browser can do. So requests for a larger number of small icons are "render-blocking" as well. Although an empty page compare to yours, I like how duckduckgo loads for example.

How do I append text to a file?

cat >> filename
This is text, perhaps pasted in from some other source.
Or else entered at the keyboard, doesn't matter. 
^D

Essentially, you can dump any text you want into the file. CTRL-D sends an end-of-file signal, which terminates input and returns you to the shell.

Read a file in Node.js

var fs = require('fs');
var path = require('path');

exports.testDir = path.dirname(__filename);
exports.fixturesDir = path.join(exports.testDir, 'fixtures');
exports.libDir = path.join(exports.testDir, '../lib');
exports.tmpDir = path.join(exports.testDir, 'tmp');
exports.PORT = +process.env.NODE_COMMON_PORT || 12346;

// Read File
fs.readFile(exports.tmpDir+'/start.html', 'utf-8', function(err, content) {
  if (err) {
    got_error = true;
  } else {
    console.log('cat returned some content: ' + content);
    console.log('this shouldn\'t happen as the file doesn\'t exist...');
    //assert.equal(true, false);
  }
});

How do I do an OR filter in a Django query?

You can use the | operator to combine querysets directly without needing Q objects:

result = Item.objects.filter(item.creator = owner) | Item.objects.filter(item.moderated = False)

(edit - I was initially unsure if this caused an extra query but @spookylukey pointed out that lazy queryset evaluation takes care of that)

g++ undefined reference to typeinfo

in my case, i used a third-party library with header files and so file. i subclassed one class, and link error like this occurred when i try to instantiate my subclass.

as mentioned by @sergiy, knowning it could be the problem of 'rtti', i managed to workaround it by put the constructor implementation into separate .cpp file and apply '-fno-rtti' compile flags to the file. it works well.

as i am still not quite clear about the internal of this link error, i am not sure whether my solution is general. however, i think it worth a shot before trying the adaptor way as mentioned by @francois . and of course, if all source codes are available(not in my case), better do recompile with '-frtti' if possible.

one more thing, if you choose to try my solution, try make the separate file as simple as possible, and do not use some fancy features of C++. take special attention on boost related things, cause much of it depends on rtti.

Perform debounce in React.js

Here is an example I came up with that wraps another class with a debouncer. This lends itself nicely to being made into a decorator/higher order function:

export class DebouncedThingy extends React.Component {
    static ToDebounce = ['someProp', 'someProp2'];
    constructor(props) {
        super(props);
        this.state = {};
    }
    // On prop maybe changed
    componentWillReceiveProps = (nextProps) => {
        this.debouncedSetState();
    };
    // Before initial render
    componentWillMount = () => {
        // Set state then debounce it from here on out (consider using _.throttle)
        this.debouncedSetState();
        this.debouncedSetState = _.debounce(this.debouncedSetState, 300);
    };
    debouncedSetState = () => {
        this.setState(_.pick(this.props, DebouncedThingy.ToDebounce));
    };
    render() {
        const restOfProps = _.omit(this.props, DebouncedThingy.ToDebounce);
        return <Thingy {...restOfProps} {...this.state} />
    }
}

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

How do I check if the Java JDK is installed on Mac?

If you are on Mac OS Big Sur, then you probably have a messed up java installation. I found info on how to fix the issue with this article: https://knasmueller.net/how-to-install-java-openjdk-15-on-macos-big-sur

  1. Download the .tar.gz file of the JDK on https://jdk.java.net/15/
  2. Navigate to the download folder, and run these commands (move the .tar.gz file, extract it and remove it after extraction):
sudo mv openjdk-15.0.2_osx-x64_bin.tar.gz /Library/Java/JavaVirtualMachines/
cd /Library/Java/JavaVirtualMachines/
sudo tar -xzf openjdk-15.0.2_osx-x64_bin.tar.gz
sudo rm openjdk-15.0.2_osx-x64_bin.tar.gz

Note: it might be 15.0.3 or higher, depending on the date of your download.

  1. run /usr/libexec/java_home -v15 and copy the output
  2. add this line to your .bash_profile or .zshrc file, depending on which shell you are using. You will probably have only one of these files existing in your home directory (~/.bash_profile or ~/.zshrc).
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-15.0.2.jdk/Contents/Home
  1. save the changes and make them effective right away by running: source ~/.bash_profile or source ~/.zshrc
  2. check that java is working - run java -v

RegExp in TypeScript

_x000D_
_x000D_
const regex = /myRegexp/

console.log('Hello myRegexp!'.replace(regex, 'World')) // = Hello World!
_x000D_
_x000D_
_x000D_

The Regex literal notation is commonly used to create new instances of RegExp

     regex needs no additional escaping
      v
/    regex   /   gm
^            ^   ^
start      end   optional modifiers

As others sugguested, you can also use the new RegExp('myRegex') constructor.
But you will have to be especially careful with escaping:

regex: 12\d45
matches: 12345

const regex = new RegExp('12\\d45')
const equalRegex = /12\d45/

Coding Conventions - Naming Enums

If I can add my $0.02, I prefer using PascalCase as enum values in C.

In C, they are basically global, and PEER_CONNECTED gets really tiring as opposed to PeerConnected.

Breath of fresh air.

Literally, it makes me breathe easier.

In Java, it is possible to use raw enum names as long as you static import them from another class.

import static pkg.EnumClass.*;

Now, you can use the unqualified names, that you qualified in a different way already.

I am currently (thinking) about porting some C code to Java and currently 'torn' between choosing Java convention (which is more verbose, more lengthy, and more ugly) and my C style.

PeerConnected would become PeerState.CONNECTED except in switch statements, where it is CONNECTED.

Now there is much to say for the latter convention and it does look nice but certain "idiomatic phrases" such as if (s == PeerAvailable) become like if (s == PeerState.AVAILABLE) and nostalgically, this is a loss of meaning to me.

I think I still prefer the Java style because of clarity but I have a hard time looking at the screaming code.

Now I realize PascalCase is already widely used in Java but very confusing it would not really be, just a tad out of place.

Can someone explain __all__ in Python?

__all__ affects how from foo import * works.

Code that is inside a module body (but not in the body of a function or class) may use an asterisk (*) in a from statement:

from foo import *

The * requests that all attributes of module foo (except those beginning with underscores) be bound as global variables in the importing module. When foo has an attribute __all__, the attribute's value is the list of the names that are bound by this type of from statement.

If foo is a package and its __init__.py defines a list named __all__, it is taken to be the list of submodule names that should be imported when from foo import * is encountered. If __all__ is not defined, the statement from foo import * imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py.

Note that __all__ doesn't have to be a list. As per the documentation on the import statement, if defined, __all__ must be a sequence of strings which are names defined or imported by the module. So you may as well use a tuple to save some memory and CPU cycles. Just don't forget a comma in case the module defines a single public name:

__all__ = ('some_name',)

See also Why is “import *” bad?

Read specific columns with pandas or other python module

Above answers are in python2. So for python 3 users I am giving this answer. You can use the bellow code:

import pandas as pd
fields = ['star_name', 'ra']

df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print(df.keys())
# See content in 'star_name'
print(df.star_name)

How to configure SSL certificates with Charles Web Proxy and the latest Android Emulator on Windows?

Things have changed a little in the way Charles provides HTTPS proxying.

First the certificates installation options have been moved to the help menu.

Help -> SSL Proxying -> Install Charles Root Certificate
Help -> SSL Proxying -> Install Charles Root Certificate in iOS Simulators

Charles SSL Proxying

Second, starting in iOS 9 you must provide a NSAppTransportSecurity option in your Info.plist and if you want Charles to work properly as a man in the middle, you must add:

<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>

as part of the your domains see full example:

<key>NSExceptionDomains</key>
    <dict>
        <key>yourdomain.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
        </dict>

The reason being (I guess) that Charles at some point communicates in clear http after acting as the man in the middle https server.

Last step is to activate SSL Proxying for this domain in Charles (right click on domain and select Enable SSL Proxying)

enable HTTP Proxying

What is Express.js?

  1. Express.js is a modular web framework for Node.js
  2. It is used for easier creation of web applications and services
  3. Express.js simplifies development and makes it easier to write secure, modular and fast applications. You can do all that in plain old Node.js, but some bugs can (and will) surface, including security concerns (eg. not escaping a string properly)
  4. Redis is an in-memory database system known for its fast performance. No, but you can use it with Express.js using a redis client

I couldn't be more concise than this. For all your other needs and information, Google is your friend.

How to close a web page on a button click, a hyperlink or a link button click?

To close a windows form (System.Windows.Forms.Form) when one of its button is clicked: in Visual Studio, open the form in the designer, right click on the button and open its property page, then select the field DialogResult an set it to OK or the appropriate value.

Java File - Open A File And Write To It

Suggestions:

  • Create a File object that refers to the already existing file on disk.
  • Use a FileWriter object, and use the constructor that takes the File object and a boolean, the latter if true would allow appending text into the File if it exists.
  • Then initialize a PrintWriter passing in the FileWriter into its constructor.
  • Then call println(...) on your PrintWriter, writing your new text into the file.
  • As always, close your resources (the PrintWriter) when you are done with it.
  • As always, don't ignore exceptions but rather catch and handle them.
  • The close() of the PrintWriter should be in the try's finally block.

e.g.,

  PrintWriter pw = null;

  try {
     File file = new File("fubars.txt");
     FileWriter fw = new FileWriter(file, true);
     pw = new PrintWriter(fw);
     pw.println("Fubars rule!");
  } catch (IOException e) {
     e.printStackTrace();
  } finally {
     if (pw != null) {
        pw.close();
     }
  }

Easy, no?

Eclipse IDE for Java - Full Dark Theme

There's a new plugin which provides full theming for Eclipse:

http://brainwy.github.io/liclipse/

It's integrated with Eclipse Color Theme so that when a new theme is selected in preferences > general > appearance > color theme, the proper background is also applied to other parts of the IDE (theming everything or just views which are previously registered according to a combo in that same page).

And besides theming it provides a bunch of other things :)

Excel data validation with suggestions/autocomplete

This is a solution how to make autocomplete drop down list with VBA :


Firstly you need to insert a combo box into the worksheet and change its properties, and then running the VBA code to enable the autocomplete.

  1. Get into the worksheet which contains the drop down list you want it to be autocompleted.

  2. Before inserting the Combo box, you need to enable the Developer tab in the ribbon.

a). In Excel 2010 and 2013, click File > Options. And in the Options dialog box, click Customize Ribbon in the right pane, check the Developer box, then click the OK button.

b). In Outlook 2007, click Office button > Excel Options. In the Excel Options dialog box, click Popular in the right bar, then check the Show Developer tabin the Ribbon box, and finally click the OK button.

  1. Then click Developer > Insert > Combo Box under ActiveX Controls.

  2. Draw the combo box in current opened worksheet and right click it. Select Properties in the right-clicking menu.

  3. Turn off the Design Mode with clicking Developer > Design Mode.

  4. Right click on the current opened worksheet tab and click View Code.

  5. Make sure that the current worksheet code editor is opened, and then copy and paste the below VBA code into it.

Code borrowed from extendoffice.com

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Update by Extendoffice: 2018/9/21
    Dim xCombox As OLEObject
    Dim xStr As String
    Dim xWs As Worksheet
    Dim xArr



    Set xWs = Application.ActiveSheet
    On Error Resume Next
    Set xCombox = xWs.OLEObjects("TempCombo")
    With xCombox
        .ListFillRange = ""
        .LinkedCell = ""
        .Visible = False
    End With
    If Target.Validation.Type = 3 Then
        Target.Validation.InCellDropdown = False
        Cancel = True
        xStr = Target.Validation.Formula1
        xStr = Right(xStr, Len(xStr) - 1)
        If xStr = "" Then Exit Sub
        With xCombox
            .Visible = True
            .Left = Target.Left
            .Top = Target.Top
            .Width = Target.Width + 5
            .Height = Target.Height + 5
            .ListFillRange = xStr
            If .ListFillRange = "" Then
                xArr = Split(xStr, ",")
                Me.TempCombo.List = xArr
            End If
            .LinkedCell = Target.Address
        End With
        xCombox.Activate
        Me.TempCombo.DropDown
    End If
End Sub

Private Sub TempCombo_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Select Case KeyCode
        Case 9
            Application.ActiveCell.Offset(0, 1).Activate
        Case 13
            Application.ActiveCell.Offset(1, 0).Activate
    End Select
End Sub
  1. Click File > Close and Return to Microsoft Excel to close the Microsoft Visual Basic for Application window.

  2. Now, just click the cell with drop down list, you can see the drop-down list is displayed as a combo box, then type the first letter into the box, the corresponding word will be completed automatically.

Note: This VBA code is not applied to merged cells.

Source : How To Autocomplete When Typing In Excel Drop Down List?

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

It's good practise to extend from a baseController and implement some base functions implement a function to check if the user instance is null like this if the user form the Userinterface then there is no user logged in

/**

*/
class BaseController extends AbstractController
{

    /**
     * @return User

     */
    protected function getUser(): ?User
    {
        return parent::getUser();
    }

    /**
     * @return bool
     */
    protected function isUserLoggedIn(): bool
    {
        return $this->getUser() instanceof User;
    }
}

In Java, what is the best way to determine the size of an object?

You have to walk the objects using reflection. Be careful as you do:

  • Just allocating an object has some overhead in the JVM. The amount varies by JVM so you might make this value a parameter. At least make it a constant (8 bytes?) and apply to anything allocated.
  • Just because byte is theoretically 1 byte doesn't mean it takes just one in memory.
  • There will be loops in object references, so you'll need to keep a HashMap or somesuch using object-equals as the comparator to eliminate infinite loops.

@jodonnell: I like the simplicity of your solution, but many objects aren't Serializable (so this would throw an exception), fields can be transient, and objects can override the standard methods.

Converting a String array into an int Array in java

private void processLine(String[] strings) {
    Integer[] intarray=new Integer[strings.length];
    for(int i=0;i<strings.length;i++) {
        intarray[i]=Integer.parseInt(strings[i]);
    }
    for(Integer temp:intarray) {
        System.out.println("convert int array from String"+temp);
    }
}

How to get out of while loop in java with Scanner method "hasNext" as condition?

If you don't want to use an EOF character for this, you can use StringTokenizer :

import java.util.*;
public class Test{
   public static void main(){
      Scanner sc = new Scanner (System.in);
      System.out.print("Enter your sentence: ");
      String s=sc.nextLine();
      StringTokenizer st=new StringTokenizer(s," ");//" " is the delimiter here.
      while (st.hasMoreTokens() ) {
        String s1 = st.nextToken();
        System.out.println(s1);
      }

      System.out.println("The loop has been ended");
   }
}

How to log out user from web site using BASIC authentication?

This JavaScript must be working for all latest version browsers:

//Detect Browser
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    // At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera;              // Chrome 1+
var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
var Host = window.location.host;


//Clear Basic Realm Authentication
if(isIE){
//IE
    document.execCommand("ClearAuthenticationCache");
    window.location = '/';
}
else if(isSafari)
{//Safari. but this works mostly on all browser except chrome
    (function(safeLocation){
        var outcome, u, m = "You should be logged out now.";
        // IE has a simple solution for it - API:
        try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
        // Other browsers need a larger solution - AJAX call with special user name - 'logout'.
        if (!outcome) {
            // Let's create an xmlhttp object
            outcome = (function(x){
                if (x) {
                    // the reason we use "random" value for password is 
                    // that browsers cache requests. changing
                    // password effectively behaves like cache-busing.
                    x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
                    x.send("");
                    // x.abort()
                    return 1 // this is **speculative** "We are done." 
                } else {
                    return
                }
            })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u )) 
        }
        if (!outcome) {
            m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
        }
        alert(m);
        window.location = '/';
        // return !!outcome
    })(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)
}
else{
//Firefox,Chrome
    window.location = 'http://log:out@'+Host+'/';
}

Delete default value of an input text on click

Just use a placeholder tag in your input instead of value

How do I install the babel-polyfill library?

The Babel docs describe this pretty concisely:

Babel includes a polyfill that includes a custom regenerator runtime and core.js.

This will emulate a full ES6 environment. This polyfill is automatically loaded when using babel-node and babel/register.

Make sure you require it at the entry-point to your application, before anything else is called. If you're using a tool like webpack, that becomes pretty simple (you can tell webpack to include it in the bundle).

If you're using a tool like gulp-babel or babel-loader, you need to also install the babel package itself to use the polyfill.

Also note that for modules that affect the global scope (polyfills and the like), you can use a terse import to avoid having unused variables in your module:

import 'babel/polyfill';

The "backspace" escape character '\b': unexpected behavior?

Use a single backspace after each character printf("hello wor\bl\bd\n");

Most efficient way to remove special characters from string

There are lots of proposed solutions here, some more efficient than others, but perhaps not very readable. Here's one that may not be the most efficient, but certainly usable for most situations, and is quite concise and readable, leveraging Linq:

string stringToclean = "This is a test.  Do not try this at home; you might get hurt. Don't believe it?";

var validPunctuation = new HashSet<char>(". -");

var cleanedVersion = new String(stringToclean.Where(x => (x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z') || validPunctuation.Contains(x)).ToArray());

var cleanedLowercaseVersion = new String(stringToclean.ToLower().Where(x => (x >= 'a' && x <= 'z') || validPunctuation.Contains(x)).ToArray());

'python' is not recognized as an internal or external command

Try "py" instead of "python" from command line:

C:\Users\Cpsa>py
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Matrix Transpose in Python

The "best" answer has already been submitted, but I thought I would add that you can use nested list comprehensions, as seen in the Python Tutorial.

Here is how you could get a transposed array:

def matrixTranspose( matrix ):
    if not matrix: return []
    return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ]

how to implement login auth in node.js

@alessioalex answer is a perfect demo for fresh node user. But anyway, it's hard to write checkAuth middleware into all routes except login, so it's better to move the checkAuth from every route to one entry with app.use. For example:

function checkAuth(req, res, next) {
  // if logined or it's login request, then go next route
  if (isLogin || (req.path === '/login' && req.method === 'POST')) {
    next()
  } else {
    res.send('Not logged in yet.')
  }
}

app.use('/', checkAuth)

How do I export an Android Studio project?

Source control is best way to handle this problem, if you don't want to pay then try bitbucket

It's free, allows private repo for upto 5 members team.

Stretch and scale CSS background

Use the border-image : yourimage property to set your image and scale it upto the entire border of your screen or window .

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

I solve it by download the reportviewer.exe and install it. After the installation, all related assemblies will be available in C:\Windows\assembly\GAC_MSIL, then you can refer it in web config

How to run an external program, e.g. notepad, using hyperlink?

Make a batch file and call the bacth file in Window.open. Here how it works

  1. make a file in notepad
  2. write your script : start wmplayer "\dotnet\sc\1234.mp4" /fullscreen
  3. save as : test.bat in \dotnet\sc\test.bat

in html

window.open('file://dotnet/sc/test.bat')

Enjoy..

How to hide a div with jQuery?

$('#myDiv').hide();

or

$('#myDiv').slideUp();

or

$('#myDiv').fadeOut();

document.createElement("script") synchronously

I had the following problem(s) with the existing answers to this question (and variations of this question on other stackoverflow threads):

  • None of the loaded code was debuggable
  • Many of the solutions required callbacks to know when loading was finished instead of truly blocking, meaning I would get execution errors from immediately calling loaded (ie loading) code.

Or, slightly more accurately:

  • None of the loaded code was debuggable (except from the HTML script tag block, if and only if the solution added a script elements to the dom, and never ever as individual viewable scripts.) => Given how many scripts I have to load (and debug), this was unacceptable.
  • Solutions using 'onreadystatechange' or 'onload' events failed to block, which was a big problem since the code originally loaded dynamic scripts synchronously using 'require([filename, 'dojo/domReady']);' and I was stripping out dojo.

My final solution, which loads the script before returning, AND has all scripts properly accessible in the debugger (for Chrome at least) is as follows:

WARNING: The following code should PROBABLY be used only in 'development' mode. (For 'release' mode I recommend prepackaging and minification WITHOUT dynamic script loading, or at least without eval).

//Code User TODO: you must create and set your own 'noEval' variable

require = function require(inFileName)
{
    var aRequest
        ,aScript
        ,aScriptSource
        ;

    //setup the full relative filename
    inFileName = 
        window.location.protocol + '//'
        + window.location.host + '/'
        + inFileName;

    //synchronously get the code
    aRequest = new XMLHttpRequest();
    aRequest.open('GET', inFileName, false);
    aRequest.send();

    //set the returned script text while adding special comment to auto include in debugger source listing:
    aScriptSource = aRequest.responseText + '\n////# sourceURL=' + inFileName + '\n';

    if(noEval)//<== **TODO: Provide + set condition variable yourself!!!!**
    {
        //create a dom element to hold the code
        aScript = document.createElement('script');
        aScript.type = 'text/javascript';

        //set the script tag text, including the debugger id at the end!!
        aScript.text = aScriptSource;

        //append the code to the dom
        document.getElementsByTagName('body')[0].appendChild(aScript);
    }
    else
    {
        eval(aScriptSource);
    }
};

Post a json object to mvc controller with jquery and ajax

I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    function submitForm() {
        var roles = ["role1", "role2", "role3"];

        jQuery.ajax({
            type: "POST",
            url: "@Url.Action("AddUser")",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(roles),
            success: function (data) { alert(data); },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });
    }
</script>

<input type="button" value="Click" onclick="submitForm()"/>

And the controller action is going to be -

    public ActionResult AddUser(List<String> Roles)
    {
        return null;
    }

Then when you click on the button -

enter image description here

AndroidStudio gradle proxy

For the new android studio 1.2 you find the gradle vm args under:

File
- Settings
  - Build, Execution, Deployment
    - Build Tools
      - Gradle

Convert from java.util.date to JodaTime

http://joda-time.sourceforge.net/quickstart.html

Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:

* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class

Mail multipart/alternative vs multipart/mixed

Here is the best: Multipart/mixed mime message with attachments and inline images

And image: https://www.qcode.co.uk/images/mime-nesting-structure.png

From: [email protected]
To: to@@qcode.co.uk
Subject: Example Email
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="MixedBoundaryString"

--MixedBoundaryString
Content-Type: multipart/related; boundary="RelatedBoundaryString"

--RelatedBoundaryString
Content-Type: multipart/alternative; boundary="AlternativeBoundaryString"

--AlternativeBoundaryString
Content-Type: text/plain;charset="utf-8"
Content-Transfer-Encoding: quoted-printable

This is the plain text part of the email.

--AlternativeBoundaryString
Content-Type: text/html;charset="utf-8"
Content-Transfer-Encoding: quoted-printable

<html>
  <body>=0D
    <img src=3D=22cid:masthead.png=40qcode.co.uk=22 width 800 height=3D80=
 =5C>=0D
    <p>This is the html part of the email.</p>=0D
    <img src=3D=22cid:logo.png=40qcode.co.uk=22 width 200 height=3D60 =5C=
>=0D
  </body>=0D
</html>=0D

--AlternativeBoundaryString--

--RelatedBoundaryString
Content-Type: image/jpgeg;name="logo.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;filename="logo.png"
Content-ID: <[email protected]>

amtsb2hiaXVvbHJueXZzNXQ2XHVmdGd5d2VoYmFmaGpremxidTh2b2hydHVqd255aHVpbnRyZnhu
dWkgb2l1b3NydGhpdXRvZ2hqdWlyb2h5dWd0aXJlaHN1aWhndXNpaHhidnVqZmtkeG5qaG5iZ3Vy
...
...
a25qbW9nNXRwbF0nemVycHpvemlnc3k5aDZqcm9wdHo7amlodDhpOTA4N3U5Nnkwb2tqMm9sd3An
LGZ2cDBbZWRzcm85eWo1Zmtsc2xrZ3g=

--RelatedBoundaryString
Content-Type: image/jpgeg;name="masthead.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;filename="masthead.png"
Content-ID: <[email protected]>

aXR4ZGh5Yjd1OHk3MzQ4eXFndzhpYW9wO2tibHB6c2tqOTgwNXE0aW9qYWJ6aXBqOTBpcjl2MC1t
dGlmOTA0cW05dGkwbWk0OXQwYVttaXZvcnBhXGtsbGo7emt2c2pkZnI7Z2lwb2F1amdpNTh1NDlh
...
...
eXN6dWdoeXhiNzhuZzdnaHQ3eW9zemlqb2FqZWt0cmZ1eXZnamhka3JmdDg3aXV2dWd5aGVidXdz
dhyuhehe76YTGSFGA=

--RelatedBoundaryString--

--MixedBoundaryString
Content-Type: application/pdf;name="Invoice_1.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="Invoice_1.pdf"

aGZqZGtsZ3poZHVpeWZoemd2dXNoamRibngganZodWpyYWRuIHVqO0hmSjtyRVVPIEZSO05SVURF
SEx1aWhudWpoZ3h1XGh1c2loZWRma25kamlsXHpodXZpZmhkcnVsaGpnZmtsaGVqZ2xod2plZmdq
...
...
a2psajY1ZWxqanNveHV5ZXJ3NTQzYXRnZnJhZXdhcmV0eXRia2xhanNueXVpNjRvNWllc3l1c2lw
dWg4NTA0

--MixedBoundaryString
Content-Type: application/pdf;name="SpecialOffer.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="SpecialOffer.pdf"

aXBvY21odWl0dnI1dWk4OXdzNHU5NTgwcDN3YTt1OTQwc3U4NTk1dTg0dTV5OGlncHE1dW4zOTgw
cS0zNHU4NTk0eWI4OTcwdjg5MHE4cHV0O3BvYTt6dWI7dWlvenZ1em9pdW51dDlvdTg5YnE4N3Z3
...
...
OTViOHk5cDV3dTh5bnB3dWZ2OHQ5dTh2cHVpO2p2Ymd1eTg5MGg3ajY4bjZ2ODl1ZGlvcjQ1amts
dfnhgjdfihn=

--MixedBoundaryString--

.

Schema multipart/related/alternative

Header
|From: email
|To: email
|MIME-Version: 1.0
|Content-Type: multipart/mixed; boundary="boundary1";
Message body
|multipart/mixed --boundary1
|--boundary1
|   multipart/related --boundary2
|   |--boundary2
|   |   multipart/alternative --boundary3
|   |   |--boundary3
|   |   |text/plain
|   |   |--boundary3
|   |   |text/html
|   |   |--boundary3--
|   |--boundary2    
|   |Inline image
|   |--boundary2    
|   |Inline image
|   |--boundary2--
|--boundary1    
|Attachment1
|--boundary1
|Attachment2
|--boundary1
|Attachment3
|--boundary1--
|
.

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

I have just tested Google Geocoder and got the same problem as you have. I noticed I only get the OVER_QUERY_LIMIT status once every 12 requests So I wait for 1 second (that's the minimum delay to wait) It slows down the application but less than waiting 1 second every request

info = getInfos(getLatLng(code)); //In here I call Google API
record(code, info);
generated++; 
if(generated%interval == 0) {
holdOn(delay); // Every x requests, I sleep for 1 second
}

With the basic holdOn method :

private void holdOn(long delay) {
        try {
            Thread.sleep(delay);
        } catch (InterruptedException ex) {
            // ignore
        }
    }

Hope it helps

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

Just to share, I've developed my own script to do it. Feel free to use it. It generates "SELECT" statements that you can then run on the tables to generate the "INSERT" statements.

select distinct 'SELECT ''INSERT INTO ' + schema_name(ta.schema_id) + '.' + so.name + ' (' + substring(o.list, 1, len(o.list)-1) + ') VALUES ('
+ substring(val.list, 1, len(val.list)-1) + ');''  FROM ' + schema_name(ta.schema_id) + '.' + so.name + ';'
from    sys.objects so
join sys.tables ta on ta.object_id=so.object_id
cross apply
(SELECT '  ' +column_name + ', '
 from information_schema.columns c
 join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
 where table_name = so.name
 order by ordinal_position
FOR XML PATH('')) o (list)
cross apply
(SELECT '''+' +case
         when data_type = 'uniqueidentifier' THEN 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
         WHEN data_type = 'timestamp' then '''''''''+CONVERT(NVARCHAR(MAX),CONVERT(BINARY(8),[' + COLUMN_NAME + ']),1)+'''''''''
         WHEN data_type = 'nvarchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
         WHEN data_type = 'varchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
         WHEN data_type = 'char' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
         WHEN data_type = 'nchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
         when DATA_TYPE='datetime' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
         when DATA_TYPE='datetime2' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
         when DATA_TYPE='geography' and column_name<>'Shape' then 'ST_GeomFromText(''POINT('+column_name+'.Lat '+column_name+'.Long)'') '
         when DATA_TYPE='geography' and column_name='Shape' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
         when DATA_TYPE='bit' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
         when DATA_TYPE='xml' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE(CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + ']),'''''''','''''''''''')+'''''''' END '
         WHEN DATA_TYPE='image' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),CONVERT(VARBINARY(MAX),[' + COLUMN_NAME + ']),1)+'''''''' END '
         WHEN DATA_TYPE='varbinary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
         WHEN DATA_TYPE='binary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
         when DATA_TYPE='time' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
         ELSE 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE CONVERT(NVARCHAR(MAX),['+column_name+']) END' end
   + '+'', '
 from information_schema.columns c
 join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
 where table_name = so.name
 order by ordinal_position
FOR XML PATH('')) val (list)
where   so.type = 'U'

SELECT using 'CASE' in SQL

Try this.

SELECT 
  CASE 
     WHEN FRUIT = 'A' THEN 'APPLE'
     WHEN FRUIT = 'B' THEN 'BANANA'
     ELSE 'UNKNOWN FRUIT'
  END AS FRUIT
FROM FRUIT_TABLE;

How to unzip files programmatically in Android?

I'm working with zip files which Java's ZipFile class isn't able to handle. Java 8 apparently can't handle compression method 12 (bzip2 I believe). After trying a number of methods including zip4j (which also fails with these particular files due to another issue), I had success with Apache's commons-compress which supports additional compression methods as mentioned here.

Note that the ZipFile class below is not the one from java.util.zip.

It's actually org.apache.commons.compress.archivers.zip.ZipFile so be careful with the imports.

try (ZipFile zipFile = new ZipFile(archiveFile)) {
    Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = entries.nextElement();
        File entryDestination = new File(destination, entry.getName());
        if (entry.isDirectory()) {
            entryDestination.mkdirs();
        } else {
            entryDestination.getParentFile().mkdirs();
            try (InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(entryDestination)) {
                IOUtils.copy(in, out);
            }
        }
    }
} catch (IOException ex) {
    log.debug("Error unzipping archive file: " + archiveFile, ex);
}

For Gradle:

compile 'org.apache.commons:commons-compress:1.18'

Export query result to .csv file in SQL Server 2008

Building on N.S's answer, I have a PowerShell script that exports to a CSV file with the quote marks around the field and comma separated and it skips the header information in the file.

add-pssnapin sqlserverprovidersnapin100
add-pssnapin sqlservercmdletsnapin100

$qry = @"
Select
  *
From
 tablename
"@

Invoke-Sqlcmd -ServerInstance Server -Database DBName -Query $qry | convertto-CSV -notype | select -skip 1  > "full path and filename.csv"

The first two lines enable the ability to use the Invoke-SqlCmd command-let.

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

Is there a "not equal" operator in Python?

You can use both != or <>.

However, note that != is preferred where <> is deprecated.

Connecting to TCP Socket from browser using javascript

The solution you are really looking for is web sockets. However, the chromium project has developed some new technologies that are direct TCP connections TCP chromium

Visual Studio 2010 always thinks project is out of date, but nothing has changed

I met this problem today, however it was a bit different. I had a CUDA DLL project in my solution. Compiling in a clean solution was OK, but otherwise it failed and the compiler always treated the CUDA DLL project as not up to date.

I tried the solution from this post.

But there is no missing header file in my solution. Then I found out the reason in my case.

I have changed the project's Intermediate Directory before, although it didn't cause trouble. And now when I changed the CUDA DLL Project's Intermediate Directory back to $(Configuration)\, everything works right again.

I guess there is some minor problem between CUDA Build Customization and non-default Intermediate Directory.

How do I execute a command and get the output of the command within C++ using POSIX?

#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>

std::string exec(const char* cmd) {
    std::array<char, 128> buffer;
    std::string result;
    std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
    if (!pipe) {
        throw std::runtime_error("popen() failed!");
    }
    while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
        result += buffer.data();
    }
    return result;
}

Pre-C++11 version:

#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>

std::string exec(const char* cmd) {
    char buffer[128];
    std::string result = "";
    FILE* pipe = popen(cmd, "r");
    if (!pipe) throw std::runtime_error("popen() failed!");
    try {
        while (fgets(buffer, sizeof buffer, pipe) != NULL) {
            result += buffer;
        }
    } catch (...) {
        pclose(pipe);
        throw;
    }
    pclose(pipe);
    return result;
}

Replace popen and pclose with _popen and _pclose for Windows.

Can't append <script> element

Adding the sourceURL in the script file helped as mentioned in this page: https://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/

  1. In the script file, add a statement with sourceURL like "//@ sourceURL=foo.js"
  2. Load the script using jQuery $.getScript() and the script will be available in "sources" tab in chrome dev tools

Objects inside objects in javascript

You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:

{el1, el2, {el31, el32, el33}, {el41, el42}}

_x000D_
_x000D_
var MainObj = {_x000D_
_x000D_
  prop1: "prop1MainObj",_x000D_
  _x000D_
  Obj1: {_x000D_
    prop1: "prop1Obj1",_x000D_
    prop2: "prop2Obj1",    _x000D_
    Obj2: {_x000D_
      prop1: "hey you",_x000D_
      prop2: "prop2Obj2"_x000D_
    }_x000D_
  },_x000D_
    _x000D_
  Obj3: {_x000D_
    prop1: "prop1Obj3",_x000D_
    prop2: "prop2Obj3"_x000D_
  },_x000D_
  _x000D_
  Obj4: {_x000D_
    prop1: true,_x000D_
    prop2: 3_x000D_
  }  _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
_x000D_
_x000D_

How to open Android Device Monitor in latest Android Studio 3.1

From Android Studio 3.1 Device Monitor available from the command line only.

In Android Studio 3.1, the Device Monitor serves less of a role than it previously did. In many cases, the functionality available through the Device Monitor is now provided by new and improved tools.

See the Device Monitor documentation for instructions for invoking the Device Monitor from the command line and for details of the tools available through the Device Monitor.

To start the standalone Device Monitor application, enter the following on the command line in the android-sdk/tools/ directory:

monitor

What are unit tests, integration tests, smoke tests, and regression tests?

Unit Testing

Unit testing is usually done by the developers side, whereas testers are partly evolved in this type of testing where testing is done unit by unit. In Java JUnit test cases can also be possible to test whether the written code is perfectly designed or not.

Integration Testing:

This type of testing is possible after the unit testing when all/some components are integrated. This type of testing will make sure that when components are integrated, do they affect each others' working capabilities or functionalities?

Smoke Testing

This type of testing is done at the last when system is integrated successfully and ready to go on production server.

This type of testing will make sure that every important functionality from start to end is working fine and system is ready to deploy on production server.

Regression Testing

This type of testing is important to test that unintended/unwanted defects are not present in the system when developer fixed some issues. This testing also make sure that all the bugs are successfully solved and because of that no other issues are occurred.

How to remove the URL from the printing page?

<style type="text/css" media="print">
  @page {
    size: auto;  
    margin: 0;  
  }
</style>
//now set manual padding to body
<style>
  body{
    padding-left: 1.3cm;
    padding-right: 1.3cm; 
    padding-top: 1.1cm;
  }
</style>

How to delete all files from a specific folder?

System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(myDirPath);

foreach (FileInfo file in myDirInfo.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
{
    dir.Delete(true); 
}

Understanding dict.copy() - shallow or deep?

Take this example:

original = dict(a=1, b=2, c=dict(d=4, e=5))
new = original.copy()

Now let's change a value in the 'shallow' (first) level:

new['a'] = 10
# new = {'a': 10, 'b': 2, 'c': {'d': 4, 'e': 5}}
# original = {'a': 1, 'b': 2, 'c': {'d': 4, 'e': 5}}
# no change in original, since ['a'] is an immutable integer

Now let's change a value one level deeper:

new['c']['d'] = 40
# new = {'a': 10, 'b': 2, 'c': {'d': 40, 'e': 5}}
# original = {'a': 1, 'b': 2, 'c': {'d': 40, 'e': 5}}
# new['c'] points to the same original['d'] mutable dictionary, so it will be changed

Is there a code obfuscator for PHP?

Nothing will be perfect. If you just want something to stop non-programmers then here's a little script I wrote you can use:

<?php
$infile=$_SERVER['argv'][1];
$outfile=$_SERVER['argv'][2];
if (!$infile || !$outfile) {
    die("Usage: php {$_SERVER['argv'][0]} <input file> <output file>\n");
}
echo "Processing $infile to $outfile\n";
$data="ob_end_clean();?>";
$data.=php_strip_whitespace($infile);
// compress data
$data=gzcompress($data,9);
// encode in base64
$data=base64_encode($data);
// generate output text
$out='<?ob_start();$a=\''.$data.'\';eval(gzuncompress(base64_decode($a)));$v=ob_get_contents();ob_end_clean();?>';
// write output text
file_put_contents($outfile,$out);

How can I disable ARC for a single file in a project?

Just use the -fno-objc-arc flag in Build Phases>Compile Sources infront of files to whom you dont want ARC to be apply.

Is "else if" faster than "switch() case"?

Since the switch statement expresses the same intent as your if / else chain but in a more restricted, formal manner, your first guess should be that the compiler will be able to optimize it better, since it can draw more conclusions about the conditions placed on your code (i.e. only one state can possibly be true, the value being compared is a primitive type, etc.) This is a pretty safe general truth when you are comparing two similar language structures for runtime performance.

How to download fetch response in react as file

I managed to download the file generated by the rest API URL much easier with this kind of code which worked just fine on my local:

    import React, {Component} from "react";
    import {saveAs} from "file-saver";

    class MyForm extends Component {

    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(event) {
        event.preventDefault();
        const form = event.target;
        let queryParam = buildQueryParams(form.elements);

        let url = 'http://localhost:8080/...whatever?' + queryParam;

        fetch(url, {
            method: 'GET',
            headers: {
                // whatever
            },
        })
            .then(function (response) {
                    return response.blob();
                }
            )
            .then(function(blob) {
                saveAs(blob, "yourFilename.xlsx");
            })
            .catch(error => {
                //whatever
            })
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit} id="whateverFormId">
                <table>
                    <tbody>
                    <tr>
                        <td>
                            <input type="text" key="myText" name="myText" id="myText"/>
                        </td>
                        <td><input key="startDate" name="from" id="startDate" type="date"/></td>
                        <td><input key="endDate" name="to" id="endDate" type="date"/></td>
                    </tr>
                    <tr>
                        <td colSpan="3" align="right">
                            <button>Export</button>
                        </td>
                    </tr>

                    </tbody>
                </table>
            </form>
        );
    }
}

function buildQueryParams(formElements) {
    let queryParam = "";

    //do code here
    
    return queryParam;
}

export default MyForm;

Unix command to check the filesize

Here's yet another option to add to the mix:

$ du -b file.txt

That is: estimate file space usage of file.txt in bytes.

JavaScript, Node.js: is Array.forEach asynchronous?

There is a package on npm for easy asynchronous for each loops.

var forEachAsync = require('futures').forEachAsync;

// waits for one request to finish before beginning the next 
forEachAsync(['dogs', 'cats', 'octocats'], function (next, element, index, array) {
  getPics(element, next);
  // then after all of the elements have been handled 
  // the final callback fires to let you know it's all done 
  }).then(function () {
    console.log('All requests have finished');
});

Also another variation forAllAsync

PHP Configuration: It is not safe to rely on the system's timezone settings

I found, bizarrely, that I could fix the errors by placing the timezone declaration at the TOP of my php.ini file.

It was already in my php.ini. Twice, actually. And I was pulling my hair out because everyone was saying there must be another ini being loaded... There wasn't.

Hope this can save someone else the time/hair loss.

Unit testing private methods in C#

Another thought here is to extend testing to "internal" classes/methods, giving more of a white-box sense of this testing. You can use InternalsVisibleToAttribute on the assembly to expose these to separate unit testing modules.

In combination with sealed class you can approach such encapsulation that test method are visible only from unittest assembly your methods. Consider that protected method in sealed class is de facto private.

[assembly: InternalsVisibleTo("MyCode.UnitTests")]
namespace MyCode.MyWatch
{
    #pragma warning disable CS0628 //invalid because of InternalsVisibleTo
    public sealed class MyWatch
    {
        Func<DateTime> _getNow = delegate () { return DateTime.Now; };


       //construktor for testing purposes where you "can change DateTime.Now"
       internal protected MyWatch(Func<DateTime> getNow)
       {
           _getNow = getNow;
       }

       public MyWatch()
       {            
       }
   }
}

And unit test:

namespace MyCode.UnitTests
{

[TestMethod]
public void TestminuteChanged()
{
    //watch for traviling in time
    DateTime baseTime = DateTime.Now;
    DateTime nowforTesting = baseTime;
    Func<DateTime> _getNowForTesting = delegate () { return nowforTesting; };

    MyWatch myWatch= new MyWatch(_getNowForTesting );
    nowforTesting = baseTime.AddMinute(1); //skip minute
    //TODO check myWatch
}

[TestMethod]
public void TestStabilityOnFebruary29()
{
    Func<DateTime> _getNowForTesting = delegate () { return new DateTime(2024, 2, 29); };
    MyWatch myWatch= new MyWatch(_getNowForTesting );
    //component does not crash in overlap year
}
}

exception in thread 'main' java.lang.NoClassDefFoundError:

I had the same problem, and stumbled onto a solution with 'Build Main Project F11'. The ide brought up an "option" that I might want to uncheck 'Compile on Save' in the Build > Compiling portion of the Project configuration dialog. Unchecking 'Complile on Save' and then doing the usual (for me) 'Clean and Build' did the trick for me.

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

ImmutableMap does not accept null values whereas Collections.unmodifiableMap() does. In addition it will never change after construction, while UnmodifiableMap may. From the JavaDoc:

An immutable, hash-based Map with reliable user-specified iteration order. Does not permit null keys or values.

Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.

How to Apply global font to whole HTML document

Use the following css:

* {
    font: Verdana, Arial, 'sans-serif' !important;/* <-- fonts */
}

The *-selector means any/all elements, but will obviously be on the bottom of the food chain when it comes to overriding more specific selectors.

Note that the !important-flag will render the font-style for * to be absolute, even if other selectors have been used to set the text (for example, the body or maybe a p).

How does MySQL CASE work?

I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even

SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;

How to jump back to NERDTree from file in tab?

You can change the tabs by ctrl-pgup and ctrl-pgdown. On that tab you came from the NERDTree is still selected and you can open another tab.

Find row in datatable with specific id

Hello just create a simple function that looks as shown below.. That returns all rows where the call parameter entered is valid or true.

 public  DataTable SearchRecords(string Col1, DataTable RecordDT_, int KeyWORD)
    {
        TempTable = RecordDT_;
        DataView DV = new DataView(TempTable);
        DV.RowFilter = string.Format(string.Format("Convert({0},'System.String')",Col1) + " LIKE '{0}'", KeyWORD);
        return DV.ToTable();
    }

and simply call it as shown below;

  DataTable RowsFound=SearchRecords("IdColumn", OriginalTable,5);

where 5 is the ID. Thanks..

Class 'DOMDocument' not found

Package php-dom is a virtual package provided by:
  php7.1-xml 7.1.3+-3+deb.sury.org~xenial+1
  php7.0-xml 7.0.17-3+deb.sury.org~xenial+1
  php5.6-xml 5.6.30-9+deb.sury.org~xenial+1
You should explicitly select one to install.

In case anyone using 5.6 versions then go with this way

sudo apt-get install php5.6-xml

For Php Ver PHP7, Ubuntu:

sudo apt-get install php7.1-xml

or by

yum install php-xml

How to create EditText with rounded corners?

Try this one,

  1. Create rounded_edittext.xml file in your Drawable

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" android:padding="15dp">
    
        <solid android:color="#FFFFFF" />
        <corners
            android:bottomRightRadius="0dp"
            android:bottomLeftRadius="0dp"
            android:topLeftRadius="0dp"
            android:topRightRadius="0dp" />
        <stroke android:width="1dip" android:color="#f06060" />
    </shape>
    
  2. Apply background for your EditText in xml file

    <EditText
        android:id="@+id/edit_expiry_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:background="@drawable/rounded_edittext"
        android:hint="@string/shop_name"
        android:inputType="text" />  
    
  3. You will get output like this

enter image description here

Sending an Intent to browser to open specific URL

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);

Hide Button After Click (With Existing Form on Page)

This is my solution. I Hide and then confirm check

onclick="return ConfirmSubmit(this);" />

function ConfirmSubmit(sender)
    {
        sender.disabled = true;
        var displayValue = sender.style.
        sender.style.display = 'none'

        if (confirm('Seguro que desea entregar los paquetes?')) {
            sender.disabled = false
            return true;
        }

        sender.disabled = false;
        sender.style.display = displayValue;
        return false;
    }

How to remove .html from URL?

To remove the .html extension from your URLs, you can use the following code in root/htaccess :

#mode_rerwrite start here

RewriteEngine On

# does not apply to existing directores, meaning that if the folder exists on server then don't change anything and don't run the rule.

RewriteCond %{REQUEST_FILENAME} !-d

#Check for file in directory with .html extension 

RewriteCond %{REQUEST_FILENAME}\.html !-f

#Here we actually show the page that has .html extension

RewriteRule ^(.*)$ $1.html [NC,L]

Thanks

Python Unicode Encode Error

Python 3.5, 2018

If you don't know what the encoding but the unicode parser is having issues you can open the file in Notepad++ and in the top bar select Encoding->Convert to ANSI. Then you can write your python like this

with open('filepath', 'r', encoding='ANSI') as file:
    for word in file.read().split():
        print(word)

Pass in an array of Deferreds to $.when()

If you're using angularJS or some variant of the Q promise library, then you have a .all() method that solves this exact problem.

var savePromises = [];
angular.forEach(models, function(model){
  savePromises.push(
    model.saveToServer()
  )
});

$q.all(savePromises).then(
  function success(results){...},
  function failed(results){...}
);

see the full API:

https://github.com/kriskowal/q/wiki/API-Reference#promiseall

https://docs.angularjs.org/api/ng/service/$q

How do I find the MySQL my.cnf location

For Ubuntu 16: /etc/mysql/mysql.conf.d/mysqld.cnf

Top 5 time-consuming SQL queries in Oracle

It depends which version of oracle you have, for 9i and below Statspack is what you are after, 10g and above, you want awr , both these tools will give you the top sql's and lots of other stuff.

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

SELECT t.*,
       @rownum := @rownum +1 AS rank
  FROM TBL_FOO t
  JOIN (SELECT @rownum := 0) r
 WHERE t.name = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

What does "Changes not staged for commit" mean

What worked for me was to go to the root folder, where .git/ is. I was inside one the child folders and got there error.

IFrame: This content cannot be displayed in a frame

The X-Frame-Options is defined in the Http Header and not in the <head> section of the page you want to use in the iframe.

Accepted values are: DENY, SAMEORIGIN and ALLOW-FROM "url"

restart mysql server on windows 7

Ctrl + alt +delete to start TASK MANAGER ,choose Service ,Then you will find MySQL, click that item by right click,then choose start, your MySQL Server will start!

How to echo xml file in php

This worked for me:

echo(header('content-type: text/xml'));

D3.js: How to get the computed width and height for an arbitrary element?

.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following

  • left, right
  • top, bottom
  • height, width

Example :

var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;

How to iterate through a table rows and get the cell values using jQuery

$(this) instead of $this

$("tr.item").each(function() {
        var quantity1 = $(this).find("input.name").val(),
            quantity2 = $(this).find("input.id").val();
});

Proof_1:

proof_2:

How can I run a php without a web server?

You can use these kind of programs to emulate an apache web server and run PHP on your computer:

http://www.wampserver.com/en/

http://www.apachefriends.org/en/xampp.html

Changing the browser zoom level

Possible in IE and chrome although it does not work in firefox:

<script>
   function toggleZoomScreen() {
       document.body.style.zoom = "80%";
   } 
</script>

<img src="example.jpg" alt="example" onclick="toggleZoomScreen()">

How to get the url parameters using AngularJS

If you're using ngRoute, you can inject $routeParams into your controller

http://docs.angularjs.org/api/ngRoute/service/$routeParams

If you're using angular-ui-router, you can inject $stateParams

https://github.com/angular-ui/ui-router/wiki/URL-Routing

How to remove the default link color of the html hyperlink 'a' tag?

<style>
a {
color:      ;
}
</style>

This code changes the color from the default to what is specified in the style. Using a:hover, you can change the color of the text from the default on hover.

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

In iOS 10+

Apple enabled the attribute playsinline in all browsers on iOS 10, so this works seamlessly:

<video src="file.mp4" playsinline>

In iOS 8 and iOS 9

Short answer: use iphone-inline-video, it enables inline playback and syncs the audio.

Long answer: You can work around this issue by simulating the playback by skimming the video instead of actually .play()'ing it.

pandas python how to count the number of records or rows in a dataframe

Regards to your question... counting one Field? I decided to make it a question, but I hope it helps...

Say I have the following DataFrame

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.normal(0, 1, (5, 2)), columns=["A", "B"])

You could count a single column by

df.A.count()
#or
df['A'].count()

both evaluate to 5.

The cool thing (or one of many w.r.t. pandas) is that if you have NA values, count takes that into consideration.

So if I did

df['A'][1::2] = np.NAN
df.count()

The result would be

 A    3
 B    5

Fatal error: Call to undefined function: ldap_connect()

Open the XAMMP php.ini file (the default path is C:\xammp\php\php.ini) and change the code (;extension=ldap) to extension=php_ldap.dll and save. Restart XAMMP and save.

php.ini

; Notes for Windows environments :
;
; - Many DLL files are located in the extensions/ (PHP 4) or ext/ (PHP 5+)
;   extension folders as well as the separate PECL DLL download (PHP 5+).
;   Be sure to appropriately set the extension_dir directive.
;
extension=bz2
extension=curl
extension=fileinfo
extension=gd2
extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=interbase
extension=php_ldap.dll

Convert a timedelta to days, hours and minutes

days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60

As for DST, I think the best thing is to convert both datetime objects to seconds. This way the system calculates DST for you.

>>> m13 = datetime(2010, 3, 13, 8, 0, 0)  # 2010 March 13 8:00 AM
>>> m14 = datetime(2010, 3, 14, 8, 0, 0)  # DST starts on this day, in my time zone
>>> mktime(m14.timetuple()) - mktime(m13.timetuple())     # difference in seconds
82800.0
>>> _/3600                                                # convert to hours
23.0

How to increase font size in NeatBeans IDE?

I would upgrade to newer Netbeans 7.1 or wait few days/weeks for 7.2, it can be a bug in Netbeans 6.8.

I just add to previous two solutions, that you can increase size temporary with ALT(CTRL) + mouse wheel as in browser. (ALT in Netbeans 7.2, CTRL in Netbeans 7.1)

Loop through columns and add string lengths as new columns

For the sake of completeness, there is also a data.table solution:

library(data.table)
result <- setDT(df)[, paste0(names(df), "_length") := lapply(.SD, stringr::str_length)]
result
#      col1     col2 col1_length col2_length
#1:     abc adf qqwe           3           8
#2:    abcd        d           4           1
#3:       a        e           1           1
#4: abcdefg        f           7           1

"Undefined reference to" template class constructor

This link explains where you're going wrong:

[35.12] Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?

Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.

This offers another solution:

How can I avoid linker errors with my template functions?

However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.

How to convert ActiveRecord results into an array of hashes

For current ActiveRecord (4.2.4+) there is a method to_hash on the Result object that returns an array of hashes. You can then map over it and convert to symbolized hashes:

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

result.to_hash.map(&:symbolize_keys)
# => [{:id => 1, :title => "title_1", :body => "body_1"},
      {:id => 2, :title => "title_2", :body => "body_2"},
      ...
     ]

See the ActiveRecord::Result docs for more info.

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

The particular exception message is telling you that the mentioned class is missing in the classpath. As the org.apache.commons.io package name hints, the mentioned class is part of the http://commons.apache.org/io project.

And indeed, Commons FileUpload has Commons IO as a dependency. You need to download and drop commons-io.jar in the /WEB-INF/lib as well.

See also:

AJAX reload page with POST

Reload the current document:

 <script type="text/javascript">
 function reloadPage()
 {
   window.location.reload()
 }
 </script>

Replace HTML Table with Divs

there is a very useful online tool for this, just automatically transform the table into divs:

http://www.html-cleaner.com/features/replace-html-table-tags-with-divs/

And the video that explains it: https://www.youtube.com/watch?v=R1ArAee6wEQ

I'm using this on a daily basis. I hope it helps ;)

In git how is fetch different than pull and how is merge different than rebase?

fetch vs pull

fetch will download any changes from the remote* branch, updating your repository data, but leaving your local* branch unchanged.

pull will perform a fetch and additionally merge the changes into your local branch.

What's the difference? pull updates you local branch with changes from the pulled branch. A fetch does not advance your local branch.

merge vs rebase

Given the following history:

          C---D---E local
         /
    A---B---F---G remote

merge joins two development histories together. It does this by replaying the changes that occurred on your local branch after it diverged on top of the remote branch, and record the result in a new commit. This operation preserves the ancestry of each commit.

The effect of a merge will be:

          C---D---E local
         /         \
    A---B---F---G---H remote

rebase will take commits that exist in your local branch and re-apply them on top of the remote branch. This operation re-writes the ancestors of your local commits.

The effect of a rebase will be:

                  C'--D'--E' local
                 /
    A---B---F---G remote

What's the difference? A merge does not change the ancestry of commits. A rebase rewrites the ancestry of your local commits.

* This explanation assumes that the current branch is a local branch, and that the branch specified as the argument to fetch, pull, merge, or rebase is a remote branch. This is the usual case. pull, for example, will download any changes from the specified branch, update your repository and merge the changes into the current branch.

Eloquent ORM laravel 5 Get Array of ids

Just an extra info, if you are using DB:

DB::table('test')->where('id', '>', 0)->pluck('id')->toArray();

And if using Eloquent model:

test::where('id', '>', 0)->lists('id')->toArray();

How to suppress Pandas Future warning ?

Found this on github...

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

import pandas

How do I clone a github project to run locally?

You clone a repository with git clone [url]. Like so,

$ git clone https://github.com/libgit2/libgit2

How to embed YouTube videos in PHP?

Just a small update to Alec Smart's answer: since AS2 is deprecated now, the '?version=3' is required to get his example to work. See the Youtube reference at YouTube Embedded Players and Player Parameters under "Selecting content to play" for details.

In other words:

<object width="425" height="350" data="http://www.youtube.com/v/Ahg6qcgoay4?version=3" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/Ahg6qcgoay4?version=3" /></object>

Apparently, the Youtube reference above does this as follows (the inner embed presumably used as a fallback for browsers that don't yet support the object tag):

<object width="640" height="390">
  <param name="movie"
         value="https://www.youtube.com/v/u1zgFlCw8Aw?version=3&autoplay=1"></param>
  <param name="allowScriptAccess" value="always"></param>
  <embed src="https://www.youtube.com/v/u1zgFlCw8Aw?version=3&autoplay=1"
         type="application/x-shockwave-flash"
         allowscriptaccess="always"
         width="640" height="390"></embed>
</object>

Or using iframes (replace http://example.com with your site's domain):

<iframe id="ytplayer" type="text/html" width="640" height="390" src="http://www.youtube.com/embed/u1zgFlCw8Aw?autoplay=1&origin=http://example.com" frameborder="0"/>

How to measure elapsed time

There are many ways to achieve this, but the most important consideration to measure elapsed time is to use System.nanoTime() and TimeUnit.NANOSECONDS as the time unit. Why should I do this? Well, it is because System.nanoTime() method returns a high-resolution time source, in nanoseconds since some reference point (i.e. Java Virtual Machine's start up).

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.

For the same reason, it is recommended to avoid the use of the System.currentTimeMillis() method for measuring elapsed time. This method returns the wall-clock time, which may change based on many factors. This will be negative for your measurements.

Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

So here you have one solution based on the System.nanoTime() method, another one using Guava, and the final one Apache Commons Lang

public class TimeBenchUtil
{
    public static void main(String[] args) throws InterruptedException
    {
        stopWatch();
        stopWatchGuava();
        stopWatchApacheCommons();
    }

    public static void stopWatch() throws InterruptedException
    {
        long endTime, timeElapsed, startTime = System.nanoTime();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);

        /* ... the code being measured ends ... */

        endTime = System.nanoTime();

        // get difference of two nanoTime values
        timeElapsed = endTime - startTime;

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }

    public static void stopWatchGuava() throws InterruptedException
    {
        // Creates and starts a new stopwatch
        Stopwatch stopwatch = Stopwatch.createStarted();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);
        /* ... the code being measured ends ... */

        stopwatch.stop(); // optional

        // get elapsed time, expressed in milliseconds
        long timeElapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }

    public static void stopWatchApacheCommons() throws InterruptedException
    {
        StopWatch stopwatch = new StopWatch();
        stopwatch.start();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);

        /* ... the code being measured ends ... */

        stopwatch.stop();    // Optional

        long timeElapsed = stopwatch.getNanoTime();

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }
}

grep for special characters in Unix

Tell grep to treat your input as fixed string using -F option.

grep -F '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log

Option -n is required to get the line number,

grep -Fn '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log

How do I detect if I am in release or debug mode?

Alternatively, you could differentiate using BuildConfig.BUILD_TYPE;

If you're running debug build BuildConfig.BUILD_TYPE.equals("debug"); returns true. And for release build BuildConfig.BUILD_TYPE.equals("release"); returns true.

Taking screenshot on Emulator from Android Studio

Long Press on Power button, then you will have the option for the screenshot. Power Button Emulator

Option for screenshot in emulator

How to find all the dependencies of a table in sql server

Query the sysdepends table:

SELECT distinct schema_name(dependentObject.uid) as schema, 
       dependentObject.*
 FROM sysdepends d 
INNER JOIN sysobjects o on d.id = o.id 
INNER JOIN sysobjects dependentObject on d.depid = dependentObject.id
WHERE o.name = 'TableName'

A way to look just for views/functions/triggers/procedures that reference the object (or any given text) by name is:

SELECT distinct schema_name(so.uid) + '.' + so.name 
  FROM syscomments sc 
 INNER JOIN  sysobjects so on sc.id = so.id 
 WHERE sc.text like '%Name%'

Join two data frames, select all columns from one and some columns from the other

function to drop duplicate columns after joining.

check it

def dropDupeDfCols(df): newcols = [] dupcols = []

for i in range(len(df.columns)):
    if df.columns[i] not in newcols:
        newcols.append(df.columns[i])
    else:
        dupcols.append(i)

df = df.toDF(*[str(i) for i in range(len(df.columns))])
for dupcol in dupcols:
    df = df.drop(str(dupcol))

return df.toDF(*newcols)

How to find all occurrences of an element in a list

You can use a list comprehension:

indices = [i for i, x in enumerate(my_list) if x == "whatever"]

How to check a Long for null in java

As mentioned already primitives can not be set to the Object type null.

What I do in such cases is just to use -1 or Long.MIN_VALUE.

Adding Google Play services version to your app's manifest?

This error can also happen when you've downloaded a new version of Google Play Services and not installed the latest SDK. Thats what happened to me. So, as the others mentioned, if you try to import Google Play Services and then open the console, you'll see a compile error. Try installing all the recent Android SDKs and try again, if this is the case.

How to determine the current shell I'm working on

None of the answers worked with fish shell (it doesn't have the variables $$ or $0).

This works for me (tested on sh, bash, fish, ksh, csh, true, tcsh, and zsh; openSUSE 13.2):

ps | tail -n 4 | sed -E '2,$d;s/.* (.*)/\1/'

This command outputs a string like bash. Here I'm only using ps, tail, and sed (without GNU extesions; try to add --posix to check it). They are all standard POSIX commands. I'm sure tail can be removed, but my sed fu is not strong enough to do this.

It seems to me, that this solution is not very portable as it doesn't work on OS X. :(

Mysql adding user for remote access

Follow instructions (steps 1 to 3 don't needed in windows):

  1. Find mysql config to edit:

    /etc/mysql/my.cnf (Mysql 5.5)

    /etc/mysql/conf.d/mysql.cnf (Mysql 5.6+)

  2. Find bind-address=127.0.0.1 in config file change bind-address=0.0.0.0 (you can set bind address to one of your interface ips or like me use 0.0.0.0)

  3. Restart mysql service run on console: service restart mysql

  4. Create a user with a safe password for remote connection. To do this run following command in mysql (if you are linux user to reach mysql console run mysql and if you set password for root run mysql -p):

    GRANT ALL PRIVILEGES 
     ON *.* TO 'remote'@'%' 
     IDENTIFIED BY 'safe_password' 
     WITH GRANT OPTION;`
    

Now you should have a user with name of user and password of safe_password with capability of remote connect.

Group By Multiple Columns

A thing to note is that you need to send in an object for Lambda expressions and can't use an instance for a class.

Example:

public class Key
{
    public string Prop1 { get; set; }

    public string Prop2 { get; set; }
}

This will compile but will generate one key per cycle.

var groupedCycles = cycles.GroupBy(x => new Key
{ 
  Prop1 = x.Column1, 
  Prop2 = x.Column2 
})

If you wan't to name the key properties and then retreive them you can do it like this instead. This will GroupBy correctly and give you the key properties.

var groupedCycles = cycles.GroupBy(x => new 
{ 
  Prop1 = x.Column1, 
  Prop2= x.Column2 
})

foreach (var groupedCycle in groupedCycles)
{
    var key = new Key();
    key.Prop1 = groupedCycle.Key.Prop1;
    key.Prop2 = groupedCycle.Key.Prop2;
}

Add an object to a python list

Is your problem similar to this:

l = [[0]] * 4
l[0][0] += 1
print l # prints "[[1], [1], [1], [1]]"

If so, you simply need to copy the objects when you store them:

import copy
l = [copy.copy(x) for x in [[0]] * 4]
l[0][0] += 1
print l # prints "[[1], [0], [0], [0]]"

The objects in question should implement a __copy__ method to copy objects. See the documentation for copy. You may also be interested in copy.deepcopy, which is there as well.

EDIT: Here's the problem:

arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(wM) # appends the wM object to the list
    wM.reset()           # clears  the wM object

You need to append a copy:

import copy
arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(copy.copy(wM)) # appends a copy to the list
    wM.reset()                      # clears the wM object

But I'm still confused as to where wM is coming from. Won't you just be copying the same wM object over and over, except clearing it after the first time so all the rest will be empty? Or does model() modify the wM (which sounds like a terrible design flaw to me)? And why are you throwing away result?

Angular ng-repeat add bootstrap row every 3 or 4 cols

This worked for me, no splicing or anything required:

HTML

<div class="row" ng-repeat="row in rows() track by $index">
    <div class="col-md-3" ng-repeat="item in items" ng-if="indexInRange($index,$parent.$index)"></div>
</div>

JavaScript

var columnsPerRow = 4;
$scope.rows = function() {
  return new Array(columnsPerRow);
};
$scope.indexInRange = function(columnIndex,rowIndex) {
  return columnIndex >= (rowIndex * columnsPerRow) && columnIndex < (rowIndex * columnsPerRow) + columnsPerRow;
};

How would you do a "not in" query with LINQ?

I did not test this with LINQ to Entities:

NorthwindDataContext dc = new NorthwindDataContext();    
dc.Log = Console.Out;

var query =    
    from c in dc.Customers 
    where !dc.Orders.Any(o => o.CustomerID == c.CustomerID)   
    select c;

Alternatively:

NorthwindDataContext dc = new NorthwindDataContext();    
dc.Log = Console.Out;

var query =    
    from c in dc.Customers 
    where dc.Orders.All(o => o.CustomerID != c.CustomerID)   
    select c;

foreach (var c in query) 
    Console.WriteLine( c );

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

WPF Datagrid set selected row

please check if code below would work for you; it iterates through cells of the datagris's first column and checks if cell content equals to the textbox.text value and selects the row.

for (int i = 0; i < dataGrid.Items.Count; i++)
{
    DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
    TextBlock cellContent = dataGrid.Columns[0].GetCellContent(row) as TextBlock;
    if (cellContent != null && cellContent.Text.Equals(textBox1.Text))
    {
        object item = dataGrid.Items[i];
        dataGrid.SelectedItem = item;
        dataGrid.ScrollIntoView(item);
        row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        break;
    }
}

hope this helps, regards

Python: Importing urllib.quote

Use six:

from six.moves.urllib.parse import quote

six will simplify compatibility problems between Python 2 and Python 3, such as different import paths.