Programs & Examples On #Procedures

SQL Server - copy stored procedures from one db to another

You can generate scriptof the stored proc's as depicted in other answers. Once the script have been generated, you can use sqlcmd to execute them against target DB like

sqlcmd -S <server name> -U <user name> -d <DB name> -i <script file> -o <output log file> 

How do I do pagination in ASP.NET MVC?

Controller

 [HttpGet]
    public async Task<ActionResult> Index(int page =1)
    {
        if (page < 0 || page ==0 )
        {
            page = 1;
        }
        int pageSize = 5;
        int totalPage = 0;
        int totalRecord = 0;
        BusinessLayer bll = new BusinessLayer();
        MatchModel matchmodel = new MatchModel();
        matchmodel.GetMatchList = bll.GetMatchCore(page, pageSize, out totalRecord, out totalPage);
        ViewBag.dbCount = totalPage;
        return View(matchmodel);
    }

BusinessLogic

  public List<Match> GetMatchCore(int page, int pageSize, out int totalRecord, out int totalPage)
    {
        SignalRDataContext db = new SignalRDataContext();
        var query = new List<Match>();
        totalRecord = db.Matches.Count();
        totalPage = (totalRecord / pageSize) + ((totalRecord % pageSize) > 0 ? 1 : 0);
        query = db.Matches.OrderBy(a => a.QuestionID).Skip(((page - 1) * pageSize)).Take(pageSize).ToList();
        return query;
    }

View for displaying total page count

 if (ViewBag.dbCount != null)
    {
        for (int i = 1; i <= ViewBag.dbCount; i++)
        {
            <ul class="pagination">
                <li>@Html.ActionLink(@i.ToString(), "Index", "Grid", new { page = @i },null)</li> 
            </ul>
        }
    }

pip or pip3 to install packages for Python 3?

Your pip is a soft link to the same executable file path with pip3. you can use the commands below to check where your pip and pip3 real paths are:

$ ls -l `which pip`
$ ls -l `which pip3`

You may also use the commands below to know more details:

$ pip show pip
$ pip3 show pip

When we install different versions of python, we may create such soft links to

  • set default pip to some version.
  • make different links for different versions.

It is the same situation with python, python2, python3

More information below if you're interested in how it happens in different cases:

Disable all dialog boxes in Excel while running VB script?

From Excel Macro Security - www.excelfunctions.net:

Macro Security in Excel 2007, 2010 & 2013:

.....

The different Excel file types provided by the latest versions of Excel make it clear when workbook contains macros, so this in itself is a useful security measure. However, Excel also has optional macro security settings, which are controlled via the options menu. These are :

'Disable all macros without notification'

  • This setting does not allow any macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.

'Disable all macros with notification'

  • This setting prevents macros from running. However, if there are macros in a workbook, a pop-up is displayed, to warn you that the macros exist and have been disabled.

'Disable all macros except digitally signed macros'

  • This setting only allow macros from trusted sources to run. All other macros do not run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.

'Enable all macros'

  • This setting allows all macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros and may not be aware of macros running while you have the file open.

If you trust the macros and are ok with enabling them, select this option:

'Enable all macros'

and this dialog box should not show up for macros.

As for the dialog for saving, after noting that this was running on Excel for Mac 2011, I came across the following question on SO, StackOverflow - Suppress dialog when using VBA to save a macro containing Excel file (.xlsm) as a non macro containing file (.xlsx). From it, removing the dialog does not seem to be possible, except for possibly by some Keyboard Input simulation. I would post another question to inquire about that. Sorry I could only get you halfway. The other option would be to use a Windows computer with Microsoft Excel, though I'm not sure if that is a option for you in this case.

Eclipse : Failed to connect to remote VM. Connection refused.

  • The port number in the Eclipse configuration and the port number of your application might not be the same.
  • You might not have been started your application with the right parameters.

    Those are the simple problems when I have faced "Connection refused" error.

DateTime.MinValue and SqlDateTime overflow

If you use DATETIME2 you may find you have to pass the parameter in specifically as DATETIME2, otherwise it may helpfully convert it to DATETIME and have the same issue.

command.Parameters.Add("@FirstRegistration",SqlDbType.DateTime2).Value = installation.FirstRegistration;

Hash String via SHA-256 in Java

This is already implemented in the runtime libs.

public static String calc(InputStream is) {
    String output;
    int read;
    byte[] buffer = new byte[8192];

    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        while ((read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
        byte[] hash = digest.digest();
        BigInteger bigInt = new BigInteger(1, hash);
        output = bigInt.toString(16);
        while ( output.length() < 32 ) {
            output = "0"+output;
        }
    } 
    catch (Exception e) {
        e.printStackTrace(System.err);
        return null;
    }

    return output;
}

In a JEE6+ environment one could also use JAXB DataTypeConverter:

import javax.xml.bind.DatatypeConverter;

String hash = DatatypeConverter.printHexBinary( 
           MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));

How to find a whole word in a String in java

Use regex + word boundaries as others answered.

"I will come and meet you at the 123woods".matches(".*\\b123woods\\b.*");

will be true.

"I will come and meet you at the 123woods".matches(".*\\bwoods\\b.*");

will be false.

Displaying output of a remote command with Ansible

I'm not sure about the syntax of your specific commands (e.g., vagrant, etc), but in general...

Just register Ansible's (not-normally-shown) JSON output to a variable, then display each variable's stdout_lines attribute:

- name: Generate SSH keys for vagrant user
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
  register: vagrant
- debug: var=vagrant.stdout_lines

- name: Show SSH public key
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
- debug: var=cat.stdout_lines

- name: Wait for user to copy SSH public key
  pause: prompt="Please add the SSH public key above to your GitHub account"
  register: pause
- debug: var=pause.stdout_lines

how to set default culture info for entire c# application

If you use a Language Resource file to set the labels in your application you need to set the its value:

CultureInfo customCulture = new CultureInfo("en-US");
Languages.Culture = customCulture;

Make a link in the Android browser start up my app?

I also faced this issue and see many absurd pages. I've learned that to make your app browsable, change the order of the XML elements, this this:

<activity
    android:name="com.example.MianActivityName"
    android:label="@string/title_activity_launcher">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter>                
        <data android:scheme="http" />     
        <!-- or you can use deep linking like  -->               

        <data android:scheme="http" android:host="xyz.abc.com"/>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <category android:name="android.intent.category.DEFAULT"/>

    </intent-filter>
</activity>

This worked for me and might help you.

How to run a program in Atom Editor?

  1. Click on Packages --> Commmand Palette --> Select Toggle.
  2. Type Install Packages and Themes.
  3. Search for Script and then install it.
  4. Press Command + I to run the code (on Mac)

Python circular importing?

For those of you who, like me, come to this issue from Django, you should know that the docs provide a solution: https://docs.djangoproject.com/en/1.10/ref/models/fields/#foreignkey

"...To refer to models defined in another application, you can explicitly specify a model with the full application label. For example, if the Manufacturer model above is defined in another application called production, you’d need to use:

class Car(models.Model):
    manufacturer = models.ForeignKey(
        'production.Manufacturer',
        on_delete=models.CASCADE,
)

This sort of reference can be useful when resolving circular import dependencies between two applications...."

How to write std::string to file?

You're currently writing the binary data in the string-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.

If you want to write to a text file, the best way to do this would probably be with an ofstream, an "out-file-stream". It behaves exactly like std::cout, but the output is written to a file.

The following example reads one string from stdin, and then writes this string to the file output.txt.

#include <fstream>
#include <string>
#include <iostream>

int main()
{
    std::string input;
    std::cin >> input;
    std::ofstream out("output.txt");
    out << input;
    out.close();
    return 0;
}

Note that out.close() isn't strictly neccessary here: the deconstructor of ofstream can handle this for us as soon as out goes out of scope.

For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/

Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str(). So you could use:

write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );

What is the difference between a Relational and Non-Relational Database?

Relational databases have a mathematical basis (set theory, relational theory), which are distilled into SQL == Structured Query Language.

NoSQL's many forms (e.g. document-based, graph-based, object-based, key-value store, etc.) may or may not be based on a single underpinning mathematical theory. As S. Lott has correctly pointed out, hierarchical data stores do indeed have a mathematical basis. The same might be said for graph databases.

I'm not aware of a universal query language for NoSQL databases.

How to calculate growth with a positive and negative number?

Use this code:

=IFERROR((This Year/Last Year)-1,IF(AND(D2=0,E2=0),0,1))

The first part of this code iferror gets rid of the N/A issues when there is a negative or a 0 value. It does this by looking at the values in e2 and d2 and makes sure they are not both 0. If they are both 0 then it will place a 0%. If only one of the cells are a 0 then it will place 100% or -100% depending on where the 0 value falls. The second part of this code (e2/d2)-1 is the same code as (this year - lastyear)/Last year

Please click here for example picture

How to turn off INFO logging in Spark?

Edit your conf/log4j.properties file and Change the following line:

   log4j.rootCategory=INFO, console

to

    log4j.rootCategory=ERROR, console

Another approach would be to :

Fireup spark-shell and type in the following:

import org.apache.log4j.Logger
import org.apache.log4j.Level

Logger.getLogger("org").setLevel(Level.OFF)
Logger.getLogger("akka").setLevel(Level.OFF)

You won't see any logs after that.

what is numeric(18, 0) in sql server 2008 r2

This page explains it pretty well.

As a numeric the allowable range that can be stored in that field is -10^38 +1 to 10^38 - 1.

The first number in parentheses is the total number of digits that will be stored. Counting both sides of the decimal. In this case 18. So you could have a number with 18 digits before the decimal 18 digits after the decimal or some combination in between.

The second number in parentheses is the total number of digits to be stored after the decimal. Since in this case the number is 0 that basically means only integers can be stored in this field.

So the range that can be stored in this particular field is -(10^18 - 1) to (10^18 - 1)

Or -999999999999999999 to 999999999999999999 Integers only

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

LaTeX source code listing like in professional books

Have a try on the listings package. Here is an example of what I used some time ago to have a coloured Java listing:

\usepackage{listings}

[...]

\lstset{language=Java,captionpos=b,tabsize=3,frame=lines,keywordstyle=\color{blue},commentstyle=\color{darkgreen},stringstyle=\color{red},numbers=left,numberstyle=\tiny,numbersep=5pt,breaklines=true,showstringspaces=false,basicstyle=\footnotesize,emph={label}}

[...]

\begin{lstlisting}
public void here() {
    goes().the().code()
}

[...]

\end{lstlisting}

You may want to customize that. There are several references of the listings package. Just google them.

What's the pythonic way to use getters and setters?

Using @property and @attribute.setter helps you to not only use the "pythonic" way but also to check the validity of attributes both while creating the object and when altering it.

class Person(object):
    def __init__(self, p_name=None):
        self.name = p_name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, new_name):
        if type(new_name) == str: #type checking for name property
            self._name = new_name
        else:
            raise Exception("Invalid value for name")

By this, you actually 'hide' _name attribute from client developers and also perform checks on name property type. Note that by following this approach even during the initiation the setter gets called. So:

p = Person(12)

Will lead to:

Exception: Invalid value for name

But:

>>>p = person('Mike')
>>>print(p.name)
Mike
>>>p.name = 'George'
>>>print(p.name)
George
>>>p.name = 2.3 # Causes an exception

c# - How to get sum of the values from List?

Use Sum()

 List<string> foo = new List<string>();
 foo.Add("1");
 foo.Add("2");
 foo.Add("3");
 foo.Add("4");

 Console.Write(foo.Sum(x => Convert.ToInt32(x)));

Prints:

10

One line if in VB .NET

One Line 'If Statement'

Easier than you think, noticed no-one has put what I've got yet, so I'll throw in my 2-cents.

In my testing you don't need the continuation? semi-colon, you can do without, also you can do it without the End If.

<C#> = Condition.

<R#> = True Return.

<E> = Else Return.

Single Condition

If <C1> Then <R1> Else <E>

Multiple Conditions

If <C1> Then <R1> Else If <C2> Then <R2> Else <E>

Infinite? Conditions

If <C1> Then <R1> Else If <C2> Then <R2> If <C3> Then <R3> If <C4> Then <R4> Else...
' Just keep adding "If <C> Then <R> Else" to get more

-Not really sure how to format this to make it more readable, so if someone could offer a edit, please do-

How to set height property for SPAN

this is to make display:inline-block work in all browsers:

Quirkly enough, in IE (6/7) , if you trigger hasLayout with "zoom:1" and then set the display to inline, it behaves as an inline block.

.inline-block {
    display: inline-block;
    zoom: 1;
    *display: inline;
}

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

Disclaimer- The main source of some definitions are wikipedia, any suggestion to improve my answer is welcome.

Although this post has an accepted answer and is a good one I was still in confusion and would like to add some more clarification regarding the difference between these terms.

(1)FULL BINARY TREE- A full binary tree is a binary tree in which every node other than the leaves has two children.This is also called strictly binary tree.

enter image description here enter image description here

The above two are the examples of full or strictly binary tree.

(2)COMPLETE BINARY TREE- Now, the definition of complete binary tree is quite ambiguous, it states :- A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. It can have between 1 and 2h nodes, as far left as possible, at the last level h

Notice the lines in italic.

The ambiguity lies in the lines in italics , "except possibly the last" which means that the last level may also be completely filled , i.e this exception need not always be satisfied. If the exception doesn't hold then it is exactly like the second image I posted, which can also be called as perfect binary tree. So, a perfect binary tree is also full and complete but not vice-versa which will be clear by one more definition I need to state:

ALMOST COMPLETE BINARY TREE- When the exception in the definition of complete binary tree holds then it is called almost complete binary tree or nearly complete binary tree . It is just a type of complete binary tree itself , but a separate definition is necessary to make it more unambiguous.

So an almost complete binary tree will look like this, you can see in the image the nodes are as far left as possible so it is more like a subset of complete binary tree , to say more rigorously every almost complete binary tree is a complete binary tree but not vice versa . :

enter image description here

What is the "hasClass" function with plain JavaScript?

This 'hasClass' function works in IE8+, FireFox and Chrome:

hasClass = function(el, cls) {
    var regexp = new RegExp('(\\s|^)' + cls + '(\\s|$)'),
        target = (typeof el.className === 'undefined') ? window.event.srcElement : el;
    return target.className.match(regexp);
}

[Updated Jan'2021] A better way:

hasClass = (el, cls) => {
  [...el.classList].includes(cls); //cls without dot
};

How to create a new instance from a class object in Python

This is how you can dynamically create a class named Child in your code, assuming Parent already exists... even if you don't have an explicit Parent class, you could use object...

The code below defines __init__() and then associates it with the class.

>>> child_name = "Child"
>>> child_parents = (Parent,)
>>> child body = """
def __init__(self, arg1):
    # Initialization for the Child class
    self.foo = do_something(arg1)
"""
>>> child_dict = {}
>>> exec(child_body, globals(), child_dict)
>>> childobj = type(child_name, child_parents, child_dict)
>>> childobj.__name__
'Child'
>>> childobj.__bases__
(<type 'object'>,)
>>> # Instantiating the new Child object...
>>> childinst = childobj()
>>> childinst
<__main__.Child object at 0x1c91710>
>>>

How to use SharedPreferences in Android to store, fetch and edit values

2.for Storing in shared prefrence

SharedPreferences.Editor editor = 
getSharedPreferences("DeviceToken",MODE_PRIVATE).edit();
                    editor.putString("DeviceTokenkey","ABABABABABABABB12345");
editor.apply();

2.for retrieving the same use

    SharedPreferences prefs = getSharedPreferences("DeviceToken", 
 MODE_PRIVATE);
  String deviceToken = prefs.getString("DeviceTokenkey", null);

Oracle SQL update based on subquery between two tables

Without examples of the dataset of staging this is a shot in the dark, but have you tried something like this?

update PRODUCTION p,
       staging s
set p.name = s.name  
    p.count = s.count
where p.id = s.id

This would work assuming the id column matches on both tables.

Is it possible to read from a InputStream with a timeout?

I would question the problem statement rather than just accept it blindly. You only need timeouts from the console or over the network. If the latter you have Socket.setSoTimeout() and HttpURLConnection.setReadTimeout() which both do exactly what is required, as long as you set them up correctly when you construct/acquire them. Leaving it to an arbitrary point later in the application when all you have is the InputStream is poor design leading to a very awkward implementation.

Error loading the SDK when Eclipse starts

On MacOS 10.10.2

  1. Removed the lines, containing "d:skin" from device.xml from:

    • /Users/user/Library/Android/sdk/system-images/android-22/android-wear/x86

    • /Users/user/Library/Android/sdk/system-images/android-22/android-wear/armeabi-v7a

  2. Restart the eclipse, the problem should be resolved.

JSTL if tag for equal strings

I think the other answers miss one important detail regarding the property name to use in the EL expression. The rules for converting from the method names to property names are specified in 'Introspector.decpitalize` which is part of the java bean standard:

This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.

Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".

So in your case the JSTL code should look like the following, note the capital 'P':

<c:if test = "${ansokanInfo.PSystem == 'NAT'}">

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

You can see the information regarding the transfer by doing:

curl_setopt($curl_exect, CURLINFO_HEADER_OUT, true);

before the request, and

$information = curl_getinfo($curl_exect);

after the request

View: http://www.php.net/manual/en/function.curl-getinfo.php

You can also use the CURLOPT_HEADER in your curl_setopt

curl_setopt($curl_exect, CURLOPT_HEADER, true);

$httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);

return $httpcode == 200;

These are just some methods of using the headers.

Initializing a two dimensional std::vector

Suppose you want to initialize a two dimensional integer vector with n rows and m column each having value 'VAL'

Write it as

std::vector<vector<int>> arr(n, vector<int>(m,VAL));

This VAL can be a integer type variable or constant such as 100

How do you get current active/default Environment profile programmatically in Spring?

Seems there is some demand to be able to access this statically.

How can I get such thing in static methods in non-spring-managed classes? – Aetherus

It's a hack, but you can write your own class to expose it. You must be careful to ensure that nothing will call SpringContext.getEnvironment() before all beans have been created, since there is no guarantee when this component will be instantiated.

@Component
public class SpringContext
{
    private static Environment environment;

    public SpringContext(Environment environment) {
        SpringContext.environment = environment;
    }

    public static Environment getEnvironment() {
        if (environment == null) {
            throw new RuntimeException("Environment has not been set yet");
        }
        return environment;
    }
}

Converting dd/mm/yyyy formatted string to Datetime

You can use "dd/MM/yyyy" format for using it in DateTime.ParseExact.

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

DateTime date = DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Here is a DEMO.

For more informations, check out Custom Date and Time Format Strings

how to use Spring Boot profiles

Working with Intellij, because I don't know how to set keyboard shortcut to mvn spring-boot:run -Dspring.profiles.active=dev, I have to do this:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <jvmArguments>
            -Dspring.profiles.active=dev
        </jvmArguments>
    </configuration>
</plugin>

How to have Java method return generic list of any type?

private Object actuallyT;

public <T> List<T> magicalListGetter(Class<T> klazz) {
    List<T> list = new ArrayList<>();
    list.add(klazz.cast(actuallyT));
    try {
        list.add(klazz.getConstructor().newInstance()); // If default constructor
    } ...
    return list;
}

One can give a generic type parameter to a method too. You have correctly deduced that one needs the correct class instance, to create things (klazz.getConstructor().newInstance()).

Change color of bootstrap navbar on hover link?

Sorry for late reply. You can only use:

   nav a:hover{

                   background-color:color name !important;


                 }

How to get response using cURL in PHP

The ultimate curl php function:

function getURL($url,$fields=null,$method=null,$file=null){
    // author   = Ighor Toth <[email protected]>
    // required:
    //      url     = include http or https 
    // optionals:
    //      fields  = must be array (e.g.: 'field1' => $field1, ...)
    //      method  = "GET", "POST"
    //      file    = if want to download a file, declare store location and file name (e.g.: /var/www/img.jpg, ...)
    // please crete 'cookies' dir to store local cookies if neeeded

    // do not modify below
    $useragent = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
    $timeout= 240;
    $dir = dirname(__FILE__);
    $_SERVER["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"] ?? '127.0.0.1';
    $cookie_file    = $dir . '/cookies/' . md5($_SERVER['REMOTE_ADDR']) . '.txt';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);    
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt($ch, CURLOPT_ENCODING, "" );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt($ch, CURLOPT_AUTOREFERER, true );
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com/');
    if($file!=null){
        if (!curl_setopt($ch, CURLOPT_FILE, $file)){ // Handle error
                die("curl setopt bit the dust: " . curl_error($ch));
        }
        //curl_setopt($ch, CURLOPT_FILE, $file);
        $timeout= 3600;
    }
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout );
    if($fields!=null){
        $postvars = http_build_query($fields); // build the urlencoded data
        if($method=="POST"){
            // set the url, number of POST vars, POST data
            curl_setopt($ch, CURLOPT_POST, count($fields));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
        }
        if($method=="GET"){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
            $url = $url.'?'.$postvars;
        }
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    $content = curl_exec($ch);
    if (!$content){
        $error = curl_error($ch);
        $info = curl_getinfo($ch);
        die("cURL request failed, error = {$error}; info = " . print_r($info, true));
    }
    if(curl_errno($ch)){
        echo 'error:' . curl_error($ch);
    } else {
        return $content;        
    }
    curl_close($ch);
}

How to get the index with the key in Python dictionary?

Use OrderedDicts: http://docs.python.org/2/library/collections.html#collections.OrderedDict

>>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2")))
>>> x["d"] = 4
>>> x.keys().index("d")
3
>>> x.keys().index("c")
1

For those using Python 3

>>> list(x.keys()).index("c")
1

phpexcel to download

$excel = new PHPExcel();
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="your_name.xls"');
header('Cache-Control: max-age=0');

// Do your stuff here

$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');

// This line will force the file to download
$writer->save('php://output');

Missing MVC template in Visual Studio 2015

Visual studio 2015 does not show MVC project template if you select .Net 4.0 or below. Select .Net 4.5 or above, and you will be able to see MVC project.

This is what showed when you select .NET Framework 4:

enter image description here

and this when you select .NET Framework 4.5:

enter image description here

However, make sure you have installed web developers tools. To do so, go to Add / remove programs -> Visual 2015 -> Modify --> Web developer tools : Check and proceed with the installation.

Python set to list

s = set([1,2,3])
print [ x for x in iter(s) ]

How do you update a DateTime field in T-SQL?

Is there maybe a trigger on the table setting it back?

Vue.js - How to properly watch for nested data

Not seeing it mentioned here, but also possible to use the vue-property-decorator pattern if you are extending your Vue class.

import { Watch, Vue } from 'vue-property-decorator';

export default class SomeClass extends Vue {
   ...

   @Watch('item.someOtherProp')
   someOtherPropChange(newVal, oldVal) {
      // do something
   }

   ...
}

Git command to show which specific files are ignored by .gitignore

It should be sufficient to use

git ls-files --others -i --exclude-standard

as that covers everything covered by

git ls-files --others -i --exclude-from=.git/info/exclude

therefore the latter is redundant.


You can make this easier by adding an alias to your ~/.gitconfig file:

git config --global alias.ignored "ls-files --others -i --exclude-standard"

Now you can just type git ignored to see the list. Much easier to remember, and faster to type.

If you prefer the more succinct display of Jason Geng's solution, you can add an alias for that like this:

git config --global alias.ignored "status --ignored -s"

However the more verbose output is more useful for troubleshooting problems with your .gitignore files, as it lists every single cotton-pickin' file that is ignored. You would normally pipe the results through grep to see if a file you expect to be ignored is in there, or if a file you don't want to be ignore is in there.

git ignored | grep some-file-that-isnt-being-ignored-properly

Then, when you just want to see a short display, it's easy enough to remember and type

git status --ignored

(The -s can normally be left off.)

How do you set the Content-Type header for an HttpClient request?

I end up having similar issue. So I discovered that the Software PostMan can generate code when clicking the "Code" button at upper/left corner. From that we can see what going on "under the hood" and the HTTP call is generated in many code language; curl command, C# RestShart, java, nodeJs, ...

That helped me a lot and instead of using .Net base HttpClient I ended up using RestSharp nuget package.

Hope that can help someone else!

How to return history of validation loss in Keras

The dictionary with histories of "acc", "loss", etc. is available and saved in hist.history variable.

How do I move files in node.js?

util.pump is deprecated in node 0.10 and generates warning message

 util.pump() is deprecated. Use readableStream.pipe() instead

So the solution for copying files using streams is:

var source = fs.createReadStream('/path/to/source');
var dest = fs.createWriteStream('/path/to/dest');

source.pipe(dest);
source.on('end', function() { /* copied */ });
source.on('error', function(err) { /* error */ });

How to use SQL LIKE condition with multiple values in PostgreSQL?

Using array or set comparisons:

create table t (str text);
insert into t values ('AAA'), ('BBB'), ('DDD999YYY'), ('DDD099YYY');

select str from t
where str like any ('{"AAA%", "BBB%", "CCC%"}');

select str from t
where str like any (values('AAA%'), ('BBB%'), ('CCC%'));

It is also possible to do an AND which would not be easy with a regex if it were to match any order:

select str from t
where str like all ('{"%999%", "DDD%"}');

select str from t
where str like all (values('%999%'), ('DDD%'));

"Gradle Version 2.10 is required." Error

If the problem persist, add the following code in the build.gradle of the top project.

buildscript {
System.properties['com.android.build.gradle.overrideVersionCheck'] = 'true'

...
}

keypress, ctrl+c (or some combo like that)

I couldn't get it to work with .keypress(), but it worked with the .keydown() function like this:

$(document).keydown(function(e) {
    if(e.key == "c" && e.ctrlKey) {
        console.log('ctrl+c was pressed');
    }
});

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

The answers above are perfectly valid, but a vectorized solution exists, in the form of numpy.select. This allows you to define conditions, then define outputs for those conditions, much more efficiently than using apply:


First, define conditions:

conditions = [
    df['eri_hispanic'] == 1,
    df[['eri_afr_amer', 'eri_asian', 'eri_hawaiian', 'eri_nat_amer', 'eri_white']].sum(1).gt(1),
    df['eri_nat_amer'] == 1,
    df['eri_asian'] == 1,
    df['eri_afr_amer'] == 1,
    df['eri_hawaiian'] == 1,
    df['eri_white'] == 1,
]

Now, define the corresponding outputs:

outputs = [
    'Hispanic', 'Two Or More', 'A/I AK Native', 'Asian', 'Black/AA', 'Haw/Pac Isl.', 'White'
]

Finally, using numpy.select:

res = np.select(conditions, outputs, 'Other')
pd.Series(res)

0           White
1        Hispanic
2           White
3           White
4           Other
5           White
6     Two Or More
7           White
8    Haw/Pac Isl.
9           White
dtype: object

Why should numpy.select be used over apply? Here are some performance checks:

df = pd.concat([df]*1000)

In [42]: %timeit df.apply(lambda row: label_race(row), axis=1)
1.07 s ± 4.16 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [44]: %%timeit
    ...: conditions = [
    ...:     df['eri_hispanic'] == 1,
    ...:     df[['eri_afr_amer', 'eri_asian', 'eri_hawaiian', 'eri_nat_amer', 'eri_white']].sum(1).gt(1),
    ...:     df['eri_nat_amer'] == 1,
    ...:     df['eri_asian'] == 1,
    ...:     df['eri_afr_amer'] == 1,
    ...:     df['eri_hawaiian'] == 1,
    ...:     df['eri_white'] == 1,
    ...: ]
    ...:
    ...: outputs = [
    ...:     'Hispanic', 'Two Or More', 'A/I AK Native', 'Asian', 'Black/AA', 'Haw/Pac Isl.', 'White'
    ...: ]
    ...:
    ...: np.select(conditions, outputs, 'Other')
    ...:
    ...:
3.09 ms ± 17 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Using numpy.select gives us vastly improved performance, and the discrepancy will only increase as the data grows.

How to fix nginx throws 400 bad request headers on any header testing tools?

Just to clearify, in /etc/nginx/nginx.conf, you can put at the beginning of the file the line

error_log /var/log/nginx/error.log debug;

And then restart nginx:

sudo service nginx restart

That way you can detail what nginx is doing and why it is returning the status code 400.

How to count instances of character in SQL Column

The easiest way is by using Oracle function:

SELECT REGEXP_COUNT(COLUMN_NAME,'CONDITION') FROM TABLE_NAME

How can I check if a jQuery plugin is loaded?

If we're talking about a proper jQuery plugin (one that extends the fn namespace), then the proper way to detect the plugin would be:

if(typeof $.fn.pluginname !== 'undefined') { ... }

Or because every plugin is pretty much guaranteed to have some value that equates to true, you can use the shorter

if ($.fn.pluginname) { ... }

BTW, the $ and jQuery are interchangable, as the odd-looking wrapper around a plugin demonstrates:

(function($) {
    //
})(jQuery))

the closure

(function($) {
    //
})

is followed immediately by a call to that closure 'passing' jQuery as the parameter

(jQuery)

the $ in the closure is set equal to jQuery

Split string with JavaScript

Assuming you're using jQuery..

var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
    var parts = line.split(' ');
    output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');

Inline for loop

What you are using is called a list comprehension in Python, not an inline for-loop (even though it is similar to one). You would write your loop as a list comprehension like so:

p = [q.index(v) if v in q else 99999 for v in vm]

When using a list comprehension, you do not call list.append because the list is being constructed from the comprehension itself. Each item in the list will be what is returned by the expression on the left of the for keyword, which in this case is q.index(v) if v in q else 99999. Incidentially, if you do use list.append inside a comprehension, then you will get a list of None values because that is what the append method always returns.

Query to list all users of a certain group

memberOf (in AD) is stored as a list of distinguishedNames. Your filter needs to be something like:

(&(objectCategory=user)(memberOf=cn=MyCustomGroup,ou=ouOfGroup,dc=subdomain,dc=domain,dc=com))

If you don't yet have the distinguished name, you can search for it with:

(&(objectCategory=group)(cn=myCustomGroup))

and return the attribute distinguishedName. Case may matter.

Set UILabel line spacing

From Interface Builder:

enter image description here

Programmatically:

SWift 4

Using label extension

extension UILabel {

    func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {

        guard let labelText = self.text else { return }

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpacing
        paragraphStyle.lineHeightMultiple = lineHeightMultiple

        let attributedString:NSMutableAttributedString
        if let labelattributedText = self.attributedText {
            attributedString = NSMutableAttributedString(attributedString: labelattributedText)
        } else {
            attributedString = NSMutableAttributedString(string: labelText)
        }

        // Line spacing attribute
        attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))

        self.attributedText = attributedString
    }
}

Now call extension function

let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"

// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) .  // try values 1.0 to 5.0

// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0


Or using label instance (Just copy & execute this code to see result)

let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40

// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))

// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))

label.attributedText = attrString

Swift 3

let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString

Dynamically change color to lighter or darker by percentage CSS (Javascript)

This is an old question, but most of the answers require the use of a preprocessor or JavaScript to operate, or they not only affect the color of the element but also the color of the elements contained within it. I am going to add a kind-of-complicated CSS-only way of doing the same thing. Probably in the future, with the more advanced CSS functions, it will be easier to do.

The idea is based on using:

  • RGB colors, so you have separate values for red, green, and blue;
  • CSS variables, to store the color values and the darkness; and
  • The calc function, to apply the change.

By default darkness will be 1 (for 100%, the regular color), and if you multiply by a number between 0 and 1, you'll be making the color darker. For example, if you multiply by 0.85 each of the values, you'll be making the colors 15% darker (100% - 15% = 85% = 0.85).

Here is an example, I created three classes: .dark, .darker, and .darkest that will make the original color 25%, 50%, and 75% darker respectively:

_x000D_
_x000D_
html {_x000D_
  --clarity: 1;_x000D_
}_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
  line-height: 100px;_x000D_
  color: white;_x000D_
  text-align: center;_x000D_
  font-family: arial, sans-serif;_x000D_
  font-size: 20px;_x000D_
  background: rgba(_x000D_
                  calc(var(--r) * var(--clarity)), _x000D_
                  calc(var(--g) * var(--clarity)), _x000D_
                  calc(var(--b) * var(--clarity))_x000D_
                );_x000D_
}_x000D_
_x000D_
.dark    { --clarity: 0.75; }_x000D_
.darker  { --clarity: 0.50; }_x000D_
.darkest { --clarity: 0.25; }_x000D_
_x000D_
.red {_x000D_
  --r: 255;_x000D_
  --g: 0;_x000D_
  --b: 0;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
  --r: 205;_x000D_
  --g: 30;_x000D_
  --b: 205;_x000D_
}
_x000D_
<div class="red">0%</div>_x000D_
<div class="red dark">25%</div>_x000D_
<div class="red darker">50%</div>_x000D_
<div class="red darkest">75%</div>_x000D_
_x000D_
<br/><br/>_x000D_
_x000D_
<div class="purple">0%</div>_x000D_
<div class="purple dark">25%</div>_x000D_
<div class="purple darker">50%</div>_x000D_
<div class="purple darkest">75%</div>
_x000D_
_x000D_
_x000D_

Failed to load ApplicationContext for JUnit test of Spring controller

If you are using Maven, add the below config in your pom.xml:

<build>
    <testResources>
                <testResource>
                    <directory>src/main/webapp</directory>
                </testResource>
    </testResources>
</build>

With this config, you will be able to access xml files in WEB-INF folder. From Maven POM Reference: The testResources element block contains testResource elements. Their definitions are similar to resource elements, but are naturally used during test phases.

Best way to show a loading/progress indicator?

This is how I did this so that only one progress dialog can be open at a time. Based off of the answer from Suraj Bajaj

private ProgressDialog progress;



public void showLoadingDialog() {

    if (progress == null) {
        progress = new ProgressDialog(this);
        progress.setTitle(getString(R.string.loading_title));
        progress.setMessage(getString(R.string.loading_message));
    }
    progress.show();
}

public void dismissLoadingDialog() {

    if (progress != null && progress.isShowing()) {
        progress.dismiss();
    }
}

I also had to use

protected void onResume() {
    dismissLoadingDialog();
    super.onResume();
}

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

You can simply pass to "default" instead of "ON". Seems more adherent to Apple logic.

(but all the other comments about the use of @obj remains valid.)

How to get file creation date/time in Bash/Debian?

If you really want to achieve that you can use a file watcher like inotifywait.

You watch a directory and you save information about file creations in separate file outside that directory.

while true; do
  change=$(inotifywait -e close_write,moved_to,create .)
  change=${change#./ * }
  if [ "$change" = ".*" ]; then ./scriptToStoreInfoAboutFile; fi
done

As no creation time is stored, you can build your own system based on inotify.

Read a Csv file with powershell and capture corresponding data

Old topic, but never clearly answered. I've been working on similar as well, and found the solution:

The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:

Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
    $Name += $_.Name
    $Phone += $_."Phone Number"
}

Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)

How to append the output to a file?

Use >> to append:

command >> file

Why is my Spring @Autowired field null?

Not entirely related to the question, but if the field injection is null, the constructor based injection will still work fine.

    private OrderingClient orderingClient;
    private Sales2Client sales2Client;
    private Settings2Client settings2Client;

    @Autowired
    public BrinkWebTool(OrderingClient orderingClient, Sales2Client sales2Client, Settings2Client settings2Client) {
        this.orderingClient = orderingClient;
        this.sales2Client = sales2Client;
        this.settings2Client = settings2Client;
    }

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

I would add mnoGoSearch to the list. Extremely performant and flexible solution, which works as Google : indexer fetches data from multiple sites, You could use basic criterias, or invent Your own hooks to have maximal search quality. Also it could fetch the data directly from the database.

The solution is not so known today, but it feets maximum needs. You could compile and install it or on standalone server, or even on Your principal server, it doesn't need so much ressources as Solr, as it's written in C and runs perfectly even on small servers.

In the beginning You need to compile it Yourself, so it requires some knowledge. I made a tiny script for Debian, which could help. Any adjustments are welcome.

As You are using Django framework, You could use or PHP client in the middle, or find a solution in Python, I saw some articles.

And, of course mnoGoSearch is open source, GNU GPL.

LINQ extension methods - Any() vs. Where() vs. Exists()

Any() returns true if any of the elements in a collection meet your predicate's criteria.

Where() returns an enumerable of all elements in a collection that meet your predicate's criteria.

Exists() does the same thing as any except it's just an older implementation that was there on the IList back before Linq.

CSS: transition opacity on mouse-out?

You're applying transitions only to the :hover pseudo-class, and not to the element itself.

.item {   
  height:200px;
  width:200px;
  background:red; 
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -ms-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

.item:hover {
  zoom: 1;
  filter: alpha(opacity=50);
  opacity: 0.5;
}

Demo: http://jsfiddle.net/7uR8z/6/

If you don't want the transition to affect the mouse-over event, but only mouse-out, you can turn transitions off for the :hover state :

.item:hover {
  -webkit-transition: none;
  -moz-transition: none;
  -ms-transition: none;
  -o-transition: none;
  transition: none;
  zoom: 1;
  filter: alpha(opacity=50);
  opacity: 0.5;
}

Demo: http://jsfiddle.net/7uR8z/3/

fix java.net.SocketTimeoutException: Read timed out

I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).

e.g. (from the doc)

     System.out.println("<< Response: " + response.getStatusLine());
     System.out.println(EntityUtils.toString(response.getEntity()));

How to use moment.js library in angular 2 typescript app?

My own version of using Moment in Angular

npm i moment --save

import * as _moment from 'moment';

...

moment: _moment.Moment = _moment();

constructor() { }

ngOnInit() {

    const unix = this.moment.format('X');
    console.log(unix);    

}

First import moment as _moment, then declare moment variable with type _moment.Moment with an initial value of _moment().

Plain import of moment wont give you any auto completion but if you will declare moment with type Moment interface from _moment namespace from 'moment' package initialized with moment namespace invoked _moment() gives you auto completion of moment's api's.

I think this is the most angular way of using moment without using @types typings or angular providers, if you're looking auto completion for vanilla javascript libraries like moment.

Check if a file exists locally using JavaScript only

Your question is ambiguous, so there are multiple possible answers depending on what you're really trying to achieve.

If you're developping as I'm guessing a desktop application using Titanium, then you can use the FileSystem module's getFile to get the file object, then check if it exists using the exists method.

Here's an example taken from the Appcelerator website:

var homeDir = Titanium.Filesystem.getUserDirectory();
var mySampleFile = Titanium.Filesystem.getFile(homeDir, 'sample.txt');

if (mySampleFile.exists()) {
    alert('A file called sample.txt already exists in your home directory.');
    ...
}

Check the getFile method reference documentation

And the exists method reference documentation

For those who thought that he was asking about an usual Web development situation, then thse are the two answers I'd have given:

1) you want to check if a server-side file exists. In this case you can use an ajax request try and get the file and react upon the received answer. Although, be aware that you can only check for files that are exposed by your web server. A better approach would be to write a server-side script (e.g., php) that would do the check for you, given a filename and call that script via ajax. Also, be aware that you could very easily create a security hole in your application/server if you're not careful enough.

2) you want to check if a client-side file exists. In this case, as pointed you by others, it is not allowed for security reasons (although IE allowed this in the past via ActiveX and the Scripting.FileSystemObject class) and it's fine like that (nobody wants you to be able to go through their files), so forget about this.

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

If you're using more than one argument it has to be in a tuple (note the extra parentheses):

'%s in %s' % (unicode(self.author),  unicode(self.publication))

As EOL points out, the unicode() function usually assumes ascii encoding as a default, so if you have non-ASCII characters, it's safer to explicitly pass the encoding:

'%s in %s' % (unicode(self.author,'utf-8'),  unicode(self.publication('utf-8')))

And as of Python 3.0, it's preferred to use the str.format() syntax instead:

'{0} in {1}'.format(unicode(self.author,'utf-8'),unicode(self.publication,'utf-8'))

Spring not autowiring in unit tests with JUnit

You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml available on the test classpath.

import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {

    @Autowired
    protected SessionFactory sessionFactory;

    @Test
    public void testDBSourceIsCorrect() throws SQLException {
        String databaseProductName = sessionFactory.getCurrentSession()
                .connection()
                .getMetaData()
                .getDatabaseProductName();
        assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
    }
}

Note: This works with Spring 2.5.2 and Hibernate 3.6.5

c# regex matches example

Regex regex = new Regex("%download#(\\d+?)%", RegexOptions.SingleLine);
Matches m = regex.Matches(input);

I think will do the trick (not tested).

String to object in JS

I implemented a solution in a few lines of code which works quite reliably.

Having an HTML element like this where I want to pass custom options:

<div class="my-element"
    data-options="background-color: #dadada; custom-key: custom-value;">
</div>

a function parses the custom options and return an object to use that somewhere:

function readCustomOptions($elem){
    var i, len, option, options, optionsObject = {};

    options = $elem.data('options');
    options = (options || '').replace(/\s/g,'').split(';');
    for (i = 0, len = options.length - 1; i < len; i++){
        option = options[i].split(':');
        optionsObject[option[0]] = option[1];
    }
    return optionsObject;
}

console.log(readCustomOptions($('.my-element')));

How do I write to a Python subprocess' stdin?

You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

The connection to adb is down, and a severe error has occurred

Sounds a bit familiar with my problem: aapt not found under the right path

I needed to clean all open projects to get it working again...

How to get device make and model on iOS?

Expanding on OhhMee's answer above, I added some failsafe to support future devices not (yet) included on the list:

#import <sys/utsname.h>
#import "MyClass.h"

@implementation MyClass
{
    //(your private ivars)
}

- (NSString*) deviceName
{
    struct utsname systemInfo;

    uname(&systemInfo);

    NSString* code = [NSString stringWithCString:systemInfo.machine
                                        encoding:NSUTF8StringEncoding];

    static NSDictionary* deviceNamesByCode = nil;

    if (!deviceNamesByCode) {

        deviceNamesByCode = @{@"i386"      : @"Simulator",
                              @"x86_64"    : @"Simulator",
                              @"iPod1,1"   : @"iPod Touch",        // (Original)
                              @"iPod2,1"   : @"iPod Touch",        // (Second Generation)
                              @"iPod3,1"   : @"iPod Touch",        // (Third Generation)
                              @"iPod4,1"   : @"iPod Touch",        // (Fourth Generation)
                              @"iPod7,1"   : @"iPod Touch",        // (6th Generation)       
                              @"iPhone1,1" : @"iPhone",            // (Original)
                              @"iPhone1,2" : @"iPhone",            // (3G)
                              @"iPhone2,1" : @"iPhone",            // (3GS)
                              @"iPad1,1"   : @"iPad",              // (Original)
                              @"iPad2,1"   : @"iPad 2",            //
                              @"iPad3,1"   : @"iPad",              // (3rd Generation)
                              @"iPhone3,1" : @"iPhone 4",          // (GSM)
                              @"iPhone3,3" : @"iPhone 4",          // (CDMA/Verizon/Sprint)
                              @"iPhone4,1" : @"iPhone 4S",         //
                              @"iPhone5,1" : @"iPhone 5",          // (model A1428, AT&T/Canada)
                              @"iPhone5,2" : @"iPhone 5",          // (model A1429, everything else)
                              @"iPad3,4"   : @"iPad",              // (4th Generation)
                              @"iPad2,5"   : @"iPad Mini",         // (Original)
                              @"iPhone5,3" : @"iPhone 5c",         // (model A1456, A1532 | GSM)
                              @"iPhone5,4" : @"iPhone 5c",         // (model A1507, A1516, A1526 (China), A1529 | Global)
                              @"iPhone6,1" : @"iPhone 5s",         // (model A1433, A1533 | GSM)
                              @"iPhone6,2" : @"iPhone 5s",         // (model A1457, A1518, A1528 (China), A1530 | Global)
                              @"iPhone7,1" : @"iPhone 6 Plus",     //
                              @"iPhone7,2" : @"iPhone 6",          //
                              @"iPhone8,1" : @"iPhone 6S",         //
                              @"iPhone8,2" : @"iPhone 6S Plus",    //
                              @"iPhone8,4" : @"iPhone SE",         //
                              @"iPhone9,1" : @"iPhone 7",          //
                              @"iPhone9,3" : @"iPhone 7",          //
                              @"iPhone9,2" : @"iPhone 7 Plus",     //
                              @"iPhone9,4" : @"iPhone 7 Plus",     //
                              @"iPhone10,1": @"iPhone 8",          // CDMA
                              @"iPhone10,4": @"iPhone 8",          // GSM
                              @"iPhone10,2": @"iPhone 8 Plus",     // CDMA
                              @"iPhone10,5": @"iPhone 8 Plus",     // GSM
                              @"iPhone10,3": @"iPhone X",          // CDMA
                              @"iPhone10,6": @"iPhone X",          // GSM
                              @"iPhone11,2": @"iPhone XS",         //
                              @"iPhone11,4": @"iPhone XS Max",     //
                              @"iPhone11,6": @"iPhone XS Max",     // China
                              @"iPhone11,8": @"iPhone XR",         //
                              @"iPhone12,1": @"iPhone 11",         //
                              @"iPhone12,3": @"iPhone 11 Pro",     //
                              @"iPhone12,5": @"iPhone 11 Pro Max", //

                              @"iPad4,1"   : @"iPad Air",          // 5th Generation iPad (iPad Air) - Wifi
                              @"iPad4,2"   : @"iPad Air",          // 5th Generation iPad (iPad Air) - Cellular
                              @"iPad4,4"   : @"iPad Mini",         // (2nd Generation iPad Mini - Wifi)
                              @"iPad4,5"   : @"iPad Mini",         // (2nd Generation iPad Mini - Cellular)
                              @"iPad4,7"   : @"iPad Mini",         // (3rd Generation iPad Mini - Wifi (model A1599))
                              @"iPad6,7"   : @"iPad Pro (12.9\")", // iPad Pro 12.9 inches - (model A1584) 
                              @"iPad6,8"   : @"iPad Pro (12.9\")", // iPad Pro 12.9 inches - (model A1652) 
                              @"iPad6,3"   : @"iPad Pro (9.7\")",  // iPad Pro 9.7 inches - (model A1673)
                              @"iPad6,4"   : @"iPad Pro (9.7\")"   // iPad Pro 9.7 inches - (models A1674 and A1675)
                              };
    }

    NSString* deviceName = [deviceNamesByCode objectForKey:code];

    if (!deviceName) {
        // Not found on database. At least guess main device type from string contents:

        if ([code rangeOfString:@"iPod"].location != NSNotFound) {
            deviceName = @"iPod Touch";
        }
        else if([code rangeOfString:@"iPad"].location != NSNotFound) {
            deviceName = @"iPad";
        }
        else if([code rangeOfString:@"iPhone"].location != NSNotFound){
            deviceName = @"iPhone";
        }
        else {
            deviceName = @"Unknown";
        }
    }

    return deviceName;
}

// (rest of class implementation omitted)

@end

I also omitted the detailed information (e.g. "model A1507, A1516, A1526 (China), A1529 | Global") and placed it in the comments instead, in case you want to use this as user-facing strings and not freak them out.


Edit: This answer provides a similar implementation using Swift 2.

Edit 2: I just added the iPad Pro models (both sizes). For future reference, the model numbers/etc. can be found in The iPhone Wiki.

Edit 3: Add support for iPhone XS, iPhone XS Max and iPhone XR.

Edit 4: Add support for iPhone 11, iPhone 11 Pro and iPhone 11 Pro Max.

Java: Difference between the setPreferredSize() and setSize() methods in components

IIRC ...

setSize sets the size of the component.

setPreferredSize sets the preferred size. The Layoutmanager will try to arrange that much space for your component.

It depends on whether you're using a layout manager or not ...

How do I programmatically click a link with javascript?

You could just redirect them to another page. Actually making it literally click a link and travel to it seems unnessacary, but I don't know the whole story.

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

importing external ".txt" file in python

You can import modules but not text files. If you want to print the content do the following:

Open a text file for reading:

f = open('words.txt', 'r')

Store content in a variable:

content = f.read()

Print content of this file:

print(content)

After you're done close a file:

f.close()

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

How to delete rows in tables that contain foreign keys to other tables

You can alter a foreign key constraint with delete cascade option as shown below. This will delete chind table rows related to master table rows when deleted.

ALTER TABLE MasterTable
ADD CONSTRAINT fk_xyz 
FOREIGN KEY (xyz) 
REFERENCES ChildTable (xyz) ON DELETE CASCADE 

Expanding tuples into arguments

This is the functional programming method. It lifts the tuple expansion feature out of syntax sugar:

apply_tuple = lambda f, t: f(*t)

Redefine apply_tuple via curry to save a lot of partial calls in the long run:

from toolz import curry
apply_tuple = curry(apply_tuple)

Example usage:

from operator import add, eq
from toolz import thread_last

thread_last(
    [(1,2), (3,4)],
    (map, apply_tuple(add)),
    list,
    (eq, [3, 7])
)
# Prints 'True'

How to get Top 5 records in SqLite?

select price from mobile_sales_details order by price desc limit 5

Note: i have mobile_sales_details table

syntax

select column_name from table_name order by column_name desc limit size.  

if you need top low price just remove the keyword desc from order by

adb is not recognized as internal or external command on windows

If you go to your android-sdk/tools folder I think you'll find a message :

The adb tool has moved to platform-tools/

If you don't see this directory in your SDK, launch the SDK and AVD Manager (execute the android tool) and install "Android SDK Platform-tools"

Please also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

So you should also add C:/android-sdk/platform-tools to you environment path. Also after you modify the PATH variable make sure that you start a new CommandPrompt window.

How can I install an older version of a package via NuGet?

I've used Xavier's answer quite a bit. I want to add that restricting the package version to a specified range is easy and useful in the latest versions of NuGet.

For example, if you never want Newtonsoft.Json to be updated past version 3.x.x in your project, change the corresponding package element in your packages.config file to look like this:

<package id="Newtonsoft.Json" version="3.5.8" allowedVersions="[3.0, 4.0)" targetFramework="net40" />

Notice the allowedVersions attribute. This will limit the version of that package to versions between 3.0 (inclusive) and 4.0 (exclusive). Then, when you do an Update-Package on the whole solution, you don't need to worry about that particular package being updated past version 3.x.x.

The documentation for this functionality is here.

iPad browser WIDTH & HEIGHT standard

The pixel width and height of your page will depend on orientation as well as the meta viewport tag, if specified. Here are the results of running jquery's $(window).width() and $(window).height() on iPad 1 browser.

When page has no meta viewport tag:

  • Portrait: 980x1208
  • Landscape: 980x661

When page has either of these two meta tags:

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1">

  • Portrait: 768x946
  • Landscape: 1024x690

With <meta name="viewport" content="width=device-width">:

  • Portrait: 768x946
  • Landscape: 768x518

With <meta name="viewport" content="height=device-height">:

  • Portrait: 980x1024
  • Landscape: 980x1024

With <meta name="viewport" content="height=device-height,width=device-width">:

  • Portrait: 768x1024
  • Landscape: 768x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width,height=device-height">

  • Portrait: 768x1024
  • Landscape: 1024x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,height=device-height">

  • Portrait: 831x1024
  • Landscape: 1520x1024

SVN check out linux

There should be svn utility on you box, if installed:

$ svn checkout http://example.com/svn/somerepo somerepo

This will check out a working copy from a specified repository to a directory somerepo on our file system.

You may want to print commands, supported by this utility:

$ svn help

uname -a output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm or the following command:

$ sudo yum install subversion

"Auth Failed" error with EGit and GitHub

I could use console to push/pull the repositories, but no in eclipse. In my case, eclipse seems can't read my SSH private key, my key started with:

-----BEGIN OPENSSH PRIVATE KEY-----

And I noticed my colleague's key started with:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED

I think currently eclipse can't take this new kind of key (OPENSSH PRIVATE KEY).

I solved it by: Regenerate your ssh key by using command:

ssh-keygen -m PEM -t rsa -b 2048

This will use the old way to generate the key: so it will starts with the headers:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED

see more information on:

https://github.com/duplicati/duplicati/issues/3360

Then you can load the key again in eclilpse by using Preferences -> Network connections -> SSH2, click "Add Private Key" (still select your private key, even you already see the name in the list of private keys, because eclipse has to reload it)

How to update MySql timestamp column to current timestamp on PHP?

Another option:

UPDATE `table` SET the_col = current_timestamp

Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now().

Mockito How to mock and assert a thrown exception?

If you want to test the exception message as well you can use JUnit's ExpectedException with Mockito:

@Rule
public ExpectedException expectedException = ExpectedException.none();

@Test
public void testExceptionMessage() throws Exception {
    expectedException.expect(AnyException.class);
    expectedException.expectMessage("The expected message");

    given(foo.bar()).willThrow(new AnyException("The expected message"));
}

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

1.) Verify your connection string with ConnectionStrings.com.

2.) Make sure you have the correct database engine installed. These were the two database engines that helped me.

Microsoft Access Database Engine 2010 Redistributable

2007 Office System Driver: Data Connectivity Components

3.) There could be an issue with your build target platform being "Any CPU", it may need to be "X86" (Properties, Build, Platform Target).

writing a batch file that opens a chrome URL

@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://tweetdeck.twitter.com/"

@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://web.whatsapp.com/"

Have a reloadData for a UITableView animate when changing

All of these answers assume that you are using a UITableView with only 1 section.

To accurately handle situations where you have more than 1 section use:

NSRange range = NSMakeRange(0, myTableView.numberOfSections);
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
[myTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];

(Note: you should make sure that you have more than 0 sections!)

Another thing to note is that you may run into a NSInternalInconsistencyException if you attempt to simultaneously update your data source with this code. If this is the case, you can use logic similar to this:

int sectionNumber = 0; //Note that your section may be different

int nextIndex = [currentItems count]; //starting index of newly added items

[myTableView beginUpdates];

for (NSObject *item in itemsToAdd) {
    //Add the item to the data source
    [currentItems addObject:item];

    //Add the item to the table view
    NSIndexPath *path = [NSIndexPath indexPathForRow:nextIndex++ inSection:sectionNumber];
    [myTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:path] withRowAnimation:UITableViewRowAnimationAutomatic];
}

[myTableView endUpdates];

Are HTTPS headers encrypted?

the URL is also encrypted, you really only have the IP, Port and if SNI, the host name that are unencrypted.

How much does it cost to develop an iPhone application?

The rates that were quoted above are what you would expect to pay US developers; however, I do know some people who have been able to get their apps built for as little as $4,000 by using offshore developers.

Here is a blog post from a group that did this: http://www.lolerapps.com/why-outsourcing-iphone-apps-was-a-no-brainer-for-us

Also, Carla White wrote a fantastic eBook about the process she used to outsource her app called "Inside Secrets to an iPhone App". She talks about how she got a great deal because she was willing to work with a team that was still learning iPhone app development.

So, there are alternatives to the higher price developers discussed above.

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

I just dragged the certificate into the "Trusted Root Certification Authorities" folder and voila everything worked nicely.

Oh. And I first added the following from a Administrator Command Prompt:

netsh http add urlacl url=https://+:8732/Servicename user=NT-MYNDIGHET\INTERAKTIV

I am not sure of the name you need for the user (mine is norwegian as you can see !): user=NT-AUTHORITY/INTERACTIVE ?

You can see all existing urlacl's by issuing the command: netsh http show urlacl

How to check if a string "StartsWith" another string?

I am not sure for javascript but in typescript i did something like

var str = "something";
(<String>str).startsWith("some");

I guess it should work on js too. I hope it helps!

bootstrap 3 navbar collapse button not working

You need to change in this markup

 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar collapse">

change the

data-target=".navbar collapse"

to

data-target=".navbar-collapse"

Reason : The value of data-target is a any class name of the associated nav div. In this case it is

<div class="collapse navbar-collapse">  <-- Look at here
     <ul class="nav navbar-nav navbar-right">
     .....
</div>

Js Fiddle Demo

Javascript change date into format of (dd/mm/yyyy)

This will ensure you get a two-digit day and month.

function formattedDate(d = new Date) {
  let month = String(d.getMonth() + 1);
  let day = String(d.getDate());
  const year = String(d.getFullYear());

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return `${day}/${month}/${year}`;
}

Or terser:

function formattedDate(d = new Date) {
  return [d.getDate(), d.getMonth()+1, d.getFullYear()]
      .map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}

How to read if a checkbox is checked in PHP?

Well, the above examples work only when you want to INSERT a value, not useful for UPDATE different values to different columns, so here is my little trick to update:


//EMPTY ALL VALUES TO 0 
$queryMU ='UPDATE '.$db->dbprefix().'settings SET menu_news = 0, menu_gallery = 0, menu_events = 0, menu_contact = 0';
            $stmtMU = $db->prepare($queryMU);
            $stmtMU->execute();
if(!empty($_POST['check_menus'])) {
    foreach($_POST['check_menus'] as $checkU) {
try {
//UPDATE only the values checked
    $queryMU ='UPDATE '.$db->dbprefix().'settings SET '.$checkU.'= 1';
            $stmtMU = $db->prepare($queryMU);
            $stmtMU->execute();  
        } catch(PDOException $e) {
          $msg = 'Error: ' . $e->getMessage();}

        }
}
<input type="checkbox" value="menu_news" name="check_menus[]" />
<input type="checkbox" value="menu_gallery" name="check_menus[]" />

....

The secret is just update all VALUES first (in this case to 0), and since the will only send the checked values, that means everything you get should be set to 1, so everything you get set it to 1.

Example is PHP but applies for everything.

Have fun :)

PowerShell Connect to FTP server and get files

Here is the full working code to download all files (with wildcard or file extension) from the FTP site to local directory. Set the variable values.

    #FTP Server Information - SET VARIABLES
    $ftp = "ftp://XXX.com/" 
    $user = 'UserName' 
    $pass = 'Password'
    $folder = 'FTP_Folder'
    $target = "C:\Folder\Folder1\"

    #SET CREDENTIALS
    $credentials = new-object System.Net.NetworkCredential($user, $pass)

    function Get-FtpDir ($url,$credentials) {
        $request = [Net.WebRequest]::Create($url)
        $request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
        if ($credentials) { $request.Credentials = $credentials }
        $response = $request.GetResponse()
        $reader = New-Object IO.StreamReader $response.GetResponseStream() 
        while(-not $reader.EndOfStream) {
            $reader.ReadLine()
        }
        #$reader.ReadToEnd()
        $reader.Close()
        $response.Close()
    }

    #SET FOLDER PATH
    $folderPath= $ftp + "/" + $folder + "/"

    $files = Get-FTPDir -url $folderPath -credentials $credentials

    $files 

    $webclient = New-Object System.Net.WebClient 
    $webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass) 
    $counter = 0
    foreach ($file in ($files | where {$_ -like "*.txt"})){
        $source=$folderPath + $file  
        $destination = $target + $file 
        $webclient.DownloadFile($source, $target+$file)

        #PRINT FILE NAME AND COUNTER
        $counter++
        $counter
        $source
    }

Add up a column of numbers at the Unix shell

sizes=( $(cat files.txt | xargs ls -l | cut -c 23-30) )
total=$(( $(IFS="+"; echo "${sizes[*]}") ))

Or you could just sum them as you read the sizes

declare -i total=0
while read x; total+=x; done < <( cat files.txt | xargs ls -l | cut -c 23-30 )

If you don't care about bite sizes and blocks is OK, then just

declare -i total=0
while read s junk; total+=s; done < <( cat files.txt | xargs ls -s )

How is TeamViewer so fast?

A bit late answer, but I suggest you have a look at a not well known project on codeplex called ConferenceXP

ConferenceXP is an open source research platform that provides simple, flexible, and extensible conferencing and collaboration using high-bandwidth networks and the advanced multimedia capabilities of Microsoft Windows. ConferenceXP helps researchers and educators develop innovative applications and solutions that feature broadcast-quality audio and video in support of real-time distributed collaboration and distance learning environments.

Full source (it's huge!) is provided. It implements the RTP protocol.

Is there a method that calculates a factorial in Java?

public int factorial(int num) {
        if (num == 1) return 1;
        return num * factorial(num - 1);
}

How can I make one python file run another?

from subprocess import Popen

Popen('python filename.py')

or how-can-i-make-one-python-file-run-another-file

Element-wise addition of 2 lists?

It's simpler to use numpy from my opinion:

import numpy as np
list1=[1,2,3]
list2=[4,5,6]
np.add(list1,list2)

Results:

Terminal execution

For detailed parameter information, check here: numpy.add

Reading Datetime value From Excel sheet

Another option: when cell type is unknown at compile time and cell is formatted as Date Range.Value returns a desired DateTime object.


public static DateTime? GetAsDateTimeOrDefault(Range cell)
{
    object cellValue = cell.Value;
    if (cellValue is DateTime result)
    {
        return result;
    }
    return null;
}

How to define optional methods in Swift protocol?

  • You need to add optional keyword prior to each method.
  • Please note, however, that for this to work, your protocol must be marked with the @objc attribute.
  • This further implies that this protocol would be applicable to classes but not structures.

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Select2 for Bootstrap 3 native plugin

https://fk.github.io/select2-bootstrap-css/index.html

this plugin uses select2 jquery plugin

nuget

PM> Install-Package Select2-Bootstrap

How to set the From email address for mailx command?

On macOS Sierra, creating ~/.mailrc with smtp setup did the trick:

set smtp-use-starttls
set smtp=smtp://smtp.gmail.com:587
set smtp-auth=login
set [email protected]
set smtp-auth-password=yourpass

Then to send mail from CLI:

echo "your message" | mail -s "your subject" [email protected]

How to join two sets in one line without using "|"

If by join you mean union, try this:

set(list(s) + list(t))

It's a bit of a hack, but I can't think of a better one liner to do it.

process.env.NODE_ENV is undefined

in package.json we have to config like below (works in Linux and Mac OS)

the important thing is "export NODE_ENV=production" after your build commands below is an example:

  "scripts": {
     "start": "export NODE_ENV=production && npm run build && npm run start-server",
     "dev": "export NODE_ENV=dev && npm run build && npm run start-server",
  } 
  • for dev environment, we have to hit "npm run dev" command

  • for a production environment, we have to hit "npm run start" command

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

A simple case that generates this error message:

In [8]: [1,2,3,4,5][np.array([1])]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-55def8e1923d> in <module>()
----> 1 [1,2,3,4,5][np.array([1])]

TypeError: only integer scalar arrays can be converted to a scalar index

Some variations that work:

In [9]: [1,2,3,4,5][np.array(1)]     # this is a 0d array index
Out[9]: 2
In [10]: [1,2,3,4,5][np.array([1]).item()]    
Out[10]: 2
In [11]: np.array([1,2,3,4,5])[np.array([1])]
Out[11]: array([2])

Basic python list indexing is more restrictive than numpy's:

In [12]: [1,2,3,4,5][[1]]
....
TypeError: list indices must be integers or slices, not list

edit

Looking again at

indices = np.random.choice(range(len(X_train)), replace=False, size=50000, p=train_probs)

indices is a 1d array of integers - but it certainly isn't scalar. It's an array of 50000 integers. List's cannot be indexed with multiple indices at once, regardless of whether they are in a list or array.

Change marker size in Google maps V3

The size arguments are in pixels. So, to double your example's marker size the fifth argument to the MarkerImage constructor would be:

new google.maps.Size(42,68)

I find it easiest to let the map API figure out the other arguments, unless I need something other than the bottom/center of the image as the anchor. In your case you could do:

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(42, 68)
);

Where does Visual Studio look for C++ header files?

Tried to add this as a comment to Rob Prouse's posting, but the lack of formatting made it unintelligible.

In Visual Studio 2010, the "Tools | Options | Projects and Solutions | VC++ Directories" dialog reports that "VC++ Directories editing in Tools > Options has been deprecated", proposing that you use the rather counter-intuitive Property Manager.

If you really, really want to update the default $(IncludePath), you have to hack the appropriate entry in one of the XML files:

\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\Win32\PlatformToolsets\v100\Microsoft.Cpp.Win32.v100.props

or

\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\x64\PlatformToolsets\v100\Microsoft.Cpp.X64.v100.props

(Probably not Microsoft-recommended.)

How to list files using dos commands?

If you just want to get the file names and not directory names then use :

dir /b /a-d > file.txt

Ruby class instance variable vs. class variable

Official Ruby FAQ: What is the difference between class variables and class instance variables?

The main difference is the behavior concerning inheritance: class variables are shared between a class and all its subclasses, while class instance variables only belong to one specific class.

Class variables in some way can be seen as global variables within the context of an inheritance hierarchy, with all the problems that come with global variables. For instance, a class variable might (accidentally) be reassigned by any of its subclasses, affecting all other classes:

class Woof

  @@sound = "woof"

  def self.sound
    @@sound
  end
end

Woof.sound  # => "woof"

class LoudWoof < Woof
  @@sound = "WOOF"
end

LoudWoof.sound  # => "WOOF"
Woof.sound      # => "WOOF" (!)

Or, an ancestor class might later be reopened and changed, with possibly surprising effects:

class Foo

  @@var = "foo"

  def self.var
    @@var
  end
end

Foo.var  # => "foo" (as expected)

class Object
  @@var = "object"
end

Foo.var  # => "object" (!)

So, unless you exactly know what you are doing and explicitly need this kind of behavior, you better should use class instance variables.

Disabling tab focus on form elements

If you're dealing with an input element, I found it useful to set the pointer focus to back itself.

$('input').on('keydown', function(e) { 
    if (e.keyCode == 9) {
        $(this).focus();
       e.preventDefault();
    }
});

SQL Error: ORA-12899: value too large for column

example : 1 and 2 table is available

1 table delete entry and select nor 2 table records and insert to no 1 table . when delete time no 1 table dont have second table records example emp id not available means this errors appeared

HTML embed autoplay="false", but still plays automatically

<embed ... autostart="0">

Replace false with 0

How to convert text to binary code in JavaScript?

Try this:

String.prototype.toBinaryString = function(spaces = 0) {
    return this.split("").map(function(character) {
        return character.charCodeAt(0).toString(2);
    }).join(" ".repeat(spaces));
}

And use it like this:

"test string".toBinaryString(1); // with spaces
"test string".toBinaryString(); // without spaces
"test string".toBinaryString(2); // with 2 spaces

Get key and value of object in JavaScript?

Object.keys(top_brands).forEach(function(key) {
  var value = top_brands[key];
  // use "key" and "value" here...
});

Btw, note that Object.keys and forEach are not available in ancient browsers, but you should use some polyfill anyway.

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

WAR file is just a JAR file, to extract it, just issue following jar command –

jar -xvf yourWARfileName.war

If the jar command is not found, which sometimes happens in the Windows command prompt, then specify full path i.e. in my case it is,

 c:\java\jdk-1.7.0\bin\jar -xvf my-file.war

CURL alternative in Python

You can use HTTP Requests that are described in the Requests: HTTP for Humans user guide.

ASP.Net MVC Redirect To A Different View

Here's what you can do:

return View("another view name", anotherviewmodel);

What does the 'b' character do in front of a string literal?

The b denotes a byte string.

Bytes are the actual data. Strings are an abstraction.

If you had multi-character string object and you took a single character, it would be a string, and it might be more than 1 byte in size depending on encoding.

If took 1 byte with a byte string, you'd get a single 8-bit value from 0-255 and it might not represent a complete character if those characters due to encoding were > 1 byte.

TBH I'd use strings unless I had some specific low level reason to use bytes.

How can I scroll to a specific location on the page using jquery?

Using jquery.easing.min.js, With fixed IE console Errors

Html

<a class="page-scroll" href="#features">Features</a>
<section id="features" class="features-section">Features Section</section>


        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="js/jquery.js"></script>
        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="js/bootstrap.min.js"></script>

        <!-- Scrolling Nav JavaScript -->
        <script src="js/jquery.easing.min.js"></script>

Jquery

//jQuery to collapse the navbar on scroll, you can use this code with in external file with name scrolling-nav.js
        $(window).scroll(function () {
            if ($(".navbar").offset().top > 50) {
                $(".navbar-fixed-top").addClass("top-nav-collapse");
            } else {
                $(".navbar-fixed-top").removeClass("top-nav-collapse");
            }
        });
        //jQuery for page scrolling feature - requires jQuery Easing plugin
        $(function () {
            $('a.page-scroll').bind('click', function (event) {
                var anchor = $(this);
                if ($(anchor).length > 0) {
                    var href = $(anchor).attr('href');
                    if ($(href.substring(href.indexOf('#'))).length > 0) {
                        $('html, body').stop().animate({
                            scrollTop: $(href.substring(href.indexOf('#'))).offset().top
                        }, 1500, 'easeInOutExpo');
                    }
                    else {
                        window.location = href;
                    }
                }
                event.preventDefault();
            });
        });

What does the NS prefix mean?

When NeXT were defining the NextStep API (as opposed to the NEXTSTEP operating system), they used the prefix NX, as in NXConstantString. When they were writing the OpenStep specification with Sun (not to be confused with the OPENSTEP operating system) they used the NS prefix, as in NSObject.

What is the difference between parseInt(string) and Number(string) in JavaScript?

parseInt("123qwe")

returns 123

Number("123qwe")

returns NaN

In other words parseInt() parses up to the first non-digit and returns whatever it had parsed. Number() wants to convert the entire string into a number, which can also be a float BTW.


EDIT #1: Lucero commented about the radix that can be used along with parseInt(). As far as that is concerned, please see THE DOCTOR's answer below (I'm not going to copy that here, the doc shall have a fair share of the fame...).


EDIT #2: Regarding use cases: That's somewhat written between the lines already. Use Number() in cases where you indirectly want to check if the given string completely represents a numeric value, float or integer. parseInt()/parseFloat() aren't that strict as they just parse along and stop when the numeric value stops (radix!), which makes it useful when you need a numeric value at the front "in case there is one" (note that parseInt("hui") also returns NaN). And the biggest difference is the use of radix that Number() doesn't know of and parseInt() may indirectly guess from the given string (that can cause weird results sometimes).

Best way to make a shell script daemon?

It really depends on what is the binary itself going to do.

For example I want to create some listener.

The starting Daemon is simple task :

lis_deamon :

#!/bin/bash

# We will start the listener as Deamon process
#    
LISTENER_BIN=/tmp/deamon_test/listener
test -x $LISTENER_BIN || exit 5
PIDFILE=/tmp/deamon_test/listener.pid

case "$1" in
      start)
            echo -n "Starting Listener Deamon .... "
            startproc -f -p $PIDFILE $LISTENER_BIN
            echo "running"
            ;;
          *)
            echo "Usage: $0 start"
            exit 1
            ;;
esac

this is how we start the daemon (common way for all /etc/init.d/ staff)

now as for the listener it self, It must be some kind of loop/alert or else that will trigger the script to do what u want. For example if u want your script to sleep 10 min and wake up and ask you how you are doing u will do this with the

while true ; do sleep 600 ; echo "How are u ? " ; done

Here is the simple listener that u can do that will listen for your commands from remote machine and execute them on local :

listener :

#!/bin/bash

# Starting listener on some port
# we will run it as deamon and we will send commands to it.
#
IP=$(hostname --ip-address)
PORT=1024
FILE=/tmp/backpipe
count=0
while [ -a $FILE ] ; do #If file exis I assume that it used by other program
  FILE=$FILE.$count
  count=$(($count + 1))
done

# Now we know that such file do not exist,
# U can write down in deamon it self the remove for those files
# or in different part of program

mknod $FILE p

while true ; do 
  netcat -l -s $IP -p $PORT < $FILE |/bin/bash > $FILE
done
rm $FILE

So to start UP it : /tmp/deamon_test/listener start

and to send commands from shell (or wrap it to script) :

test_host#netcat 10.184.200.22 1024
uptime
 20:01pm  up 21 days  5:10,  44 users,  load average: 0.62, 0.61, 0.60
date
Tue Jan 28 20:02:00 IST 2014
 punt! (Cntrl+C)

Hope this will help.

How to create a file in Ruby

Try using "w+" as the write mode instead of just "w":

File.open("out.txt", "w+") { |file| file.write("boo!") }

sql primary key and index

a PK will become a clustered index unless you specify non clustered

calling java methods in javascript code

When it is on server side, use web services - maybe RESTful with JSON.

  • create a web service (for example with Tomcat)
  • call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at methodReturningString.

Java code:

public class MethodInvocation extends Applet {
    public void noArgMethod() { ... }
    public void someMethod(String arg) { ... }
    public void someMethod(int arg) { ... }
    public int  methodReturningInt() { return 5; }
    public String methodReturningString() { return "Hello"; }
    public OtherClass methodReturningObject() { return new OtherClass(); }
}

public class OtherClass {
    public void anotherMethod();
}

Web page and JavaScript code:

<applet id="app"
        archive="examples.jar"
        code="MethodInvocation" ...>
</applet>
<script language="javascript">
    app.noArgMethod();
    app.someMethod("Hello");
    app.someMethod(5);
    var five = app.methodReturningInt();
    var hello = app.methodReturningString();
    app.methodReturningObject().anotherMethod();
</script>

Print range of numbers on same line

Same can be achieved by using stdout.

>>> from sys import stdout
>>> for i in range(1,11):
...     stdout.write(str(i)+' ')
...
1 2 3 4 5 6 7 8 9 10 

Alternatively, same can be done by using reduce() :

>>> xrange = range(1,11)
>>> print reduce(lambda x, y: str(x) + ' '+str(y), xrange)
1 2 3 4 5 6 7 8 9 10
>>>

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

What is the correct way to free memory in C#

  1. Yes
  2. What do you mean by the same? It will be re-executed every time the method is run.
  3. Yes, the .Net garbage collector uses an algorithm that starts with any global/in-scope variables, traverses them while following any reference it finds recursively, and deletes any object in memory deemed to be unreachable. see here for more detail on Garbage Collection
  4. Yes, the memory from all variables declared in a method is released when the method exits as they are all unreachable. In addition, any variables that are declared but never used will be optimized out by the compiler, so in reality your Foo variable will never ever take up memory.
  5. the using statement simply calls dispose on an IDisposable object when it exits, so this is equivalent to your second bullet point. Both will indicate that you are done with the object and tell the GC that you are ready to let go of it. Overwriting the only reference to the object will have a similar effect.

Disable submit button on form submit

Specifically if someone is facing problem in Chrome:

What you need to do to fix this is to use the onSubmit tag in the <form> element to set the submit button disabled. This will allow Chrome to disable the button immediately after it is pressed and the form submission will still go ahead...

<form name ="myform" method="POST" action="dosomething.php" onSubmit="document.getElementById('submit').disabled=true;"> 
     <input type="submit" name="submit" value="Submit" id="submit"> 
</form>

Assignment makes pointer from integer without cast

char cString1[]

This is an array, i.e. a pointer to the first element of a range of elements of the same data type. Note you're not passing the array by-value but by-pointer.

char strToLower(...)

However, this returns a char. So your assignment

cString1 = strToLower(cString1);

has different types on each side of the assignment operator .. you're actually assigning a 'char' (sort of integer) to an array, which resolves to a simple pointer. Due to C++'s implicit conversion rules this works, but the result is rubbish and further access to the array causes undefined behaviour.

The solution is to make strToLower return char*.

Explicitly select items from a list or tuple

list( myBigList[i] for i in [87, 342, 217, 998, 500] )

I compared the answers with python 2.5.2:

  • 19.7 usec: [ myBigList[i] for i in [87, 342, 217, 998, 500] ]

  • 20.6 usec: map(myBigList.__getitem__, (87, 342, 217, 998, 500))

  • 22.7 usec: itemgetter(87, 342, 217, 998, 500)(myBigList)

  • 24.6 usec: list( myBigList[i] for i in [87, 342, 217, 998, 500] )

Note that in Python 3, the 1st was changed to be the same as the 4th.


Another option would be to start out with a numpy.array which allows indexing via a list or a numpy.array:

>>> import numpy
>>> myBigList = numpy.array(range(1000))
>>> myBigList[(87, 342, 217, 998, 500)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index
>>> myBigList[[87, 342, 217, 998, 500]]
array([ 87, 342, 217, 998, 500])
>>> myBigList[numpy.array([87, 342, 217, 998, 500])]
array([ 87, 342, 217, 998, 500])

The tuple doesn't work the same way as those are slices.

How to link to part of the same document in Markdown?

Universal solutions

This question seems to have a different answer according to the markdown implementation.
In fact, the official Markdown documentation is silent on this topic.
In such cases, and if you want a portable solution, you could use HTML.

Before any header, or in the same header line, define an ID using some HTML tag.
For example: <a id="Chapter1"></a>
You will see this in your code but not in the rendered document.

Full example:

See a full example (online and editable) here.

## Content

* [Chapter 1](#Chapter1)
* [Chapter 2](#Chapter2)

<div id="Chapter1"></div>
## Chapter 1

Some text here.  
Some text here.
Some text here.

## Chapter 2 <span id="Chapter2"><span>

Some text here.  
Some text here.
Some text here.

To test this example, you must add some extra space between the content list and the first chapter or reduce the window height.
Also, do not use spaces in the name of the ids.

new Runnable() but no new thread?

Runnable is just an interface, which provides the method run. Threads are implementations and use Runnable to call the method run().

A field initializer cannot reference the nonstatic field, method, or property

You need to put that code into the constructor of your class:

private Reminders reminder = new Reminders();
private dynamic defaultReminder;

public YourClass()
{
    defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}

The reason is that you can't use one instance variable to initialize another one using a field initializer.

Vertical Text Direction

I was searching for an actual vertical text and not the rotated text in HTML as shown below. So I could achieve it by using the following method.

enter image description here HTML:-

<p class="vericaltext">
Hi This is Vertical Text!
</p>

CSS:-

.vericaltext{
    width:1px;
    word-wrap: break-word;
    font-family: monospace; /* this is just for good looks */
}

JSFiddle! Demo.

Update:- If you need the whitespaces to be displayed, then add the following property to your css.

white-space: pre;

So, the css class shall be

.vericaltext{
    width:1px;
    word-wrap: break-word;
    font-family: monospace; /* this is just for good looks */
    white-space: pre;/* this is for displaying whitespaces */
}

JSFiddle! Demo With Whitespace

Update 2 (28-JUN-2015)

Since white-space: pre; doesnt seem to work (for this specific use) on Firefox(as of now), just change that line to

white-space: pre-wrap;

So, the css class shall be

.vericaltext{
    width:1px;
    word-wrap: break-word;
    font-family: monospace; /* this is just for good looks */
    white-space:pre-wrap; /* this is for displaying whitespaces including Moz-FF.*/
}

JsFiddle Demo FF Compatible.

How do you create a Marker with a custom icon for google maps API v3?

LatLng hello = new LatLng(X, Y);          // whereX & Y are coordinates

Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
                R.drawable.university);   // where university is the icon name that is used as a marker.

mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(icon)).position(hello).title("Hello World!"));

mMap.moveCamera(CameraUpdateFactory.newLatLng(hello));

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

In my case it was a circular reference. I had MyService calling Myservice2 And MyService2 calling MyService.

Not good :(

C#, Looping through dataset and show each record from a dataset column

foreach (DataTable table in ds.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        var ParentId=dr["ParentId"].ToString();
    }
}

How to delete columns in a CSV file?

Try:

result= data.drop('year', 1)
result.head(5)

MySQL "Group By" and "Order By"

Do a GROUP BY after the ORDER BY by wrapping your query with the GROUP BY like this:

SELECT t.* FROM (SELECT * FROM table ORDER BY time DESC) t GROUP BY t.from

How many socket connections possible?

Which operating system?

For windows machines, if you're writing a server to scale well, and therefore using I/O Completion Ports and async I/O, then the main limitation is the amount of non-paged pool that you're using for each active connection. This translates directly into a limit based on the amount of memory that your machine has installed (non-paged pool is a finite, fixed size amount that is based on the total memory installed).

For connections that don't see much traffic you can reduce make them more efficient by posting 'zero byte reads' which don't use non-paged pool and don't affect the locked pages limit (another potentially limited resource that may prevent you having lots of socket connections open).

Apart from that, well, you will need to profile but I've managed to get more than 70,000 concurrent connections on a modestly specified (760MB memory) server; see here http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html for more details.

Obviously if you're using a less efficient architecture such as 'thread per connection' or 'select' then you should expect to achieve less impressive figures; but, IMHO, there's simply no reason to select such architectures for windows socket servers.

Edit: see here http://blogs.technet.com/markrussinovich/archive/2009/03/26/3211216.aspx; the way that the amount of non-paged pool is calculated has changed in Vista and Server 2008 and there's now much more available.

100% height minus header?

If your browser supports CSS3, try using the CSS element Calc()

height: calc(100% - 65px);

you might also want to adding browser compatibility options:

height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */

also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622

Convert timestamp to string

try this

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String string  = dateFormat.format(new Date());
System.out.println(string);

you can create any format see this

How can I style the border and title bar of a window in WPF?

I found a more straight forward solution from @DK comment in this question, the solution is written by Alex and described here with source, To make customized window:

  1. download the sample project here
  2. edit the generic.xaml file to customize the layout.
  3. enjoy :).

SPAN vs DIV (inline-block)

  1. Inline-block is a halfway point between setting an element’s display to inline or to block. It keeps the element in the inline flow of the document like display:inline does, but you can manipulate the element’s box attributes (width, height and vertical margins) like you can with display:block.

  2. We must not use block elements within inline elements. This is invalid and there is no reason to do such practices.

Xcode Error: "The app ID cannot be registered to your development team."

My problem was I was modifying the settings for the wrong version of my app.

enter image description here

I had "Debug" selected instead of "Release", so my bundle identifier was not accurate when it came time to Archive.

How can I map True/False to 1/0 in a Pandas DataFrame?

You can use a transformation for your data frame:

df = pd.DataFrame(my_data condition)

transforming True/False in 1/0

df = df*1

Calculate rolling / moving average in C++

Simple class to calculate rolling average and also rolling standard deviation:

#define _stdev(cnt, sum, ssq) sqrt((((double)(cnt))*ssq-pow((double)(sum),2)) / ((double)(cnt)*((double)(cnt)-1)))

class moving_average {
private:
    boost::circular_buffer<int> *q;
    double sum;
    double ssq;
public:
    moving_average(int n)  {
        sum=0;
        ssq=0;
        q = new boost::circular_buffer<int>(n);
    }
    ~moving_average() {
        delete q;
    }
    void push(double v) {
        if (q->size() == q->capacity()) {
            double t=q->front();
            sum-=t;
            ssq-=t*t;
            q->pop_front();
        }
        q->push_back(v);
        sum+=v;
        ssq+=v*v;
    }
    double size() {
        return q->size();
    }
    double mean() {
        return sum/size();
    }
    double stdev() {
        return _stdev(size(), sum, ssq);
    }

};

Capitalize first letter. MySQL

Vincents excellent answer for Uppercase First Letter works great for the first letter only capitalization of an entire column string..

BUT what if you want to Uppercase the First Letter of EVERY word in the strings of a table column?

eg: "Abbeville High School"

I hadn't found an answer to this in Stackoverflow. I had to cobble together a few answers I found in Google to provide a solid solution to the above example. Its not a native function but a user created function which MySQL version 5+ allows.

If you have Super/Admin user status on MySQL or have a local mysql installation on your own computer you can create a FUNCTION (like a stored procedure) which sits in your database and can be used in all future SQL query on any part of the db.

The function I created allows me to use this new function I called "UC_Words" just like the built in native functions of MySQL so that I can update a complete column like this:

UPDATE Table_name
SET column_name = UC_Words(column_name) 

To insert the function code, I changed the MySQL standard delimiter(;) whilst creating the function, and then reset it back to normal after the function creation script. I also personally wanted the output to be in UTF8 CHARSET too.

Function creation =

DELIMITER ||  

CREATE FUNCTION `UC_Words`( str VARCHAR(255) ) RETURNS VARCHAR(255) CHARSET utf8 DETERMINISTIC  
BEGIN  
  DECLARE c CHAR(1);  
  DECLARE s VARCHAR(255);  
  DECLARE i INT DEFAULT 1;  
  DECLARE bool INT DEFAULT 1;  
  DECLARE punct CHAR(17) DEFAULT ' ()[]{},.-_!@;:?/';  
  SET s = LCASE( str );  
  WHILE i < LENGTH( str ) DO  
     BEGIN  
       SET c = SUBSTRING( s, i, 1 );  
       IF LOCATE( c, punct ) > 0 THEN  
        SET bool = 1;  
      ELSEIF bool=1 THEN  
        BEGIN  
          IF c >= 'a' AND c <= 'z' THEN  
             BEGIN  
               SET s = CONCAT(LEFT(s,i-1),UCASE(c),SUBSTRING(s,i+1));  
               SET bool = 0;  
             END;  
           ELSEIF c >= '0' AND c <= '9' THEN  
            SET bool = 0;  
          END IF;  
        END;  
      END IF;  
      SET i = i+1;  
    END;  
  END WHILE;  
  RETURN s;  
END ||  

DELIMITER ; 

This works a treat outputting Uppercase first letters on multiple words within a string.

Assuming your MySQL login username has sufficient privileges - if not, and you cant set up a temporary DB on your personal machine to convert your tables, then ask your shared hosting provider if they will set this function for you.

How to set initial size of std::vector?

You need to use the reserve function to set an initial allocated size or do it in the initial constructor.

vector<CustomClass *> content(20000);

or

vector<CustomClass *> content;
...
content.reserve(20000);

When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated.

Cannot find the '@angular/common/http' module

You should import http from @angular/http in your service:

import {Http} from '@angular/http';

constructor(private http: http) {} // <--Then Inject it here


// now you can use it in any function eg:
getUsers() {
    return this.http.get('whateverURL');
}

What does iterator->second mean?

The type of the elements of an std::map (which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K and value is V is std::pair<const K, V> - the key is const to prevent you from interfering with the internal sorting of map values.

std::pair<> has two members named first and second (see here), with quite an intuitive meaning. Thus, given an iterator i to a certain map, the expression:

i->first

Which is equivalent to:

(*i).first

Refers to the first (const) element of the pair object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:

i->second

Which is equivalent to:

(*i).second

Refers to the second element of the pair - i.e. to the corresponding value in the map.

"Untrusted App Developer" message when installing enterprise iOS Application

You absolutely can avoid this issue if you manage the device with MDM or have access to Apple Configurator.

The solution is to push either the Developer or iOS Distribution certificate to the device via MDM or Apple Configurator. Once you do that, any application signed by that cert will be trusted.

When you click on "Do you trust this developer", you're essentially adding that certificate manually on a per-app basis.

How to copy selected lines to clipboard in vim

For GVIM, hit v to go into visual mode; select text and hit Ctrl+Insert to copy selection into global clipboard.

From the menu you can see that the shortcut key is "+y i.e. hold Shift key, then press ", then + and then release Shift and press y (cumbersome in comparison to Shift+Insert).

What is the purpose and use of **kwargs?

Here's a simple function that serves to explain the usage:

def print_wrap(arg1, *args, **kwargs):
    print(arg1)
    print(args)
    print(kwargs)
    print(arg1, *args, **kwargs)

Any arguments that are not specified in the function definition will be put in the args list, or the kwargs list, depending on whether they are keyword arguments or not:

>>> print_wrap('one', 'two', 'three', end='blah', sep='--')
one
('two', 'three')
{'end': 'blah', 'sep': '--'}
one--two--threeblah

If you add a keyword argument that never gets passed to a function, an error will be raised:

>>> print_wrap('blah', dead_arg='anything')
TypeError: 'dead_arg' is an invalid keyword argument for this function

Crontab Day of the Week syntax

You can also use day names like Mon for Monday, Tue for Tuesday, etc. It's more human friendly.

How can one change the timestamp of an old commit in Git?

Use git filter-branch with an env filter that sets GIT_AUTHOR_DATE and GIT_COMMITTER_DATE for the specific hash of the commit you're looking to fix.

This will invalidate that and all future hashes.

Example:

If you wanted to change the dates of commit 119f9ecf58069b265ab22f1f97d2b648faf932e0, you could do so with something like this:

git filter-branch --env-filter \
    'if [ $GIT_COMMIT = 119f9ecf58069b265ab22f1f97d2b648faf932e0 ]
     then
         export GIT_AUTHOR_DATE="Fri Jan 2 21:38:53 2009 -0800"
         export GIT_COMMITTER_DATE="Sat May 19 01:01:01 2007 -0700"
     fi'

Loop through properties in JavaScript object with Lodash

For your stated desire to "check if a property exists" you can directly use Lo-Dash's has.

var exists = _.has(myObject, propertyNameToCheck);

How to launch Safari and open URL from iOS app

Here's what I did:

  1. I created an IBAction in the header .h files as follows:

    - (IBAction)openDaleDietrichDotCom:(id)sender;
    
  2. I added a UIButton on the Settings page containing the text that I want to link to.

  3. I connected the button to IBAction in File Owner appropriately.

  4. Then implement the following:

Objective-C

- (IBAction)openDaleDietrichDotCom:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.daledietrich.com"]];
}

Swift

(IBAction in viewController, rather than header file)

if let link = URL(string: "https://yoursite.com") {
  UIApplication.shared.open(link)
}

Use -notlike to filter out multiple strings in PowerShell

Using select-string:

Get-EventLog Security | where {$_.UserName | select-string -notmatch user1,user2}

How can I get terminal output in python?

The easiest way is to use the library commands

import commands
print commands.getstatusoutput('echo "test" | wc')

How to get the host name of the current machine as defined in the Ansible hosts file?

This is an alternative:

- name: Install this only for local dev machine
  pip: name=pyramid
  delegate_to: localhost

How to create an android app using HTML 5

You can write complete apps for almost any smartphone platform (Android, iOS,...) using Phonegap. (http://www.phonegap.com)

It is an open source framework that exposes native capabilities to a web view, so that you can do anything a native app can do.

This is very suitable for cross platform development if you're not building something that has to be pixel perfect in every way, or is very hardware intensive.

If you are looking for UI Frameworks that can be used to build such apps, there is a wide range of different libraries. (Like Sencha, jQuery mobile, ...)

And to be a little biased, there is something I built as well: http://www.m-gwt.com

Loop through array of values with Arrow Function

In short:

someValues.forEach((element) => {
    console.log(element);
});

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx

    Set-ExecutionPolicy RemoteSigned
    
  2. Run this python script on your powershell script helloworld.py:

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    
    p = subprocess.Popen(["powershell.exe", 
                  "C:\\Users\\USER\\Desktop\\helloworld.ps1"], 
                  stdout=sys.stdout)
    p.communicate()
    

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

C:\Users\MacEwin\Desktop>python helloworld.py
Hello World

'NOT LIKE' in an SQL query

You need to specify the column in both expressions.

SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'

How can I generate an HTML report for Junit results?

There are multiple options available for generating HTML reports for Selenium WebDriver scripts.

1. Use the JUNIT TestWatcher class for creating your own Selenium HTML reports

The TestWatcher JUNIT class allows overriding the failed() and succeeded() JUNIT methods that are called automatically when JUNIT tests fail or pass.

The TestWatcher JUNIT class allows overriding the following methods:

  • protected void failed(Throwable e, Description description)

failed() method is invoked when a test fails

  • protected void finished(Description description)

finished() method is invoked when a test method finishes (whether passing or failing)

  • protected void skipped(AssumptionViolatedException e, Description description)

skipped() method is invoked when a test is skipped due to a failed assumption.

  • protected void starting(Description description)

starting() method is invoked when a test is about to start

  • protected void succeeded(Description description)

succeeded() method is invoked when a test succeeds

See below sample code for this case:

import static org.junit.Assert.assertTrue;
import org.junit.Test;

public class TestClass2 extends WatchManClassConsole {

    @Test public void testScript1() {
        assertTrue(1 < 2); >
    }

    @Test public void testScript2() {
        assertTrue(1 > 2);
    }

    @Test public void testScript3() {
        assertTrue(1 < 2);
    }

    @Test public void testScript4() {
        assertTrue(1 > 2);
    }
}

import org.junit.Rule; 
import org.junit.rules.TestRule; 
import org.junit.rules.TestWatcher; 
import org.junit.runner.Description; 
import org.junit.runners.model.Statement; 

public class WatchManClassConsole {

    @Rule public TestRule watchman = new TestWatcher() { 

        @Override public Statement apply(Statement base, Description description) { 
            return super.apply(base, description); 
        } 

        @Override protected void succeeded(Description description) { 
            System.out.println(description.getDisplayName() + " " + "success!"); 
        } 

        @Override protected void failed(Throwable e, Description description) { 
            System.out.println(description.getDisplayName() + " " + e.getClass().getSimpleName()); 
        }
    }; 
}

2. Use the Allure Reporting framework

Allure framework can help with generating HTML reports for your Selenium WebDriver projects.

The reporting framework is very flexible and it works with many programming languages and unit testing frameworks.

You can read everything about it at http://allure.qatools.ru/.

You will need the following dependencies and plugins to be added to your pom.xml file

  1. maven surefire
  2. aspectjweaver
  3. allure adapter

See more details including code samples on this article: http://test-able.blogspot.com/2015/10/create-selenium-html-reports-with-allure-framework.html

Error checking for NULL in VBScript

I will just add a blank ("") to the end of the variable and do the comparison. Something like below should work even when that variable is null. You can also trim the variable just in case of spaces.

If provider & "" <> "" Then 
    url = url & "&provider=" & provider 
End if

how do you filter pandas dataframes by multiple columns

You can filter by multiple columns (more than two) by using the np.logical_and operator to replace & (or np.logical_or to replace |)

Here's an example function that does the job, if you provide target values for multiple fields. You can adapt it for different types of filtering and whatnot:

def filter_df(df, filter_values):
    """Filter df by matching targets for multiple columns.

    Args:
        df (pd.DataFrame): dataframe
        filter_values (None or dict): Dictionary of the form:
                `{<field>: <target_values_list>}`
            used to filter columns data.
    """
    import numpy as np
    if filter_values is None or not filter_values:
        return df
    return df[
        np.logical_and.reduce([
            df[column].isin(target_values) 
            for column, target_values in filter_values.items()
        ])
    ]

Usage:

df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1, 2, 3, 4]})

filter_df(df, {
    'a': [1, 2, 3],
    'b': [1, 2, 4]
})

Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules

I'm quite a beginner in Python and I found the answer of Anand was very good but quite complicated to me, so I try to reformulate :

1) insert and append methods are not specific to sys.path and as in other languages they add an item into a list or array and :
* append(item) add item to the end of the list,
* insert(n, item) inserts the item at the nth position in the list (0 at the beginning, 1 after the first element, etc ...).

2) As Anand said, python search the import files in each directory of the path in the order of the path, so :
* If you have no file name collisions, the order of the path has no impact,
* If you look after a function already defined in the path and you use append to add your path, you will not get your function but the predefined one.

But I think that it is better to use append and not insert to not overload the standard behaviour of Python, and use non-ambiguous names for your files and methods.

How to convert signed to unsigned integer in python

Since version 3.2 :

def toSigned(n, byte_count): 
  return int.from_bytes(n.to_bytes(byte_count, 'little'), 'little', signed=True)

output :

In [8]: toSigned(5, 1)                                                                                                                                                                                                                                                                                                     
Out[8]: 5

In [9]: toSigned(0xff, 1)                                                                                                                                                                                                                                                                                                  
Out[9]: -1

Is there any WinSCP equivalent for linux?

If you're using Gnome, you can go to: Places -> Connect to Server in nautilus and choose SSH. If you have a SSH agent running and configured, no password will be asked! (This is the same as sftp://root@servername/directory in Nautilus)

In Konqueror, you can simply type: fish://servername.

per Mike R: In Ubuntu Unity 14.0.4 its under Files > Connect to Server in the Menu or Network > Connect to Server in the sidebar

jQuery UI Datepicker - Multiple Date Selections

Just had a requirement for this; here is the code I used. Apply it to an input as normal, I am using the class typeof__multidatepicker.

It maintains a list of unique dates in the owner textbox. You can also type in there, this is not validated - obviously the server needs to check the resulting list!

I tried to get it to work with the datepicker's linked textbox but failed, so it creates an invisible input for the datepicker (it doesn't seem to work with display:none, hence the odd styling).

It is positioned over the main input so the datepicker appears in the correct place, and is 1px in width so you can still type into the main textbox.

It's for an intranet with a fixed platform so I haven't done much cross-browser testing.

Remember to include the handler on the body or it works confusingly.

$('.typeof__multidatepicker').each(
    function()
    {
        var _this = $(this);                        

        var picker = $('<input tabindex="-1" style="position:absolute;opacity:0;width:1px" type="text"/>');

        picker.insertAfter(this)
        .position({my:'left top', at:'left top', of:this})
        .datepicker({
            beforeShow:
                function()
                {
                    _this.data('mdp-popped', true);
                },
            onClose: 
                function(dt, dpicker)
                {   
                    var date = $.datepicker.formatDate(picker.datepicker('option', 'dateFormat'), picker.datepicker('getDate'));
                    var hash = {};
                    var curr = _this.val() ? _this.val().split(/\s*,\s*/) : [];
                    var a = [];

                    $.each(curr, 
                        function() 
                        { 
                            if(this != '' && !/^\s+$/.test(this)) 
                            {   
                                a.push(this); 
                                hash[this] = true;
                            }
                        }
                    );

                    if(date && !hash[date])
                    {
                        a.push(date);

                        _this.val(a.join(', '));
                    }                                                                   

                    _this.data('mdp-popped', false);
                    _this.data('mdp-justclosed', true);
                }
        }); 

        _this.on('focus', 
            function(e) 
            {                               
                if(!_this.data('mdp-popped') && !_this.data('mdp-justclosed'))
                    _this.next().datepicker('show'); 

                _this.data('mdp-justclosed', false);
            }
        );
    }
);

$('body').on('click', function(e) { $('.typeof__multidatepicker').data('mdp-justclosed', false); });

How to call a SOAP web service on Android

To call a SOAP web Service from android , try to use this client

DON'T FORGET TO ADD ksoap2-android.jar in your java build path

public class WsClient {
    private static final String SOAP_ACTION = "somme";
    private static final String OPERATION_NAME = "somme";
    private static final String WSDL_TARGET_NAMESPACE = "http://example.ws";
    private static final String SOAP_ADDRESS = "http://192.168.1.2:8080/axis2/services/Calculatrice?wsdl";

    public String caclculerSomme() {

        String res = null;
        SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
                OPERATION_NAME);
        request.addProperty("a", "5");
        request.addProperty("b", "2");

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);

        try {
            httpTransport.call(SOAP_ACTION, envelope);
            String result = envelope.getResponse().toString();
            res = result;
            System.out.println("############# resull is :" + result);
        } catch (Exception exception) {
            System.out.println("########### ERRER" + exception.getMessage());
        }

        return res;
    }
}

CSS Animation and Display None

When animating height (from 0 to auto), using transform: scaleY(0); is another useful approach to hide the element, instead of display: none;:

.section {
  overflow: hidden;
  transition: transform 0.3s ease-out;
  height: auto;
  transform: scaleY(1);
  transform-origin: top;

  &.hidden {
    transform: scaleY(0);
  }
}

Convert date to YYYYMM format

SELECT CONVERT(nvarchar(6), GETDATE(), 112)

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

As mentioned by removing the colon : and replacing with slash / before the sid worked for me.

I have had this issue before, too.

How to compile and run a C/C++ program on the Android system

if you have installed NDK succesfully then start with it sample application

http://developer.android.com/sdk/ndk/overview.html#samples

if you are interested another ways of this then may this will help

http://shareprogrammingtips.blogspot.com/2018/07/cross-compile-cc-based-programs-and-run.html

I also want to know is it possible to push the compiled binary into android device or AVD and run using the terminal of the android device or AVD?

here you can see NestedVM

NestedVM provides binary translation for Java Bytecode. This is done by having GCC compile to a MIPS binary which is then translated to a Java class file. Hence any application written in C, C++, Fortran, or any other language supported by GCC can be run in 100% pure Java with no source changes.


Example: Cross compile Hello world C program and run it on android

Overloading operators in typedef structs (c++)

try this:

struct Pos{
    int x;
    int y;

    inline Pos& operator=(const Pos& other){
        x=other.x;
        y=other.y;
        return *this;
    }

    inline Pos operator+(const Pos& other) const {
        Pos res {x+other.x,y+other.y};
        return res;
    }

    const inline bool operator==(const Pos& other) const {
        return (x==other.x and y == other.y);
    }
 };  

How to prevent Browser cache on Angular 2 site?

angular-cli resolves this by providing an --output-hashing flag for the build command (versions 6/7, for later versions see here). Example usage:

ng build --output-hashing=all

Bundling & Tree-Shaking provides some details and context. Running ng help build, documents the flag:

--output-hashing=none|all|media|bundles (String)

Define the output filename cache-busting hashing mode.
aliases: -oh <value>, --outputHashing <value>

Although this is only applicable to users of angular-cli, it works brilliantly and doesn't require any code changes or additional tooling.

Update

A number of comments have helpfully and correctly pointed out that this answer adds a hash to the .js files but does nothing for index.html. It is therefore entirely possible that index.html remains cached after ng build cache busts the .js files.

At this point I'll defer to How do we control web page caching, across all browsers?

VMWare Player vs VMWare Workstation

Workstation has some features that Player lacks, such as teams (groups of VMs connected by private LAN segments) and multi-level snapshot trees. It's aimed at power users and developers; they even have some hooks for using a debugger on the host to debug code in the VM (including kernel-level stuff). The core technology is the same, though.

Correct way to write line to file?

This should be as simple as:

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')

From The Documentation:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

Some useful reading:

How to check identical array in most efficient way?

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

Div width 100% minus fixed amount of pixels

While Guffa's answer works in many situations, in some cases you may not want the left and/or right pieces of padding to be the parent of the center div. In these cases, you can use a block formatting context on the center and float the padding divs left and right. Here's the code

The HTML:

<div class="container">
    <div class="left"></div>
    <div class="right"></div>
    <div class="center"></div>
</div>

The CSS:

.container {
    width: 100px;
    height: 20px;
}

.left, .right {
    width: 20px;
    height: 100%;
    float: left;
    background: black;   
}

.right {
    float: right;
}

.center {
    overflow: auto;
    height: 100%;
    background: blue;
}

I feel that this element hierarchy is more natural when compared to nested nested divs, and better represents what's on the page. Because of this, borders, padding, and margin can be applied normally to all elements (ie: this 'naturality' goes beyond style and has ramifications).

Note that this only works on divs and other elements that share its 'fill 100% of the width by default' property. Inputs, tables, and possibly others will require you to wrap them in a container div and add a little more css to restore this quality. If you're unlucky enough to be in that situation, contact me and I'll dig up the css.

jsfiddle here: jsfiddle.net/RgdeQ

Enjoy!