Programs & Examples On #Webby

How to use sessions in an ASP.NET MVC 4 application?

This is how session state works in ASP.NET and ASP.NET MVC:

ASP.NET Session State Overview

Basically, you do this to store a value in the Session object:

Session["FirstName"] = FirstNameTextBox.Text;

To retrieve the value:

var firstName = Session["FirstName"];

How to find and replace all occurrences of a string recursively in a directory tree?

it is much simpler than that.

for i in `find *` ; do sed -i -- 's/search string/target string/g' $i; done

find i => will iterate over all the files in the folder and in subfolders.

sed -i => will replace in the files the relevant string if exists.

Why don't self-closing script elements work?

The people above have already pretty much explained the issue, but one thing that might make things clear is that, though people use <br/> and such all the time in HTML documents, any / in such a position is basically ignored, and only used when trying to make something both parseable as XML and HTML. Try <p/>foo</p>, for example, and you get a regular paragraph.

How to mute an html5 video player using jQuery

If you don't want to jQuery, here's the vanilla JavaScript:

///Mute
var video = document.getElementById("your-video-id");
video.muted= true;

//Unmute
var video = document.getElementById("your-video-id");
video.muted= false;

It will work for audio too, just put the element's id and it will work (and change the var name if you want, to 'media' or something suited for both audio/video as you like).

Xampp Access Forbidden php

The only solution that worked for me after spending hours researching online

sudo chmod -R 0777 /opt/lampp/htdocs/projectname

How to extract code of .apk file which is not working?

step 1:

enter image description hereDownload dex2jar here. Create a java project and paste (dex2jar-0.0.7.11-SNAPSHOT/lib ) jar files .

Copy apk file into java project

Run it and after refresh the project ,you get jar file .Using java decompiler you can view all java class files

step 2: Download java decompiler here

Configure active profile in SpringBoot via Maven

You can run using the following command. Here I want to run using spring profile local:

spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=local"

Class is not abstract and does not override abstract method

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

To work around this, you have 3 options:

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

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

And

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

Finally

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

And you can switch in between them, like so:

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

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

Again, just an example.

Spring JPA @Query with LIKE

Using Query creation from method names, check table 4 where they explain some keywords.

  1. Using Like: select ... like :username

     List<User> findByUsernameLike(String username);
    
  2. StartingWith: select ... like :username%

     List<User> findByUsernameStartingWith(String username);
    
  3. EndingWith: select ... like %:username

     List<User> findByUsernameEndingWith(String username);
    
  4. Containing: select ... like %:username%

     List<User> findByUsernameContaining(String username);
    

Notice that the answer that you are looking for is number 4. You don't have to use @Query

How to check empty object in angular 2 template using *ngIf

You could also use something like that:

<div class="comeBack_up" *ngIf="isEmptyObject(previous_info)"  >

with the isEmptyObject method defined in your component:

isEmptyObject(obj) {
  return (obj && (Object.keys(obj).length === 0));
}

What is the mouse down selector in CSS?

Pro-tip Note: for some reason, CSS syntax needs the :active snippet after the :hover for the same element in order to be effective

http://www.w3schools.com/cssref/sel_active.asp

How to create a multi line body in C# System.Net.Mail.MailMessage

Something that worked for me was simply separating data with a :

message.Body = FirstLine + ":" + SecondLine;

I hope this helps

Type definition in object literal in TypeScript

In TypeScript if we are declaring object then we'd use the following syntax:

[access modifier] variable name : { /* structure of object */ }

For example:

private Object:{ Key1: string, Key2: number }

How to upload files to server using JSP/Servlet?

Another source of this problem occurs if you are using Geronimo with its embedded Tomcat. In this case, after many iterations of testing commons-io and commons-fileupload, the problem arises from a parent classloader handling the commons-xxx jars. This has to be prevented. The crash always occurred at:

fileItems = uploader.parseRequest(request);

Note that the List type of fileItems has changed with the current version of commons-fileupload to be specifically List<FileItem> as opposed to prior versions where it was generic List.

I added the source code for commons-fileupload and commons-io into my Eclipse project to trace the actual error and finally got some insight. First, the exception thrown is of type Throwable not the stated FileIOException nor even Exception (these will not be trapped). Second, the error message is obfuscatory in that it stated class not found because axis2 could not find commons-io. Axis2 is not used in my project at all but exists as a folder in the Geronimo repository subdirectory as part of standard installation.

Finally, I found 1 place that posed a working solution which successfully solved my problem. You must hide the jars from parent loader in the deployment plan. This was put into geronimo-web.xml with my full file shown below.

Pasted from <http://osdir.com/ml/user-geronimo-apache/2011-03/msg00026.html> 



<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<web:web-app xmlns:app="http://geronimo.apache.org/xml/ns/j2ee/application-2.0" xmlns:client="http://geronimo.apache.org/xml/ns/j2ee/application-client-2.0" xmlns:conn="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2" xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2" xmlns:ejb="http://openejb.apache.org/xml/ns/openejb-jar-2.2" xmlns:log="http://geronimo.apache.org/xml/ns/loginconfig-2.0" xmlns:name="http://geronimo.apache.org/xml/ns/naming-1.2" xmlns:pers="http://java.sun.com/xml/ns/persistence" xmlns:pkgen="http://openejb.apache.org/xml/ns/pkgen-2.1" xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" xmlns:web="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1">
    <dep:environment>
        <dep:moduleId>
            <dep:groupId>DataStar</dep:groupId>
            <dep:artifactId>DataStar</dep:artifactId>
            <dep:version>1.0</dep:version>
            <dep:type>car</dep:type>
        </dep:moduleId>

<!--Don't load commons-io or fileupload from parent classloaders-->
        <dep:hidden-classes>
            <dep:filter>org.apache.commons.io</dep:filter>
            <dep:filter>org.apache.commons.fileupload</dep:filter>
        </dep:hidden-classes>
        <dep:inverse-classloading/>        


    </dep:environment>
    <web:context-root>/DataStar</web:context-root>
</web:web-app>

Exception: Can't bind to 'ngFor' since it isn't a known native property

In my case, the module containing the component using the *ngFor resulting in this error, was not included in the app.module.ts. Including it there in the imports array resolved the issue for me.

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

VBA, if a string contains a certain letter

Try:

If myString like "*A*" Then

Can I scale a div's height proportionally to its width using CSS?

You could assign both the width and height of the element using either vw or vh. For example:

#anyElement {
    width: 20vh;
    height: 20vh;
}

This would set both the width and height to 20% of the browser's current height, retaining the aspect ratio. However, this only works if you want to scale proportionate to the viewport dimensions.

Detect backspace and del on "input" event?

With jQuery

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.

http://api.jquery.com/event.which/

jQuery('#input').on('keydown', function(e) {
    if( e.which == 8 || e.which == 46 ) return false;
});

RegEx for matching UK Postcodes

I've been looking for a UK postcode regex for the last day or so and stumbled on this thread. I worked my way through most of the suggestions above and none of them worked for me so I came up with my own regex which, as far as I know, captures all valid UK postcodes as of Jan '13 (according to the latest literature from the Royal Mail).

The regex and some simple postcode checking PHP code is posted below. NOTE:- It allows for lower or uppercase postcodes and the GIR 0AA anomaly but to deal with the, more than likely, presence of a space in the middle of an entered postcode it also makes use of a simple str_replace to remove the space before testing against the regex. Any discrepancies beyond that and the Royal Mail themselves don't even mention them in their literature (see http://www.royalmail.com/sites/default/files/docs/pdf/programmers_guide_edition_7_v5.pdf and start reading from page 17)!

Note: In the Royal Mail's own literature (link above) there is a slight ambiguity surrounding the 3rd and 4th positions and the exceptions in place if these characters are letters. I contacted Royal Mail directly to clear it up and in their own words "A letter in the 4th position of the Outward Code with the format AANA NAA has no exceptions and the 3rd position exceptions apply only to the last letter of the Outward Code with the format ANA NAA." Straight from the horse's mouth!

<?php

    $postcoderegex = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';

    $postcode2check = str_replace(' ','',$postcode2check);

    if (preg_match($postcoderegex, $postcode2check)) {

        echo "$postcode2check is a valid postcode<br>";

    } else {

        echo "$postcode2check is not a valid postcode<br>";

    }

?>

I hope it helps anyone else who comes across this thread looking for a solution.

Add vertical scroll bar to panel

Panel has an AutoScroll property. Just set that property to True and the panel will automatically add a scroll bar when needed.

Count of "Defined" Array Elements

An array length is not the number of elements in a array, it is the highest index + 1. length property will report correct element count only if there are valid elements in consecutive indices.

var a = [];
a[23] = 'foo';
a.length;  // 24

Saying that, there is no way to exclude undefined elements from count without using any form of a loop.

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Is there a java setting for disabling certificate validation?

It is very simple .In my opinion it is the best way for everyone

       Unirest.config().verifySsl(false);
       HttpResponse<String> response = null;
       try {
           Gson gson = new Gson();
           response = Unirest.post("your_api_url")
                   .header("Authorization", "Basic " + "authkey")
                   .header("Content-Type", "application/json")
                   .body("request_body")
                   .asString();
           System.out.println("------RESPONSE -------"+ gson.toJson(response.getBody()));
       } catch (Exception e) {
           System.out.println("------RESPONSE ERROR--");
           e.printStackTrace();
       }
   }

TLS 1.2 not working in cURL

TLS 1.2 is only supported since OpenSSL 1.0.1 (see the Major version releases section), you have to update your OpenSSL.

It is not necessary to set the CURLOPT_SSLVERSION option. The request involves a handshake which will apply the newest TLS version both server and client support. The server you request is using TLS 1.2, so your php_curl will use TLS 1.2 (by default) as well if your OpenSSL version is (or newer than) 1.0.1.

Remove large .pack file created by git

As loganfsmyth already stated in his answer, you need to purge git history because the files continue to exist there even after deleting them from the repo. Official GitHub docs recommend BFG which I find easier to use than filter-branch:

Deleting files from history

Download BFG from their website. Make sure you have java installed, then create a mirror clone and purge history. Make sure to replace YOUR_FILE_NAME with the name of the file you'd like to delete:

git clone --mirror git://example.com/some-big-repo.git
java -jar bfg.jar --delete-files YOUR_FILE_NAME some-big-repo.git
cd some-big-repo.git
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push

Delete a folder

Same as above but use --delete-folders

java -jar bfg.jar --delete-folders YOUR_FOLDER_NAME some-big-repo.git

Other options

BFG also allows for even fancier options (see docs) like these:

Remove all files bigger than 100M from history:

java -jar bfg.jar --strip-blobs-bigger-than 100M some-big-repo.git

Important!

When running BFG, be careful that both YOUR_FILE_NAME and YOUR_FOLDER_NAME are indeed just file/folder names. They're not paths, so something like foo/bar.jpg will not work! Instead all files/folders with the specified name will be removed from repo history, no matter which path or branch they existed.

Extracting hours from a DateTime (SQL Server 2005)

DATEPART(HOUR, [date]) returns the hour in military time ( 00 to 23 ) If you want 1AM, 3PM etc, you need to case it out:

SELECT Run_Time_Hour =
CASE DATEPART(HOUR, R.date_schedule)
    WHEN 0 THEN  '12AM'
    WHEN 1 THEN   '1AM'
    WHEN 2 THEN   '2AM'
    WHEN 3 THEN   '3AM'
    WHEN 4 THEN   '4AM'
    WHEN 5 THEN   '5AM'
    WHEN 6 THEN   '6AM'
    WHEN 7 THEN   '7AM'
    WHEN 8 THEN   '8AM'
    WHEN 9 THEN   '9AM'
    WHEN 10 THEN '10AM'
    WHEN 11 THEN '11AM'
    WHEN 12 THEN '12PM'
    ELSE CONVERT(varchar, DATEPART(HOUR, R.date_schedule)-12) + 'PM'
END
FROM
    dbo.ARCHIVE_RUN_SCHEDULE R

Set Focus on EditText

If we create an EditText dynamically then we have to set the requestFocus() as given below.

    EditText editText = new EditText(this);
    editText.setWidth(600);
    editText.requestFocus();

If already we declared the component in the xml view then we have to find it and we can the focus as given below.

EditText e1=(EditText) findViewById(R.id.editText1);
e1.requestFocus();

It sets only focus to the corresponding EditText component.

webpack command not working

webpack is not only in your node-modules/webpack/bin/ directory, it's also linked in node_modules/.bin.

You have the npm bin command to get the folder where npm will install executables.

You can use the scripts property of your package.json to use webpack from this directory which will be exported.

"scripts": {
  "scriptName": "webpack --config etc..."
}

For example:

"scripts": {
  "build": "webpack --config webpack.config.js"
}

You can then run it with:

npm run build

Or even with arguments:

npm run build -- <args>

This allow you to have you webpack.config.js in the root folder of your project without having webpack globally installed or having your webpack configuration in the node_modules folder.

How do I disable directory browsing?

Add this in your .htaccess file:

Options -Indexes

If it is not work for any reason, try this within your .htaccess file:

IndexIgnore *

Margin while printing html page

Updated, Simple Solution

@media print {
   body {
       display: table;
       table-layout: fixed;
       padding-top: 2.5cm;
       padding-bottom: 2.5cm;
       height: auto;
   }
}

Old Solution

Create section with each page, and use the below code to adjust margins, height and width.

If you are printing A4 size.

Then user

Size : 8.27in and 11.69 inches

@page Section1 {
    size: 8.27in 11.69in; 
    margin: .5in .5in .5in .5in; 
    mso-header-margin: .5in; 
    mso-footer-margin: .5in; 
    mso-paper-source: 0;
}



div.Section1 {
    page: Section1;
} 

then create a div with all your content in it.

<div class="Section1"> 
    type your content here... 
</div>

Counting the number of True Booleans in a Python List

list has a count method:

>>> [True,True,False].count(True)
2

This is actually more efficient than sum, as well as being more explicit about the intent, so there's no reason to use sum:

In [1]: import random

In [2]: x = [random.choice([True, False]) for i in range(100)]

In [3]: %timeit x.count(True)
970 ns ± 41.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [4]: %timeit sum(x)
1.72 µs ± 161 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

How to specify function types for void (not Void) methods in Java8?

I feel you should be using the Consumer interface instead of Function<T, R>.

A Consumer is basically a functional interface designed to accept a value and return nothing (i.e void)

In your case, you can create a consumer elsewhere in your code like this:

Consumer<Integer> myFunction = x -> {
    System.out.println("processing value: " + x);    
    .... do some more things with "x" which returns nothing...
}

Then you can replace your myForEach code with below snippet:

public static void myForEach(List<Integer> list, Consumer<Integer> myFunction) 
{
  list.forEach(x->myFunction.accept(x));
}

You treat myFunction as a first-class object.

Convert PEM to PPK file format

To SSH connectivity to AWS EC2 instance, You don't need to convert the .PEM file to PPK file even on windows machine, Simple SSH using 'git bash' tool. No need to download and convert these softwares - Hope this will save your time of downloading and converting keys and get you more time on EC2 things.

how to delete installed library form react native project

I will post my answer here since it's the first result in google's search

1) react-native unlink <Module Name>

2) npm unlink <Module Name>

3) npm uninstall --save <Module name

How to get JSON Key and Value?

It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):

$.each(result[0], function(key, value){
    console.log(key, value);
});

If you might have more than one element and you'd like to iterate over them all, you could nest $.each():

$.each(result, function(key, value){
    $.each(value, function(key, value){
        console.log(key, value);
    });
});

JMS Topic vs Queues

Queue is JMS managed object used for holding messages waiting for subscribers to consume. When all subscribers consumed the message , message will be removed from queue.

Topic is that all subscribers to a topic receive the same message when the message is published.

How do I determine whether my calculation of pi is accurate?

You could use multiple approaches and see if they converge to the same answer. Or grab some from the 'net. The Chudnovsky algorithm is usually used as a very fast method of calculating pi. http://www.craig-wood.com/nick/articles/pi-chudnovsky/

Change color of PNG image via CSS?

You might want to take a look at Icon fonts. http://css-tricks.com/examples/IconFont/

EDIT: I'm using Font-Awesome on my latest project. You can even bootstrap it. Simply put this in your <head>:

<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet">

<!-- And if you want to support IE7, add this aswell -->
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome-ie7.min.css" rel="stylesheet">

And then go ahead and add some icon-links like this:

<a class="icon-thumbs-up"></a>

Here's the full cheat sheet

--edit--

Font-Awesome uses different class names in the new version, probably because this makes the CSS files drastically smaller, and to avoid ambiguous css classes. So now you should use:

<a class="fa fa-thumbs-up"></a>

EDIT 2:

Just found out github also uses its own icon font: Octicons It's free to download. They also have some tips on how to create your very own icon fonts.

Accessing SQL Database in Excel-VBA

Suggested changes:

  • Do not invoke the Command object's Execute method;
  • Set the Recordset object's Source property to be your Command object;
  • Invoke the Recordset object's Open method with no parameters;
  • Remove the parentheses from around the Recordset object in the call to CopyFromRecordset;
  • Actually declare your variables :)

Revised code:

Sub GetDataFromADO()

    'Declare variables'
        Dim objMyConn As ADODB.Connection
        Dim objMyCmd As ADODB.Command
        Dim objMyRecordset As ADODB.Recordset

        Set objMyConn = New ADODB.Connection
        Set objMyCmd = New ADODB.Command
        Set objMyRecordset = New ADODB.Recordset

    'Open Connection'
        objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;User ID=abc;Password=abc;"    
        objMyConn.Open

    'Set and Excecute SQL Command'
        Set objMyCmd.ActiveConnection = objMyConn
        objMyCmd.CommandText = "select * from mytable"
        objMyCmd.CommandType = adCmdText

    'Open Recordset'
        Set objMyRecordset.Source = objMyCmd
        objMyRecordset.Open

    'Copy Data to Excel'
        ActiveSheet.Range("A1").CopyFromRecordset objMyRecordset

End Sub

Why does this code using random strings print "hello world"?

Random always return the same sequence. It's used for shuffling arrays and other operations as permutations.

To get different sequences, it's necessary initialize the sequence in some position, called "seed".

The randomSting get the random number in the i position (seed = -229985452) of the "random" sequence. Then uses the ASCII code for the next 27 character in the sequence after the seed position until this value are equal to 0. This return the "hello". The same operation is done for "world".

I think that the code did not work for any other words. The guy that programmed that knows the random sequence very well.

It's very great geek code!

How do I assert my exception message with JUnit Test annotation?

If using @Rule, the exception set is applied to all the test methods in the Test class.

Restart pods when configmap updates in Kubernetes?

The current best solution to this problem (referenced deep in https://github.com/kubernetes/kubernetes/issues/22368 linked in the sibling answer) is to use Deployments, and consider your ConfigMaps to be immutable.

When you want to change your config, create a new ConfigMap with the changes you want to make, and point your deployment at the new ConfigMap. If the new config is broken, the Deployment will refuse to scale down your working ReplicaSet. If the new config works, then your old ReplicaSet will be scaled to 0 replicas and deleted, and new pods will be started with the new config.

Not quite as quick as just editing the ConfigMap in place, but much safer.

How to call a function from a string stored in a variable?

The easiest way to call a function safely using the name stored in a variable is,

//I want to call method deploy that is stored in functionname 
$functionname = 'deploy';

$retVal = {$functionname}('parameters');

I have used like below to create migration tables in Laravel dynamically,

foreach(App\Test::$columns as $name => $column){
        $table->{$column[0]}($name);
}

Run ScrollTop with offset of element by ID

No magic involved, just subtract from the offset top of the element

$('html, body').animate({scrollTop: $('#contact').offset().top -100 }, 'slow');

SQL Server 2005 Setting a variable to the result of a select query

-- Sql Server 2005 Management studio


use Master
go
DECLARE @MyVar bigint
SET @myvar = (SELECT count(*) FROM spt_values);
SELECT @myvar

Result: 2346 (in my db)

-- Note: @myvar = @Myvar

jQuery Upload Progress and AJAX file upload

Here are some options for using AJAX to upload files:

UPDATE: Here is a JQuery plug-in for Multiple File Uploading.

Efficient way to Handle ResultSet in Java

A couple of things to enhance the other answers. First, you should never return a HashMap, which is a specific implementation. Return instead a plain old java.util.Map. But that's actually not right for this example, anyway. Your code only returns the last row of the ResultSet as a (Hash)Map. You instead want to return a List<Map<String,Object>>. Think about how you should modify your code to do that. (Or you could take Dave Newton's suggestion).

Does WGET timeout?

According to the man page of wget, there are a couple of options related to timeouts -- and there is a default read timeout of 900s -- so I say that, yes, it could timeout.


Here are the options in question :

-T seconds
--timeout=seconds

Set the network timeout to seconds seconds. This is equivalent to specifying --dns-timeout, --connect-timeout, and --read-timeout, all at the same time.


And for those three options :

--dns-timeout=seconds

Set the DNS lookup timeout to seconds seconds.
DNS lookups that don't complete within the specified time will fail.
By default, there is no timeout on DNS lookups, other than that implemented by system libraries.

--connect-timeout=seconds

Set the connect timeout to seconds seconds.
TCP connections that take longer to establish will be aborted.
By default, there is no connect timeout, other than that implemented by system libraries.

--read-timeout=seconds

Set the read (and write) timeout to seconds seconds.
The "time" of this timeout refers to idle time: if, at any point in the download, no data is received for more than the specified number of seconds, reading fails and the download is restarted.
This option does not directly affect the duration of the entire download.


I suppose using something like

wget -O - -q -t 1 --timeout=600 http://www.example.com/cron/run

should make sure there is no timeout before longer than the duration of your script.

(Yeah, that's probably the most brutal solution possible ^^ )

Use string.Contains() with switch()

You can do the check at first and then use the switch as you like.

For example:

string str = "parameter"; // test1..test2..test3....

if (!message.Contains(str)) return ;

Then

switch(str)
{
  case "test1" : {} break;
  case "test2" : {} break;
  default : {} break;
}

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

You can try this:

Select To_date ('15/2/2007 00:00:00', 'DD/MM/YYYY HH24:MI:SS'),
       To_date ('28/2/2007 10:12', 'DD/MM/YYYY HH24:MI:SS')
  From DUAL;

Source: http://notsyncing.org/2008/02/manipulando-fechas-con-horas-en-plsql-y-sql/

Where are shared preferences stored?

Just to save some of you time...

On my Galaxy S v.2.3.3 Shared Preferences are not stored in:/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml

but are now located in: /dbdata/databases/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml

I believe they changed this in 2.3

What is VanillaJS?

This is a joke for those who are excited about the JavaScript frameworks and do not know the pure Javascript.

So VanillaJS is the same as pure Javascript.

Vanilla in slang means:

unexciting, normal, conventional, boring

Here is a nice presentation on YouTube about VanillaJS: What is Vanilla JS?

get string from right hand side

Simplest solution:

substr('299123456',-6,6)

Get the contents of a table row with a button click

Find element with id in row using jquery

$(document).ready(function () {
$("button").click(function() {
    //find content of different elements inside a row.
    var nameTxt = $(this).closest('tr').find('.name').text();
    var emailTxt = $(this).closest('tr').find('.email').text();
    //assign above variables text1,text2 values to other elements.
    $("#name").val( nameTxt );
    $("#email").val( emailTxt );
    });
});

String replace method is not replacing characters

And when I debug this the logic does fall into the sentence.replace.

Yes, and then you discard the return value.

Strings in Java are immutable - when you call replace, it doesn't change the contents of the existing string - it returns a new string with the modifications. So you want:

sentence = sentence.replace("and", " ");

This applies to all the methods in String (substring, toLowerCase etc). None of them change the contents of the string.

Note that you don't really need to do this in a condition - after all, if the sentence doesn't contain "and", it does no harm to perform the replacement:

String sentence = "Define, Measure, Analyze, Design and Verify";
sentence = sentence.replace("and", " ");

Get time of specific timezone

You can use getUTCDate() and the related getUTC...() methods to access a time based off UTC time, and then convert.

If you wish, you can use valueOf(), which returns the number of seconds, in UTC, since the Unix epoch, and work with that, but it's likely going to be much more involved.

Angular2 multiple router-outlet in the same template

You can not use multiple router outlets in the same template with ngIf condition. But you can use it in the way shown below:

<div *ngIf="loading">
  <span>loading true</span>
  <ng-container *ngTemplateOutlet="template"></ng-container>
</div>

<div *ngIf="!loading">
  <span>loading false</span>
  <ng-container *ngTemplateOutlet="template"></ng-container>
  </div>

  <ng-template #template>
    <router-outlet> </router-outlet>
  </ng-template>

How can I listen to the form submit event in javascript?

This is the simplest way you can have your own javascript function be called when an onSubmit occurs.

HTML

<form>
    <input type="text" name="name">
    <input type="submit" name="submit">
</form>

JavaScript

window.onload = function() {
    var form = document.querySelector("form");
    form.onsubmit = submitted.bind(form);
}

function submitted(event) {
    event.preventDefault();
}

retrieve data from db and display it in table in php .. see this code whats wrong with it?

This is a very simple code I use and you manipulate it to change the colour and size of the table as you see fit.

First connect to the database:

<?php
$connect=mysql_connect('localhost', 'root', 'password');

mysql_select_db("name");
//here u select the data you want to retrieve from the db

$query="select * from tablename";

$result= mysql_query($query);

//here you check to see if any data has been found and you define the width of the table

If($result){

echo "<table width ='340' align='left'>
      <tr color ='#5D9951>";
$i=0;

    If(mysql_num_rows($result)>0)
    {
         //here you fetch the data from the database and print it in the respective columns   
        while($i<mysql_num_fields($result))
        {    
             echo "<th>".mysql_field_name($result, $i)."</th>";
             $i++;
        }
        echo "</tr>";

        $color=1;

        while($rows=mysql_fetch_array($result, MYSQL_ASSOC))
        {    
            If ($color==1){
                echo "<tr color='#'#cccccc'>";

                foreach ($rows as $data){
                    echo "<td align='center'>".$data. "</td>";
                }

                $color=2;
            }
            $color=1;
        }
     } else {
        echo"no results found";
        echo "</table>";
    } else {
        echo "error running query:".MYSQL_error();
}
?>

It's a very elementary piece of code but it helps if you are not used to using functions.

Which one is the best PDF-API for PHP?

I personally generate XSL:FO from PHP and use Apache FOP to convert it to PDF. Not a PHP-native solution, not very efficient either, but it works well even if you need to generate PDF with very complex layouts.

Nested lists python

I think you want to access list values and their indices simultaneously and separately:

l = [[2,2,2],[3,3,3],[4,4,4],[5,5,5]]
l_len = len(l)
l_item_len = len(l[0])
for i in range(l_len):
    for j in range(l_item_len):
        print(f'List[{i}][{j}] : {l[i][j]}'  )

displayname attribute vs display attribute

DisplayName sets the DisplayName in the model metadata. For example:

[DisplayName("foo")]
public string MyProperty { get; set; }

and if you use in your view the following:

@Html.LabelFor(x => x.MyProperty)

it would generate:

<label for="MyProperty">foo</label>

Display does the same, but also allows you to set other metadata properties such as Name, Description, ...

Brad Wilson has a nice blog post covering those attributes.

How to send a POST request with BODY in swift

There are few changes I would like to notify. You can access request, JSON, error from response object from now on.

        let urlstring = "Add URL String here"
        let parameters: [String: AnyObject] = [
            "IdQuiz" : 102,
            "IdUser" : "iosclient",
            "User" : "iosclient",
            "List": [
                [
                    "IdQuestion" : 5,
                    "IdProposition": 2,
                    "Time" : 32
                ],
                [
                    "IdQuestion" : 4,
                    "IdProposition": 3,
                    "Time" : 9
                ]
            ]
        ]

        Alamofire.request(.POST, urlstring, parameters: parameters, encoding: .JSON).responseJSON { response in
            print(response.request)  // original URL request
            print(response.response) // URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization

            if let JSON = response.result.value {
                print("JSON: \(JSON)")
            }
            response.result.error
        }

Compiler error: "initializer element is not a compile-time constant"

Because you are asking the compiler to initialize a static variable with code that is inherently dynamic.

How do I get which JRadioButton is selected from a ButtonGroup

I would just loop through your JRadioButtons and call isSelected(). If you really want to go from the ButtonGroup you can only get to the models. You could match the models to the buttons, but then if you have access to the buttons, why not use them directly?

How can I list ALL DNS records?

What you want is called a zone transfer. You can request a zone transfer using dig -t axfr.

A zone is a domain and all of the domains below it that are not delegated to another server.

Note that zone transfers are not always supported. They're not used in normal lookup, only in replicating DNS data between servers; but there are other protocols that can be used for that (such as rsync over ssh), there may be a security risk from exposing names, and zone transfer responses cost more to generate and send than usual DNS lookups.

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

How do I debug jquery AJAX calls?

Make your JQuery call more robust by adding success and error callbacks like this:

 $('#ChangePermission').click(function() {
     $.ajax({
         url: 'change_permission.php',
         type: 'POST',
         data: {
             'user': document.GetElementById("user").value,
             'perm': document.GetElementById("perm").value
         },
         success: function(result) { //we got the response
             alert('Successfully called');
         },
         error: function(jqxhr, status, exception) {
             alert('Exception:', exception);
         }
     })
 })

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

May be this can help you- Add the system variable _JAVA_OPTIONS and in the "new variable value" add "-Xmx1024M" Xmx sets the maximum heap memory size

How do I associate file types with an iPhone application?

In addition to Brad's excellent answer, I have found out that (on iOS 4.2.1 at least) when opening custom files from the Mail app, your app is not fired or notified if the attachment has been opened before. The "open with…" popup appears, but just does nothing.

This seems to be fixed by (re)moving the file from the Inbox directory. A safe approach seems to be to both (re)move the file as it is opened (in -(BOOL)application:openURL:sourceApplication:annotation:) as well as going through the Documents/Inbox directory, removing all items, e.g. in applicationDidBecomeActive:. That last catch-all may be needed to get the app in a clean state again, in case a previous import causes a crash or is interrupted.

How to get StackPanel's children to fill maximum space downward?

The reason that this is happening is because the stack panel measures every child element with positive infinity as the constraint for the axis that it is stacking elements along. The child controls have to return how big they want to be (positive infinity is not a valid return from the MeasureOverride in either axis) so they return the smallest size where everything will fit. They have no way of knowing how much space they really have to fill.

If your view doesn’t need to have a scrolling feature and the answer above doesn't suit your needs, I would suggest implement your own panel. You can probably derive straight from StackPanel and then all you will need to do is change the ArrangeOverride method so that it divides the remaining space up between its child elements (giving them each the same amount of extra space). Elements should render fine if they are given more space than they wanted, but if you give them less you will start to see glitches.

If you want to be able to scroll the whole thing then I am afraid things will be quite a bit more difficult, because the ScrollViewer gives you an infinite amount of space to work with which will put you in the same position as the child elements were originally. In this situation you might want to create a new property on your new panel which lets you specify the viewport size, you should be able to bind this to the ScrollViewer’s size. Ideally you would implement IScrollInfo, but that starts to get complicated if you are going to implement all of it properly.

Invalid syntax when using "print"?

That is because in Python 3, they have replaced the print statement with the print function.

The syntax is now more or less the same as before, but it requires parens:

From the "what's new in python 3" docs:

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

How to post data to specific URL using WebClient in C#

//Making a POST request using WebClient.
Function()
{    
  WebClient wc = new WebClient();

  var URI = new Uri("http://your_uri_goes_here");

  //If any encoding is needed.
  wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
  //Or any other encoding type.

  //If any key needed

  wc.Headers["KEY"] = "Your_Key_Goes_Here";

  wc.UploadStringCompleted += 
      new UploadStringCompletedEventHandler(wc_UploadStringCompleted);

  wc.UploadStringAsync(URI,"POST","Data_To_Be_sent");    
}

void wc__UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)    
{  
  try            
  {          
     MessageBox.Show(e.Result); 
     //e.result fetches you the response against your POST request.         
  }
  catch(Exception exc)         
  {             
     MessageBox.Show(exc.ToString());            
  }
}

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

Anderscc has got it correct. Thanks. It worked for me but not 100%.

I had to set

$mail->SMTPDebug = 0;

Setting it to 1, can cause errors especially if you are passing some data as json to next page. Example - Performing verification if mail is sent, using json to pass data through ajax.

I had to lower my gmail account security settings to get rid of errors: " SMTP connect() failed " and " SMTP ERROR: Password command failed "

Solution: This problem can be caused by either 'less secure' applications trying to use the email account (this is according to google help, not sure how they judge what is secure and what is not) OR if you are trying to login several time in a row OR if you change countries (for example use VPN, move code to different server or actually try to login from different part of the world).

Links that fix the problem (you must be logged into google account):

Note: You can go to the following stackoverflow answer link for more detailed reference.

https://stackoverflow.com/a/25175234

PHP to search within txt file and echo the whole line

one way...

$needle = "blah";
$content = file_get_contents('file.txt');
preg_match('~^(.*'.$needle.'.*)$~',$content,$line);
echo $line[1];

though it would probably be better to read it line by line with fopen() and fread() and use strpos()

SHOW PROCESSLIST in MySQL command: sleep

Sleep meaning that thread is do nothing. Time is too large beacuse anthor thread query,but not disconnect server, default wait_timeout=28800;so you can set values smaller,eg 10. also you can kill the thread.

How to play a local video with Swift?

Sure you can use Swift!

1. Adding the video file

Add the video (lets call it video.m4v) to your Xcode project

2. Checking your video is into the Bundle

Open the Project Navigator cmd + 1

Then select your project root > your Target > Build Phases > Copy Bundle Resources.

Your video MUST be here. If it's not, then you should add it using the plus button

enter image description here

3. Code

Open your View Controller and write this code.

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        playVideo()
    }

    private func playVideo() {
        guard let path = Bundle.main.path(forResource: "video", ofType:"m4v") else {
            debugPrint("video.m4v not found")
            return
        }
        let player = AVPlayer(url: URL(fileURLWithPath: path))
        let playerController = AVPlayerViewController()
        playerController.player = player
        present(playerController, animated: true) {
            player.play()
        }
    }
}

GET and POST methods with the same Action name in the same Controller

You can't have multiple actions with the same name. You could add a parameter to one method and that would be valid. For example:

    public ActionResult Index(int i)
    {
        Some Code--Some Code---Some Code
        return View();
    }

There are a few ways to do to have actions that differ only by request verb. My favorite and, I think, the easiest to implement is to use the AttributeRouting package. Once installed simply add an attribute to your method as follows:

  [GET("Resources")]
  public ActionResult Index()
  {
      return View();
  }

  [POST("Resources")]
  public ActionResult Create()
  {
      return RedirectToAction("Index");
  }

In the above example the methods have different names but the action name in both cases is "Resources". The only difference is the request verb.

The package can be installed using NuGet like this:

PM> Install-Package AttributeRouting

If you don't want the dependency on the AttributeRouting packages you could do this by writing a custom action selector attribute.

What is /dev/null 2>&1?

I use >> /dev/null 2>&1 for a silent cronjob. A cronjob will do the job, but not send a report to my email.

As far as I know, don't remove /dev/null. It's useful, especially when you run cPanel, it can be used for throw-away cronjob reports.

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

In Firefox the onchange fires only when you tab or else click outside the input field. The same is true of Onblur. The difference is that onblur will fire whether you changed anything in the field or not. It is possible that ENTER will fire one or both of these, but you wouldn't know that if you disable the ENTER in your forms to prevent unexpected submits.

CSS - Expand float child DIV height to parent's height

<div class="parent" style="height:500px;">
<div class="child-left floatLeft" style="height:100%">
</div>

<div class="child-right floatLeft" style="height:100%">
</div>
</div>

I used inline style just to give idea.

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

django import error - No module named core.management

all of you guys didn't mention a case where someone "like me" would install django befor installing virtualenv...so for all the people of my kind ther if you did that...reinstall django after activating the virtualenv..i hope this helps

how to load url into div tag

Not using iframes puts you in a world of handling #document security issues with cross domain and links firing unexpected ways that was not intended for originally, do you really need bad Advertisements?

You can use jquery .load function to send the page to whatever html element you want to target, assuming your not getting this from another domain.

You can use javascript .innerHTML value to set and to rewrite the element with whatever you want, but if you add another file you might be writing against 2 documents in 1... like a in another

iframes are old, another way we can add "src" into the html alone without any use for javascript. But it's old, prehistoric, and just plain OLD! Frameset makes it worse because I can put #document in those to handle multiple html files. An Old way people created navigation menu's Long and before people had FLIP phones.

1.) Yes you will have to work in Javascript if you do NOT want to use an Iframe.

2.) There is a good hack in which you can set the domain to equal each other without having to set server stuff around. Means you will have to have edit capabilities of the documents.

3.) javascript window.document is limited to the iframe itself and can NOT go above the iframe if you want to grab something through the DOM itself. Because it treats it like a separate tab, it also defines it in another document object model.

Android Color Picker

Here's another library:

https://github.com/eltos/SimpleDialogFragments

Features color wheel and pallet picker dialogs

Fixing Segmentation faults in C++

I don't know of any methodology to use to fix things like this. I don't think it would be possible to come up with one either for the very issue at hand is that your program's behavior is undefined (I don't know of any case when SEGFAULT hasn't been caused by some sort of UB).

There are all kinds of "methodologies" to avoid the issue before it arises. One important one is RAII.

Besides that, you just have to throw your best psychic energies at it.

Check whether variable is number or string in JavaScript

For detecting numbers, the following passage from JavaScript: The Good Parts by Douglas Crockford is relevant:

The isFinite function is the best way of determining whether a value can be used as a number because it rejects NaN and Infinity . Unfortunately, isFinite will attempt to convert its operand to a number, so it is not a good test if a value is not actually a number. You may want to define your own isNumber function:

var isNumber = function isNumber(value) { return typeof value === 'number' &&
            isFinite(value);
};

What is the equivalent of the C++ Pair<L,R> in Java?

This is Java. You have to make your own tailored Pair class with descriptive class and field names, and not to mind that you will reinvent the wheel by writing hashCode()/equals() or implementing Comparable again and again.

what does mysql_real_escape_string() really do?

Say you want to save the string I'm a "foobar" in the database.
Your query will look something like INSERT INTO foos (text) VALUES ("$text").
With the $text variable replaced, this will look like this:

INSERT INTO foos (text) VALUES ("I'm a "foobar"")

Now, where exactly does the string end? You may know, an SQL parser doesn't. Not only will this simply break this query, it can also be abused to inject SQL commands you didn't intend.

mysql_real_escape_string makes sure such ambiguities do not occur by escaping characters which have special meaning to an SQL parser:

mysql_real_escape_string($text)  =>  I\'m a \"foobar\"

This becomes:

INSERT INTO foos (text) VALUES ("I\'m a \"foobar\"")

This makes the statement unambiguous and safe. The \ signals that the following character is not to be taken by its special meaning as string terminator. There are a few such characters that mysql_real_escape_string takes care of.

Escaping is a pretty universal thing in programming languages BTW, all along the same lines. If you want to type the above sentence literally in PHP, you need to escape it as well for the same reasons:

$text = 'I\'m a "foobar"';
// or
$text = "I'm a \"foobar\"";

Remove Item from ArrayList

remove(int index) method of arraylist removes the element at the specified position(index) in the list. After removing arraylist items shifts any subsequent elements to the left.

Means if a arraylist contains {20,15,30,40}

I have called the method: arraylist.remove(1)

then the data 15 will be deleted and 30 & 40 these two items will be left shifted by 1.

For this reason you have to delete higher index item of arraylist first.

So..for your given situation..the code will be..

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");

int i[] = {1,3,5};

for (int j = i.length-1; j >= 0; j--) {
    list.remove(i[j]);
}

How do I center text horizontally and vertically in a TextView?

You can do like this to get text centered

<TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center" />

Format in kotlin string templates

Unfortunately, there's no built-in support for formatting in string templates yet, as a workaround, you can use something like:

"pi = ${pi.format(2)}"

the .format(n) function you'd need to define yourself as

fun Double.format(digits: Int) = "%.${digits}f".format(this)

There's clearly a piece of functionality here that is missing from Kotlin at the moment, we'll fix it.

Maven: The packaging for this project did not assign a file to the build artifact

This worked for me when I got the same error message...

mvn install deploy

Android emulator failed to allocate memory 8

This following solution worked for me. In the following configuration file:

C:\Users\<user>\.android\avd\<avd-profile-name>.avd\config.ini

Replace

hw.ramSize=1024

by

hw.ramSize=1024MB

"Android library projects cannot be launched"?

our project surely is configured as "library" thats why you get the message : "Android library projects cannot be launched."

right-click in your project and select Properties. In the Properties window -> "Android" -> uncheck the option "is Library" and apply -> Click "ok" to close the properties window.

HTML5 video won't play in Chrome only

I had a similar issue, no videos would play in Chrome. Tried installing beta 64bit, going back to Chrome 32bit release.

The only thing that worked for me was updating my video drivers.

I have the NVIDIA GTS 240. Downloaded, installed the drivers and restarted and Chrome 38.0.2125.77 beta-m (64-bit) starting playing HTML5 videos again on youtube, vimeo and others. Hope this helps anyone else.

C#: Converting byte array to string and printing out to console

I've used this simple code in my codebase:

static public string ToReadableByteArray(byte[] bytes)
{
    return string.Join(", ", bytes);
}

To use:

Console.WriteLine(ToReadableByteArray(bytes));

TensorFlow, "'module' object has no attribute 'placeholder'"

If you have this error after an upgrade to TensorFlow 2.0, you can still use 1.X API by replacing:

import tensorflow as tf

by

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

Find IP address of directly connected device

Mmh ... there are many ways. I answer another network discovery question, and I write a little getting started.

Some tcpip stacks reply to icmp broadcasts. So you can try a PING to your network broadcast address.

For example, you have ip 192.168.1.1 and subnet 255.255.255.0

  1. ping 192.168.1.255
  2. stop the ping after 5 seconds
  3. watch the devices replies : arp -a

Note : on step 3. you get the lists of the MAC-to-IP cached entries, so there are also the hosts in your subnet you exchange data to in the last minutes, even if they don't reply to icmp_get.

Note (2) : now I am on linux. I am not sure, but it can be windows doesn't reply to icm_get via broadcast.

Is it the only one device attached to your pc ? Is it a router or another simple pc ?

How to include External CSS and JS file in Laravel 5

First you have to install the Illuminate Html helper class:

composer require "illuminate/html":"5.0.*"

Next you need to open /config/app.php and update as follows:

'providers' => [

...

Illuminate\Html\HtmlServiceProvider::class,
],

'aliases' => [

...

'Form' => Illuminate\Html\FormFacade::class, 
'HTML' => Illuminate\Html\HtmlFacade::class,
],

To confirm it’s working use the following command:

php artisan tinker
> Form::text('foo')
"<input name=\"foo\" type=\"text\">"

To include external css in you files, use the following syntax:

{!! HTML::style('foo/bar.css') !!}

How do you list the primary key of a SQL Server table?

SELECT t.name AS 'table', i.name AS 'index', it.xtype,

(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k 
    ON k.indid = i.indid 
        AND c.colid = k.colid 
        AND c.id = t.id 
        AND k.keyno = 1 
        AND k.id = t.id)
    AS 'column1',

(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k 
    ON k.indid = i.indid 
        AND c.colid = k.colid 
        AND c.id = t.id 
        AND k.keyno = 2 
        AND k.id = t.id)
    AS 'column2',

(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k 
    ON k.indid = i.indid 
        AND c.colid = k.colid 
        AND c.id = t.id 
        AND k.keyno = 3
        AND k.id = t.id)
    AS 'column3',

(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k 
    ON k.indid = i.indid 
        AND c.colid = k.colid 
        AND c.id = t.id 
        AND k.keyno = 4
        AND k.id = t.id)
    AS 'column4',

(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k 
    ON k.indid = i.indid 
        AND c.colid = k.colid 
        AND c.id = t.id 
        AND k.keyno = 5
        AND k.id = t.id)
    AS 'column5',

(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k 
    ON k.indid = i.indid 
        AND c.colid = k.colid 
        AND c.id = t.id 
        AND k.keyno = 6
        AND k.id = t.id)
    AS 'column6',

(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k 
    ON k.indid = i.indid 
        AND c.colid = k.colid 
        AND c.id = t.id 
        AND k.keyno = 7
        AND k.id = t.id)
    AS 'column7',

(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k 
    ON k.indid = i.indid 
        AND c.colid = k.colid 
        AND c.id = t.id 
        AND k.keyno = 8 
        AND k.id = t.id)
    AS 'column8',

(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k 
    ON k.indid = i.indid 
        AND c.colid = k.colid 
        AND c.id = t.id 
        AND k.keyno = 9 
        AND k.id = t.id)
    AS 'column9',

(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k 
    ON k.indid = i.indid 
        AND c.colid = k.colid 
        AND c.id = t.id 
        AND k.keyno = 10
        AND k.id = t.id)
    AS 'column10',

FROM sysobjects t
    INNER JOIN sysindexes i ON i.id = t.id 
    INNER JOIN sysobjects it ON it.parent_obj = t.id AND it.name = i.name

WHERE it.xtype = 'PK'
ORDER BY t.name, i.name

Run Batch File On Start-up

If your Windows language is different from English, you can launch the Task Scheduler by

  1. Press Windows+X
  2. Select your language translation of "Computer Management"
  3. Follow the instruction in the answer provided by prankin

What's in an Eclipse .classpath/.project file?

Complete reference is not available for the mentioned files, as they are extensible by various plug-ins.

Basically, .project files store project-settings, such as builder and project nature settings, while .classpath files define the classpath to use during running. The classpath files contains src and target entries that correspond with folders in the project; the con entries are used to describe some kind of "virtual" entries, such as the JVM libs or in case of eclipse plug-ins dependencies (normal Java project dependencies are displayed differently, using a special src entry).

Why doesn't logcat show anything in my Android?

If you're using Eclipse Mars (at least, Mars.1 or Mars.2), try the solution described here: Logcat show invisible messages in Eclipse Mars.

It helped in my case.

console.log timestamps in Chrome?

This adds a "log" function to the local scope (using this) using as many arguments as you want:

this.log = function() {
    var args = [];
    args.push('[' + new Date().toUTCString() + '] ');
    //now add all the other arguments that were passed in:
    for (var _i = 0, _len = arguments.length; _i < _len; _i++) {
      arg = arguments[_i];
      args.push(arg);
    }

    //pass it all into the "real" log function
    window.console.log.apply(window.console, args); 
}

So you can use it:

this.log({test: 'log'}, 'monkey', 42);

Outputs something like this:

[Mon, 11 Mar 2013 16:47:49 GMT] Object {test: "log"} monkey 42

Arrays.fill with multidimensional array in Java

Arrays.fill works only with one-dimensional array

Source of java.util.Arrays:

public static void fill(Object[] a, Object val) {
        int i = 0;

        for(int len = a.length; i < len; ++i) {
            a[i] = val;
        }

Use own loops for initialization array

Python int to binary string?

Calculator with all neccessary functions for DEC,BIN,HEX: (made and tested with Python 3.5)

You can change the input test numbers and get the converted ones.

# CONVERTER: DEC / BIN / HEX

def dec2bin(d):
    # dec -> bin
    b = bin(d)
    return b

def dec2hex(d):
    # dec -> hex
    h = hex(d)
    return h

def bin2dec(b):
    # bin -> dec
    bin_numb="{0:b}".format(b)
    d = eval(bin_numb)
    return d,bin_numb

def bin2hex(b):
    # bin -> hex
    h = hex(b)
    return h

def hex2dec(h):
    # hex -> dec
    d = int(h)
    return d

def hex2bin(h):
    # hex -> bin
    b = bin(h)
    return b


## TESTING NUMBERS
numb_dec = 99
numb_bin = 0b0111 
numb_hex = 0xFF


## CALCULATIONS
res_dec2bin = dec2bin(numb_dec)
res_dec2hex = dec2hex(numb_dec)

res_bin2dec,bin_numb = bin2dec(numb_bin)
res_bin2hex = bin2hex(numb_bin)

res_hex2dec = hex2dec(numb_hex)
res_hex2bin = hex2bin(numb_hex)



## PRINTING
print('------- DECIMAL to BIN / HEX -------\n')
print('decimal:',numb_dec,'\nbin:    ',res_dec2bin,'\nhex:    ',res_dec2hex,'\n')

print('------- BINARY to DEC / HEX -------\n')
print('binary: ',bin_numb,'\ndec:    ',numb_bin,'\nhex:    ',res_bin2hex,'\n')

print('----- HEXADECIMAL to BIN / HEX -----\n')
print('hexadec:',hex(numb_hex),'\nbin:    ',res_hex2bin,'\ndec:    ',res_hex2dec,'\n')

Warning: implode() [function.implode]: Invalid arguments passed

function my_get_tags_sitemap(){
    if ( !function_exists('wp_tag_cloud') || get_option('cb2_noposttags')) return;
    $unlinkTags = get_option('cb2_unlinkTags'); 
    echo '<div class="tags"><h2>Tags</h2>';
    $ret = []; // here you need to add array which you call inside implode function
    if($unlinkTags)
    {
        $tags = get_tags();
        foreach ($tags as $tag){
            $ret[]= $tag->name;
        }
        //ERROR OCCURS HERE
        echo implode(', ', $ret);
    }
    else
    {
        wp_tag_cloud('separator=, &smallest=11&largest=11');
    }
    echo '</div>';
}

How do I make a list of data frames?

This isn't related to your question, but you want to use = and not <- within the function call. If you use <-, you'll end up creating variables y1 and y2 in whatever environment you're working in:

d1 <- data.frame(y1 <- c(1, 2, 3), y2 <- c(4, 5, 6))
y1
# [1] 1 2 3
y2
# [1] 4 5 6

This won't have the seemingly desired effect of creating column names in the data frame:

d1
#   y1....c.1..2..3. y2....c.4..5..6.
# 1                1                4
# 2                2                5
# 3                3                6

The = operator, on the other hand, will associate your vectors with arguments to data.frame.

As for your question, making a list of data frames is easy:

d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6))
d2 <- data.frame(y1 = c(3, 2, 1), y2 = c(6, 5, 4))
my.list <- list(d1, d2)

You access the data frames just like you would access any other list element:

my.list[[1]]
#   y1 y2
# 1  1  4
# 2  2  5
# 3  3  6

Invalid use side-effecting operator Insert within a function

Functions cannot be used to modify base table information, use a stored procedure.

PHP regular expressions: No ending delimiter '^' found in

Your regex pattern needs to be in delimiters:

$numpattern="/^([0-9]+)$/";

How do I set a textbox's value using an anchor with jQuery?

Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')

Getting Textbox value in Javascript

Use

document.getElementById('<%= txt_model_code.ClientID %>')

instead of

document.getElementById('txt_model_code')`

Also you can use onClientClick instead of onClick.

Java, How do I get current index/key in "for each" loop

Example from current code I'm working with:

int index=-1;
for (Policy rule : rules)
{   
     index++;
     // do stuff here
}

Lets you cleanly start with an index of zero, and increment as you process.

Javascript/jQuery: Set Values (Selection) in a multiple Select

Iterate through the loop using the value in a dynamic selector that utilizes the attribute selector.

var values="Test,Prof,Off";
$.each(values.split(","), function(i,e){
    $("#strings option[value='" + e + "']").prop("selected", true);
});

Working Example http://jsfiddle.net/McddQ/1/

how to use "tab space" while writing in text file

You can use \t to create a tab in a file.

How to set a timeout on a http.request() in Node?

Curious, what happens if you use straight net.sockets instead? Here's some sample code I put together for testing purposes:

var net = require('net');

function HttpRequest(host, port, path, method) {
  return {
    headers: [],
    port: 80,
    path: "/",
    method: "GET",
    socket: null,
    _setDefaultHeaders: function() {

      this.headers.push(this.method + " " + this.path + " HTTP/1.1");
      this.headers.push("Host: " + this.host);
    },
    SetHeaders: function(headers) {
      for (var i = 0; i < headers.length; i++) {
        this.headers.push(headers[i]);
      }
    },
    WriteHeaders: function() {
      if(this.socket) {
        this.socket.write(this.headers.join("\r\n"));
        this.socket.write("\r\n\r\n"); // to signal headers are complete
      }
    },
    MakeRequest: function(data) {
      if(data) {
        this.socket.write(data);
      }

      this.socket.end();
    },
    SetupRequest: function() {
      this.host = host;

      if(path) {
        this.path = path;
      }
      if(port) {
        this.port = port;
      }
      if(method) {
        this.method = method;
      }

      this._setDefaultHeaders();

      this.socket = net.createConnection(this.port, this.host);
    }
  }
};

var request = HttpRequest("www.somesite.com");
request.SetupRequest();

request.socket.setTimeout(30000, function(){
  console.error("Connection timed out.");
});

request.socket.on("data", function(data) {
  console.log(data.toString('utf8'));
});

request.WriteHeaders();
request.MakeRequest();

App.Config change value

For a .NET 4.0 console application, none of these worked for me. So I modified Kevn Aenmey's answer as below and it worked:

private static void UpdateSetting(string key, string value)
{
    Configuration configuration = ConfigurationManager.
        OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
    configuration.AppSettings.Settings[key].Value = value;
    configuration.Save();

    ConfigurationManager.RefreshSection("appSettings");
}

Only the first line is different, constructed upon the actual executing assembly.

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

In my case:

I had 4 configurations(+ DebugQa and ReleaseQa) Cocoapods is used as a dependency Manager

For Debug, I gathered on the device and in the simulator, and on qa only on the device.

It helped to set BuildActiveArchitecture to yes in PodsProject

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

Checking Count() before the WHERE clause solved my problem. It is cheaper than ToList()

if (authUserList != null && _list.Count() > 0)
    _list = _list.Where(l => authUserList.Contains(l.CreateUserId));

Email and phone Number Validation in android

Try this

public class Validation {

    public final static boolean isValidEmail(CharSequence target) {
        if (target == null) {
        return false;
        } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    } 

    public static final boolean isValidPhoneNumber(CharSequence target) {
        if (target.length()!=10) {
            return false;
        } else {
            return android.util.Patterns.PHONE.matcher(target).matches();
        }
    }

}

Using Java generics for JPA findAll() query with WHERE clause

This will work, and if you need where statement you can add it as parameter.

class GenericDAOWithJPA<T, ID extends Serializable> {

.......

public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

Double precision - decimal places

In most contexts where double values are used, calculations will have a certain amount of uncertainty. The difference between 1.33333333333333300 and 1.33333333333333399 may be less than the amount of uncertainty that exists in the calculations. Displaying the value of "2/3 + 2/3" as "1.33333333333333" is apt to be more meaningful than displaying it as "1.33333333333333319", since the latter display implies a level of precision that doesn't really exist.

In the debugger, however, it is important to uniquely indicate the value held by a variable, including essentially-meaningless bits of precision. It would be very confusing if a debugger displayed two variables as holding the value "1.333333333333333" when one of them actually held 1.33333333333333319 and the other held 1.33333333333333294 (meaning that, while they looked the same, they weren't equal). The extra precision shown by the debugger isn't apt to represent a numerically-correct calculation result, but indicates how the code will interpret the values held by the variables.

Purpose of Unions in C and C++

Others have mentioned the architecture differences (little - big endian).

I read the problem that since the memory for the variables is shared, then by writing to one, the others change and, depending on their type, the value could be meaningless.

eg. union{ float f; int i; } x;

Writing to x.i would be meaningless if you then read from x.f - unless that is what you intended in order to look at the sign, exponent or mantissa components of the float.

I think there is also an issue of alignment: If some variables must be word aligned then you might not get the expected result.

eg. union{ char c[4]; int i; } x;

If, hypothetically, on some machine a char had to be word aligned then c[0] and c[1] would share storage with i but not c[2] and c[3].

How to convert empty spaces into null values, using SQL Server?

Maybe something like this?

UPDATE [MyTable]
SET [SomeField] = NULL
WHERE [SomeField] is not NULL
AND LEN(LTRIM(RTRIM([SomeField]))) = 0

SQL: How to get the id of values I just INSERTed?

This is how I've done it using parameterized commands.

MSSQL

 INSERT INTO MyTable (Field1, Field2) VALUES (@Value1, @Value2); 
 SELECT SCOPE_IDENTITY(); 

MySQL

 INSERT INTO MyTable (Field1, Field2) VALUES (?Value1, ?Value2);
 SELECT LAST_INSERT_ID();

How to detect if a browser is Chrome using jQuery?

As a quick addition, and I'm surprised nobody has thought of this, you could use the in operator:

"chrome" in window

Obviously this isn't using JQuery, but I figured I'd put it since it's handy for times when you aren't using any external libraries.

C# 4.0: Convert pdf to byte[] and vice versa

// loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.
// note that for Linux, you will not need the c: part
// just swap out the example folder here with your actual full file path
string pdfFilePath = "c:/pdfdocuments/myfile.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);

// munge bytes with whatever pdf software you want, i.e. http://sourceforge.net/projects/itextsharp/
// bytes = MungePdfBytes(bytes); // MungePdfBytes is your custom method to change the PDF data
// ...
// make sure to cleanup after yourself

// and save back - System.IO.File.WriteAll* makes sure all bytes are written properly - this will overwrite the file, if you don't want that, change the path here to something else
System.IO.File.WriteAllBytes(pdfFilePath, bytes);

Run task only if host does not belong to a group

You can set a control variable in vars files located in group_vars/ or directly in hosts file like this:

[vagrant:vars]
test_var=true

[location-1]
192.168.33.10 hostname=apollo

[location-2]
192.168.33.20 hostname=zeus

[vagrant:children]
location-1
location-2

And run tasks like this:

- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var

Rails: How to list database tables/objects using the Rails console?

You can use rails dbconsole to view the database that your rails application is using. It's alternative answer rails db. Both commands will direct you the command line interface and will allow you to use that database query syntax.

Setting transparent images background in IrfanView

You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.

You just need to re-open the image with IrfanView after changing the view color to white.

To change the viewing color in Irfanview go to:

Options > Properties/Settings > Viewing > Main window color

Sort arrays of primitive types in descending order

You cannot use Comparators for sorting primitive arrays.

Your best bet is to implement (or borrow an implementation) of a sorting algorithm that is appropriate for your use case to sort the array (in reverse order in your case).

Can someone provide an example of a $destroy event for scopes in AngularJS?

$destroy can refer to 2 things: method and event

1. method - $scope.$destroy

.directive("colorTag", function(){
  return {
    restrict: "A",
    scope: {
      value: "=colorTag"
    },
    link: function (scope, element, attrs) {
      var colors = new App.Colors();
      element.css("background-color", stringToColor(scope.value));
      element.css("color", contrastColor(scope.value));

      // Destroy scope, because it's no longer needed.
      scope.$destroy();
    }
  };
})

2. event - $scope.$on("$destroy")

See @SunnyShah's answer.

Bootstrap 3 - How to load content in modal body via AJAX?

In the case where you need to update the same modal with content from different Ajax / API calls here's a working solution.

$('.btn-action').click(function(){
    var url = $(this).data("url"); 
    $.ajax({
        url: url,
        dataType: 'json',
        success: function(res) {

            // get the ajax response data
            var data = res.body;

            // update modal content here
            // you may want to format data or 
            // update other modal elements here too
            $('.modal-body').text(data);

            // show modal
            $('#myModal').modal('show');

        },
        error:function(request, status, error) {
            console.log("ajax call went wrong:" + request.responseText);
        }
    });
});

Bootstrap 3 Demo
Bootstrap 4 Demo

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123

Why do package names often begin with "com"

It's just a namespace definition to avoid collision of class names. The com.domain.package.Class is an established Java convention wherein the namespace is qualified with the company domain in reverse.

How to remove components created with Angular-CLI

There's the --dry-run flag which will allow you to preview the changes, and/or you can use the Angular Console App to generate the cli flags for you, using their easy GUI. It auto-previews everything before you commit to it.

How to present UIAlertController when not in a view controller?

Zev Eisenberg's answer is simple and straightforward, but it does not always work, and it may fail with this warning message:

Warning: Attempt to present <UIAlertController: 0x7fe6fd951e10>  
 on <ThisViewController: 0x7fe6fb409480> which is already presenting 
 <AnotherViewController: 0x7fe6fd109c00>

This is because the windows rootViewController is not at the top of the presented views. To correct this we need to walk up the presentation chain, as shown in my UIAlertController extension code written in Swift 3:

   /// show the alert in a view controller if specified; otherwise show from window's root pree
func show(inViewController: UIViewController?) {
    if let vc = inViewController {
        vc.present(self, animated: true, completion: nil)
    } else {
        // find the root, then walk up the chain
        var viewController = UIApplication.shared.keyWindow?.rootViewController
        var presentedVC = viewController?.presentedViewController
        while presentedVC != nil {
            viewController = presentedVC
            presentedVC = viewController?.presentedViewController
        }
        // now we present
        viewController?.present(self, animated: true, completion: nil)
    }
}

func show() {
    show(inViewController: nil)
}

Updates on 9/15/2017:

Tested and confirmed that the above logic still works great in the newly available iOS 11 GM seed. The top voted method by agilityvision, however, does not: the alert view presented in a newly minted UIWindow is below the keyboard and potentially prevents the user from tapping its buttons. This is because in iOS 11 all windowLevels higher than that of keyboard window is lowered to a level below it.

One artifact of presenting from keyWindow though is the animation of keyboard sliding down when alert is presented, and sliding up again when alert is dismissed. If you want the keyboard to stay there during presentation, you can try to present from the top window itself, as shown in below code:

func show(inViewController: UIViewController?) {
    if let vc = inViewController {
        vc.present(self, animated: true, completion: nil)
    } else {
        // get a "solid" window with the highest level
        let alertWindow = UIApplication.shared.windows.filter { $0.tintColor != nil || $0.className() == "UIRemoteKeyboardWindow" }.sorted(by: { (w1, w2) -> Bool in
            return w1.windowLevel < w2.windowLevel
        }).last
        // save the top window's tint color
        let savedTintColor = alertWindow?.tintColor
        alertWindow?.tintColor = UIApplication.shared.keyWindow?.tintColor

        // walk up the presentation tree
        var viewController = alertWindow?.rootViewController
        while viewController?.presentedViewController != nil {
            viewController = viewController?.presentedViewController
        }

        viewController?.present(self, animated: true, completion: nil)
        // restore the top window's tint color
        if let tintColor = savedTintColor {
            alertWindow?.tintColor = tintColor
        }
    }
}

The only not so great part of the above code is that it checks the class name UIRemoteKeyboardWindow to make sure we can include it too. Nevertheless the above code does work great in iOS 9, 10 and 11 GM seed, with the right tint color and without the keyboard sliding artifacts.

Fatal Error :1:1: Content is not allowed in prolog

Looks like you forgot adding correct headers to your get request (ask the REST API developer or you specific API description):

HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.header("Accept", "application/xml")
connection.setRequestMethod("GET");
connection.connect();

or

connection.header("Accept", "application/xml;version=1")

Set a button background image iPhone programmatically

This will work

UIImage *buttonImage = [UIImage imageNamed:@"imageName.png"];
[btn setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:btn];

Is there a way to detach matplotlib plots so that the computation can continue?

If you are working in console, i.e. IPython you could use plt.show(block=False) as pointed out in the other answers. But if you're lazy you could just type:

plt.show(0)

Which will be the same.

How do I compare version numbers in Python?

You can use the semver package to determine if a version satisfies a semantic version requirement. This is not the same as comparing two actual versions, but is a type of comparison.

For example, version 3.6.0+1234 should be the same as 3.6.0.

import semver
semver.match('3.6.0+1234', '==3.6.0')
# True

from packaging import version
version.parse('3.6.0+1234') == version.parse('3.6.0')
# False

from distutils.version import LooseVersion
LooseVersion('3.6.0+1234') == LooseVersion('3.6.0')
# False

Grant execute permission for a user on all stored procedures in database?

use below code , change proper database name and user name and then take that output and execute in SSMS. FOR SQL 2005 ABOVE

USE <database_name> 
select 'GRANT EXECUTE ON ['+name+'] TO [userName]  '  
from sys.objects  
where type ='P' 
and is_ms_shipped = 0  

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

Pandas split column of lists into multiple columns

You can use DataFrame constructor with lists created by to_list:

import pandas as pd

d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
                ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
print (df2)
       teams
0  [SF, NYG]
1  [SF, NYG]
2  [SF, NYG]
3  [SF, NYG]
4  [SF, NYG]
5  [SF, NYG]
6  [SF, NYG]

df2[['team1','team2']] = pd.DataFrame(df2.teams.tolist(), index= df2.index)
print (df2)
       teams team1 team2
0  [SF, NYG]    SF   NYG
1  [SF, NYG]    SF   NYG
2  [SF, NYG]    SF   NYG
3  [SF, NYG]    SF   NYG
4  [SF, NYG]    SF   NYG
5  [SF, NYG]    SF   NYG
6  [SF, NYG]    SF   NYG

And for new DataFrame:

df3 = pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2'])
print (df3)
  team1 team2
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG

Solution with apply(pd.Series) is very slow:

#7k rows
df2 = pd.concat([df2]*1000).reset_index(drop=True)

In [121]: %timeit df2['teams'].apply(pd.Series)
1.79 s ± 52.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [122]: %timeit pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2'])
1.63 ms ± 54.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList

What about of

import java.util.Collections;

List<A> abc = Collections.synchronizedList(new ArrayList<>());

UITableView Separator line

Simplest way to add a separator line under each tableview cell can be done in the storyboard itself. First select the tableview, then in the attribute inspector select the separator line property to be single line. After this, select the separator inset to be custom and update the left inset to be 0 from the left.

Example

The entity name must immediately follow the '&' in the entity reference

Do

<script>//<![CDATA[
    /* script */
//]]></script>

Maven Unable to locate the Javac Compiler in:

Go to Window -> Preferences... -> Java -> Installed JREs

Edit JRE Home = JAVA_HOME or JAVA_HOME\jre

For example if you use jdk1.6.0_04 which is installed in C:\Program Files, do the following change:

C:\Program Files\Java\jdk1.6.0_04\jre or C:\Program Files\Java\jdk1.6.0_04 instead of the default one which is at C:\Program Files\Java\jre7

How to downgrade or install an older version of Cocoapods

If you need to install an older version (for example 0.25):

pod _0.25.0_ install

Equal height rows in a flex container

you can do it by fixing the height of "P" tag or fixing the height of "list-item".

I have done by fixing the height of "P"

and overflow should be hidden.

_x000D_
_x000D_
.list{_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
  max-width: 500px;_x000D_
}_x000D_
_x000D_
.list-item{_x000D_
  background-color: #ccc;_x000D_
  display: flex;_x000D_
  padding: 0.5em;_x000D_
  width: 25%;_x000D_
  margin-right: 1%;_x000D_
  margin-bottom: 20px;_x000D_
}_x000D_
.list-content{_x000D_
  width: 100%;_x000D_
}_x000D_
p{height:100px;overflow:hidden;}
_x000D_
<ul class="list">_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
    <h2>box 1</h2>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p>_x000D_
    </div>_x000D_
  </li>_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
    <h3>box 2</h3>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
    </div>_x000D_
  </li>_x000D_
  _x000D_
    <li class="list-item">_x000D_
    <div class="list-content">_x000D_
    <h3>box 2</h3>_x000D_
    <p>Lorem ipsum dolor</p>_x000D_
    </div>_x000D_
  </li>_x000D_
  _x000D_
    <li class="list-item">_x000D_
    <div class="list-content">_x000D_
    <h3>box 2</h3>_x000D_
    <p>Lorem ipsum dolor</p>_x000D_
    </div>_x000D_
  </li>_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h1>h1</h1>_x000D_
    </div>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How do I duplicate a line or selection within Visual Studio Code?

In VSCode Ctrl+CCtrl+V duplicates the whole line below.

I prefer this to the accepted answer, because it only requires one hand to do this and feels way more natural.

The accepted answer will probably do it for most people, however Down sits the other side of the keyboard. So you have two options, use both hands on (Left Hand:L Shift+L Alt+ Right Hand:Up/Down), or with a single hand use the right R Shift+R Alt+Up/Down. The second option feels weird in my opinion. I'd rather use the option where my hand naturally sits on the keyboard, and if its one hand, even better.

jQuery send HTML data through POST

If you want to send an arbitrary amount of data to your server, POST is the only reliable method to do that. GET would also be possible but clients and servers allow just a limited URL length (something like 2048 characters).

How do I extract data from JSON with PHP?

Intro

First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode().

 $data = json_decode($json);

Therein you might find:

These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.

There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.

Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.


Accessing object properties

You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property.

$json = '
{
    "type": "donut",
    "name": "Cake"
}';

$yummy = json_decode($json);

echo $yummy->type; //donut

Accessing array elements

You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0].

$json = '
[
    "Glazed",
    "Chocolate with Sprinkles",
    "Maple"
]';

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles

Iterate over it with foreach.

foreach ($toppings as $topping) {
    echo $topping, "\n";
}

Glazed
Chocolate with Sprinkles
Maple

Or mess about with any of the bazillion built-in array functions.


Accessing nested items

The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

echo $yummy->toppings[2]->id; //5004

Passing true as the second argument to json_decode()

When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key'].

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json, true);

echo $yummy['toppings'][2]['type']; //Maple

Accessing associative array items

When decoding a JSON object to an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value) syntax, eg

$json = '
{
    "foo": "foo value",
    "bar": "bar value",
    "baz": "baz value"
}';

$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo "The value of key '$key' is '$value'", PHP_EOL;
}

Prints

The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'


Don't know how the data is structured

Read the documentation for whatever it is you're getting the JSON from.

Look at the JSON - where you see curly brackets {} expect an object, where you see square brackets [] expect an array.

Hit the decoded data with a print_r():

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

print_r($yummy);

and check the output:

stdClass Object
(
    [type] => donut
    [name] => Cake
    [toppings] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 5002
                    [type] => Glazed
                )

            [1] => stdClass Object
                (
                    [id] => 5006
                    [type] => Chocolate with Sprinkles
                )

            [2] => stdClass Object
                (
                    [id] => 5004
                    [type] => Maple
                )

        )

)

It'll tell you where you have objects, where you have arrays, along with the names and values of their members.

If you can only get so far into it before you get lost - go that far and hit that with print_r():

print_r($yummy->toppings[0]);
stdClass Object
(
    [id] => 5002
    [type] => Glazed
)

Take a look at it in this handy interactive JSON explorer.

Break the problem down into pieces that are easier to wrap your head around.


json_decode() returns null

This happens because either:

  1. The JSON consists entirely of just that, null.
  2. The JSON is invalid - check the result of json_last_error_msg or put it through something like JSONLint.
  3. It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to json_decode().

If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.


Object property name contains a special character

Sometimes you'll have an object property name that contains something like a hyphen - or at sign @ which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);

echo $thing->{'@attributes'}->answer; //42

If you have an integer as property see: How to access object properties with names like integers? as reference.


Someone put JSON in your JSON

It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';

$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);

echo $toppings[0]->type; //Glazed

Data doesn't fit in memory

If your JSON is too large for json_decode() to handle at once things start to get tricky. See:


How to sort it

See: Reference: all basic ways to sort arrays and data in PHP.

How to check if a key exists in Json Object and get its value

JSONObject root= new JSONObject();
JSONObject container= root.getJSONObject("LabelData");

try{
//if key will not be available put it in the try catch block your program 
 will work without error 
String Video=container.getString("video");
}
catch(JsonException e){

 if key will not be there then this block will execute

 } 
 if(video!=null || !video.isEmpty){
  //get Value of video
}else{
  //other vise leave it
 }

i think this might help you

PHP - Notice: Undefined index:

How are you loading this page? Is it getting anything on POST to load? If it's not, then the $name = $_POST['Name']; assignation doesn't have any 'Name' on POST.

Best practices with STDIN in Ruby?

Following are some things I found in my collection of obscure Ruby.

So, in Ruby, a simple no-bells implementation of the Unix command cat would be:

#!/usr/bin/env ruby
puts ARGF.read

ARGF is your friend when it comes to input; it is a virtual file that gets all input from named files or all from STDIN.

ARGF.each_with_index do |line, idx|
    print ARGF.filename, ":", idx, ";", line
end

# print all the lines in every file passed via command line that contains login
ARGF.each do |line|
    puts line if line =~ /login/
end

Thank goodness we didn’t get the diamond operator in Ruby, but we did get ARGF as a replacement. Though obscure, it actually turns out to be useful. Consider this program, which prepends copyright headers in-place (thanks to another Perlism, -i) to every file mentioned on the command-line:

#!/usr/bin/env ruby -i

Header = DATA.read

ARGF.each_line do |e|
  puts Header if ARGF.pos - e.length == 0
  puts e
end

__END__
#--
# Copyright (C) 2007 Fancypants, Inc.
#++

Credit to:

Direct method from SQL command text to DataSet

public DataSet GetDataSet(string ConnectionString, string SQL)
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = SQL;
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();

    ///conn.Open();
    da.Fill(ds);
    ///conn.Close();

    return ds;
}

YouTube URL in Video Tag

This would be easy to do :

<iframe width="420" height="345"
src="http://www.youtube.com/embed/XGSy3_Czz8k">
</iframe>

Is just an example.

How to run php files on my computer

3 easy steps to run your PHP program is:

  1. The easiest way is to install MAMP!

  2. Do a 2-minute setup of MAMP.

  3. Open the localhost server in your browser at the created port to see your program up and runing!

How to run SQL script in MySQL?

If you’re at the MySQL command line mysql> you have to declare the SQL file as source.

mysql> source \home\user\Desktop\test.sql;

How do I change TextView Value inside Java Code?

First, add a textView in the XML file

<TextView  
    android:id="@+id/rate_id"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/what_U_want_to_display_in_first_time"
    />

then add a button in xml file with id btn_change_textView and write this two line of code in onCreate() method of activity

Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);

then use clickListener() on button object like this

btn.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
      
        textView.setText("write here what u want to display after button click in string");
    }
});

How to fix committing to the wrong Git branch?

If the branch you wanted to apply your changes to already exists (branch develop, for example), follow the instructions that were provided by fotanus below, then:

git checkout develop
git rebase develop my_feature # applies changes to correct branch
git checkout develop # 'cuz rebasing will leave you on my_feature
git merge develop my_feature # will be a fast-forward
git branch -d my_feature

And obviously you could use tempbranch or any other branch name instead of my_feature if you wanted.

Also, if applicable, delay the stash pop (apply) until after you've merged at your target branch.

Setting onSubmit in React.js

You can pass the event as argument to the function and then prevent the default behaviour.

var OnSubmitTest = React.createClass({
        render: function() {
        doSomething = function(event){
           event.preventDefault();
           alert('it works!');
        }

        return <form onSubmit={this.doSomething}>
        <button>Click me</button>
        </form>;
    }
});

bootstrap 3 wrap text content within div for horizontal alignment

1) Maybe oveflow: hidden; will do the trick?

2) You need to set the size of each div with the text and button so that each of these divs have the same height. Then for your button:

button {
  position: absolute;
  bottom: 0;
}

RGB to hex and hex to RGB

For convert directly from jQuery you can try:

  function rgbToHex(color) {
    var bg = color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
      return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return     "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
  }

  rgbToHex($('.col-tab-bar .col-tab span').css('color'))

Undo git update-index --assume-unchanged <file>

If you are using Git Extensions, then follow below steps:

  1. Go to commit window.
  2. Click on the dropdown named Working directory changes.
  3. Select Show assummed-unchanged files option.
  4. Right click on the file you want to unassumme.
  5. Select Do no assumme unchanged.

You are done.

How to read user input into a variable in Bash?

Also you can try zenity !

user=$(zenity --entry --text 'Please enter the username:') || exit 1

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

Replace non-ASCII characters with a single space

What about this one?

def replace_trash(unicode_string):
     for i in range(0, len(unicode_string)):
         try:
             unicode_string[i].encode("ascii")
         except:
              #means it's non-ASCII
              unicode_string=unicode_string[i].replace(" ") #replacing it with a single space
     return unicode_string

Start an Activity with a parameter

Kotlin code:

Start the SecondActivity:

startActivity(Intent(context, SecondActivity::class.java)
    .putExtra(SecondActivity.PARAM_GAME_ID, gameId))

Get the Id in SecondActivity:

class CaptureActivity : AppCompatActivity() {

    companion object {
        const val PARAM_GAME_ID = "PARAM_GAME_ID"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val gameId = intent.getStringExtra(PARAM_GAME_ID)
        // TODO use gameId
    }
}

where gameId is String? (can be null)

HTML Button Close Window

This site: http://www.computerhope.com/issues/ch000178.htm answers it with the script below

< input type="button" value="Close this window" onclick="self.close()">

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

In my case i have included jdbc api dependencies in the project so the "Hello World" not printed. After removing the below dependency it works like a charm.

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

SVN 405 Method Not Allowed

This means that the folder/file that you are trying to put on svn already exists there. My advice is that before doing anything just right click on the folder/file and click on repo-browser. By doing this you will be able to see all the files/sub-folders etc that are already present on svn. If the required file/folder is not present on the svn then you just delete(after taking backup) the file that you you want to add and then run an update.

What is content-type and datatype in an AJAX request?

See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.

They are both used in the request to the server so the server knows what kind of data to receive/send.

For..In loops in JavaScript - key value pairs

for (var k in target){
    if (target.hasOwnProperty(k)) {
         alert("Key is " + k + ", value is " + target[k]);
    }
}

hasOwnProperty is used to check if your target really has that property, rather than having inherited it from its prototype. A bit simpler would be:

for (var k in target){
    if (typeof target[k] !== 'function') {
         alert("Key is " + k + ", value is" + target[k]);
    }
}

It just checks that k is not a method (as if target is array you'll get a lot of methods alerted, e.g. indexOf, push, pop,etc.)

CURRENT_DATE/CURDATE() not working as default DATE value

I have the current latest version of MySQL: 8.0.20

So my table name is visit, my column name is curdate.

alter table visit modify curdate date not null default (current_date);

This writes the default date value with no timestamp.

When should I create a destructor?

When you have unmanaged resources and you need to make sure they will be cleaned up when your object goes away. Good example would be COM objects or File Handlers.

How to change the name of an iOS app?

A note on the bundle display name -- this is the right way to change the name in your app menu, but you'll likely have to reset content and settings in your iOS simulator before you see the change actually take effect.

Check that an email address is valid on iOS

To check if a string variable contains a valid email address, the easiest way is to test it against a regular expression. There is a good discussion of various regex's and their trade-offs at regular-expressions.info.

Here is a relatively simple one that leans on the side of allowing some invalid addresses through: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$

How you can use regular expressions depends on the version of iOS you are using.

iOS 4.x and Later

You can use NSRegularExpression, which allows you to compile and test against a regular expression directly.

iOS 3.x

Does not include the NSRegularExpression class, but does include NSPredicate, which can match against regular expressions.

NSString *emailRegex = ...;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
BOOL isValid = [emailTest evaluateWithObject:checkString];

Read a full article about this approach at cocoawithlove.com.

iOS 2.x

Does not include any regular expression matching in the Cocoa libraries. However, you can easily include RegexKit Lite in your project, which gives you access to the C-level regex APIs included on iOS 2.0.

How to write the Fibonacci Sequence?

15 minutes into a tutorial I used when learning Python, it asked the reader to write a program that would calculate a Fibonacci sequence from 3 input numbers (first Fibonacci number, second number, and number at which to stop the sequence). The tutorial had only covered variables, if/thens, and loops up to that point. No functions yet. I came up with the following code:

sum = 0
endingnumber = 1                

print "\n.:Fibonacci sequence:.\n"

firstnumber = input("Enter the first number: ")
secondnumber = input("Enter the second number: ")
endingnumber = input("Enter the number to stop at: ")

if secondnumber < firstnumber:

    print "\nSecond number must be bigger than the first number!!!\n"

else:

while sum <= endingnumber:

    print firstnumber

    if secondnumber > endingnumber:

        break

    else:

        print secondnumber
        sum = firstnumber + secondnumber
        firstnumber = sum
        secondnumber = secondnumber + sum

As you can see, it's really inefficient, but it DOES work.

How do I rename a column in a SQLite database table?

Since version 2018-09-15 (3.25.0) sqlite supports renaming columns

https://sqlite.org/changes.html

In Python, how do I determine if an object is iterable?

Not really "correct" but can serve as quick check of most common types like strings, tuples, floats, etc...

>>> '__iter__' in dir('sds')
True
>>> '__iter__' in dir(56)
False
>>> '__iter__' in dir([5,6,9,8])
True
>>> '__iter__' in dir({'jh':'ff'})
True
>>> '__iter__' in dir({'jh'})
True
>>> '__iter__' in dir(56.9865)
False

Build project into a JAR automatically in Eclipse

You want a .jardesc file. They do not kick off automatically, but it's within 2 clicks.

  1. Right click on your project
  2. Choose Export > Java > JAR file
  3. Choose included files and name output JAR, then click Next
  4. Check "Save the description of this JAR in the workspace" and choose a name for the new .jardesc file

Now, all you have to do is right click on your .jardesc file and choose Create JAR and it will export it in the same spot.

Time comparison

The following assumes that your hours and minutes are stored as ints in variables named hh and mm respectively.

if ((hh > START_HOUR || (hh == START_HOUR && mm >= START_MINUTE)) &&
        (hh < END_HOUR || (hh == END_HOUR && mm <= END_MINUTE))) {
    ...
}

JQuery - how to select dropdown item based on value

 $('#mySelect').val('ab').change();

 // or

 $('#mySelect').val('ab').trigger("change");

How to identify and switch to the frame in selenium webdriver when frame does not have id

you can use cssSelector,

driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")));

How to cherry-pick multiple commits

Here's a script that will allow you to cherry-pick multiple commits in a row simply by telling the script which source and target branches for the cherry picks and the number of commits:

https://gist.github.com/nickboldt/99ac1dc4eb4c9ff003a1effef2eb2d81

To cherry-pick from your branch to master (uses the current branch as source):

./gcpl.sh -m

To cherry-pick the latest 5 commits from your 6.19.x branch to master:

./gcpl.sh -c 5 -s 6.19.x -t master

How to move/rename a file using an Ansible task on a remote system

I know it's a YEARS old topic, but I got frustrated and built a role for myself to do exactly this for an arbitrary list of files. Extend as you see fit:

main.yml

- name: created destination directory
  file:
    path: /path/to/directory
    state: directory
    mode: '0750'
- include_tasks: move.yml
  loop:
    - file1
    - file2
    - file3

move.yml

- name: stat the file
  stat:
    path: {{ item }}
  register: my_file

- name: hard link the file into directory
  file:
    src: /original/path/to/{{ item }}
    dest: /path/to/directory/{{ item }}
    state: hard
  when: my_file.stat.exists

- name: Delete the original file
  file:
    path: /original/path/to/{{ item }}
    state: absent
  when: my_file.stat.exists

Note that hard linking is preferable to copying here, because it inherently preserves ownership and permissions (in addition to not consuming more disk space for a second copy of the file).

Clear MySQL query cache without restarting server

according the documentation, this should do it...

RESET QUERY CACHE 

How to insert 1000 rows at a time

Simplest way.

Just stop execution in 10 sec.

Create table SQL_test  ( ID INT IDENTITY(1,1), UserName varchar(100)) 
while 1=1 
insert into SQL_test values ('TEST') 

How to deep merge instead of shallow merge?

Sometimes you don't need deep merge, even if you think so. For example, if you have a default config with nested objects and you want to extend it deeply with your own config, you can create a class for that. The concept is very simple:

function AjaxConfig(config) {

  // Default values + config

  Object.assign(this, {
    method: 'POST',
    contentType: 'text/plain'
  }, config);

  // Default values in nested objects

  this.headers = Object.assign({}, this.headers, { 
    'X-Requested-With': 'custom'
  });
}

// Define your config

var config = {
  url: 'https://google.com',
  headers: {
    'x-client-data': 'CI22yQEI'
  }
};

// Extend the default values with your own
var fullMergedConfig = new AjaxConfig(config);

// View in DevTools
console.log(fullMergedConfig);

You can convert it to a function (not a constructor).