Programs & Examples On #Email templates

Email templates are HTML based documents typically used in conjunction with email marketing services to send branded messages.

git status shows modifications, git checkout -- <file> doesn't remove them

There are a lot of solutions here and I maybe should have tried some of these before I came up with my own. Anyway here is one more ...

Our issue was that we had no enforcement for endlines and the repository had a mix of DOS / Unix. Worse still was that it was actually an open source repo in this position, and which we had forked. The decision was made by those with primary ownership of the OS repository to change all endlines to Unix and the commit was made that included a .gitattributes to enforce the line endings.

Unfortunately this seemed to cause problems much like described here where once a merge of code from before the DOS-2-Unix was done the files would forever be marked as changed and couldn't be reverted.

During my research for this I came across - https://help.github.com/articles/dealing-with-line-endings/ - If I face this problem again I would first start by trying this out.


Here is what I did:

  1. I'd initially done a merge before realising I had this problem and had to abort that - git reset --hard HEAD (I ran into a merge conflict. How can I abort the merge?)

  2. I opened the files in question in VIM and changed to Unix (:set ff=unix). A tool like dos2unix could be used instead of course

  3. committed

  4. merged the master in (the master has the DOS-2-Unix changes)

    git checkout old-code-branch; git merge master

  5. Resolved conflicts and the files were DOS again so had to :set ff=unix when in VIM. (Note I have installed https://github.com/itchyny/lightline.vim which allowed me to see what the file format is on the VIM statusline)

  6. committed. All sorted!

mkdir's "-p" option

The man pages is the best source of information you can find... and is at your fingertips: man mkdir yields this about -p switch:

-p, --parents
    no error if existing, make parent directories as needed

Use case example: Assume I want to create directories hello/goodbye but none exist:

$mkdir hello/goodbye
mkdir:cannot create directory 'hello/goodbye': No such file or directory
$mkdir -p hello/goodbye
$

-p created both, hello and goodbye

This means that the command will create all the directories necessaries to fulfill your request, not returning any error in case that directory exists.

About rlidwka, Google has a very good memory for acronyms :). My search returned this for example: http://www.cs.cmu.edu/~help/afs/afs_acls.html

 Directory permissions

l (lookup)
    Allows one to list the contents of a directory. It does not allow the reading of files. 
i (insert)
    Allows one to create new files in a directory or copy new files to a directory. 
d (delete)
    Allows one to remove files and sub-directories from a directory. 
a (administer)
    Allows one to change a directory's ACL. The owner of a directory can always change the ACL of a directory that s/he owns, along with the ACLs of any subdirectories in that directory. 

File permissions

r (read)
    Allows one to read the contents of file in the directory. 
w (write)
    Allows one to modify the contents of files in a directory and use chmod on them. 
k (lock)
    Allows programs to lock files in a directory. 

Hence rlidwka means: All permissions on.

It's worth mentioning, as @KeithThompson pointed out in the comments, that not all Unix systems support ACL. So probably the rlidwka concept doesn't apply here.

Convert file to byte array and vice versa

You can't do this. A File is just an abstract way to refer to a file in the file system. It doesn't contain any of the file contents itself.

If you're trying to create an in-memory file that can be referred to using a File object, you aren't going to be able to do that, either, as explained in this thread, this thread, and many other places..

Turning a Comma Separated string into individual rows

I know it has a lot of answers, but I want to write my version of split function like others and like string_split SQL Server 2016 native function.

create function [dbo].[Split]
(
    @Value nvarchar(max),
    @Delimiter nvarchar(50)
)
returns @tbl table
(
    Seq int primary key identity(1, 1),
    Value nvarchar(max)
)
as begin
    declare @Xml xml = cast('<d>' + replace(@Value, @Delimiter, '</d><d>') + '</d>' as xml)

    insert into @tbl
            (Value)
    select  a.split.value('.', 'nvarchar(max)') as Value
    from    @Xml.nodes('/d') a(split)
    
    return
end
  • Seq column is primary key to support fast join with other real table or Split function returned table.
  • Used XML function to support large data (looping version will slow down significantly when you have large data)

Here's a answer to question.

CREATE TABLE Testdata
(
    SomeID INT,
    OtherID INT,
    String VARCHAR(MAX)
)

INSERT Testdata SELECT 1,  9, '18,20,22'
INSERT Testdata SELECT 2,  8, '17,19'
INSERT Testdata SELECT 3,  7, '13,19,20'
INSERT Testdata SELECT 4,  6, ''
INSERT Testdata SELECT 9, 11, '1,2,3,4'


select  t.SomeID, t.OtherID, s.Value
from    Testdata t
        cross apply dbo.Split(t.String, ',') s

--Output
SomeID  OtherID Value
1       9       18
1       9       20
1       9       22
2       8       17
2       8       19
3       7       13
3       7       19
3       7       20
4       6       
9       11      1
9       11      2
9       11      3
9       11      4

Joining Split with other split

declare @Names nvarchar(max) = 'a,b,c,d'
declare @Codes nvarchar(max) = '10,20,30,40'

select  n.Seq, n.Value Name, c.Value Code
from    dbo.Split(@Names, ',') n
        inner join dbo.Split(@Codes, ',') c on n.Seq = c.Seq

--Output
Seq Name    Code
1   a       10
2   b       20
3   c       30
4   d       40

Split two times

declare @NationLocSex nvarchar(max) = 'Korea,Seoul,1;Vietnam,Kiengiang,0;China,Xian,0'

; with rows as
(
    select  Value
    from    dbo.Split(@NationLocSex, ';')
)
select  rw.Value r, cl.Value c
from    rows rw
        cross apply dbo.Split(rw.Value, ',') cl

--Output
r                       c
Korea,Seoul,1           Korea
Korea,Seoul,1           Seoul
Korea,Seoul,1           1
Vietnam,Kiengiang,0     Vietnam
Vietnam,Kiengiang,0     Kiengiang
Vietnam,Kiengiang,0     0
China,Xian,0            China
China,Xian,0            Xian
China,Xian,0            0

Split to columns

declare @Numbers nvarchar(50) = 'First,Second,Third'

; with t as
(
    select  case when Seq = 1 then Value end f1,
            case when Seq = 2 then Value end f2,
            case when Seq = 3 then Value end f3
    from    dbo.Split(@Numbers, ',')
)
select  min(f1) f1, min(f2) f2, min(f3) f3
from    t

--Output
f1      f2      f3
First   Second  Third

Generate rows by range


declare @Ranges nvarchar(50) = '1-2,4-6'

declare @Numbers table (Num int)
insert into @Numbers values (1),(2),(3),(4),(5),(6),(7),(8)

; with t as
(
    select  r.Seq, r.Value,
            min(case when ft.Seq = 1 then ft.Value end) ValueFrom,
            min(case when ft.Seq = 2 then ft.Value end) ValueTo
    from    dbo.Split(@Ranges, ',') r
            cross apply dbo.Split(r.Value, '-') ft
    group by r.Seq, r.Value
)
select  t.Seq, t.Value, t.ValueFrom, t.ValueTo, n.Num
from    t
        inner join @Numbers n on n.Num between t.ValueFrom and t.ValueTo

--Output
Seq Value   ValueFrom   ValueTo Num
1   1-2     1           2       1
1   1-2     1           2       2
2   4-6     4           6       4
2   4-6     4           6       5
2   4-6     4           6       6

Update .NET web service to use TLS 1.2

For me below worked:

Step 1: Downloaded and installed the web Installer exe from https://www.microsoft.com/en-us/download/details.aspx?id=48137 on the application server. Rebooted the application server after installation was completed.

Step 2: Added below changes in the web.config

<system.web>
    <compilation targetFramework="4.6"/> <!-- Changed framework 4.0 to 4.6 -->
    <!--Added this httpRuntime -->
    <httpRuntime targetFramework="4.6" />
</system.web>

Step 3: After completing step 1 and 2, it gave an error, "WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)" and to resolve this error, I added below key in appsettings in my web.config file

<appSettings>
      <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

UTF-8 encoded html pages show ? (questions marks) instead of characters

Tell PDO your charset initially.... something like

PDO("mysql:host=$host;dbname=$DB_name;charset=utf8;", $username, $password);

Notice the: charset=utf8; part.

hope it helps!

How to truncate a foreign key constrained table?

Easy if you are using phpMyAdmin.

Just uncheck Enable foreign key checks option under SQL tab and run TRUNCATE <TABLE_NAME>

enter image description here

Align text in a table header

Try using style for th

th {text-align:center}

CSS disable text selection

Don't apply these properties to the whole body. Move them to a class and apply that class to the elements you want to disable select:

.disable-select {
  -webkit-user-select: none;  
  -moz-user-select: none;    
  -ms-user-select: none;      
  user-select: none;
}

How to encode the plus (+) symbol in a URL

Is you want a plus (+) symbol in the body you have to encode it as 2B.

For example: Try this

Convert utf8-characters to iso-88591 and back in PHP

You need to use the iconv package, specifically its iconv function.

Stretch background image css?

I think what you are looking for is

.style1 {
  background: url('http://localhost/msite/images/12.PNG');
  background-repeat: no-repeat;
  background-position: center;
  -webkit-background-size: contain;
  -moz-background-size: contain;
  -o-background-size: contain;
  background-size: contain;
}

Storing integer values as constants in Enum manner in java

The most common valid reason for wanting an integer constant associated with each enum value is to interoperate with some other component which still expects those integers (e.g. a serialization protocol which you can't change, or the enums represent columns in a table, etc).

In almost all cases I suggest using an EnumMap instead. It decouples the components more completely, if that was the concern, or if the enums represent column indices or something similar, you can easily make changes later on (or even at runtime if need be).

 private final EnumMap<Page, Integer> pageIndexes = new EnumMap<Page, Integer>(Page.class);
 pageIndexes.put(Page.SIGN_CREATE, 1);
 //etc., ...

 int createIndex = pageIndexes.get(Page.SIGN_CREATE);

It's typically incredibly efficient, too.

Adding data like this to the enum instance itself can be very powerful, but is more often than not abused.

Edit: Just realized Bloch addressed this in Effective Java / 2nd edition, in Item 33: Use EnumMap instead of ordinal indexing.

JSON.parse vs. eval()

JSON is just a subset of JavaScript. But eval evaluates the full JavaScript language and not just the subset that’s JSON.

How to create an Array with AngularJS's ng-model

How to create an array of inputs with ng-model

Use the ng-repeat directive:

<ol>
  <li ng-repeat="n in [] | range:count">
    <input name="telephone-{{$index}}"
           ng-model="telephones[$index].value" >
  </li>
</ol>

The DEMO

_x000D_
_x000D_
angular.module("app",[])_x000D_
.controller("ctrl",function($scope){_x000D_
  $scope.count = 3;_x000D_
  $scope.telephones = [];_x000D_
})_x000D_
.filter("range",function() {_x000D_
  return (x,n) => Array.from({length:n},(x,index)=>(index));_x000D_
})
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>_x000D_
<body ng-app="app" ng-controller="ctrl">_x000D_
    <button>_x000D_
      Array length_x000D_
      <input type="number" ng-model="count" _x000D_
             ng-change="telephones.length=count">_x000D_
    </button>_x000D_
    <ol>_x000D_
      <li ng-repeat="n in [] | range:count">_x000D_
        <input name="telephone-{{$index}}"_x000D_
               ng-model="telephones[$index].value" >_x000D_
      </li>_x000D_
    </ol>  _x000D_
    {{telephones}}_x000D_
</body>
_x000D_
_x000D_
_x000D_

MySQL stored procedure return value

You have done the stored procedure correctly but I think you have not referenced the valido variable properly. I was looking at some examples and they have put an @ symbol before the parameter like this @Valido

This statement SELECT valido; should be like this SELECT @valido;

Look at this link mysql stored-procedure: out parameter. Notice the solution with 7 upvotes. He has reference the parameter with an @ sign, hence I suggested you add an @ sign before your parameter valido

I hope that works for you. if it does vote up and mark it as the answer. If not, tell me.

setting JAVA_HOME & CLASSPATH in CentOS 6

Search here for centos jre install all users:

The easiest way to set an environment variable in CentOS is to use export as in

$> export JAVA_HOME=/usr/java/jdk.1.5.0_12

$> export PATH=$PATH:$JAVA_HOME

However, variables set in such a manner are transient i.e. they will disappear the moment you exit the shell. Obviously this is not helpful when setting environment variables that need to persist even when the system reboots. In such cases, you need to set the variables within the system wide profile. In CentOS (I’m using v5.2), the folder /etc/profile.d/ is the recommended place to add customizations to the system profile. For example, when installing the Sun JDK, you might need to set the JAVA_HOME and JRE_HOME environment variables. In this case: Create a new file called java.sh

vim /etc/profile.d/java.sh

Within this file, initialize the necessary environment variables

export JRE_HOME=/usr/java/jdk1.5.0_12/jre
export PATH=$PATH:$JRE_HOME/bin

export JAVA_HOME=/usr/java/jdk1.5.0_12
export JAVA_PATH=$JAVA_HOME

export PATH=$PATH:$JAVA_HOME/bin

Now when you restart your machine, the environment variables within java.sh will be automatically initialized (checkout /etc/profile if you are curious how the files in /etc/profile.d/ are loaded).

PS: If you want to load the environment variables within java.sh without having to restart the machine, you can use the source command as in:

$> source java.sh

How do I change TextView Value inside Java Code?

I presume that this question is a continuation of this one.

What are you trying to do? Do you really want to dynamically change the text in your TextView objects when the user clicks a button? You can certainly do that, if you have a reason, but, if the text is static, it is usually set in the main.xml file, like this:

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

The string "@string/rate" refers to an entry in your strings.xml file that looks like this:

<string name="rate">Rate</string>

If you really want to change this text later, you can do so by using Nikolay's example - you'd get a reference to the TextView by utilizing the id defined for it within main.xml, like this:


final TextView textViewToChange = (TextView) findViewById(R.id.rate);
textViewToChange.setText(
    "The new text that I'd like to display now that the user has pushed a button.");

Animate background image change with jQuery

Ok, I figured it out, this is pretty simple with a little html trick:

http://jsfiddle.net/kRjrn/8/

HTML

<body>
    <div id="background">.
    </div>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>    
</body>?

javascript

$(document).ready(function(){
    $('#background').animate({ opacity: 1 }, 3000);
});?

CSS

#background {
    background-image: url("http://media.noupe.com//uploads/2009/10/wallpaper-pattern.jpg");
    opacity: 0;
    margin: 0;
    padding: 0;
    z-index: -1;
    position: absolute;
    width: 100%;
    height: 100%;
}?

SQL Call Stored Procedure for each Row without using a cursor

I like to do something similar to this (though it is still very similar to using a cursor)

[code]

-- Table variable to hold list of things that need looping
DECLARE @holdStuff TABLE ( 
    id INT IDENTITY(1,1) , 
    isIterated BIT DEFAULT 0 , 
    someInt INT ,
    someBool BIT ,
    otherStuff VARCHAR(200)
)

-- Populate your @holdStuff with... stuff
INSERT INTO @holdStuff ( 
    someInt ,
    someBool ,
    otherStuff
)
SELECT  
    1 , -- someInt - int
    1 , -- someBool - bit
    'I like turtles'  -- otherStuff - varchar(200)
UNION ALL
SELECT  
    42 , -- someInt - int
    0 , -- someBool - bit
    'something profound'  -- otherStuff - varchar(200)

-- Loop tracking variables
DECLARE @tableCount INT
SET     @tableCount = (SELECT COUNT(1) FROM [@holdStuff])

DECLARE @loopCount INT
SET     @loopCount = 1

-- While loop variables
DECLARE @id INT
DECLARE @someInt INT
DECLARE @someBool BIT
DECLARE @otherStuff VARCHAR(200)

-- Loop through item in @holdStuff
WHILE (@loopCount <= @tableCount)
    BEGIN

        -- Increment the loopCount variable
        SET @loopCount = @loopCount + 1

        -- Grab the top unprocessed record
        SELECT  TOP 1 
            @id = id ,
            @someInt = someInt ,
            @someBool = someBool ,
            @otherStuff = otherStuff
        FROM    @holdStuff
        WHERE   isIterated = 0

        -- Update the grabbed record to be iterated
        UPDATE  @holdAccounts
        SET     isIterated = 1
        WHERE   id = @id

        -- Execute your stored procedure
        EXEC someRandomSp @someInt, @someBool, @otherStuff

    END

[/code]

Note that you don't need the identity or the isIterated column on your temp/variable table, i just prefer to do it this way so i don't have to delete the top record from the collection as i iterate through the loop.

How to use the DropDownList's SelectedIndexChanged event

You should add AutoPostBack="true" to DropDownList1

                <asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
                    DataSourceID="Sql_fur_model_manu"    
                    DataTextField="manufacturer" DataValueField="manufacturer" 
                    onselectedindexchanged="ddmanu_SelectedIndexChanged">
                </asp:DropDownList>

How to bind Events on Ajax loaded Content?

use jQuery.live() instead . Documentation here

e.g

$("mylink").live("click", function(event) { alert("new link clicked!");});

How do I rename the android package name?

  1. Goto your AndroidManifest.xml.
  2. place your cursor in the package name like shown below don't select it just place it.

Just place your cursor on it

  1. Then press shift+F6 you will get a popup window as shown below select Rename package.

enter image description here

  1. Enter your new name and select Refactor. (Note since my cursor is on "something" only something is renamed.)

That's it done.

Adding horizontal spacing between divs in Bootstrap 3

From what I understand you want to make a navigation bar or something similar to it. What I recommend doing is making a list and editing the items from there. Just try this;

<ul>
    <li class='item col-md-12 panel' id='gameplay-title'>Title</li>
    <li class='item col-md-6 col-md-offset-3 panel' id='gameplay-scoreboard'>Scoreboard</li>
</ul>

And so on... To add more categories add another ul in there. Now, for the CSS you just need this;

ul {
    list-style: none;
}
.item {
    display: inline;
    padding-right: 20px;
}

Can I make a <button> not submit a form?

The button element has a default type of submit.

You can make it do nothing by setting a type of button:

<button type="button">Cancel changes</button>

What represents a double in sql server?

float is the closest equivalent.

SqlDbType Enumeration

For Lat/Long as OP mentioned.

A metre is 1/40,000,000 of the latitude, 1 second is around 30 metres. Float/double give you 15 significant figures. With some quick and dodgy mental arithmetic... the rounding/approximation errors would be the about the length of this fill stop -> "."

grabbing first row in a mysql query only

You can get the total number of rows containing a specific name using:

SELECT COUNT(*) FROM tbl_foo WHERE name = 'sarmen'

Given the count, you can now get the nth row using:

SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT (n - 1), 1

Where 1 <= n <= COUNT(*) from the first query.

Example:

getting the 3rd row

SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT 2, 1

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Go to dev.twitter.com and create an application. This will provide you with the credentials you need. Here is an implementation I've recently written with PHP and cURL.

<?php
    function buildBaseString($baseURI, $method, $params) {
        $r = array();
        ksort($params);
        foreach($params as $key=>$value){
            $r[] = "$key=" . rawurlencode($value);
        }
        return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
    }

    function buildAuthorizationHeader($oauth) {
        $r = 'Authorization: OAuth ';
        $values = array();
        foreach($oauth as $key=>$value)
            $values[] = "$key=\"" . rawurlencode($value) . "\"";
        $r .= implode(', ', $values);
        return $r;
    }

    $url = "https://api.twitter.com/1.1/statuses/user_timeline.json";

    $oauth_access_token = "YOURVALUE";
    $oauth_access_token_secret = "YOURVALUE";
    $consumer_key = "YOURVALUE";
    $consumer_secret = "YOURVALUE";

    $oauth = array( 'oauth_consumer_key' => $consumer_key,
                    'oauth_nonce' => time(),
                    'oauth_signature_method' => 'HMAC-SHA1',
                    'oauth_token' => $oauth_access_token,
                    'oauth_timestamp' => time(),
                    'oauth_version' => '1.0');

    $base_info = buildBaseString($url, 'GET', $oauth);
    $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
    $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
    $oauth['oauth_signature'] = $oauth_signature;

    // Make requests
    $header = array(buildAuthorizationHeader($oauth), 'Expect:');
    $options = array( CURLOPT_HTTPHEADER => $header,
                      //CURLOPT_POSTFIELDS => $postfields,
                      CURLOPT_HEADER => false,
                      CURLOPT_URL => $url,
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_SSL_VERIFYPEER => false);

    $feed = curl_init();
    curl_setopt_array($feed, $options);
    $json = curl_exec($feed);
    curl_close($feed);

    $twitter_data = json_decode($json);

//print it out
print_r ($twitter_data);

?>

This can be run from the command line:

$ php <name of PHP script>.php

Android: Getting a file URI from a content URI?

If you have a content Uri with content://com.externalstorage... you can use this method to get absolute path of a folder or file on Android 19 or above.

public static String getPath(final Context context, final Uri uri) {
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        System.out.println("getPath() uri: " + uri.toString());
        System.out.println("getPath() uri authority: " + uri.getAuthority());
        System.out.println("getPath() uri path: " + uri.getPath());

        // ExternalStorageProvider
        if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            System.out.println("getPath() docId: " + docId + ", split: " + split.length + ", type: " + type);

            // This is for checking Main Memory
            if ("primary".equalsIgnoreCase(type)) {
                if (split.length > 1) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1] + "/";
                } else {
                    return Environment.getExternalStorageDirectory() + "/";
                }
                // This is for checking SD Card
            } else {
                return "storage" + "/" + docId.replace(":", "/");
            }

        }
    }
    return null;
}

You can check each part of Uri using println. Returned values for my SD card and device main memory are listed below. You can access and delete if file is on memory, but I wasn't able to delete file from SD card using this method, only read or opened image using this absolute path. If you find a solution to delete using this method, please share.

SD CARD

getPath() uri: content://com.android.externalstorage.documents/tree/612E-B7BF%3A/document/612E-B7BF%3A
getPath() uri authority: com.android.externalstorage.documents
getPath() uri path: /tree/612E-B7BF:/document/612E-B7BF:
getPath() docId: 612E-B7BF:, split: 1, type: 612E-B7BF

MAIN MEMORY

getPath() uri: content://com.android.externalstorage.documents/tree/primary%3A/document/primary%3A
getPath() uri authority: com.android.externalstorage.documents
getPath() uri path: /tree/primary:/document/primary:
getPath() docId: primary:, split: 1, type: primary

If you wish to get Uri with file:/// after getting path use

DocumentFile documentFile = DocumentFile.fromFile(new File(path));
documentFile.getUri() // will return a Uri with file Uri

How to define servlet filter order of execution using annotations in WAR

  1. Make the servlet filter implement the spring Ordered interface.
  2. Declare the servlet filter bean manually in configuration class.
    import org.springframework.core.Ordered;
    
    public class MyFilter implements Filter, Ordered {

        @Override
        public void init(FilterConfig filterConfig) {
            // do something
        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            // do something
        }

        @Override
        public void destroy() {
            // do something
        }

        @Override
        public int getOrder() {
            return -100;
        }
    }


    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;

    @Configuration
    @ComponentScan
    public class MyAutoConfiguration {

        @Bean
        public MyFilter myFilter() {
            return new MyFilter();
        }
    }

How to check if Thread finished execution

It depends on how you want to use it. Using a Join is one way. Another way of doing it is let the thread notify the caller of the thread by using an event. For instance when you have your graphical user interface (GUI) thread that calls a process which runs for a while and needs to update the GUI when it finishes, you can use the event to do this. This website gives you an idea about how to work with events:

http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx

Remember that it will result in cross-threading operations and in case you want to update the GUI from another thread, you will have to use the Invoke method of the control which you want to update.

How to write console output to a txt file

You can use System.setOut() at the start of your program to redirect all output via System.out to your own PrintStream.

How to obtain the chat_id of a private Telegram channel?

Open the private channel, then:


WARNING be sure to add -100 prefix when using Telegram Bot API:

  • if the channel ID is for example 1192292378
  • then you should use -1001192292378

Difference between using gradlew and gradle

gradlew is a wrapper(w - character) that uses gradle.

Under the hood gradlew performs three main things:

  • Download and install the correct gradle version
  • Parse the arguments
  • Call a gradle task

Using Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.

To create a wrapper run:

gradle wrapper

This command generate:

gradle-wrapper.properties will contain the information about the Gradle distribution

*./ Is used on Unix to specify the current directory

How to construct a relative path in Java from two absolute paths (or URLs)?

It's a little roundabout, but why not use URI? It has a relativize method which does all the necessary checks for you.

String path = "/var/data/stuff/xyz.dat";
String base = "/var/data";
String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();
// relative == "stuff/xyz.dat"

Please note that for file path there's java.nio.file.Path#relativize since Java 1.7, as pointed out by @Jirka Meluzin in the other answer.

Identifying and removing null characters in UNIX

A large number of unwanted NUL characters, say one every other byte, indicates that the file is encoded in UTF-16 and that you should use iconv to convert it to UTF-8.

What's the best way to store Phone number in Django models

Others mentioned django-phonenumber-field. To get the display format how you want you need to set PHONENUMBER_DEFAULT_FORMAT setting to "E164", "INTERNATIONAL", "NATIONAL", or "RFC3966", however you want it displayed. See the GitHub source.

Using the "With Clause" SQL Server 2008

Try the sp_foreachdb procedure.

RegEx match open tags except XHTML self-contained tags

It seems to me you're trying to match tags without a "/" at the end. Try this:

<([a-zA-Z][a-zA-Z0-9]*)[^>]*(?<!/)>

Insert Data Into Tables Linked by Foreign Key

Use stored procedures.

And even assuming you would want not to use stored procedures - there is at most 3 commands to be run, not 4. Second getting id is useless, as you can do "INSERT INTO ... RETURNING".

Visual Studio 2015 Update 3 Offline Installer (ISO)

[UPDATE]
As per March 7, 2017, Visual Studio 2017 was released for general availability.

You can refer to Mehdi Dehghani answer for the direct download links or the old-fashioned ways using the website, vibs2006 answer
And you can also combine it with ray pixar answer to make it a complete full standalone offline installer.


Note:
I don't condone any illegal use of the offline installer.
Please stop piracy and follow the EULA.

The community edition is free even for commercial use, under some condition.
You can see the EULA in this link below.
https://www.visualstudio.com/support/legal/mt171547
Thank you.


Instruction for official offline installer:

  1. Open this link

    https://www.visualstudio.com/downloads/

  2. Scroll Down (DO NOT FORGET!)

  3. Click on "Visual Studio 2015" panel heading
  4. Choose the edition that you want

    These menu should be available in that panel:

    • Community 2015
    • Enterprise 2015
    • Professional 2015
    • Enterprise 2015
    • Visual Studio 2015 Update
    • Visual Studio 2015 Language Pack
    • Visual Studio Test Professional 2015 Language Pack
    • Test Professional 2015
    • Express 2015 for Desktop
    • Express 2015 for Windows 10


  1. Choose the language that you want in the drop-down menu (above the Download button)

    The language drop-down menu should be like this:

    • English for English
    • Deutsch for German
    • Español for Spanish
    • Français for French
    • Italiano for Italian
    • ??????? for Russian
    • ??? for Japanese
    • ???? for Chinese (Simplified)
    • ???? for Chinese (Traditional)
    • ??? for Korean


  1. Check on "ISO" in radio-button menu (on the left side of the Download button)

    The radio-button menu should be like this:

    • Web installer
    • ISO
  2. Click the Download button

Could not load file or assembly 'System.Data.SQLite'

This is an old post, but it may help some people searching on this error to try setting "Enable 32-Bit Applications" to True for the app pool. That is what resolved the error for me. I came upon this solution by reading some the comments to @beckelmw's answer.

Error when creating a new text file with python?

If the file does not exists, open(name,'r+') will fail.

You can use open(name, 'w'), which creates the file if the file does not exist, but it will truncate the existing file.

Alternatively, you can use open(name, 'a'); this will create the file if the file does not exist, but will not truncate the existing file.

Access denied for user 'root'@'localhost' with PHPMyAdmin

Edit your phpmyadmin config.inc.php file and if you have Password, insert that in front of Password in following code:

$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = '**your-root-username**';
$cfg['Servers'][$i]['password'] = '**root-password**';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

Invoke-WebRequest, POST with parameters

For some picky web services, the request needs to have the content type set to JSON and the body to be a JSON string. For example:

Invoke-WebRequest -UseBasicParsing http://example.com/service -ContentType "application/json" -Method POST -Body "{ 'ItemID':3661515, 'Name':'test'}"

or the equivalent for XML, etc.

sending mail from Batch file

There are multiple methods for handling this problem.

My advice is to use the powerful Windows freeware console application SendEmail.

sendEmail.exe -f [email protected] -o message-file=body.txt -u subject message -t [email protected] -a attachment.zip -s smtp.gmail.com:446 -xu gmail.login -xp gmail.password

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

How can I run a PHP script in the background after a form is submitted?

for background worker i think you should try this technique it will help to call as many as pages you like all pages will run at once independently without waiting for each page response as asynchronous.

form_action_page.php

     <?php

    post_async("http://localhost/projectname/testpage.php", "Keywordname=testValue");
    //post_async("http://localhost/projectname/testpage.php", "Keywordname=testValue2");
    //post_async("http://localhost/projectname/otherpage.php", "Keywordname=anyValue");
    //call as many as pages you like all pages will run at once //independently without waiting for each page response as asynchronous.

  //your form db insertion or other code goes here do what ever you want //above code will work as background job this line will direct hit before //above lines response     
                ?>
                <?php

                /*
                 * Executes a PHP page asynchronously so the current page does not have to wait for it to     finish running.
                 *  
                 */
                function post_async($url,$params)
                {

                    $post_string = $params;

                    $parts=parse_url($url);

                    $fp = fsockopen($parts['host'],
                        isset($parts['port'])?$parts['port']:80,
                        $errno, $errstr, 30);

                    $out = "GET ".$parts['path']."?$post_string"." HTTP/1.1\r\n";//you can use POST instead of GET if you like
                    $out.= "Host: ".$parts['host']."\r\n";
                    $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
                    $out.= "Content-Length: ".strlen($post_string)."\r\n";
                    $out.= "Connection: Close\r\n\r\n";
                    fwrite($fp, $out);
                    fclose($fp);
                }
                ?>

testpage.php

    <?
    echo $_REQUEST["Keywordname"];//case1 Output > testValue
//here do your background operations it will not halt main page
    ?>

PS:if you want to send url parameters as loop then follow this answer :https://stackoverflow.com/a/41225209/6295712

How to get year/month/day from a date object?

var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();

newdate = year + "/" + month + "/" + day;

or you can set new date and give the above values

How do I get a YouTube video thumbnail from the YouTube API?

I think their are a lots of answer for thumbnail, but I want to add some other URLs to get YouTube thumbnail very easily. I am just taking some text from Asaph's answer. Here are some URLs to get YouTube thumbnails:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/default.jpg

For the high quality version of the thumbnail use a URL similar to this:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

There is also a medium quality version of the thumbnail, using a URL similar to the high quality:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

For the standard definition version of the thumbnail, use a URL similar to this:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/sddefault.jpg

For the maximum resolution version of the thumbnail use a URL similar to this:

https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

Why an interface can not implement another interface?

However, interface is 100% abstract class and abstract class can implements interface(100% abstract class) without implement its methods. What is the problem when it is defining as "interface" ?

This is simply a matter of convention. The writers of the java language decided that "extends" is the best way to describe this relationship, so that's what we all use.

In general, even though an interface is "a 100% abstract class," we don't think about them that way. We usually think about interfaces as a promise to implement certain key methods rather than a class to derive from. And so we tend to use different language for interfaces than for classes.

As others state, there are good reasons for choosing "extends" over "implements."

Checking whether a string starts with XXXX

I did a little experiment to see which of these methods

  • string.startswith('hello')
  • string.rfind('hello') == 0
  • string.rpartition('hello')[0] == ''
  • string.rindex('hello') == 0

are most efficient to return whether a certain string begins with another string.

Here is the result of one of the many test runs I've made, where each list is ordered to show the least time it took (in seconds) to parse 5 million of each of the above expressions during each iteration of the while loop I used:

['startswith: 1.37', 'rpartition: 1.38', 'rfind: 1.62', 'rindex: 1.62']
['startswith: 1.28', 'rpartition: 1.44', 'rindex: 1.67', 'rfind: 1.68']
['startswith: 1.29', 'rpartition: 1.42', 'rindex: 1.63', 'rfind: 1.64']
['startswith: 1.28', 'rpartition: 1.43', 'rindex: 1.61', 'rfind: 1.62']
['rpartition: 1.48', 'startswith: 1.48', 'rfind: 1.62', 'rindex: 1.67']
['startswith: 1.34', 'rpartition: 1.43', 'rfind: 1.64', 'rindex: 1.64']
['startswith: 1.36', 'rpartition: 1.44', 'rindex: 1.61', 'rfind: 1.63']
['startswith: 1.29', 'rpartition: 1.37', 'rindex: 1.64', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.44', 'rfind: 1.66', 'rindex: 1.68']
['startswith: 1.44', 'rpartition: 1.41', 'rindex: 1.61', 'rfind: 2.24']
['startswith: 1.34', 'rpartition: 1.45', 'rindex: 1.62', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.38', 'rindex: 1.67', 'rfind: 1.74']
['rpartition: 1.37', 'startswith: 1.38', 'rfind: 1.61', 'rindex: 1.64']
['startswith: 1.32', 'rpartition: 1.39', 'rfind: 1.64', 'rindex: 1.61']
['rpartition: 1.35', 'startswith: 1.36', 'rfind: 1.63', 'rindex: 1.67']
['startswith: 1.29', 'rpartition: 1.36', 'rfind: 1.65', 'rindex: 1.84']
['startswith: 1.41', 'rpartition: 1.44', 'rfind: 1.63', 'rindex: 1.71']
['startswith: 1.34', 'rpartition: 1.46', 'rindex: 1.66', 'rfind: 1.74']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.38', 'rpartition: 1.48', 'rfind: 1.68', 'rindex: 1.68']
['startswith: 1.35', 'rpartition: 1.42', 'rfind: 1.63', 'rindex: 1.68']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.65', 'rindex: 1.75']
['startswith: 1.37', 'rpartition: 1.46', 'rfind: 1.74', 'rindex: 1.75']
['startswith: 1.31', 'rpartition: 1.48', 'rfind: 1.67', 'rindex: 1.74']
['startswith: 1.44', 'rpartition: 1.46', 'rindex: 1.69', 'rfind: 1.74']
['startswith: 1.44', 'rpartition: 1.42', 'rfind: 1.65', 'rindex: 1.65']
['startswith: 1.36', 'rpartition: 1.44', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.34', 'rpartition: 1.46', 'rfind: 1.61', 'rindex: 1.74']
['startswith: 1.35', 'rpartition: 1.56', 'rfind: 1.68', 'rindex: 1.69']
['startswith: 1.32', 'rpartition: 1.48', 'rindex: 1.64', 'rfind: 1.65']
['startswith: 1.28', 'rpartition: 1.43', 'rfind: 1.59', 'rindex: 1.66']

I believe that it is pretty obvious from the start that the startswith method would come out the most efficient, as returning whether a string begins with the specified string is its main purpose.

What surprises me is that the seemingly impractical string.rpartition('hello')[0] == '' method always finds a way to be listed first, before the string.startswith('hello') method, every now and then. The results show that using str.partition to determine if a string starts with another string is more efficient then using both rfind and rindex.

Another thing I've noticed is that string.rindex('hello') == 0 and string.rindex('hello') == 0 have a good battle going on, each rising from fourth to third place, and dropping from third to fourth place, which makes sense, as their main purposes are the same.

Here is the code:

from time import perf_counter

string = 'hello world'
places = dict()

while True:
    start = perf_counter()
    for _ in range(5000000):
        string.startswith('hello')
    end = perf_counter()
    places['startswith'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rfind('hello') == 0
    end = perf_counter()
    places['rfind'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rpartition('hello')[0] == ''
    end = perf_counter()
    places['rpartition'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rindex('hello') == 0
    end = perf_counter()
    places['rindex'] = round(end - start, 2)
    
    print([f'{b}: {str(a).ljust(4, "4")}' for a, b in sorted(i[::-1] for i in places.items())])

How to wait for a process to terminate to execute another process in batch file

This is my adaptation johnrefling's. This work also in WindowsXP; in my case i start the same application at the end, because i want reopen it with different parametrs. My application is a WindowForm .NET

@echo off
taskkill -im:MyApp.exe
:loop1
tasklist | find /i "MyApp.exe" >nul 2>&1
if errorlevel 1 goto cont1
echo "Waiting termination of process..."
:: timeout /t 1 /nobreak >nul 2>&1      ::this don't work in windows XP
:: from: https://stackoverflow.com/questions/1672338/how-to-sleep-for-five-seconds-in-a-batch-file-cmd/33286113#33286113
typeperf "\System\Processor Queue Length" -si 1 -sc 1 >nul s
goto loop1
:cont1
echo "Process terminated, start new application"
START "<SYMBOLIC-TEXT-NAME>" "<full-path-of-MyApp2.exe>" "MyApp2-param1" "MyApp2-param2"
pause

Vertically align text next to an image?

You probably want this:

<div>
   <img style="width:30px; height:30px;">
   <span style="vertical-align:50%; line-height:30px;">Didn't work.</span>
</div>

As others have suggested, try vertical-align on the image:

<div>
   <img style="width:30px; height:30px; vertical-align:middle;">
   <span>Didn't work.</span>
</div>

CSS isn't annoying. You just don't read the documentation. ;P

Downloading and unzipping a .zip file without writing to disk

My suggestion would be to use a StringIO object. They emulate files, but reside in memory. So you could do something like this:

# get_zip_data() gets a zip archive containing 'foo.txt', reading 'hey, foo'

import zipfile
from StringIO import StringIO

zipdata = StringIO()
zipdata.write(get_zip_data())
myzipfile = zipfile.ZipFile(zipdata)
foofile = myzipfile.open('foo.txt')
print foofile.read()

# output: "hey, foo"

Or more simply (apologies to Vishal):

myzipfile = zipfile.ZipFile(StringIO(get_zip_data()))
for name in myzipfile.namelist():
    [ ... ]

In Python 3 use BytesIO instead of StringIO:

import zipfile
from io import BytesIO

filebytes = BytesIO(get_zip_data())
myzipfile = zipfile.ZipFile(filebytes)
for name in myzipfile.namelist():
    [ ... ]

Custom events in jQuery?

I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):

 $("p").bind("myCustomEvent", function(e, myName, myValue){
      $(this).text(myName + ", hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent", [ "John" ]);
    });

How to debug (only) JavaScript in Visual Studio?

The debugger should automatically attach to the browser with Visual Studio 2012. You can use the debugger keyword to halt at a certain point in the application or use the breakpoints directly inside VS.

You can also detatch the default debugger in Visual Studio and use the Developer Tools which come pre loaded with Internet Explorer or FireBug etc.

To do this goto Visual Studio -> Debug -> Detatch All and then click Start debugging in Internet Explorer. You can then set breakpoints at this level. enter image description here

WAITING at sun.misc.Unsafe.park(Native Method)

From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.

Getting multiple values with scanf()

Just to add, we can use array as well:

int i, array[4];
printf("Enter Four Ints: ");
for(i=0; i<4; i++) {
    scanf("%d", &array[i]);
}

How do I tell Spring Boot which main class to use for the executable jar?

Since Spring Boot 1.5, you can complete ignore the error-prone string literal in pom or build.gradle. The repackaging tool (via maven or gradle plugin) will pick the one annotated with @SpringBootApplication for you. (Refer to this issue for detail: https://github.com/spring-projects/spring-boot/issues/6496 )

How to fix Subversion lock error

I solved a similar problem. SVN client gave me an error:

"svn: E200002: Failed to create new lock."

I tried everything including "Cleanup" and "Still Lock" but with no success. Then I solved the problem simply, I went to my svn server and deleted the locks folder:

at "c:/svn/my_repository/locks"

It turned out that there are broken files in it.

Need to perform Wildcard (*,?, etc) search on a string using Regex

You need to convert your wildcard expression to a regular expression. For example:

    private bool WildcardMatch(String s, String wildcard, bool case_sensitive)
    {
        // Replace the * with an .* and the ? with a dot. Put ^ at the
        // beginning and a $ at the end
        String pattern = "^" + Regex.Escape(wildcard).Replace(@"\*", ".*").Replace(@"\?", ".") + "$";

        // Now, run the Regex as you already know
        Regex regex;
        if(case_sensitive)
            regex = new Regex(pattern);
        else
            regex = new Regex(pattern, RegexOptions.IgnoreCase);

        return(regex.IsMatch(s));
    } 

Safest way to get last record ID from a table

I think this one will also work:

SELECT * FROM ORDER BY id DESC LIMIT 0 , 1

How to update/refresh specific item in RecyclerView

Add the changed text to your model data list

mdata.get(position).setSuborderStatusId("5");
mdata.get(position).setSuborderStatus("cancelled");
notifyItemChanged(position);

Get Value of a Edit Text field

Get value from an EditText control in android. EditText getText property use to get value an EditText:

EditText txtname = findViewById(R.id.name);
String name      =  txtname.getText().toString();

Find the index of a dict within a list, by matching the dict's value

lst = [{'id':'1234','name':'Jason'}, {'id':'2345','name':'Tom'}, {'id':'3456','name':'Art'}]

tom_index = next((index for (index, d) in enumerate(lst) if d["name"] == "Tom"), None)
# 1

If you need to fetch repeatedly from name, you should index them by name (using a dictionary), this way get operations would be O(1) time. An idea:

def build_dict(seq, key):
    return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq))

info_by_name = build_dict(lst, key="name")
tom_info = info_by_name.get("Tom")
# {'index': 1, 'id': '2345', 'name': 'Tom'}

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I would change the query in the following ways:

  1. Do the aggregation in subqueries. This can take advantage of more information about the table for optimizing the group by.
  2. Combine the second and third subqueries. They are aggregating on the same column. This requires using a left outer join to ensure that all data is available.
  3. By using count(<fieldname>) you can eliminate the comparisons to is null. This is important for the second and third calculated values.
  4. To combine the second and third queries, it needs to count an id from the mde table. These use mde.mdeid.

The following version follows your example by using union all:

SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
       SUM(TOTALMAILED) as TotalMailed,
       SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
       SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
              NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract
       where SentDate is not null
       group by SentDate
      ) union all
      (select MDE.ReturnMailDate AS ReceiptDate, 0,
              COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
              SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract MDE left outer join
            DTSharedData.dbo.ScanData SD
            ON SD.ScanDataID = MDE.ReturnScanDataID
       group by MDE.ReturnMailDate;
      )
     ) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;

The following does something similar using full outer join:

SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
       sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
       mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
      from MailDataExtract
      where SentDate is not null
      group by cast(SentDate as date)
     ) sd full outer join
    (select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
            COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
            SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
     from MailDataExtract MDE left outer join
          DTSharedData.dbo.ScanData SD
          ON SD.ScanDataID = MDE.ReturnScanDataID
     group by cast(MDE.ReturnMailDate as date)
    ) mde
    on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;

How do I see the commit differences between branches in git?

I'd suggest the following to see the difference "in commits". For symmetric difference, repeat the command with inverted args:

git cherry -v master [your branch, or HEAD as default]

Gradle project refresh failed after Android Studio update

Although this has been answered a long time ago, I had the same problem with an app after updating to

Gradle 2.1.2

The solution I found (on top of the one given by @WarrenFaith was to:

File -> Synchronize

This solved all the errors generated by the Gradle update.

Sending HTTP POST Request In Java

simplest way to send parameters with the post request:

String postURL = "http://www.example.com/page.php";

HttpPost post = new HttpPost(postURL);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "10"));

UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(ent);

HttpClient client = new DefaultHttpClient();
HttpResponse responsePOST = client.execute(post);

You have done. now you can use responsePOST. Get response content as string:

BufferedReader reader = new BufferedReader(new  InputStreamReader(responsePOST.getEntity().getContent()), 2048);

if (responsePOST != null) {
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(" line : " + line);
        sb.append(line);
    }
    String getResponseString = "";
    getResponseString = sb.toString();
//use server output getResponseString as string value.
}

Check if a record exists in the database

I had a requirement to register user. In that case I need to check whether that username is already present in the database or not. I have tried the below in C# windows form application(EntityFramework) and it worked.

 var result = incomeExpenseManagementDB.Users.FirstOrDefault(x => x.userName == registerUserView.uNameText);
  if (result == null) {
      register.registerUser(registerUserView.fnameText, registerUserView.lnameText, registerUserView.eMailText, registerUserView.mobileText, registerUserView.bDateText, registerUserView.uNameText, registerUserView.pWordText);
  } else {
      MessageBox.Show("User Alreay Exist. Try with Different Username");
  }

nodejs mongodb object id to string

Try this:

user._id.toString()

A MongoDB ObjectId is a 12-byte UUID can be used as a HEX string representation with 24 chars in length. You need to convert it to string to show it in console using console.log.

So, you have to do this:

console.log(user._id.toString());

What is the difference between a definition and a declaration?

Declaration: "Somewhere, there exists a foo."

Definition: "...and here it is!"

How to open URL in Microsoft Edge from the command line?

While the accepted answer is correct, it has the unwanted artifact of flashing a console window when running from a non-console application.

The solution I found works best, which is only mentioned here in a comments to the question, is the following command line:

explorer.exe "microsoft-edge:<URL>"

Keep in mind that if contains the % sign you will need to type %% as Windows uses the symbol for variable expansion.

Hope someone finds this helpful.

How to Install Sublime Text 3 using Homebrew

As per latest updates, caskroom packages have moved to homebrew. So try following commands:

brew tap homebrew/cask
brew cask install sublime-text

These 2 terminal commands will be enough for installing sublime.

Java Currency Number format

Format from 1000000.2 to 1 000 000,20

private static final DecimalFormat DF = new DecimalFormat();

public static String toCurrency(Double d) {
    if (d == null || "".equals(d) || "NaN".equals(d)) {
        return " - ";
    }
    BigDecimal bd = new BigDecimal(d);
    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
    DecimalFormatSymbols symbols = DF.getDecimalFormatSymbols();
    symbols.setGroupingSeparator(' ');
    String ret = DF.format(bd) + "";
    if (ret.indexOf(",") == -1) {
        ret += ",00";
    }
    if (ret.split(",")[1].length() != 2) {
        ret += "0";
    }
    return ret;
}

How to get the cookie value in asp.net website

You may use Request.Cookies collection to read the cookies.

if(Request.Cookies["key"]!=null)
{
   var value=Request.Cookies["key"].Value;
}

How can I check the size of a file in a Windows batch script?

I prefer to use a DOS function. Feels cleaner to me.

SET SIZELIMIT=1000
CALL :FileSize %1 FileSize
IF %FileSize% GTR %SIZELIMIT% Echo Large file

GOTO :EOF

:FileSize
SET %~2=%~z1

GOTO :EOF

.gitignore and "The following untracked working tree files would be overwritten by checkout"

These two functions

  1. git rm --cached
  2. git checkout -f another-branch

did NOT work for me.

Instead, I physically removed the file (in eclipse) as what Git tells you to do;

Please move or remove them before you can switch branches.

and then I add/committed it.

and then I pulled and it worked!

What does "both" mean in <div style="clear:both">

Clear:both gives you that space between them.

For example your code:

  <div style="float:left">Hello</div>
  <div style="float:right">Howdy dere pardner</div>

Will currently display as :

Hello  ...................   Howdy dere pardner

If you add the following to above snippet,

  <div style="clear:both"></div>

In between them it will display as:

Hello ................ 
                       Howdy dere pardner

giving you that space between hello and Howdy dere pardner.

Js fiiddle http://jsfiddle.net/Qk5vR/1/

Recommended way to embed PDF in HTML?

To stream the file to the browser, see Stack Overflow question How to stream a PDF file as binary to the browser using .NET 2.0 - note that, with minor variations, this should work whether you're serving up a file from the file system or dynamically generated.

With that said, the referenced MSDN article takes a rather simplistic view of the world, so you may want to read Successfully Stream a PDF to browser through HTTPS as well for some of the headers you may need to supply.

Using that approach, an iframe is probably the best way to go. Have one webform that streams the file, and then put the iframe on another page with its src attribute set to the first form.

Django - Static file not found

If your static URL is correct but still:

Not found: /static/css/main.css

Perhaps your WSGI problem.

? Config WSGI serves both development env and production env

==========================project/project/wsgi.py==========================

import os
from django.conf import settings
from django.contrib.staticfiles.handlers import StaticFilesHandler
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
if settings.DEBUG:
    application = StaticFilesHandler(get_wsgi_application())
else:
    application = get_wsgi_application()

How to sort an array of integers correctly

Try this code as below

var a = [5, 17, 29, 48, 64, 21];
function sortA(arr) {
return arr.sort(function(a, b) {
return a - b;
})
;} 
alert(sortA(a));

How to download a file using a Java REST service and a data stream

See example here: Input and Output binary streams using JERSEY?

Pseudo code would be something like this (there are a few other similar options in above mentioned post):

@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
     public void write(OutputStream output) throws IOException, WebApplicationException {
        try {
          //
          // 1. Get Stream to file from first server
          //
          while(<read stream from first server>) {
              output.write(<bytes read from first server>)
          }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
              // close input stream
        }
    }
}

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

Because you have used absolute positioning, and specified a top percentage, only margin-top will affect the location of your .item object. If instead you positioned it using bottom: 50%, then you'd need margin-bottom -8px to centre it, and margin-top would have no effect.

Margin affects the boundaries of an element in terms of positioning it, either absolutely as in your case, or relative to neighbouring elements. Imagine that margin is the foundations of your element on which it sits. They are typically the same size as it, but can be made larger or smaller on any or all of the four edges.

Your CSS tells the browser to position the top of your element the margin at a point 50% of the way down the page. However, as all elements are not a single pixel, the browser needs to know which part of it to line up 50% of the way down the page. For lining up the top of the element, it uses the top margin. By default this is in line with the top of the element, but you can alter it with CSS.

In your case, top 50% would result in the top of the element starting in the middle of the page. By applying a negative top margin, the browser uses the point 8px into the element from the top (ie the line across the middle of it) as the place to position at 50%.

If you apply a positive margin to the bottom, this extends the line the browser uses to position the bottom out away from the element itself, giving a gap between it and any adjacent element below, or affecting where it is placed absolutely if positioning based on the bottom.

Oracle's default date format is YYYY-MM-DD, WHY?

The biggest PITA of Oracle is that is does not have a default date format!

In your installation of Oracle the combination of Locales and install options has picked (the very sensible!) YYYY-MM-DD as the format for outputting dates. Another installation could have picked "DD/MM/YYYY" or "YYYY/DD/MM".

If you want your SQL to be portable to another Oracle site I would recommend you always wrap a TO_CHAR(datecol,'YYYY-MM-DD') or similar function around each date column your SQL or alternativly set the defualt format immediatly after you connect with

ALTER SESSION 
SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS'; 

or similar.

How add class='active' to html menu with php

I think you need to put your $page = 'one'; above the require_once.. otherwise I don't understand the question.

Using Git, show all commits that are in one branch, but not the other(s)

You probably just want

git branch --contains branch-to-delete

This will list all branches which contain the commits from "branch-to-delete". If it reports more than just "branch-to-delete", the branch has been merged.

Your alternatives are really just rev-list syntax things. e.g. git log one-branch..another-branch shows everything that one-branch needs to have everything another-branch has.

You may also be interested in git show-branch as a way to see what's where.

Validating input using java.util.Scanner

Overview of Scanner.hasNextXXX methods

java.util.Scanner has many hasNextXXX methods that can be used to validate input. Here's a brief overview of all of them:

Scanner is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern), which lets you define what pattern separates your tokens. There are also find and skip methods that ignores delimiters.

The following discussion will keep the regex as simple as possible, so the focus remains on Scanner.


Example 1: Validating positive ints

Here's a simple example of using hasNextInt() to validate positive int from the input.

Scanner sc = new Scanner(System.in);
int number;
do {
    System.out.println("Please enter a positive number!");
    while (!sc.hasNextInt()) {
        System.out.println("That's not a number!");
        sc.next(); // this is important!
    }
    number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);

Here's an example session:

Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5

Note how much easier Scanner.hasNextInt() is to use compared to the more verbose try/catch Integer.parseInt/NumberFormatException combo. By contract, a Scanner guarantees that if it hasNextInt(), then nextInt() will peacefully give you that int, and will not throw any NumberFormatException/InputMismatchException/NoSuchElementException.

Related questions


Example 2: Multiple hasNextXXX on the same token

Note that the snippet above contains a sc.next() statement to advance the Scanner until it hasNextInt(). It's important to realize that none of the hasNextXXX methods advance the Scanner past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!

This has two consequences:

  • If you need to skip the "garbage" input that fails your hasNextXXX test, then you need to advance the Scanner one way or another (e.g. next(), nextLine(), skip, etc).
  • If one hasNextXXX test fails, you can still test if it perhaps hasNextYYY!

Here's an example of performing multiple hasNextXXX tests.

Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
    System.out.println(
        sc.hasNextInt() ? "(int) " + sc.nextInt() :
        sc.hasNextLong() ? "(long) " + sc.nextLong() :  
        sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
        sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
        "(String) " + sc.next()
    );
}

Here's an example session:

5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit

Note that the order of the tests matters. If a Scanner hasNextInt(), then it also hasNextLong(), but it's not necessarily true the other way around. More often than not you'd want to do the more specific test before the more general test.


Example 3 : Validating vowels

Scanner has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.

Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
    System.out.println("That's not a vowel!");
    sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);

Here's an example session:

Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e

In regex, as a Java string literal, the pattern "[aeiou]" is what is called a "character class"; it matches any of the letters a, e, i, o, u. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner.

API links

Related questions

References


Example 4: Using two Scanner at once

Sometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner, where the second Scanner takes the nextLine() from the first Scanner as input. Here's an example:

Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
    Scanner lineSc = new Scanner(sc.nextLine());
    int sum = 0;
    while (lineSc.hasNextInt()) {
        sum += lineSc.nextInt();
    }
    System.out.println("Sum is " + sum);
}

Here's an example session:

Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit

In addition to Scanner(String) constructor, there's also Scanner(java.io.File) among others.


Summary

  • Scanner provides a rich set of features, such as hasNextXXX methods for validation.
  • Proper usage of hasNextXXX/nextXXX in combination means that a Scanner will NEVER throw an InputMismatchException/NoSuchElementException.
  • Always remember that hasNextXXX does not advance the Scanner past any input.
  • Don't be shy to create multiple Scanner if necessary. Two simple Scanner is often better than one overly complex Scanner.
  • Finally, even if you don't have any plans to use the advanced regex features, do keep in mind which methods are regex-based and which aren't. Any Scanner method that takes a String pattern argument is regex-based.
    • Tip: an easy way to turn any String into a literal pattern is to Pattern.quote it.

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

Android Button setOnClickListener Design

Android lambada solution

public void registerButtons(){
    register(R.id.buttonName1, ()-> {/*Your code goes here*/});
    register(R.id.buttonName2, ()-> {/*Your code goes here*/});
    register(R.id.buttonName3, ()-> {/*Your code goes here*/});
}

private void register(int buttonResourceId, Runnable r){
    findViewById(buttonResourceId).setOnClickListener(v -> r.run());
}

Switch case solution solution

public void registerButtons(){
    register(R.id.buttonName1);
    register(R.id.buttonName2);
    register(R.id.buttonName3);
}

private void register(int buttonResourceId){
    findViewById(buttonResourceId).setOnClickListener(buttonClickListener);
}

private OnClickListener buttonClickListener = new OnClickListener() {

    @Override
    public void onClick(View v){
        switch (v.getId()) {
            case R.id.buttonName1:
                // TODO Auto-generated method stub
                break;
            case R.id.buttonName2:
                // TODO Auto-generated method stub
                break;
            case View.NO_ID:
            default:
                // TODO Auto-generated method stub
                break;
        }
    }
};

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

@Test annotation must be imported from org.junit.jupiter.api.Test so the Junit5 can read it. Junit4 use @Test annotations imported from org.junit.Test package.

How to use cookies in Python Requests

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session() 
# all cookies received will be stored in the session object

s.post('http://www...',data=payload)
s.get('http://www...')

Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

How to save requests (python) cookies to a file?

How to split a string with any whitespace chars as delimiters

Since it is a regular expression, and i'm assuming u would also not want non-alphanumeric chars like commas, dots, etc that could be surrounded by blanks (e.g. "one , two" should give [one][two]), it should be:

myString.split(/[\s\W]+/)

Difference between string and StringBuilder in C#

String vs. StringBuilder

  • String

    • Under System namespace

    • Immutable (readonly) instance

    • Performance degrades when continuous change of value occurs

    • Thread-safe

  • StringBuilder (mutable string)

    1. Under System.Text namespace
    2. Mutable instance
    3. Shows better performance since new changes are made to an existing instance

For a descriptive article about this topic with a lot of examples using ObjectIDGenerator, follow this link.

Related Stack Overflow question: Mutability of string when string doesn't change in C#

Maintain/Save/Restore scroll position when returning to a ListView

You can maintain the scroll state after a reload if you save the state before you reload and restore it after. In my case I made a asynchronous network request and reloaded the list in a callback after it completed. This is where I restore state. Code sample is Kotlin.

val state = myList.layoutManager.onSaveInstanceState()

getNewThings() { newThings: List<Thing> ->

    myList.adapter.things = newThings
    myList.layoutManager.onRestoreInstanceState(state)
}

Java Immutable Collections

The difference is that you can't have a reference to an immutable collection which allows changes. Unmodifiable collections are unmodifiable through that reference, but some other object may point to the same data through which it can be changed.

e.g.

List<String> strings = new ArrayList<String>();
List<String> unmodifiable = Collections.unmodifiableList(strings);
unmodifiable.add("New string"); // will fail at runtime
strings.add("Aha!"); // will succeed
System.out.println(unmodifiable);

Why maven settings.xml file is not there?

settings.xml is not required (and thus not autocreated in ~/.m2 folder) unless you want to change the default settings.

Standalone maven and the maven in eclipse will use the same local repository (~/.m2 folder). This means if some artifacts/dependencies are downloaded by standalone maven, it will not be again downloaded by maven in eclipse.

Based on the version of Eclipse that you use, you may have different maven version in eclipse compared to the standalone. It should not matter in most cases.

How do I remove duplicates from a C# array?

Generic Extension method :

public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
{
    if (source == null)
        throw new ArgumentNullException(nameof(source));

    HashSet<TSource> set = new HashSet<TSource>(comparer);
    foreach (TSource item in source)
    {
        if (set.Add(item))
        {
            yield return item;
        }
    }
}

Multiple INNER JOIN SQL ACCESS

Thanks HansUp for your answer, it is very helpful and it works!

I found three patterns working in Access, yours is the best, because it works in all cases.

  • INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM
         ((class
           INNER JOIN person AS cr 
           ON class.C_P_ClassRep=cr.P_Nr
         )
         INNER JOIN person AS cr2
         ON class.C_P_ClassRep2nd=cr2.P_Nr
      )
    

    ;

  • INNER JOIN "chained-set pattern"

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM person AS cr
    INNER JOIN ( class 
       INNER JOIN ( person AS cr2
       ) ON class.C_P_ClassRep2nd=cr2.P_Nr
    ) ON class.C_P_ClassRep=cr.P_Nr
    ;
    
  • CROSS JOIN with WHERE

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM class, person AS cr, person AS cr2
    WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
    ;
    

Checking to see if one array's elements are in another array in PHP

There's little wrong with using array_intersect() and count() (instead of empty).

For example:

$bFound = (count(array_intersect($criminals, $people))) ? true : false;

Regular Expression Match to test for a valid year

If you need to match YYYY or YYYYMMDD you can use:

^((?:(?:(?:(?:(?:[1-9]\d)(?:0[48]|[2468][048]|[13579][26])|(?:(?:[2468][048]|[13579][26])00))(?:0?2(?:29)))|(?:(?:[1-9]\d{3})(?:(?:(?:0?[13578]|1[02])(?:31))|(?:(?:0?[13-9]|1[0-2])(?:29|30))|(?:(?:0?[1-9])|(?:1[0-2]))(?:0?[1-9]|1\d|2[0-8])))))|(?:19|20)\d{2})$

Does HTML5 <video> playback support the .avi format?

The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. User agents are free to support any video formats they feel are appropriate.

http://en.wikipedia.org/wiki/HTML5_video

How to restart counting from 1 after erasing table in MS Access?

You can use:

CurrentDb.Execute "ALTER TABLE yourTable ALTER COLUMN myID COUNTER(1,1)"

I hope you have no relationships that use this table, I hope it is empty, and I hope you understand that all you can (mostly) rely on an autonumber to be is unique. You can get gaps, jumps, very large or even negative numbers, depending on the circumstances. If your autonumber means something, you have a major problem waiting to happen.

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

You only have to add group = 1 into the ggplot or geom_line aes().

For line graphs, the data points must be grouped so that it knows which points to connect. In this case, it is simple -- all points should be connected, so group=1. When more variables are used and multiple lines are drawn, the grouping for lines is usually done by variable.

Reference: Cookbook for R, Chapter: Graphs Bar_and_line_graphs_(ggplot2), Line graphs.

Try this:

plot5 <- ggplot(df, aes(year, pollution, group = 1)) +
         geom_point() +
         geom_line() +
         labs(x = "Year", y = "Particulate matter emissions (tons)", 
              title = "Motor vehicle emissions in Baltimore")

What is setBounds and how do I use it?

The way that Java Swing UIs work is that for each JPanel there is always a LayoutManager that decides on where to exactly place your components. Each layout managers works differently, so if you use for example a BorderLayout, setBounds() is not used by the LayoutManager, instead component placement is decided by East,West,South,North,Center.

For the NullLayoutManager (in case you used new JPanel(null)) however, each component has to have an x and y coordinate. Stupid Sidenote: if your UI would be three-dimensional there would also be a z coordinate.

So with public void Component.setBounds(int x, int y, int width, int height) you specify where your component is placed and how many pixel it is wide and high.

Here's an example:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JTableInNullLayout
{
  public static void main(String[] argv) throws Exception {

      JPanel panel = new JPanel(null);

      JLabel helloLabel = new JLabel("Hello world!");
      helloLabel.setBounds( 10, 50, 60, 20 ); // x, y, width, height
      panel.add(helloLabel);

      JFrame frame = new JFrame();
      frame.add(panel);
      frame.setPreferredSize( new Dimension(200,200));
      frame.pack();
      frame.setVisible(true);
  }
}

Rails Root directory path?

For super correctness, you should use:

Rails.root.join('foo','bar')

which will allow your app to work on platforms where / is not the directory separator, should anyone try and run it on one.

SQL query return data from multiple tables

Ok, I found this post very interesting and I would like to share some of my knowledge on creating a query. Thanks for this Fluffeh. Others who may read this and may feel that I'm wrong are 101% free to edit and criticise my answer. (Honestly, I feel very thankful for correcting my mistake(s).)

I'll be posting some of the frequently asked questions in MySQL tag.


Trick No. 1 (rows that matches to multiple conditions)

Given this schema

CREATE TABLE MovieList
(
    ID INT,
    MovieName VARCHAR(25),
    CONSTRAINT ml_pk PRIMARY KEY (ID),
    CONSTRAINT ml_uq UNIQUE (MovieName)
);

INSERT INTO MovieList VALUES (1, 'American Pie');
INSERT INTO MovieList VALUES (2, 'The Notebook');
INSERT INTO MovieList VALUES (3, 'Discovery Channel: Africa');
INSERT INTO MovieList VALUES (4, 'Mr. Bean');
INSERT INTO MovieList VALUES (5, 'Expendables 2');

CREATE TABLE CategoryList
(
    MovieID INT,
    CategoryName VARCHAR(25),
    CONSTRAINT cl_uq UNIQUE(MovieID, CategoryName),
    CONSTRAINT cl_fk FOREIGN KEY (MovieID) REFERENCES MovieList(ID)
);

INSERT INTO CategoryList VALUES (1, 'Comedy');
INSERT INTO CategoryList VALUES (1, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Drama');
INSERT INTO CategoryList VALUES (3, 'Documentary');
INSERT INTO CategoryList VALUES (4, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Action');

QUESTION

Find all movies that belong to at least both Comedy and Romance categories.

Solution

This question can be very tricky sometimes. It may seem that a query like this will be the answer:-

SELECT  DISTINCT a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName = 'Comedy' AND
        b.CategoryName = 'Romance'

SQLFiddle Demo

which is definitely very wrong because it produces no result. The explanation of this is that there is only one valid value of CategoryName on each row. For instance, the first condition returns true, the second condition is always false. Thus, by using AND operator, both condition should be true; otherwise, it will be false. Another query is like this,

SELECT  DISTINCT a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName IN ('Comedy','Romance')

SQLFiddle Demo

and the result is still incorrect because it matches to record that has at least one match on the categoryName. The real solution would be by counting the number of record instances per movie. The number of instance should match to the total number of the values supplied in the condition.

SELECT  a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName IN ('Comedy','Romance')
GROUP BY a.MovieName
HAVING COUNT(*) = 2

SQLFiddle Demo (the answer)


Trick No. 2 (maximum record for each entry)

Given schema,

CREATE TABLE Software
(
    ID INT,
    SoftwareName VARCHAR(25),
    Descriptions VARCHAR(150),
    CONSTRAINT sw_pk PRIMARY KEY (ID),
    CONSTRAINT sw_uq UNIQUE (SoftwareName)  
);

INSERT INTO Software VALUES (1,'PaintMe','used for photo editing');
INSERT INTO Software VALUES (2,'World Map','contains map of different places of the world');
INSERT INTO Software VALUES (3,'Dictionary','contains description, synonym, antonym of the words');

CREATE TABLE VersionList
(
    SoftwareID INT,
    VersionNo INT,
    DateReleased DATE,
    CONSTRAINT sw_uq UNIQUE (SoftwareID, VersionNo),
    CONSTRAINT sw_fk FOREIGN KEY (SOftwareID) REFERENCES Software(ID)
);

INSERT INTO VersionList VALUES (3, 2, '2009-12-01');
INSERT INTO VersionList VALUES (3, 1, '2009-11-01');
INSERT INTO VersionList VALUES (3, 3, '2010-01-01');
INSERT INTO VersionList VALUES (2, 2, '2010-12-01');
INSERT INTO VersionList VALUES (2, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 3, '2011-12-01');
INSERT INTO VersionList VALUES (1, 2, '2010-12-01');
INSERT INTO VersionList VALUES (1, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 4, '2012-12-01');

QUESTION

Find the latest version on each software. Display the following columns: SoftwareName,Descriptions,LatestVersion (from VersionNo column),DateReleased

Solution

Some SQL developers mistakenly use MAX() aggregate function. They tend to create like this,

SELECT  a.SoftwareName, a.Descriptions,
        MAX(b.VersionNo) AS LatestVersion, b.DateReleased
FROM    Software a
        INNER JOIN VersionList b
            ON a.ID = b.SoftwareID
GROUP BY a.ID
ORDER BY a.ID

SQLFiddle Demo

(most RDBMS generates a syntax error on this because of not specifying some of the non-aggregated columns on the group by clause) the result produces the correct LatestVersion on each software but obviously the DateReleased are incorrect. MySQL doesn't support Window Functions and Common Table Expression yet as some RDBMS do already. The workaround on this problem is to create a subquery which gets the individual maximum versionNo on each software and later on be joined on the other tables.

SELECT  a.SoftwareName, a.Descriptions,
        b.LatestVersion, c.DateReleased
FROM    Software a
        INNER JOIN
        (
            SELECT  SoftwareID, MAX(VersionNO) LatestVersion
            FROM    VersionList
            GROUP BY SoftwareID
        ) b ON a.ID = b.SoftwareID
        INNER JOIN VersionList c
            ON  c.SoftwareID = b.SoftwareID AND
                c.VersionNO = b.LatestVersion
GROUP BY a.ID
ORDER BY a.ID

SQLFiddle Demo (the answer)


So that was it. I'll be posting another soon as I recall any other FAQ on MySQL tag. Thank you for reading this little article. I hope that you have atleast get even a little knowledge from this.

UPDATE 1


Trick No. 3 (Finding the latest record between two IDs)

Given Schema

CREATE TABLE userList
(
    ID INT,
    NAME VARCHAR(20),
    CONSTRAINT us_pk PRIMARY KEY (ID),
    CONSTRAINT us_uq UNIQUE (NAME)  
);

INSERT INTO userList VALUES (1, 'Fluffeh');
INSERT INTO userList VALUES (2, 'John Woo');
INSERT INTO userList VALUES (3, 'hims056');

CREATE TABLE CONVERSATION
(
    ID INT,
    FROM_ID INT,
    TO_ID INT,
    MESSAGE VARCHAR(250),
    DeliveryDate DATE
);

INSERT INTO CONVERSATION VALUES (1, 1, 2, 'hi john', '2012-01-01');
INSERT INTO CONVERSATION VALUES (2, 2, 1, 'hello fluff', '2012-01-02');
INSERT INTO CONVERSATION VALUES (3, 1, 3, 'hey hims', '2012-01-03');
INSERT INTO CONVERSATION VALUES (4, 1, 3, 'please reply', '2012-01-04');
INSERT INTO CONVERSATION VALUES (5, 3, 1, 'how are you?', '2012-01-05');
INSERT INTO CONVERSATION VALUES (6, 3, 2, 'sample message!', '2012-01-05');

QUESTION

Find the latest conversation between two users.

Solution

SELECT    b.Name SenderName,
          c.Name RecipientName,
          a.Message,
          a.DeliveryDate
FROM      Conversation a
          INNER JOIN userList b
            ON a.From_ID = b.ID
          INNER JOIN userList c
            ON a.To_ID = c.ID
WHERE     (LEAST(a.FROM_ID, a.TO_ID), GREATEST(a.FROM_ID, a.TO_ID), DeliveryDate)
IN
(
    SELECT  LEAST(FROM_ID, TO_ID) minFROM,
            GREATEST(FROM_ID, TO_ID) maxTo,
            MAX(DeliveryDate) maxDate
    FROM    Conversation
    GROUP BY minFROM, maxTo
)

SQLFiddle Demo

How to create circular ProgressBar in android?

You can try this Circle Progress library

enter image description here

enter image description here

NB: please always use same width and height for progress views

DonutProgress:

 <com.github.lzyzsd.circleprogress.DonutProgress
        android:id="@+id/donut_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

CircleProgress:

  <com.github.lzyzsd.circleprogress.CircleProgress
        android:id="@+id/circle_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

ArcProgress:

<com.github.lzyzsd.circleprogress.ArcProgress
        android:id="@+id/arc_progress"
        android:background="#214193"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:arc_progress="55"
        custom:arc_bottom_text="MEMORY"/>

Set colspan dynamically with jquery

I've also found that if you had display:none, then programmatically changed it to be visible, you might also have to set

$tr.css({display:'table-row'});

rather than display:inline or display:block otherwise the cell might only show as taking up 1 cell, no matter how large you have the colspan set to.

https with WCF error: "Could not find base address that matches scheme https"

Look at your base address and your endpoint address (can't see it in your sample code). most likely you missed a column or some other typo e.g. https// instead of https://

Watching variables in SSIS during debug

Drag the variable from Variables pane to Watch pane and voila!

Java Strings: "String s = new String("silly");"

Strings are treated a bit specially in java, they're immutable so it's safe for them to be handled by reference counting.

If you write

String s = "Polish";
String t = "Polish";

then s and t actually refer to the same object, and s==t will return true, for "==" for objects read "is the same object" (or can, anyway, I"m not sure if this is part of the actual language spec or simply a detail of the compiler implementation-so maybe it's not safe to rely on this) .

If you write

String s = new String("Polish");
String t = new String("Polish");

then s!=t (because you've explicitly created a new string) although s.equals(t) will return true (because string adds this behavior to equals).

The thing you want to write,

CaseInsensitiveString cis = "Polish";

can't work because you're thinking that the quotations are some sort of short-circuit constructor for your object, when in fact this only works for plain old java.lang.Strings.

MySQL select where column is not empty

To check if field is NULL use IS NULL, IS NOT NULL operators.

MySql reference http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html

Best way to stress test a website

I have used WebLOAD for this kind of project. It's easy to create scripts, and it has built in support for monitoring ASP.NET stats

How do I increase the contrast of an image in Python OpenCV

I would like to suggest a method using the LAB color channel. Wikipedia has enough information regarding what the LAB color channel is about.

I have done the following using OpenCV 3.0.0 and python:

import cv2

#-----Reading the image-----------------------------------------------------
img = cv2.imread('Dog.jpg', 1)
cv2.imshow("img",img) 

#-----Converting image to LAB Color model----------------------------------- 
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
cv2.imshow("lab",lab)

#-----Splitting the LAB image to different channels-------------------------
l, a, b = cv2.split(lab)
cv2.imshow('l_channel', l)
cv2.imshow('a_channel', a)
cv2.imshow('b_channel', b)

#-----Applying CLAHE to L-channel-------------------------------------------
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
cl = clahe.apply(l)
cv2.imshow('CLAHE output', cl)

#-----Merge the CLAHE enhanced L-channel with the a and b channel-----------
limg = cv2.merge((cl,a,b))
cv2.imshow('limg', limg)

#-----Converting image from LAB Color model to RGB model--------------------
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
cv2.imshow('final', final)

#_____END_____#

You can run the code as it is. To know what CLAHE (Contrast Limited Adaptive Histogram Equalization)is about, you can again check Wikipedia.

How do I use .toLocaleTimeString() without displaying seconds?

This works for me:

var date = new Date();
var string = date.toLocaleTimeString([], {timeStyle: 'short'});

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

Okay adding to @null's awesome post about using the Asset Catalog.

You may need to do the following to get the App's Icon linked and working for Ad-Hoc distributions / production to be seen in Organiser, Test flight and possibly unknown AppStore locations.


After creating the Asset Catalog, take note of the name of the Launch Images and App Icon names listed in the .xassets in Xcode.

By Default this should be

  • AppIcon
  • LaunchImage

[To see this click on your .xassets folder/icon in Xcode.] (this can be changed, so just take note of this variable for later)


What is created now each build is the following data structures in your .app:

For App Icons:

iPhone

  • AppIcon57x57.png (iPhone non retina) [Notice the Icon name prefix]
  • [email protected] (iPhone retina)

And the same format for each of the other icon resolutions.

iPad

  • AppIcon72x72~ipad.png (iPad non retina)
  • AppIcon72x72@2x~ipad.png (iPad retina)

(For iPad it is slightly different postfix)


Main Problem

Now I noticed that in my Info.plist in Xcode 5.0.1 it automatically attempted and failed to create a key for "Icon files (iOS 5)" after completing the creation of the Asset Catalog.

If it did create a reference successfully / this may have been patched by Apple or just worked, then all you have to do is review the image names to validate the format listed above.

Final Solution:

Add the following key to you main .plist

I suggest you open your main .plist with a external text editor such as TextWrangler rather than in Xcode to copy and paste the following key in.

<key>CFBundleIcons</key>
<dict>
    <key>CFBundlePrimaryIcon</key>
    <dict>
        <key>CFBundleIconFiles</key>
        <array>
            <string>AppIcon57x57.png</string>
            <string>[email protected]</string>
            <string>AppIcon72x72~ipad.png</string>
            <string>AppIcon72x72@2x~ipad.png</string>
        </array>
    </dict>
</dict>

Please Note I have only included my example resolutions, you will need to add them all.


If you want to add this Key in Xcode without an external editor, Use the following:

  • Icon files (iOS 5) - Dictionary
  • Primary Icon - Dictionary
  • Icon files - Array
  • Item 0 - String = AppIcon57x57.png And for each other item / app icon.

Now when you finally archive your project the final .xcarchive payload .plist will now include the above stated icon locations to build and use.

Do not add the following to any .plist: Just an example of what Xcode will now generate for your final payload

<key>IconPaths</key>
<array>
    <string>Applications/Example.app/AppIcon57x57.png</string>
    <string>Applications/Example.app/[email protected]</string>
    <string>Applications/Example.app/AppIcon72x72~ipad.png</string>
    <string>Applications/Example.app/AppIcon72x72@2x~ipad.png</string>
</array>

Changing text color of menu item in navigation drawer

This works for me. in place of customTheme you can put you theme in styles. in this code you can also change the font and text size.

    <style name="MyTheme.NavMenu" parent="CustomTheme">
            <item name="android:textSize">16sp</item>
            <item name="android:fontFamily">@font/ssp_semi_bold</item>
            <item name="android:textColorPrimary">@color/yourcolor</item>
        </style>

here is my navigation view

<android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:theme="@style/MyTheme.NavMenu"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer">

        <include layout="@layout/layout_update_available"/>

    </android.support.design.widget.NavigationView>

How to convert View Model into JSON object in ASP.NET MVC?

@Html.Raw(Json.Encode(object)) can be used to convert the View Modal Object to JSON

wget/curl large file from google drive

Here is workaround which I came up download files from Google Drive to my Google Cloud Linux shell.

  1. Share the file to PUBLIC and with Edit permissions using advanced sharing.
  2. You will get a sharing link which would have an ID. See the link:- drive.google.com/file/d/[ID]/view?usp=sharing
  3. Copy that ID and Paste it in the following link:-

googledrive.com/host/[ID]

  1. The above link would be our download link.
  2. Use wget to download the file:-

wget https://googledrive.com/host/[ID]

  1. This command will download the file with name as [ID] with no extension and but with same file size on the same location where you ran the wget command.
  2. Actually, I downloaded a zipped folder in my practice. so I renamed that awkward file using:-

mv [ID] 1.zip

  1. then using

unzip 1.zip

we will get the files.

How to recursively delete an entire directory with PowerShell 2.0?

I took another approach inspired by @john-rees above - especially when his approach started to fail for me at some point. Basically recurse the subtree and sort files by their path-length - delete from longest to the shortest

Get-ChildItem $tfsLocalPath -Recurse |  #Find all children
    Select-Object FullName,@{Name='PathLength';Expression={($_.FullName.Length)}} |  #Calculate the length of their path
    Sort-Object PathLength -Descending | #sort by path length descending
    %{ Get-Item -LiteralPath $_.FullName } | 
    Remove-Item -Force

Regarding the -LiteralPath magic, here's another gotchya that may be hitting you: https://superuser.com/q/212808

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

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

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

Adding a leading zero to some values in column in MySQL

Possibly:

select lpad(column, 8, 0) from table;

Edited in response to question from mylesg, in comments below:

ok, seems to make the change on the query- but how do I make it stick (change it) permanently in the table? I tried an UPDATE instead of SELECT

I'm assuming that you used a query similar to:

UPDATE table SET columnName=lpad(nums,8,0);

If that was successful, but the table's values are still without leading-zeroes, then I'd suggest you probably set the column as a numeric type? If that's the case then you'd need to alter the table so that the column is of a text/varchar() type in order to preserve the leading zeroes:

First:

ALTER TABLE `table` CHANGE `numberColumn` `numberColumn` CHAR(8);

Second, run the update:

UPDATE table SET `numberColumn`=LPAD(`numberColum`, 8, '0');

This should, then, preserve the leading-zeroes; the down-side is that the column is no longer strictly of a numeric type; so you may have to enforce more strict validation (depending on your use-case) to ensure that non-numerals aren't entered into that column.

References:

Where can I find the assembly System.Web.Extensions dll?

I had this problem myself. Most of the information I could find online was related to people having this problem with an ASP.NET web application. I was creating a Win Forms stand alone app so most of the advice wasn't helpful for me.

Turns out that the problem was that my project was set to use the ".NET 4 Framework Client Profile" as the target framework and the System.Web.Extensions reference was not in the list for adding. I changed the target to ".NET 4 Framework" and then the reference was available by the normal methods.

Here is what worked for me step by step:

  1. Right Click you project Select Properties
  2. Change your Target Framework to ".NET Framework 4"
  3. Do whatever you need to do to save the changes and close the preferences tab
  4. Right click on the References item in your Solution Explorer
  5. Choose Add Reference...
  6. In the .NET tab, scroll down to System.Web.Extensions and add it.

The identity used to sign the executable is no longer valid

you debug it on simulator only if you don't have iPhone Developer certificate. check on left corner in xcode you select simulator not device.

Find and replace - Add carriage return OR Newline

Just a minor word of warning... a lot of environments use, or need, "\r\n" and not just "\n". I ran into an issue with Visual Studio not matching my regex string at the end of the line because I left off the "\r" of "\r\n", so my string couldn't match with a missing invisible character.

So, if you are doing a find, or a replace, consider the "\r".

For a little more detail on "\r" and "\n", see: https://stackoverflow.com/a/3451192/4427457

Visual Studio Code Tab Key does not insert a tab

Click on the explorer or any other window that is not the editor then press Ctrl + Shift (for Mac only) + M, this is the command to "Toggle Tab Key Moves Focus" on the Keyboard Shortcuts.

How do I start an activity from within a Fragment?

Use the Base Context of the Activity in which your fragment resides to start an Intent.

Intent j = new Intent(fBaseCtx, NewactivityName.class);         
startActivity(j);

where fBaseCtx is BaseContext of your current activity. You can get it as fBaseCtx = getBaseContext();

Get only records created today in laravel

No need to use Carbon::today because laravel uses function now() instead as a helper function

So to get any records that have been created today you can use the below code:

Model::whereDay('created_at', now()->day)->get();

You need to use whereDate so created_at will be converted to date.

What's the difference between window.location= and window.location.replace()?

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

window.location.replace replaces the current history item so you can't go back to it.

See window.location:

assign(url): Load the document at the provided URL.

replace(url):Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Oh and generally speaking:

window.location.href = url;

is favoured over:

window.location = url;

how to align text vertically center in android

Try to put android:gravity="center_vertical|right" inside parent LinearLayout else as you are inside RelativeLayout you can put android:layout_centerInParent="true" inside your scrollView.

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

this in JS:

The value of this in JS is 100% determined by how a function is called, and not how it is defined. We can relatively easily find the value of this by the 'left of the dot rule':

  1. When the function is created using the function keyword the value of this is the object left of the dot of the function which is called
  2. If there is no object left of the dot then the value of this inside a function is often the global object (global in node, window in browser). I wouldn't recommend using the this keyword here because it is less explicit than using something like window!
  3. There exist certain constructs like arrow functions and functions created using the Function.prototype.bind() a function that can fix the value of this. These are exceptions of the rule but are really helpful to fix the value of this.

Example in nodeJS

module.exports.data = 'module data';
// This outside a function in node refers to module.exports object
console.log(this);

const obj1 = {
    data: "obj1 data",
    met1: function () {
        console.log(this.data);
    },
    met2: () => {
        console.log(this.data);
    },
};

const obj2 = {
    data: "obj2 data",
    test1: function () {
        console.log(this.data);
    },
    test2: function () {
        console.log(this.data);
    }.bind(obj1),
    test3: obj1.met1,
    test4: obj1.met2,
};

obj2.test1();
obj2.test2();
obj2.test3();
obj2.test4();
obj1.met1.call(obj2);

Output:

enter image description here

Let me walk you through the outputs 1 by 1 (ignoring the first log starting from the second):

  1. this is obj2 because of the left of the dot rule, we can see how test1 is called obj2.test1();. obj2 is left of the dot and thus the this value.
  2. Even though obj2 is left of the dot, test2 is bound to obj1 via the bind() method. So the this value is obj1.
  3. obj2 is left of the dot from the function which is called: obj2.test3(). Therefore obj2 will be the value of this.
  4. In this case: obj2.test4() obj2 is left of the dot. However, arrow functions don't have their own this binding. Therefore it will bind to the this value of the outer scope which is the module.exports an object which was logged in the beginning.
  5. We can also specify the value of this by using the call function. Here we can pass in the desired this value as an argument, which is obj2 in this case.

How to hide element label by element id in CSS?

Despite other answers here, you should not use display:none to hide the label element.

The accessible way to hide a label visually is to use an 'off-left' or 'clip' rule in your CSS. Using display:none will prevent people who use screen-readers from having access to the content of the label element. Using display:none hides content from all users, and that includes screen-reader users (who benefit most from label elements).

label[for="foo"] { 
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

The W3C and WAI offer more guidance on this topic, including CSS for the 'clip' technique.

How to POST a JSON object to a JAX-RS service

I faced the same 415 http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON. In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.

As mentioned in the other responses I have correctly set the Accept and Content-Type headers to application/json, but it doesn't suffice.

Solution

I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.

Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:

Wrong

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

Right

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {

    public NumberDTO() {
    }

    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

I lost hours, I hope this'll save yours ;-)

How to quickly clear a JavaScript Object?

Well, at the risk of making things too easy...

for (var member in myObject) delete myObject[member];

...would seem to be pretty effective in cleaning the object in one line of code with a minimum of scary brackets. All members will be truly deleted instead of left as garbage.

Obviously if you want to delete the object itself, you'll still have to do a separate delete() for that.

How to dynamic filter options of <select > with jQuery?

This is a simple solution where you clone the lists options and keep them in an object for recovery later. The scripts cleans out the list and add only the options that contains the input text. This should also work cross browser. I got some help from this post: https://stackoverflow.com/a/5748709/542141

Html

<input id="search_input" placeholder="Type to filter">
<select id="theList" class="List" multiple="multiple">

or razor

@Html.ListBoxFor(g => g.SelectedItem, Model.items, new { @class = "List", @id = "theList" })

script

<script type="text/javascript">
  $(document).ready(function () {
    //copy options
    var options = $('#theList option').clone();
    //react on keyup in textbox
    $('#search_input').keyup(function () {
      var val = $(this).val();
      $('#theList').empty();
      //take only the options containing your filter text or all if empty
      options.filter(function (idx, el) {
        return val === '' || $(el).text().indexOf(val) >= 0;
      }).appendTo('#theList');//add it to list
     });
  });
</script>

Property 'catch' does not exist on type 'Observable<any>'

In angular 8:

//for catch:
import { catchError } from 'rxjs/operators';

//for throw:
import { Observable, throwError } from 'rxjs';

//and code should be written like this.

getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
  }

  erroHandler(error: HttpErrorResponse) {
    return throwError(error.message || 'server Error');
  }

How to avoid scientific notation for large numbers in JavaScript?

I had the same issue with oracle returning scientic notation, but I needed the actual number for a url. I just used a PHP trick by subtracting zero, and I get the correct number.

for example 5.4987E7 is the val.

newval = val - 0;

newval now equals 54987000

How to find if directory exists in Python

Python 3.4 introduced the pathlib module into the standard library, which provides an object oriented approach to handle filesystem paths. The is_dir() and exists() methods of a Path object can be used to answer the question:

In [1]: from pathlib import Path

In [2]: p = Path('/usr')

In [3]: p.exists()
Out[3]: True

In [4]: p.is_dir()
Out[4]: True

Paths (and strings) can be joined together with the / operator:

In [5]: q = p / 'bin' / 'vim'

In [6]: q
Out[6]: PosixPath('/usr/bin/vim') 

In [7]: q.exists()
Out[7]: True

In [8]: q.is_dir()
Out[8]: False

Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.

How do I sort an NSMutableArray with custom objects in it?

Sorting NSMutableArray is very simple:

NSMutableArray *arrayToFilter =
     [[NSMutableArray arrayWithObjects:@"Photoshop",
                                       @"Flex",
                                       @"AIR",
                                       @"Flash",
                                       @"Acrobat", nil] autorelease];

NSMutableArray *productsToRemove = [[NSMutableArray array] autorelease];

for (NSString *products in arrayToFilter) {
    if (fliterText &&
        [products rangeOfString:fliterText
                        options:NSLiteralSearch|NSCaseInsensitiveSearch].length == 0)

        [productsToRemove addObject:products];
}
[arrayToFilter removeObjectsInArray:productsToRemove];

How do I build a graphical user interface in C++?

I use FLTK because Qt is not free. I don't choose wxWidgets, because my first test with a simple Hello, World! program produced an executable of 24 MB, FLTK 0.8 MB...

firefox proxy settings via command line

I needed to set an additional option to allow SSO passthrough to our intranet site. I added some code to an example above.

pushd "%APPDATA%\Mozilla\Firefox\Profiles\*.default"
echo user_pref("network.proxy.type", 4);>>prefs.js
echo user_pref("network.automatic-ntlm-auth.trusted-uris","site.domain.com, sites.domain.com");>>prefs.js
popd

Running Windows batch file commands asynchronously

Create a batch file with the following lines:

start foo.exe
start bar.exe
start baz.exe 

The start command runs your command in a new window, so all 3 commands would run asynchronously.

Rebuild Docker container on file changes

Whenever changes are made in dockerfile or compose or requirements , re-Run it using docker-compose up --build . So that images get rebuild and refreshed

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

As balusC said SERVER_NAME is not reliable and can be changed in apache config , server name config of server and firewall that can be between you and server.

Following function always return real host (user typed host) without port and it's almost reliable:

function getRealHost(){
   list($realHost,)=explode(':',$_SERVER['HTTP_HOST']);
   return $realHost;
}

Update a column value, replacing part of a string

UPDATE yourtable
SET url = REPLACE(url, 'http://domain1.com/images/', 'http://domain2.com/otherfolder/')
WHERE url LIKE ('http://domain1.com/images/%');

relevant docs: http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_replace

How can I add a vertical scrollbar to my div automatically?

I'm not quite sure what you're attempting to use the div for, but this is an example with some random text.

Mr_Green gave the correct instructions when he said to add overflow-y: auto as that restricts it to vertical scrolling. This is a JSFiddle example:

JSFiddle

Laravel Carbon subtract days from current date

From Laravel 5.6 you can use whereDate:

$users = Users::where('status_id', 'active')
       ->whereDate( 'created_at', '>', now()->subDays(30))
       ->get();

You also have whereMonth / whereDay / whereYear / whereTime

Are querystring parameters secure in HTTPS (HTTP + SSL)?

The entire transmission, including the query string, the whole URL, and even the type of request (GET, POST, etc.) is encrypted when using HTTPS.

How to set IntelliJ IDEA Project SDK

For a new project select the home directory of the jdk

eg C:\Java\jdk1.7.0_99 or C:\Program Files\Java\jdk1.7.0_99

For an existing project.

1) You need to have a jdk installed on the system.

for instance in

C:\Java\jdk1.7.0_99

2) go to project structure under File menu ctrl+alt+shift+S

3) SDKs is located under Platform Settings. Select it.

4) click the green + up the top of the window.

5) select JDK (I have to use keyboard to select it do not know why).

select the home directory for your jdk installation.

should be good to go.

Iterating through all the cells in Excel VBA or VSTO 2005

For a VB or C# app, one way to do this is by using Office Interop. This depends on which version of Excel you're working with.

For Excel 2003, this MSDN article is a good place to start. Understanding the Excel Object Model from a Visual Studio 2005 Developer's Perspective

You'll basically need to do the following:

  • Start the Excel application.
  • Open the Excel workbook.
  • Retrieve the worksheet from the workbook by name or index.
  • Iterate through all the Cells in the worksheet which were retrieved as a range.
  • Sample (untested) code excerpt below for the last step.

    Excel.Range allCellsRng;
    string lowerRightCell = "IV65536";
    allCellsRng = ws.get_Range("A1", lowerRightCell).Cells;
    foreach (Range cell in allCellsRng)
    {
        if (null == cell.Value2 || isBlank(cell.Value2))
        {
          // Do something.
        }
        else if (isText(cell.Value2))
        {
          // Do something.
        }
        else if (isNumeric(cell.Value2))
        {
          // Do something.
        }
    }

For Excel 2007, try this MSDN reference.

*ngIf and *ngFor on same element causing error

As everyone pointed out even though having multiple template directives in a single element works in angular 1.x it is not allowed in Angular 2. you can find more info from here : https://github.com/angular/angular/issues/7315

2016 angular 2 beta

solution is to use the <template> as a placeholder, so the code goes like this

<template *ngFor="let nav_link of defaultLinks"  >
   <li *ngIf="nav_link.visible">
       .....
   </li>
</template>

but for some reason above does not work in 2.0.0-rc.4 in that case you can use this

<template ngFor let-nav_link [ngForOf]="defaultLinks" >
   <li *ngIf="nav_link.visible">
       .....
   </li> 
</template>

Updated Answer 2018

With updates, right now in 2018 angular v6 recommend to use <ng-container> instead of <template>

so here is the updated answer.

<ng-container *ngFor="let nav_link of defaultLinks" >
   <li *ngIf="nav_link.visible">
       .....
   </li> 
</ng-container>

What is the standard way to add N seconds to datetime.time in Python?

You can use full datetime variables with timedelta, and by providing a dummy date then using time to just get the time value.

For example:

import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.
print(a.time())
print(b.time())

results in the two values, three seconds apart:

11:34:59
11:35:02

You could also opt for the more readable

b = a + datetime.timedelta(seconds=3)

if you're so inclined.


If you're after a function that can do this, you can look into using addSecs below:

import datetime

def addSecs(tm, secs):
    fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
    fulldate = fulldate + datetime.timedelta(seconds=secs)
    return fulldate.time()

a = datetime.datetime.now().time()
b = addSecs(a, 300)
print(a)
print(b)

This outputs:

 09:11:55.775695
 09:16:55

How can I import data into mysql database via mysql workbench?

For MySQL Workbench 6.1: in the home window click on the server instance(connection)/ or create a new one. In the thus opened 'connection' tab click on 'server' -> 'data import'. The rest of the steps remain as in Vishy's answer.

Regular expression that doesn't contain certain string

In general it's a pain to write a regular expression not containing a particular string. We had to do this for models of computation - you take an NFA, which is easy enough to define, and then reduce it to a regular expression. The expression for things not containing "cat" was about 80 characters long.

Edit: I just finished and yes, it's:

aa([^a] | a[^a])aa

Here is a very brief tutorial. I found some great ones before, but I can't see them anymore.

Bootstrap carousel multiple frames at once

Update 2019-03-06 -- Bootstrap v4.3.1

It seems the new Bootstrap version adds a margin-right: -100% to each item, therefore in the responsive solution given in the most upvoted answer in here, this property should be reset, e.g.:

.carousel-inner .carousel-item {
    margin-right: inherit;
}

A working codepen with v4.3.1 in LESS.

How to set the context path of a web application in Tomcat 7.0

Here follows the only solutions that worked for me. Add this to the Host node in the conf/server.xml

<Context path="" docBase="yourAppContextName">

  <!-- Default set of monitored resources -->
  <WatchedResource>WEB-INF/web.xml</WatchedResource>

</Context>

go to Tomcat server.xml file and set path blank

JOIN two SELECT statement results

If Age and Palt are columns in the same Table, you can count(*) all tasks and sum only late ones like this:

select ks,
       count(*) tasks,
       sum(case when Age > Palt then 1 end) late
  from Table
 group by ks

how to implement a long click listener on a listview

I think this above code will work on LongClicking the listview, not the individual items.

why not use registerForContextMenu(listView). and then get the callback in OnCreateContextMenu.

For most use cases this will work same.

How do I get list of all tables in a database using TSQL?

SELECT * FROM information_schema.tables
where TABLE_TYPE = 'BASE TABLE'

SQL Server 2012

How to filter keys of an object with lodash?

Lodash has a _.pickBy function which does exactly what you're looking for.

_x000D_
_x000D_
var thing = {_x000D_
  "a": 123,_x000D_
  "b": 456,_x000D_
  "abc": 6789_x000D_
};_x000D_
_x000D_
var result = _.pickBy(thing, function(value, key) {_x000D_
  return _.startsWith(key, "a");_x000D_
});_x000D_
_x000D_
console.log(result.abc) // 6789_x000D_
console.log(result.b)   // undefined
_x000D_
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

How do I use Apache tomcat 7 built in Host Manager gui?

Solution for a fresh install of Tomcat 7 on Ubuntu 12.04.

Edit this file - /etc/tomcat7/tomcat-users.xml to add this xml section -

<tomcat-users>
<role rolename="admin"/>
<role rolename="admin-gui"/>
<role rolename="manager-gui"/>
<user username="tomcatadmin" password="tomcat2009" roles="admin,admin-gui,manager-gui"/>
</tomcat-users>

restart Tomcat -

service tomcat7 restart

urls to access managers -

  1. tomcat test page - http://localhost:8080/
  2. manager webapp - http://localhost:8080/manager/html
  3. host-manager webapp - http://localhost:8080/host-manager/html

just wanted to put the latest info out there.

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

I recommend setting an alternative location for your npm modules.

npm config set prefix C:\Dev\npm-repository\npm --global 
npm config set cache C:\Dev\npm-repository\npm-cache --global  

Of course you can set the location to wherever best suits.

This has worked well for me and gets around any permissions issues that you may encounter.

Draw a curve with css

You could use an asymmetrical border to make curves with CSS.

border-radius: 50%/100px 100px 0 0;

VIEW DEMO

_x000D_
_x000D_
.box {_x000D_
  width: 500px; _x000D_
  height: 100px;  _x000D_
  border: solid 5px #000;_x000D_
  border-color: #000 transparent transparent transparent;_x000D_
  border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

How to display text in pygame?

When displaying I sometimes make a new file called Funk. This will have the font, size etc. This is the code for the class:

import pygame

def text_to_screen(screen, text, x, y, size = 50,
            color = (200, 000, 000), font_type = 'data/fonts/orecrusherexpand.ttf'):
    try:

        text = str(text)
        font = pygame.font.Font(font_type, size)
        text = font.render(text, True, color)
        screen.blit(text, (x, y))

    except Exception, e:
        print 'Font Error, saw it coming'
        raise e

Then when that has been imported when I want to display text taht updates E.G score I do:

Funk.text_to_screen(screen, 'Text {0}'.format(score), xpos, ypos)

If it is just normal text that isn't being updated:

Funk.text_to_screen(screen, 'Text', xpos, ypos)

You may notice {0} on the first example. That is because when .format(whatever) is used that is what will be updated. If you have something like Score then target score you'd do {0} for score then {1} for target score then .format(score, targetscore)

How do I make an HTML text box show a hint when empty?

You can add and remove a special CSS class and modify the input value onfocus/onblur with JavaScript:

<input type="text" class="hint" value="Search..."
    onfocus="if (this.className=='hint') { this.className = ''; this.value = ''; }"
    onblur="if (this.value == '') { this.className = 'hint'; this.value = 'Search...'; }">

Then specify a hint class with the styling you want in your CSS for example:

input.hint {
    color: grey;
}

How do I add a Maven dependency in Eclipse?

In fact when you open the pom.xml, you should see 5 tabs in the bottom. Click the pom.xml, and you can type whatever dependencies you want.

enter image description here

TypeError: can't pickle _thread.lock objects

I had the same problem with Pool() in Python 3.6.3.

Error received: TypeError: can't pickle _thread.RLock objects

Let's say we want to add some number num_to_add to each element of some list num_list in parallel. The code is schematically like this:

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1 

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list)) 
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

    def run_parallel(self, num, shared_new_num_list):
        new_num = num + self.num_to_add # uses class parameter
        shared_new_num_list.append(new_num)

The problem here is that self in function run_parallel() can't be pickled as it is a class instance. Moving this parallelized function run_parallel() out of the class helped. But it's not the best solution as this function probably needs to use class parameters like self.num_to_add and then you have to pass it as an argument.

Solution:

def run_parallel(num, shared_new_num_list, to_add): # to_add is passed as an argument
    new_num = num + to_add
    shared_new_num_list.append(new_num)

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list, self.num_to_add)) # num_to_add is passed as an argument
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

Other suggestions above didn't help me.

How can I compile a Java program in Eclipse without running it?

Right click on the file on package Explorer Then go to Show in Under it go to terminal Eclipse will have a terminal then Use javac fileName to compile

How to declare a global variable in php?

You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.

$foo = "New";
$closure = (function($bar) use ($foo) {
    echo "$foo $bar";
})("York");

demo | info

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

You can restore the default action (if it is a HREF follow) by doing this:

window.location = $(this).attr('href');

How to add DOM element script to head section?

try out ::

_x000D_
_x000D_
var script = document.createElement("script");_x000D_
script.type="text/javascript";_x000D_
script.innerHTML="alert('Hi!');";_x000D_
document.getElementsByTagName('head')[0].appendChild(script);
_x000D_
_x000D_
_x000D_

Export/import jobs in Jenkins

It is very easy just download plugin name

Job Import Plugin

Enter the URL of your Remote Jenkins server and it will import the jobs automatically

int to hex string

Try the following:

ToString("X4")

See The X format specifier on MSDN.

Join String list elements with a delimiter in one step

You can use : org.springframework.util.StringUtils;

String stringDelimitedByComma = StringUtils.collectionToCommaDelimitedString(myList);

How to open a WPF Popup when another control is clicked, using XAML markup only?

The following approach is the same as Helge Klein's, except that the popup closes automatically when you click anywhere outside the Popup (including the ToggleButton itself):

<ToggleButton x:Name="Btn" IsHitTestVisible="{Binding ElementName=Popup, Path=IsOpen, Mode=OneWay, Converter={local:BoolInverter}}">
    <TextBlock Text="Click here for popup!"/>
</ToggleButton>

<Popup IsOpen="{Binding IsChecked, ElementName=Btn}" x:Name="Popup" StaysOpen="False">
    <Border BorderBrush="Black" BorderThickness="1" Background="LightYellow">
        <CheckBox Content="This is a popup"/>
    </Border>
</Popup>

"BoolInverter" is used in the IsHitTestVisible binding so that when you click the ToggleButton again, the popup closes:

public class BoolInverter : MarkupExtension, IValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool)
            return !(bool)value;
        return value;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Convert(value, targetType, parameter, culture);
    }
}

...which shows the handy technique of combining IValueConverter and MarkupExtension in one.

I did discover one problem with this technique: WPF is buggy when two popups are on the screen at the same time. Specifically, if your toggle button is on the "overflow popup" in a toolbar, then there will be two popups open after you click it. You may then find that the second popup (your popup) will stay open when you click anywhere else on your window. At that point, closing the popup is difficult. The user cannot click the ToggleButton again to close the popup because IsHitTestVisible is false because the popup is open! In my app I had to use a few hacks to mitigate this problem, such as the following test on the main window, which says (in the voice of Louis Black) "if the popup is open and the user clicks somewhere outside the popup, close the friggin' popup.":

PreviewMouseDown += (s, e) =>
{
    if (Popup.IsOpen)
    {
        Point p = e.GetPosition(Popup.Child);
        if (!IsInRange(p.X, 0, ((FrameworkElement)Popup.Child).ActualWidth) ||
            !IsInRange(p.Y, 0, ((FrameworkElement)Popup.Child).ActualHeight))
            Popup.IsOpen = false;
    }
};
// Elsewhere...
public static bool IsInRange(int num, int lo, int hi) => 
    num >= lo && num <= hi;

Using new line(\n) in string and rendering the same in HTML

You could use a pre tag instead of a div. This would automatically display your \n's in the correct way.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
         var display_txt = "1st line text" +"\n" + "2nd line text";
         $('#somediv').html(display_txt).css("color", "green");
});
</script>
</head>
<body>

<pre>
<p id="somediv"></p>
</pre>

</body>
</html>

Google Maps API v3: Can I setZoom after fitBounds?

Edit: See Matt Diamond's comment below.

Got it! Try this:

map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() { 
  if (map.getZoom() > 16) map.setZoom(16); 
  google.maps.event.removeListener(listener); 
});

Modify to your needs.

Count immediate child div elements using jQuery

$("#foo > div").length

Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.

Build error: You must add a reference to System.Runtime

Install the .NET Runtime as well as the targeting pack for the .NET version you're targeting.

The developer pack is just these two things bundled together but as of today doesn't seem to have a 4.6 version so you'll have to install the two items separately.

Downloads can be found here: http://blogs.msdn.com/b/dotnet/p/dotnet_sdks.aspx#

Find an item in List by LINQ?

This will help you in getting the first or default value in your Linq List search

var results = _List.Where(item => item == search).FirstOrDefault();

This search will find the first or default value it will return.

How to merge multiple dicts with same key or different key?

assuming all keys are always present in all dicts:

ds = [d1, d2]
d = {}
for k in d1.iterkeys():
    d[k] = tuple(d[k] for d in ds)

Note: In Python 3.x use below code:

ds = [d1, d2]
d = {}
for k in d1.keys():
  d[k] = tuple(d[k] for d in ds)

and if the dic contain numpy arrays:

ds = [d1, d2]
d = {}
for k in d1.keys():
  d[k] = np.concatenate(list(d[k] for d in ds))

Send JSON data from Javascript to PHP?

Javascript file using jQuery (cleaner but library overhead):

$.ajax({
    type: 'POST',
    url: 'process.php',
    data: {json: JSON.stringify(json_data)},
    dataType: 'json'
});

PHP file (process.php):

directions = json_decode($_POST['json']);
var_dump(directions);

Note that if you use callback functions in your javascript:

$.ajax({
    type: 'POST',
    url: 'process.php',
    data: {json: JSON.stringify(json_data)},
    dataType: 'json'
})
.done( function( data ) {
    console.log('done');
    console.log(data);
})
.fail( function( data ) {
    console.log('fail');
    console.log(data);
});

You must, in your PHP file, return a JSON object (in javascript formatting), in order to get a 'done/success' outcome in your Javascript code. At a minimum return/print:

print('{}');

See Ajax request return 200 OK but error event is fired instead of success

Although for anything a bit more serious you should be sending back a proper header explicitly with the appropriate response code.

how to know status of currently running jobs

This query will give you the exact output for current running jobs. This will also shows the duration of running job in minutes.

   WITH
    CTE_Sysession (AgentStartDate)
    AS 
    (
        SELECT MAX(AGENT_START_DATE) AS AgentStartDate FROM MSDB.DBO.SYSSESSIONS
    )   
SELECT sjob.name AS JobName
        ,CASE 
            WHEN SJOB.enabled = 1 THEN 'Enabled'
            WHEN sjob.enabled = 0 THEN 'Disabled'
            END AS JobEnabled
        ,sjob.description AS JobDescription
        ,CASE 
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL  THEN 'Running'
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NOT NULL AND HIST.run_status = 1 THEN 'Stopped'
            WHEN HIST.run_status = 0 THEN 'Failed'
            WHEN HIST.run_status = 3 THEN 'Canceled'
        END AS JobActivity
        ,DATEDIFF(MINUTE,act.start_execution_date, GETDATE()) DurationMin
        ,hist.run_date AS JobRunDate
        ,run_DURATION/10000 AS Hours
        ,(run_DURATION%10000)/100 AS Minutes 
        ,(run_DURATION%10000)%100 AS Seconds
        ,hist.run_time AS JobRunTime 
        ,hist.run_duration AS JobRunDuration
        ,'tulsql11\dba' AS JobServer
        ,act.start_execution_date AS JobStartDate
        ,act.last_executed_step_id AS JobLastExecutedStep
        ,act.last_executed_step_date AS JobExecutedStepDate
        ,act.stop_execution_date AS JobStopDate
        ,act.next_scheduled_run_date AS JobNextRunDate
        ,sjob.date_created AS JobCreated
        ,sjob.date_modified AS JobModified      
            FROM MSDB.DBO.syssessions AS SYS1
        INNER JOIN CTE_Sysession AS SYS2 ON SYS2.AgentStartDate = SYS1.agent_start_date
        JOIN  msdb.dbo.sysjobactivity act ON act.session_id = SYS1.session_id
        JOIN msdb.dbo.sysjobs sjob ON sjob.job_id = act.job_id
        LEFT JOIN  msdb.dbo.sysjobhistory hist ON hist.job_id = act.job_id AND hist.instance_id = act.job_history_id
        WHERE ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL
        ORDER BY ACT.start_execution_date DESC

Add number of days to a date

//add the two day

$date = "**2-4-2016**"; //stored into date to variable

echo date("d-m-Y",strtotime($date.**' +2 days'**));

//print output
**4-4-2016**

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

With the Underscore.js

var arr=['a','a1','b'] _.filter(arr, function(a){ return a.indexOf('a') > -1; })

How to click a link whose href has a certain substring in Selenium?

You can do this:

//first get all the <a> elements
List<WebElement> linkList=driver.findElements(By.tagName("a"));

//now traverse over the list and check
for(int i=0 ; i<linkList.size() ; i++)
{
    if(linkList.get(i).getAttribute("href").contains("long"))
    {
        linkList.get(i).click();
        break;
    }
}

in this what we r doing is first we are finding all the <a> tags and storing them in a list.After that we are iterating the list one by one to find <a> tag whose href attribute contains long string. And then we click on that particular <a> tag and comes out of the loop.

How to create a inset box-shadow only on one side?

This is what you are looking for. It has examples for each side you want with a shadow.

.top-box
{
    box-shadow: inset 0 7px 9px -7px rgba(0,0,0,0.4);
}
.left-box
{
    box-shadow: inset 7px 0 9px -7px rgba(0,0,0,0.4);
}
.right-box
{
    box-shadow: inset -7px 0 9px -7px rgba(0,0,0,0.4);
}
.bottom-box
{
    box-shadow: inset 0 -7px 9px -7px rgba(0,0,0,0.4);
}

See the snippet for more examples:

_x000D_
_x000D_
body {
    background-color:#0074D9;
}
div {
    background-color:#ffffff;
    padding:20px;
    margin-top:10px;
}
.top-box {
    box-shadow: inset 0 7px 9px -7px rgba(0,0,0,0.7);
}
.left-box {
    box-shadow: inset 7px 0 9px -7px rgba(0,0,0,0.7);
}
.right-box {
    box-shadow: inset -7px 0 9px -7px rgba(0,0,0,0.7);
}
.bottom-box {
    box-shadow: inset 0 -7px 9px -7px rgba(0,0,0,0.7);
}
.top-gradient-box {
    background: linear-gradient(to bottom, #999 0, #ffffff 7px, #ffffff 100%);
}
.left-gradient-box {
    background: linear-gradient(to right, #999 0, #ffffff 7px, #ffffff 100%);
}
.right-gradient-box {
    background: linear-gradient(to left, #999 0, #ffffff 7px, #ffffff 100%);
}
.bottom-gradient-box {
    background: linear-gradient(to top, #999 0, #ffffff 7px, #ffffff 100%);
}
_x000D_
<div class="top-box">
        This area has a top shadow using box-shadow
</div>

<div class="left-box">
        This area has a left shadow using box-shadow
</div>

<div class="right-box">
        This area has a right shadow using box-shadow
</div>

<div class="bottom-box">
        This area has a bottom shadow using box-shadow
</div>

<div class="top-gradient-box">
        This area has a top shadow using gradients
</div>
<div class="left-gradient-box">
        This area has a left shadow using gradients
</div>
<div class="right-gradient-box">
        This area has a right shadow using gradients
</div>
<div class="bottom-gradient-box">
        This area has a bottom shadow using gradients
</div>
_x000D_
_x000D_
_x000D_

Dynamically Dimensioning A VBA Array?

You can use a dynamic array when you don't know the number of values it will contain until run-time:

Dim Zombies() As Integer
ReDim Zombies(NumberOfZombies)

Or you could do everything with one statement if you're creating an array that's local to a procedure:

ReDim Zombies(NumberOfZombies) As Integer

Fixed-size arrays require the number of elements contained to be known at compile-time. This is why you can't use a variable to set the size of the array—by definition, the values of a variable are variable and only known at run-time.

You could use a constant if you knew the value of the variable was not going to change:

Const NumberOfZombies = 2000

but there's no way to cast between constants and variables. They have distinctly different meanings.

C# DateTime to "YYYYMMDDHHMMSS" format

Get the date as a DateTime object instead of a String. Then you can format it as you want.

  • MM/dd/yyyy 08/22/2006
  • dddd, dd MMMM yyyy Tuesday, 22 August 2006
  • dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
  • dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
  • dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
  • dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
  • dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
  • MM/dd/yyyy HH:mm 08/22/2006 06:30
  • MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
  • MM/dd/yyyy H:mm 08/22/2006 6:30
  • MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
  • MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07

Click here for more patterns

git push >> fatal: no configured push destination

The command (or the URL in it) to add the github repository as a remote isn't quite correct. If I understand your repository name correctly, it should be;

git remote add demo_app '[email protected]:levelone/demo_app.git'