Programs & Examples On #Proactive

Load image with jQuery and append it to the DOM

$('<img src="'+ imgPath +'">').load(function() {
  $(this).width(some).height(some).appendTo('#some_target');
});

If you want to do for several images then:

function loadImage(path, width, height, target) {
    $('<img src="'+ path +'">').load(function() {
      $(this).width(width).height(height).appendTo(target);
    });
}

Use:

loadImage(imgPath, 800, 800, '#some_target');

"CASE" statement within "WHERE" clause in SQL Server 2008

select TUM1.userid,TUM1.first_name + ' ' +TUM1.last_name as NAME,tum1.Business_Title,TUM1.manager_id,tum2.First_Name + ' ' + tum2.Last_Name as [MANAGER NAME],TUM1.project,TUM1.project_code,TUM1.rcc_code,TUM1.department,TCM.Company_Name,
case 
when tum1.Gender_ID=1 then 'male' 
else 'female' 
end 'GENDER'
,tum1.Band as BAND,
case when tum1.Inactive=0 then 'STILL IN COMPANY'
else 'LEFT COMPANY' 
end 'ACTIVE/INACTIVE'
from tbl_user_master TUM1
join tbl_Company_Master TCM on TCM.Company_Code=TUM1.Company_Code 
join tbl_User_Master TUM2 on TUM1.Manager_ID=TUM2.UserID 
where tum1.UserID in ('54545414')

Git submodule push

A submodule is nothing but a clone of a git repo within another repo with some extra meta data (gitlink tree entry, .gitmodules file )

$ cd your_submodule
$ git checkout master
<hack,edit>
$ git commit -a -m "commit in submodule"
$ git push
$ cd ..
$ git add your_submodule
$ git commit -m "Updated submodule"

Eclipse CDT: Symbol 'cout' could not be resolved

I had a similar problem with *std::shared_ptr* with Eclipse using MinGW and gcc 4.8.1. No matter what, Eclipse would not resolve *shared_ptr*. To fix this, I manually added the __cplusplus macro to the C++ symbols and - viola! - Eclipse can find it. Since I specified -std=c++11 as a compile option, I (ahem) assumed that the Eclipse code analyzer would use that option as well. So, to fix this:

  1. Project Context -> C/C++ General -> Paths and Symbols -> Symbols Tab
  2. Select C++ in the Languages panel.
  3. Add symbol __cplusplus with a value of 201103.

The only problem with this is that gcc will complain that the symbol is already defined(!) but the compile will complete as before.

Inline elements shifting when made bold on hover

try this:

.nav {
  font-family: monospace;
}

How to change colors of a Drawable in Android?

This code snippet worked for me:

PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(getResources().getColor(R.color.your_color),PorterDuff.Mode.MULTIPLY);

imgView.getDrawable().setColorFilter(porterDuffColorFilter);
imgView.setBackgroundColor(Color.TRANSPARENT)

GridView - Show headers on empty data source

<asp:GridView ID="grdGroup"  EmptyDataText="No Records Found" ShowHeaderWhenEmpty="True" runat="server">

This is a basic example of Gridview with EmptyDataText and ShowHeaderWhenEmpty

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

A bit similar to @bpile answer, my case was a my.cnf entry setting collation-server = utf8_general_ci. After I realized that (and after trying everything above), I forcefully switched my database to utf8_general_ci instead of utf8_unicode_ci and that was it:

ALTER DATABASE `db` CHARACTER SET utf8 COLLATE utf8_general_ci;

How to use XPath in Python?

Another library is 4Suite: http://sourceforge.net/projects/foursuite/

I do not know how spec-compliant it is. But it has worked very well for my use. It looks abandoned.

how do I loop through a line from a csv file in powershell

Import-Csv $path | Foreach-Object { 

    foreach ($property in $_.PSObject.Properties)
    {
        doSomething $property.Name, $property.Value
    } 

}

Django - taking values from POST request

If you need to do something on the front end you can respond to the onsubmit event of your form. If you are just posting to admin/start you can access post variables in your view through the request object. request.POST which is a dictionary of post variables

Select single item from a list

Just to complete the answer, If you are using the LINQ syntax, you can just wrap it since it returns an IEnumerable:

(from int x in intList
 where x > 5
 select x * 2).FirstOrDefault()

Drawing Circle with OpenGL

We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say base=X and Y=vertical. Now we can write X=hypotenuse*cos? and Y=hypotenuse*sin?. We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say X=base and Y=vertical. Now we can write X=hypotenuse * cos? and Y=hypotenuse * sin?.

Now look at this code

void display(){
float x,y;
glColor3f(1, 1, 0);
for(double i =0; i <= 360;){
    glBegin(GL_TRIANGLES);
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    i=i+.5;
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    glVertex2d(0, 0);
    glEnd();
    i=i+.5;
}
glEnd();

glutSwapBuffers();
}

node: command not found

The problem is that your PATH does not include the location of the node executable.

You can likely run node as "/usr/local/bin/node".

You can add that location to your path by running the following command to add a single line to your bashrc file:

echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc

When does Git refresh the list of remote branches?

To update the local list of remote branches:

git remote update origin --prune

To show all local and remote branches that (local) Git knows about

git branch -a

Twitter Bootstrap 3, vertically center content

Option 1 is to use display:table-cell. You need to unfloat the Bootstrap col-* using float:none..

.center {
    display:table-cell;
    vertical-align:middle;
    float:none;
}

http://bootply.com/94394


Option 2 is display:flex to vertical align the row with flexbox:

.row.center {
   display: flex;
   align-items: center;
}

http://www.bootply.com/7rAuLpMCwr


Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456

Copy a file from one folder to another using vbscripting

For copying the single file, here is the code:

Function CopyFiles(FiletoCopy,DestinationFolder)
   Dim fso
                Dim Filepath,WarFileLocation
                Set fso = CreateObject("Scripting.FileSystemObject")
                If  Right(DestinationFolder,1) <>"\"Then
                    DestinationFolder=DestinationFolder&"\"
                End If
    fso.CopyFile FiletoCopy,DestinationFolder,True
                FiletoCopy = Split(FiletoCopy,"\")

End Function

Gets last digit of a number

Another interesting way to do it which would also allow more than just the last number to be taken would be:

int number = 124454;
int overflow = (int)Math.floor(number/(1*10^n))*10^n;

int firstDigits = number - overflow;
//Where n is the number of numbers you wish to conserve</code>

In the above example if n was 1 then the program would return: 4

If n was 3 then the program would return 454

python: after installing anaconda, how to import pandas

even after installing anaconda i got the same error and entering python3 showed this:

$ python3
Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

enter this command: source ~/.bashrc (it is kind of restarting the terminal) after running the command enter python3 again:

$ python3
Python 3.7.4 (default, Aug 13 2019, 20:35:49) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

this means anaconda is added. now import pandas will work.

How can I make an svg scale with its parent container?

Messing around & found this CSS seems to contain the SVG in Chrome browser up to the point where the container is larger than the image:

div.inserted-svg-logo svg { max-width:100%; }

Also seems to be working in FF + IE 11.

Creating a simple configuration file and parser in C++

In general, it's easiest to parse such typical config files in two stages: first read the lines, and then parse those one by one.
In C++, lines can be read from a stream using std::getline(). While by default it will read up to the next '\n' (which it will consume, but not return), you can pass it some other delimiter, too, which makes it a good candidate for reading up-to-some-char, like = in your example.

For simplicity, the following presumes that the = are not surrounded by whitespace. If you want to allow whitespaces at these positions, you will have to strategically place is >> std::ws before reading the value and remove trailing whitespaces from the keys. However, IMO the little added flexibility in the syntax is not worth the hassle for a config file reader.

const char config[] = "url=http://example.com\n"
                      "file=main.exe\n"
                      "true=0";

std::istringstream is_file(config);

std::string line;
while( std::getline(is_file, line) )
{
  std::istringstream is_line(line);
  std::string key;
  if( std::getline(is_line, key, '=') )
  {
    std::string value;
    if( std::getline(is_line, value) ) 
      store_line(key, value);
  }
}

(Adding error handling is left as an exercise to the reader.)

How do I filter query objects by date range in Django?

You can use django's filter with datetime.date objects:

import datetime
samples = Sample.objects.filter(sampledate__gte=datetime.date(2011, 1, 1),
                                sampledate__lte=datetime.date(2011, 1, 31))

Compare if BigDecimal is greater than zero

Use compareTo() function that's built into the class.

Check table exist or not before create it in Oracle

My solution is just compilation of best ideas in thread, with a little improvement. I use both dedicated procedure (@Tomasz Borowiec) to facilitate reuse, and exception handling (@Tobias Twardon) to reduce code and to get rid of redundant table name in procedure.

DECLARE

    PROCEDURE create_table_if_doesnt_exist(
        p_create_table_query VARCHAR2
    ) IS
    BEGIN
        EXECUTE IMMEDIATE p_create_table_query;
    EXCEPTION
        WHEN OTHERS THEN
        -- suppresses "name is already being used" exception
        IF SQLCODE = -955 THEN
            NULL; 
        END IF;
    END;

BEGIN
    create_table_if_doesnt_exist('
        CREATE TABLE "MY_TABLE" (
            "ID" NUMBER(19) NOT NULL PRIMARY KEY,
            "TEXT" VARCHAR2(4000),
            "MOD_TIME" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ');
END;
/

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

As of SQL 2014, this can be accomplished via inline index creation:

CREATE TABLE MyTable(
    a int NOT NULL
    ,b smallint NOT NULL
    ,c smallint NOT NULL
    ,d smallint NOT NULL
    ,e smallint NOT NULL

    -- This creates a primary key
    ,CONSTRAINT PK_MyTable PRIMARY KEY CLUSTERED (a)

    -- This creates a unique nonclustered index on columns b and c
    ,CONSTRAINT IX_MyTable1 UNIQUE (b, c)

    -- This creates a standard non-clustered index on (d, e)
    ,INDEX IX_MyTable4 NONCLUSTERED (d, e)
);
GO

Prior to SQL 2014, CREATE/ALTER TABLE only accepted CONSTRAINTs to be added, not indexes. The fact that primary key and unique constraints are implemented in terms of an index is a side effect.

Set background image in CSS using jquery

Remove the semi-colon after no-repeat, in the url and try it .

$("#globalsearchstr").focus(function(){
    $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
});

Vuejs: v-model array in multiple input

You're thinking too DOM, it's a hard as hell habit to break. Vue recommends you approach it data first.

It's kind of hard to tell in your exact situation but I'd probably use a v-for and make an array of finds to push to as I need more.

Here's how I'd set up my instance:

new Vue({
  el: '#app',
  data: {
    finds: []
  },
  methods: {
    addFind: function () {
      this.finds.push({ value: '' });
    }
  }
});

And here's how I'd set up my template:

<div id="app">
  <h1>Finds</h1>
  <div v-for="(find, index) in finds">
    <input v-model="find.value" :key="index">
  </div>
  <button @click="addFind">
    New Find
  </button>
</div>

Although, I'd try to use something besides an index for the key.

Here's a demo of the above: https://jsfiddle.net/crswll/24txy506/9/

How to get JSON objects value if its name contains dots?

in javascript, object properties can be accessed with . operator or with associative array indexing using []. ie. object.property is equivalent to object["property"]

this should do the trick

var smth = mydata.list[0]["points.bean.pointsBase"][0].time;

How do I set the version information for an existing .exe, .dll?

There is this tool ChangeVersion [1]

List of features (from the website):

  • command line interface
  • support for .EXE, .DLL and .RES files
  • update FileVersion and ProductVersion based on a version mask
  • add/change/remove version key strings
  • adjust file flags (debug, special, private etc)
  • update project files ( .bdsproj | .bpr | .bpk | .dproj )
  • add/change main application icon
  • use ini file with configuration
  • Windows Vista support (needs elevation)
  • easy to integrate into a continuous build environment

Full Disclosure: I know the guy who wrote this tool, I used to work with him. But this also means that I know he makes quality software ;)


[1] the link is dead. There seems to be mirrored version at download.cnet.com.

ASP.NET DateTime Picker

There is an easy, out of the box implementation: the HTML 5 input type="date" and the other date-related input types.

Okay, you can't style the controls that much and it doesn't work on every browser, but still it can be a very good option in the long term if all modern browsers support it and don't want to include heavy libraries that don't always work that good on mobile devices.

How can I take a screenshot/image of a website using Python?

On the Mac, there's webkit2png and on Linux+KDE, you can use khtml2png. I've tried the former and it works quite well, and heard of the latter being put to use.

I recently came across QtWebKit which claims to be cross platform (Qt rolled WebKit into their library, I guess). But I've never tried it, so I can't tell you much more.

The QtWebKit links shows how to access from Python. You should be able to at least use subprocess to do the same with the others.

How to enter special characters like "&" in oracle database?

Justin's answer is the way to go, but also as an FYI you can use the chr() function with the ascii value of the character you want to insert. For this example it would be:

INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 '||chr(38)||' Oracle_14'); 

How to convert a file to utf-8 in Python?

You can use the codecs module, like this:

import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)

EDIT: added BLOCKSIZE parameter to control file chunk size.

Reverting to a previous revision using TortoiseSVN

In the TortoiseSVN context menu, select 'Update to Revision', enter the desired revision number, and voilà :)

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

in my case I have used - (Hyphen) in my script name in case of Jenkinsfile Library. Got resolved after replacing Hyphen(-) with Underscore(_)

Return from lambda forEach() in java

I suggest you to first try to understand Java 8 in the whole picture, most importantly in your case it will be streams, lambdas and method references.

You should never convert existing code to Java 8 code on a line-by-line basis, you should extract features and convert those.

What I identified in your first case is the following:

  • You want to add elements of an input structure to an output list if they match some predicate.

Let's see how we do that, we can do it with the following:

List<Player> playersOfTeam = players.stream()
    .filter(player -> player.getTeam().equals(teamName))
    .collect(Collectors.toList());

What you do here is:

  1. Turn your input structure into a stream (I am assuming here that it is of type Collection<Player>, now you have a Stream<Player>.
  2. Filter out all unwanted elements with a Predicate<Player>, mapping every player to the boolean true if it is wished to be kept.
  3. Collect the resulting elements in a list, via a Collector, here we can use one of the standard library collectors, which is Collectors.toList().

This also incorporates two other points:

  1. Code against interfaces, so code against List<E> over ArrayList<E>.
  2. Use diamond inference for the type parameter in new ArrayList<>(), you are using Java 8 after all.

Now onto your second point:

You again want to convert something of legacy Java to Java 8 without looking at the bigger picture. This part has already been answered by @IanRoberts, though I think that you need to do players.stream().filter(...)... over what he suggested.

How to resolve javax.mail.AuthenticationFailedException issue?

You need to implement a custom Authenticator

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;


class GMailAuthenticator extends Authenticator {
     String user;
     String pw;
     public GMailAuthenticator (String username, String password)
     {
        super();
        this.user = username;
        this.pw = password;
     }
    public PasswordAuthentication getPasswordAuthentication()
    {
       return new PasswordAuthentication(user, pw);
    }
}

Now use it in the Session

Session session = Session.getInstance(props, new GMailAuthenticator(username, password));

Also check out the JavaMail FAQ

Converting java.util.Properties to HashMap<String,String>

this is only because the constructor of HashMap requires an arg of Map generic type and Properties implements Map.

This will work, though with a warning

    Properties properties = new Properties();
    Map<String, String> map = new HashMap(properties);

How to count the number of letters in a string without the spaces?

I managed to condense it into two lines of code:

string = input("Enter your string\n")
print(len(string) - string.count(" "))

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

Based on yghm's workaround, I coded up a convenience class that allows me to solve the problem with a one-liner (after adding the new class to my source code of course). The one-liner is:

     AndroidBug5497Workaround.assistActivity(this);

And the implementation class is:


public class AndroidBug5497Workaround {

    // For more information, see https://issuetracker.google.com/issues/36911528
    // To use this class, simply invoke assistActivity() on an Activity that already has its content view set.

    public static void assistActivity (Activity activity) {
        new AndroidBug5497Workaround(activity);
    }

    private View mChildOfContent;
    private int usableHeightPrevious;
    private FrameLayout.LayoutParams frameLayoutParams;

    private AndroidBug5497Workaround(Activity activity) {
        FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
        mChildOfContent = content.getChildAt(0);
        mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                possiblyResizeChildOfContent();
            }
        });
        frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
    }

    private void possiblyResizeChildOfContent() {
        int usableHeightNow = computeUsableHeight();
        if (usableHeightNow != usableHeightPrevious) {
            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
            int heightDifference = usableHeightSansKeyboard - usableHeightNow;
            if (heightDifference > (usableHeightSansKeyboard/4)) {
                // keyboard probably just became visible
                frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
            } else {
                // keyboard probably just became hidden
                frameLayoutParams.height = usableHeightSansKeyboard;
            }
            mChildOfContent.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }

    private int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
        return (r.bottom - r.top);
    }
}

Hope this helps someone.

How to read .pem file to get private and public key

I think in your private key definition, You should replace:

X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);

with:

PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);

Look your openssl command:

$openssl **pkcs8** -topk8 -inform PEM -outform PEM -in mykey.pem \ -out private_key.pem -nocrypt

And the java Exception:

Only PCKS8 codification 

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

You need to apply the event handler in the context of that element:

var elem = document.getElementById("linkid");
if (typeof elem.onclick == "function") {
    elem.onclick.apply(elem);
}

Otherwise this would reference the context the above code is executed in.

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

The usage of MAC id is most easier way if the task is about logging the unique id a system.

the change of mac id is though possible, even the change of other ids of a system are also possible is that respective device is replaced.

so, unless what for a unique id is required is not known, we may not be able to find an appropriate solution.

However, the below link is helpful extracting mac addresses. http://www.stratos.me/2008/07/find-mac-address-using-java/

Difference between two dates in Python

Use - to get the difference between two datetime objects and take the days member.

from datetime import datetime

def days_between(d1, d2):
    d1 = datetime.strptime(d1, "%Y-%m-%d")
    d2 = datetime.strptime(d2, "%Y-%m-%d")
    return abs((d2 - d1).days)

How to Automatically Close Alerts using Twitter Bootstrap

Using the 'close' action on the alert does not work for me, because it removes the alert from the DOM and I need the alert multiple times (I'm posting data with ajax and I show a message to the user on every post). So I created this function that create the alert every time I need it and then starts a timer to close the created alert. I pass into the function the id of the container to which I want to append the alert, the type of alert ('success', 'danger', etc.) and the message. Here is my code:

function showAlert(containerId, alertType, message) {
    $("#" + containerId).append('<div class="alert alert-' + alertType + '" id="alert' + containerId + '">' + message + '</div>');
    $("#alert" + containerId).alert();
    window.setTimeout(function () { $("#alert" + containerId).alert('close'); }, 2000);
}

How do I include a pipe | in my linux find -exec command?

the solution is easy: execute via sh

... -exec sh -c "zcat {} | agrep -dEOE 'grep' " \;

Convert to binary and keep leading zeros in Python

Sometimes you just want a simple one liner:

binary = ''.join(['{0:08b}'.format(ord(x)) for x in input])

Python 3

Git push rejected "non-fast-forward"

Here is another solution to resolve this issue

>git pull
>git commit -m "any meaning full message"
>git push

Fastest way to check if a string is JSON in PHP?

Another suggestion from me :)

function isJson(string $string) {
  return ($result = json_decode($string, true)) ? $result : $string;
}

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The accepted answer is correct regarding the Invoke-Command cmdlet, but more broadly speaking, cmdlets can have parameter sets where groups of input parameters are defined, such that you can't use two parameters that aren't members of the same parameter set.

If you're running into this error with any other cmdlet, look up its Microsoft documentation, and see if the the top of the page has distinct sets of parameters listed. For example, the documentation for Set-AzureDeployment defines three sets at the top of the page.

PHP foreach with Nested Array?

As I understand , all of previous answers , does not make an Array output, In my case : I have a model with parent-children structure (simplified code here):

public function parent(){

    return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
}


public function children()
{

    return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
}

and if you want to have all of children IDs as an Array , This approach is fine and working for me :

public function allChildren()
{
    $allChildren = [];
    if ($this->has_branch) {

        foreach ($this->children as $child) {

            $subChildren = $child->allChildren();

            if (count($subChildren) == 1) {
                $allChildren  [] = $subChildren[0];
            } else if (count($subChildren) > 1) {
                $allChildren += $subChildren;
            }
        }
    }
    $allChildren  [] = $this->id;//adds self Id to children Id list

    return $allChildren; 
}

the allChildren() returns , all of childrens as a simple Array .

Git Bash is extremely slow on Windows 7 x64

While your problem might be network-based, I've personally sped up my local git status calls tenfold (7+ seconds down to 700 ms) by doing two modifications. This is on a 700 MB repository with 21,000 files and excessive numbers of large binary files.

One is enabling parallel index preloads. From a command prompt:

git config core.preloadindex true
This changed time git status from 7 seconds to 2.5 seconds.

Update!

The following is no longer necessary. A patch has fixed this as of mysysgit 1.9.4
https://github.com/msysgit/git/commit/64d63240762df22e92b287b145d75a0d68a66988
However, you must enable the fix by typing
git config core.fscache true

I also disabled the UAC and the "luafv" driver (reboot required). This disables a driver in Windows Vista, 7 and 8 that redirects programs trying to write to system locations and instead redirects those accesses to a user directory.

To see a discussion on how this affects Git performance, read here: https://code.google.com/p/msysgit/issues/detail?id=320

To disable this driver, in regedit, change the "start" key at HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/luafv to 4 to disable the driver. Then, put UAC to its lowest setting, "never notify".

If the disabling of this driver makes you wary (it should), an alternative is running on a drive (or partition) different than your system partition. Apparently the driver only runs on file access on the system partition. I have a second hard drive and see identical results when run with this registry modification on my C drive as I do without it on the D drive.

This change takes time git status from 2.5 seconds down to 0.7 seconds.

You also might want to follow https://github.com/msysgit/git/pull/94 and https://github.com/git/git/commit/d637d1b9a8fb765a8542e69bd2e04b3e229f663b to check out what additional work is underway for speed issues in Windows.

What is the reason for the error message "System cannot find the path specified"?

You just need to:

Step 1: Go home directory of C:\ with typing cd.. (2 times)

Step 2: It appears now C:\>

Step 3: Type dir Windows\System32\run

That's all, it shows complete files & folder details inside target folder.

enter image description here

Details: I used Windows\System32\com folder as example, you should type your own folder name etc. Windows\System32\run

How to Position a table HTML?

As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.

To position an element, a <table> in your case you want to use either padding or margins.

the difference between margins and paddings can be seen as the "box model":

box model image

Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.

I highly recommend the article above if you need to learn how to use CSS.

To move the table down and right I would use margins like so:

table{
    margin:25px 0 0 25px;
}

This is in shorthand so the margins are as follows:

margin: top right bottom left;

How do I pass options to the Selenium Chrome driver using Python?

Found the chrome Options class in the Selenium source code.

Usage to create a Chrome driver instance:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=chrome_options)

Python and JSON - TypeError list indices must be integers not str

You can simplify your code down to

url = "http://worldcup.kimonolabs.com/api/players?apikey=xxx"
json_obj = urllib2.urlopen(url).read
player_json_list = json.loads(json_obj)
for player in readable_json_list:
    print player['firstName']

You were trying to access a list element using dictionary syntax. the equivalent of

foo = [1, 2, 3, 4]
foo["1"]

It can be confusing when you have lists of dictionaries and keeping the nesting in order.

How to set a fixed width column with CSS flexbox

In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.

flex-basis: 25%;

This will be a lot smoother when testing.

// VARIABLES
$screen-xs:                                         480px;
$screen-sm:                                         768px;
$screen-md:                                         992px;
$screen-lg:                                         1200px;
$screen-xl:                                         1400px;
$screen-xxl:                                        1600px;

// QUERIES
@media screen (max-width: $screen-lg) {
    flex-basis: 25%;
}

@media screen (max-width: $screen-md) {
    flex-basis: 33.33%;
}

What is the preferred Bash shebang?

Using a shebang line to invoke the appropriate interpreter is not just for BASH. You can use the shebang for any interpreted language on your system such as Perl, Python, PHP (CLI) and many others. By the way, the shebang

#!/bin/sh -

(it can also be two dashes, i.e. --) ends bash options everything after will be treated as filenames and arguments.

Using the env command makes your script portable and allows you to setup custom environments for your script hence portable scripts should use

#!/usr/bin/env bash

Or for whatever the language such as for Perl

#!/usr/bin/env perl

Be sure to look at the man pages for bash:

man bash

and env:

man env

Note: On Debian and Debian-based systems, like Ubuntu, sh is linked to dash not bash. As all system scripts use sh. This allows bash to grow and the system to stay stable, according to Debian.

Also, to keep invocation *nix like I never use file extensions on shebang invoked scripts, as you cannot omit the extension on invocation on executables as you can on Windows. The file command can identify it as a script.

Get total size of file in bytes

You can use the length() method on File which returns the size in bytes.

React: trigger onChange if input value is changing by state?

The other answers talked about direct binding in render hence I want to add few points regarding that.

You are not recommended to bind the function directly in render or anywhere else in the component except in constructor. Because for every function binding a new function/object will be created in webpack bundle js file hence the bundle size will grow. Your component will re-render for many reasons like when you do setState, new props received, when you do this.forceUpdate() etc. So if you directly bind your function in render it will always create a new function. Instead do function binding always in constructor and call the reference wherever required. In this way it creates new function only once because constructor gets called only once per component.

How you should do is something like below

constructor(props){
  super(props);
  this.state = {
    value: 'random text'
  }
  this.handleChange = this.handleChange.bind(this);
}

handleChange (e) {
  console.log('handle change called');
  this.setState({value: e.target.value});
}

<input value={this.state.value} onChange={this.handleChange}/>

You can also use arrow functions but arrow functions also does create new function every time the component re-renders in certain cases. You should know about when to use arrow function and when are not suppose to. For detailed explation about when to use arrow functions check the accepted answer here

How to recover deleted rows from SQL server table?

You have Full data + Transaction log backups, right? You can restore to another Database from backups and then sync the deleted rows back. Lots of work though...

(Have you looked at Redgate's SQL Log Rescue? Update: it's SQL Server 2000 only)

There is Log Explorer

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

Although this may not solve your problem, it did for me when I wanted to do a similar thing. Instead of setting the header I used the footer of the section above. What saved me was that this section was small and static in nature, so it never scrolled below the bottom of the view.

<SELECT multiple> - how to allow only one item selected?

Late to answer but might help someone else, here is how to do it without removing the 'multiple' attribute.

$('.myDropdown').chosen({
    //Here you can change the value of the maximum allowed options
    max_selected_options: 1
});

Combining border-top,border-right,border-left,border-bottom in CSS

I can relate to the problem, there should be a shorthand like...

border: 1px solid red top bottom left;

Of course that doesn't work! Kobi's answer gave me an idea. Let's say you want to do top, bottom and left, but not right. Instead of doing border-top: border-left: border-bottom: (three statements) you could do two like this, the zero cancels out the right side.

border: 1px dashed yellow;
border-width:1px 0 1px 1px;

Two statements instead of three, small improvement :-D

H.264 file size for 1 hr of HD video

It really depends on many settings, on both the audio and video side of things. If you follow the compression-settings of this video, then it's approximately 3GB per hour. If you have a Mac, I would definitely recommend using 'Compressor' as it is fairly easy to use and works flawless.

As far as storage is concerned, if you're looking at 100hrs / 300GB, I would definitely go with an external hard drive. Video files are so huge, that they (even if they don't totally fill up your hard disk) really do confuse your computer. Make sure to make some time for compressing the whole thing because it takes hours and hours and hours.... for 100 hrs worth of footage, it'll take days.

What is the best way to redirect a page using React Router?

One of the simplest way: use Link as follows:

import { Link } from 'react-router-dom';

<Link to={`your-path`} activeClassName="current">{your-link-name}</Link>

If we want to cover the whole div section as link:

 <div>
     <Card as={Link} to={'path-name'}>
         .... 
           card content here
         ....
     </Card>
 </div>

How to consume a SOAP web service in Java

Here you can find a nice tutorial of how you can create and consume a SOAP service through WSDL. Long story short you need to call wsimport tool from command line (you can find it in your jdk) with parameters like -s (source for .java files) -d (destination for .class files) and the wsdl link.

$ wsimport -s "C:\workspace\soap\src\main\java\com\test\soap\ws" -d "C:\workspace\soap\target\classes\com\test\soap\ws" http://localhost:8855/soap/test?wsdl

After the stubs are created, you can call the webservices very easy something like:

TestHarnessService harnessService = new TestHarnessService();
ITestApi testApi = harnessService.getBasicHttpBindingITestApi();
testApi.resetLogMemoryTarget();

Set angular scope variable in markup

You can use ng-init as shown below

<div class="TotalForm">
  <label>B/W Print Total</label>
  <div ng-init="{{BWCount=(oMachineAccounts|sumByKey:'BWCOUNT')}}">{{BWCount}}</div>
</div>
<div class="TotalForm">
  <label>Color Print Total</label>
  <div ng-init="{{ColorCount=(oMachineAccounts|sumByKey:'COLORCOUNT')}}">{{ColorCount}}</div>
</div>

and then use the local scope variable in other sections:

<div>Total: BW: {{BWCount}}</div>
<div>Total: COLOR: {{ColorCount}}</div>

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

SOLUTION!

just set -config parameter location correctly, i.e :

openssl ....................  -config C:\bin\apache\apache2.4.9\conf\openssl.cnf

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

JQuery - File attributes

Just try

var file = $("#uploadedfile").prop("files")[0];
var fileName = file.name;
var fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");

It worked for me

How do I declare and assign a variable on a single line in SQL

Here goes:

DECLARE @var nvarchar(max) = 'Man''s best friend';

You will note that the ' is escaped by doubling it to ''.

Since the string delimiter is ' and not ", there is no need to escape ":

DECLARE @var nvarchar(max) = '"My Name is Luca" is a great song';

The second example in the MSDN page on DECLARE shows the correct syntax.

MySQL - Get row number on select

Take a look at this.

Change your query to:

SET @rank=0;
SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount
  FROM orders
  GROUP BY itemID
  ORDER BY ordercount DESC;
SELECT @rank;

The last select is your count.

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

Recursively update Windows 7 until it shows no more updates, using Windows Update check option in Windows 7.

Then download and install Visual C++ Redistributable vc_redist.x64.exe from the Windows website.

Then try to run Apache server.

How do I remove whitespace from the end of a string in Python?

>>> "    xyz     ".rstrip()
'    xyz'

There is more about rstrip in the documentation.

How to disable auto-play for local video in iframe

If you are using HTML5, using the Video tag is suitable for this purpose.

You can use the Video Tag this way for no autoplay:

<video width="320" height="240" controls>
    <source src="videos/example.mp4" type="video/mp4">
</video>

To enable auto-play,

<video width="320" height="240" controls autoplay>
    <source src="videos/example.mp4" type="video/mp4">
</video>

How to perform a for loop on each character in a string in Bash?

#!/bin/bash

word=$(echo 'Your Message' |fold -w 1)

for letter in ${word} ; do echo "${letter} is a letter"; done

Here is the output:

Y is a letter o is a letter u is a letter r is a letter M is a letter e is a letter s is a letter s is a letter a is a letter g is a letter e is a letter

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

I had the following property working for me in IntelliJ 2017

  <properties>
        <java.version>1.8</java.version>       
  </properties>

How to get a value from a cell of a dataframe?

The quickest/easiest options I have found are the following. 501 represents the row index.

df.at[501,'column_name']
df.get_value(501,'column_name')

Cache busting via params

Hope this should help you to inject external JS file

<script type="text/javascript"> 
var cachebuster = Math.round(new Date().getTime() / 1000); 
document.write('<scr'+'ipt type="text/javascript" src="external.js?cb=' +cachebuster+'"></scr' + 'ipt>');
</script>

Source - Cachebuster code in JavaScript

Calculating percentile of dataset column

The quantile() function will do much of what you probably want, but since the question was ambiguous, I will provide an alternate answer that does something slightly different from quantile().

ecdf(infert$age)(infert$age)

will generate a vector of the same length as infert$age giving the proportion of infert$age that is below each observation. You can read the ecdf documentation, but the basic idea is that ecdf() will give you a function that returns the empirical cumulative distribution. Thus ecdf(X)(Y) is the value of the cumulative distribution of X at the points in Y. If you wanted to know just the probability of being below 30 (thus what percentile 30 is in the sample), you could say

ecdf(infert$age)(30)

The main difference between this approach and using the quantile() function is that quantile() requires that you put in the probabilities to get out the levels, and this requires that you put in the levels to get out the probabilities.

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

For Intellij users the following worked for me:

Right click on your package

Maven > Reimport 

and

Maven > Generate Sources and Update Folders

Get original URL referer with PHP?

try this

(isset ($_SERVER['HTTP_CLIENT_IP']) ? 
    $_SERVER['HTTP_CLIENT_IP'] : 
    (isset ($_SERVER['HTTP_X_FORWARDED_FOR']) ? 
        $_SERVER['HTTP_X_FORWARDED_FOR'] : 
        $_SERVER['REMOTE_ADDR']
    )
)

How to add a new object (key-value pair) to an array in javascript?

If you're doing jQuery, and you've got a serializeArray thing going on concerning your form data, such as :

var postData = $('#yourform').serializeArray();

// postData (array with objects) : 
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, etc]

...and you need to add a key/value to this array with the same structure, for instance when posting to a PHP ajax request then this :

postData.push({"name": "phone", "value": "1234-123456"});

Result:

// postData : 
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, {"name":"phone","value":"1234-123456"}]

GDB: break if variable equal value

You can use a watchpoint for this (A breakpoint on data instead of code).

You can start by using watch i.
Then set a condition for it using condition <breakpoint num> i == 5

You can get the breakpoint number by using info watch

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

Trim spaces from start and end of string

If using jQuery is an option:

/**
 * Trim the site input[type=text] fields globally by removing any whitespace from the
 * beginning and end of a string on input .blur()
 */
$('input[type=text]').blur(function(){
    $(this).val($.trim($(this).val()));
});

or simply:

$.trim(string);

How to insert a new line in Linux shell script?

echo $'Create the snapshots\nSnapshot created\n'

How do I create a table based on another table

select * into newtable from oldtable

Get domain name from given url

private static final String hostExtractorRegexString = "(?:https?://)?(?:www\\.)?(.+\\.)(com|au\\.uk|co\\.in|be|in|uk|org\\.in|org|net|edu|gov|mil)";
private static final Pattern hostExtractorRegexPattern = Pattern.compile(hostExtractorRegexString);

public static String getDomainName(String url){
    if (url == null) return null;
    url = url.trim();
    Matcher m = hostExtractorRegexPattern.matcher(url);
    if(m.find() && m.groupCount() == 2) {
        return m.group(1) + m.group(2);
    }
    return null;
}

Explanation : The regex has 4 groups. The first two are non-matching groups and the next two are matching groups.

The first non-matching group is "http" or "https" or ""

The second non-matching group is "www." or ""

The second matching group is the top level domain

The first matching group is anything after the non-matching groups and anything before the top level domain

The concatenation of the two matching groups will give us the domain/host name.

PS : Note that you can add any number of supported domains to the regex.

Wait for a void async method

do a AutoResetEvent, call the function then wait on AutoResetEvent and then set it inside async void when you know it is done.

You can also wait on a Task that returns from your void async

How to print object array in JavaScript?

Not sure about the subelements, but all browsers should support this now:

for (val of lineChartData) {
  document.write(val);
}

This might give you some ideas For-each over an array in JavaScript?

sprintf like functionality in Python

I'm not completely certain that I understand your goal, but you can use a StringIO instance as a buffer:

>>> import StringIO 
>>> buf = StringIO.StringIO()
>>> buf.write("A = %d, B = %s\n" % (3, "bar"))
>>> buf.write("C=%d\n" % 5)
>>> print(buf.getvalue())
A = 3, B = bar
C=5

Unlike sprintf, you just pass a string to buf.write, formatting it with the % operator or the format method of strings.

You could of course define a function to get the sprintf interface you're hoping for:

def sprintf(buf, fmt, *args):
    buf.write(fmt % args)

which would be used like this:

>>> buf = StringIO.StringIO()
>>> sprintf(buf, "A = %d, B = %s\n", 3, "foo")
>>> sprintf(buf, "C = %d\n", 5)
>>> print(buf.getvalue())
A = 3, B = foo
C = 5

How can I delete a query string parameter in JavaScript?

function removeQueryStringParameter(uri, key, value) 
{

var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");

    var separator = uri.indexOf('?') !== -1 ? "&" : "?";

    if (uri.match(re)) {

        return uri.replace(re, '');

    }
}

Formatting text in a TextBlock

There are various Inline elements that can help you, for the simplest formatting options you can use Bold, Italic and Underline:

<TextBlock>
    Sample text with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> words.
</TextBlock>

enter image description here

I think it is worth noting, that those elements are in fact just shorthands for Span elements with various properties set (i.e.: for Bold, the FontWeight property is set to FontWeights.Bold).

This brings us to our next option: the aforementioned Span element.

You can achieve the same effects with this element as above, but you are granted even more possibilities; you can set (among others) the Foreground or the Background properties:

<TextBlock>
    Sample text with <Span FontWeight="Bold">bold</Span>, <Span FontStyle="Italic">italic</Span> and <Span TextDecorations="Underline">underlined</Span> words. <Span Foreground="Blue">Coloring</Span> <Span Foreground="Red">is</Span> <Span Background="Cyan">also</Span> <Span Foreground="Silver">possible</Span>.
</TextBlock>

enter image description here

The Span element may also contain other elements like this:

<TextBlock>
    <Span FontStyle="Italic">Italic <Span Background="Yellow">text</Span> with some <Span Foreground="Blue">coloring</Span>.</Span>
</TextBlock>

enter image description here

There is another element, which is quite similar to Span, it is called Run. The Run cannot contain other inline elements while the Span can, but you can easily bind a variable to the Run's Text property:

<TextBlock>
    Username: <Run FontWeight="Bold" Text="{Binding UserName}"/>
</TextBlock>

enter image description here

Also, you can do the whole formatting from code-behind if you prefer:

TextBlock tb = new TextBlock();
tb.Inlines.Add("Sample text with ");
tb.Inlines.Add(new Run("bold") { FontWeight = FontWeights.Bold });
tb.Inlines.Add(", ");
tb.Inlines.Add(new Run("italic ") { FontStyle = FontStyles.Italic });
tb.Inlines.Add("and ");
tb.Inlines.Add(new Run("underlined") { TextDecorations = TextDecorations.Underline });
tb.Inlines.Add("words.");

How to get cookie's expire time

Putting an encoded json inside the cookie is my favorite method, to get properly formated data out of a cookie. Try that:

$expiry = time() + 12345;
$data = (object) array( "value1" => "just for fun", "value2" => "i'll save whatever I want here" );
$cookieData = (object) array( "data" => $data, "expiry" => $expiry );
setcookie( "cookiename", json_encode( $cookieData ), $expiry );

then when you get your cookie next time:

$cookie = json_decode( $_COOKIE[ "cookiename" ] );

you can simply extract the expiry time, which was inserted as data inside the cookie itself..

$expiry = $cookie->expiry;

and additionally the data which will come out as a usable object :)

$data = $cookie->data;
$value1 = $cookie->data->value1;

etc. I find that to be a much neater way to use cookies, because you can nest as many small objects within other objects as you wish!

Sort a list of tuples by 2nd item (integer value)

From python wiki:

>>> from operator import itemgetter, attrgetter    
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]    
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

How to search for a string in cell array in MATLAB?

>> strs = {'HA' 'KU' 'LA' 'MA' 'TATA'};
>> tic; ind=find(ismember(strs,'KU')); toc

Elapsed time is 0.001976 seconds.

>> tic; find(strcmp('KU', strs)); toc

Elapsed time is 0.000014 seconds.

SO, clearly strcmp('KU', strs) takes much lesser time than ismember(strs,'KU')

jQuery ui datepicker with Angularjs

var selectDate = element.datepicker({
    dateFormat:'dd/mm/yy',
    onSelect:function (date) {
        ngModelCtrl.$setViewValue(date);
        scope.$apply();
    }
}).on('changeDate', function(ev) {
    selectDate.hide();
    ngModelCtrl.$setViewValue(element.val());
    scope.$apply();
});                            

Run cron job only if it isn't already running

# one instance only (works unless your cmd has 'grep' in it)
ALREADY_RUNNING_EXIT_STATUS=0
bn=`basename $0`
proc=`ps -ef | grep -v grep | grep "$bn" | grep -v " $$ "`
[ $? -eq 0 ] && {
    pid=`echo $proc | awk '{print $2}'`
    echo "$bn already running with pid $pid"
    exit $ALREADY_RUNNING_EXIT_STATUS
}

UPDATE .. better way using flock:

/usr/bin/flock -n /tmp/your-app.lock /path/your-app args 

What Are The Best Width Ranges for Media Queries

Try this one with retina display

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

Update

/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width: 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width: 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) {
  /* Styles */
}

/* iPad 3 (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPad 3 (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen and (min-width: 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen and (min-width: 1824px) {
  /* Styles */
}

/* iPhone 4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (landscape) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (portrait) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (landscape) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (portrait) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (landscape) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (portrait) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

How to Deserialize XML document

Here's a working version. I changed the XmlElementAttribute labels to XmlElement because in the xml the StockNumber, Make and Model values are elements, not attributes. Also I removed the reader.ReadToEnd(); (that function reads the whole stream and returns a string, so the Deserialize() function couldn't use the reader anymore...the position was at the end of the stream). I also took a few liberties with the naming :).

Here are the classes:

[Serializable()]
public class Car
{
    [System.Xml.Serialization.XmlElement("StockNumber")]
    public string StockNumber { get; set; }

    [System.Xml.Serialization.XmlElement("Make")]
    public string Make { get; set; }

    [System.Xml.Serialization.XmlElement("Model")]
    public string Model { get; set; }
}


[Serializable()]
[System.Xml.Serialization.XmlRoot("CarCollection")]
public class CarCollection
{
    [XmlArray("Cars")]
    [XmlArrayItem("Car", typeof(Car))]
    public Car[] Car { get; set; }
}

The Deserialize function:

CarCollection cars = null;
string path = "cars.xml";

XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));

StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();

And the slightly tweaked xml (I needed to add a new element to wrap <Cars>...Net is picky about deserializing arrays):

<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>

Sticky and NON-Sticky sessions

I've made an answer with some more details here : https://stackoverflow.com/a/11045462/592477

Or you can read it there ==>

When you use loadbalancing it means you have several instances of tomcat and you need to divide loads.

  • If you're using session replication without sticky session : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send some of these requests to the first tomcat instance, and send some other of these requests to the secondth instance, and other to the third.
  • If you're using sticky session without replication : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send the first user request to one of the three tomcat instances, and all the other requests that are sent by this user during his session will be sent to the same tomcat instance. During these requests, if you shutdown or restart this tomcat instance (tomcat instance which is used) the loadbalancer sends the remaining requests to one other tomcat instance that is still running, BUT as you don't use session replication, the instance tomcat which receives the remaining requests doesn't have a copy of the user session then for this tomcat the user begin a session : the user loose his session and is disconnected from the web app although the web app is still running.
  • If you're using sticky session WITH session replication : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send the first user request to one of the three tomcat instances, and all the other requests that are sent by this user during his session will be sent to the same tomcat instance. During these requests, if you shutdown or restart this tomcat instance (tomcat instance which is used) the loadbalancer sends the remaining requests to one other tomcat instance that is still running, as you use session replication, the instance tomcat which receives the remaining requests has a copy of the user session then the user keeps on his session : the user continue to browse your web app without being disconnected, the shutdown of the tomcat instance doesn't impact the user navigation.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

Include .so library in apk in android studio

I had the same problem. Check out the comment in https://gist.github.com/khernyo/4226923#comment-812526

It says:

for gradle android plugin v0.3 use "com.android.build.gradle.tasks.PackageApplication"

That should fix your problem.

MySQL: How to copy rows, but change a few fields?

If you have loads of columns in your table and don't want to type out each one you can do it using a temporary table, like;

SELECT *
INTO #Temp
FROM Table WHERE Event_ID = "120"
GO

UPDATE #TEMP
SET Column = "Changed"
GO

INSERT INTO Table
SELECT *
FROM #Temp

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

To get multiple stats, collapse the index, and retain column names:

df = df.groupby(['col1','col2']).agg(['mean', 'count'])
df.columns = [ ' '.join(str(i) for i in col) for col in df.columns]
df.reset_index(inplace=True)
df

Produces:

**enter image description here**

Creating a Plot Window of a Particular Size

A convenient function for saving plots is ggsave(), which can automatically guess the device type based on the file extension, and smooths over differences between devices. You save with a certain size and units like this:

ggsave("mtcars.png", width = 20, height = 20, units = "cm")

In R markdown, figure size can be specified by chunk:

```{r, fig.width=6, fig.height=4}  
plot(1:5)
```

How can I remove a child node in HTML using JavaScript?

    var p=document.getElementById('childId').parentNode;
    var c=document.getElementById('childId');
    p.removeChild(c);
    alert('Deleted');

p is parent node and c is child node
parentNode is a JavaScript variable which contains parent reference

Easy to understand

Java - Best way to print 2D array?

That's the best I guess:

   for (int[] row : matrix){
    System.out.println(Arrays.toString(row));
   }

Executing Shell Scripts from the OS X Dock?

In the Script Editor:

do shell script "/full/path/to/your/script -with 'all desired args'"

Save as an application bundle.

As long as all you want to do is get the effect of the script, this will work fine. You won't see STDOUT or STDERR.

Compile/run assembler in Linux?

For Ubuntu 18.04 installnasm . Open the terminal and type:

sudo apt install as31 nasm

nasm docs

For compiling and running:

nasm -f elf64 example.asm # assemble the program  
ld -s -o example example.o # link the object file nasm produced into an executable file  
./example # example is an executable file

Where is web.xml in Eclipse Dynamic Web Project

If your deployment descriptor tab is disabled, then click on update libraries it will also do your work. It will create. Xml file in Web content

How can I connect to a Tor hidden service using cURL in PHP?

Try to add this:

curl_setopt($ch, CURLOPT_HEADER, 1); 
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); 

How to get the selected value from RadioButtonList?

The ASPX code will look something like this:

 <asp:RadioButtonList ID="rblist1" runat="server">

    <asp:ListItem Text ="Item1" Value="1" />
    <asp:ListItem Text ="Item2" Value="2" />
    <asp:ListItem Text ="Item3" Value="3" />
    <asp:ListItem Text ="Item4" Value="4" />

    </asp:RadioButtonList>

    <asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" />

And the code behind:

protected void Button1_Click(object sender, EventArgs e)
        {
            string selectedValue = rblist1.SelectedValue;
            Response.Write(selectedValue);
        }

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

There are a lot of different ways to look at this decision from development, IT, and business objectives, so don't feel bad if it seems overwhelming. But also - don't overthink scalability.

Think about your requirements.

I've engineered websites which have serviced over 8M uniques a day and delivered terabytes of video a week built on infrastructures starting at $250k in capital hardware unr by a huge $MM IT labor staff.

But I've also had smaller websites which were designed to generate $10-$20k per year, didn't have very high traffic, db or processing requirements, and I ran those off a $10/mo generic hosting account without compromise.

In the future, deployment will look more like Heroku than AWS, just because of progress. There is zero value in the IT knob-turning of scaling internet infrastructures which isn't increasingly automatable, and none of it has anything to do with the value of the product or service you are offering.

Also, keep in mind with a commercial website - scalability is what we often call a 'good problem to have' - although scalability issues with sites like Facebook and Twitter were very high-profile, they had zero negative effect on their success - the news might have even contributed to more signups (all press is good press).

If you have a service which is generating a 100k+ uniques a day and having scaling issues, I'd be glad to take it off your hands for you no matter what the language, db, platform, or infrastructure you are running on!

Scalability is a fixable implementation problem - not having customers is an existential issue.

Using generic std::function objects with member functions in one class

A non-static member function must be called with an object. That is, it always implicitly passes "this" pointer as its argument.

Because your std::function signature specifies that your function doesn't take any arguments (<void(void)>), you must bind the first (and the only) argument.

std::function<void(void)> f = std::bind(&Foo::doSomething, this);

If you want to bind a function with parameters, you need to specify placeholders:

using namespace std::placeholders;
std::function<void(int,int)> f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2);

Or, if your compiler supports C++11 lambdas:

std::function<void(int,int)> f = [=](int a, int b) {
    this->doSomethingArgs(a, b);
}

(I don't have a C++11 capable compiler at hand right now, so I can't check this one.)

Call break in nested if statements

To make multiple checking statements more readable (and avoid nested ifs):

var tmp = 'Test[[email protected]]';

var posStartEmail = undefined;
var posEndEmail = undefined;
var email = undefined;

do {
    if (tmp.toLowerCase().substring(0,4) !== 'test') { break; }

    posStartEmail = tmp.toLowerCase().substring(4).indexOf('[');
    posEndEmail = tmp.toLowerCase().substring(4).indexOf(']');

    if (posStartEmail === -1 || posEndEmail === -1) { break; }

    email = tmp.substring(posStartEmail+1+4,posEndEmail);

    if (email.indexOf('@') === -1) { break; }

// all checks are done - do what you intend to do

    alert ('All checks are ok')

    break; // the most important break of them all

} while(true);

Best way to do multiple constructors in PHP

I created this method to let use it not only on constructors but in methods:

My constructor:

function __construct() {
    $paramsNumber=func_num_args();
    if($paramsNumber==0){
        //do something
    }else{
        $this->overload('__construct',func_get_args());
    }
}

My doSomething method:

public function doSomething() {
    $paramsNumber=func_num_args();
    if($paramsNumber==0){
        //do something
    }else{
        $this->overload('doSomething',func_get_args());
    }
}

Both works with this simple method:

public function overloadMethod($methodName,$params){
    $paramsNumber=sizeof($params);
    //methodName1(), methodName2()...
    $methodNameNumber =$methodName.$paramsNumber;
    if (method_exists($this,$methodNameNumber)) {
        call_user_func_array(array($this,$methodNameNumber),$params);
    }
}

So you can declare

__construct1($arg1), __construct2($arg1,$arg2)...

or

methodName1($arg1), methodName2($arg1,$arg2)...

and so on :)

And when using:

$myObject =  new MyClass($arg1, $arg2,..., $argN);

it will call __constructN, where you defined N args

then $myObject -> doSomething($arg1, $arg2,..., $argM)

it will call doSomethingM, , where you defined M args;

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

How to get the filename without the extension from a path in Python?

Use .stem from pathlib in Python 3.4+

from pathlib import Path

Path('/root/dir/sub/file.ext').stem

will return

'file'

Note that if your file has multiple extensions .stem will only remove the last extension. For example, Path('file.tar.gz').stem will return 'file.tar'.

python - checking odd/even numbers and changing outputs on number size

My solution basically we have two string and with the & we get the right index:

res = ["Even", "Odd"]
print(res[x & 1])

Please note that it seems slower than other alternatives:

#!/usr/bin/env python3
import math
import random
from timeit import timeit

res = ["Even", "Odd"]

def foo(x):
    return res[x & 1]

def bar(x):
    if x & 1:
        return "Odd"
    return "Even"

la = lambda x : "Even" if not x % 2 else "Odd"

iter = 10000000

time = timeit('bar(random.randint(1, 1000))', "from __main__ import bar, random", number=iter)
print(time)
time = timeit('la(random.randint(1, 1000))', "from __main__ import la, random", number=iter)
print(time)
time = timeit('foo(random.randint(1, 1000))', "from __main__ import foo, random", number=iter)
print(time)

output:
8.05739480999182
8.170479692984372
8.892275177990086

Scala: what is the best way to append an element to an Array?

val array2 = array :+ 4
//Array(1, 2, 3, 4)

Works also "reversed":

val array2 = 4 +: array
Array(4, 1, 2, 3)

There is also an "in-place" version:

var array = Array( 1, 2, 3 )
array +:= 4
//Array(4, 1, 2, 3)
array :+= 0
//Array(4, 1, 2, 3, 0)

Is there an equivalent of 'which' on the Windows command line?

I have created tool similar to Ned Batchelder:

Searching .dll and .exe files in PATH

While my tool is primarly for searching of various dll versions it shows more info (date, size, version) but it do not use PATHEXT (I hope to update my tool soon).

How to get file creation & modification date/times in Python?

It may worth taking a look at the crtime library which implements cross-platform access to the file creation time.

from crtime import get_crtimes_in_dir

for fname, date in get_crtimes_in_dir(".", raise_on_error=True, as_epoch=False):
    print(fname, date)
    # file_a.py Mon Mar 18 20:51:18 CET 2019

Fastest way to download a GitHub project

There is a new (sometime pre April 2013) option on the site that says "Clone in Windows".

This works very nicely if you already have the Windows GitHub Client as mentioned by @Tommy in his answer on this related question (How to download source in ZIP format from GitHub?).

Use space as a delimiter with cut command

I just discovered that you can also use "-d ":

cut "-d "

Test

$ cat a
hello how are you
I am fine
$ cut "-d " -f2 a
how
am

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

  1. Download apache-maven-3.3.9-bin.zip file and extract it.

  2. Then set system variable M2_HOME = B:\sql software\apache-maven-3.3.9 or as appropriate

  3. Also set variable M2 = %M2_HOME%\bin

  4. Open CMD and write mvn

I solved thank you

Getting XML Node text value with Java DOM

If you are open to vtd-xml, which excels at both performance and memory efficiency, below is the code to do what you are looking for...in both XPath and manual navigation... the overall code is much concise and easier to understand ...

import com.ximpleware.*;
public class queryText {
    public static void main(String[] s) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", true))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        // first manually navigate
        if(vn.toElement(VTDNav.FC,"tag")){
            int i= vn.getText();
            if (i!=-1){
                System.out.println("text ===>"+vn.toString(i));
            }
            if (vn.toElement(VTDNav.NS,"tag")){
                i=vn.getText();
                System.out.println("text ===>"+vn.toString(i));
            }
        }

        // second version use XPath
        ap.selectXPath("/add/tag/text()");
        int i=0;
        while((i=ap.evalXPath())!= -1){
            System.out.println("text node ====>"+vn.toString(i));
        }
    }
}

How can I disable an <option> in a <select> based on its value in JavaScript?

You can also use this function,

function optionDisable(selectId, optionIndices)
{
    for (var idxCount=0; idxCount<optionIndices.length;idxCount++)
    {
        document.getElementById(selectId).children[optionIndices[idxCount]].disabled="disabled";
        document.getElementById(selectId).children[optionIndices[idxCount]].style.backgroundColor = '#ccc';
        document.getElementById(selectId).children[optionIndices[idxCount]].style.color = '#f00';
    }
}

Returning a boolean value in a JavaScript function

You could simplify this a lot:

  • Check whether one is not empty
  • Check whether they are equal

This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:

function validatePassword()
{
   var password = document.getElementById("password");
   var confirm_password = document.getElementById("password_confirm");

   return password.value !== "" && password.value === confirm_password.value;
       //       not empty       and              equal
}

How is the java memory pool divided?

With Java8, non heap region no more contains PermGen but Metaspace, which is a major change in Java8, supposed to get rid of out of memory errors with java as metaspace size can be increased depending on the space required by jvm for class data.

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

Subset data.frame by date

The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input

class(EPL2011_12$Date)

The output should read [1] "Date". If it doesn't, you should format it as a date by inputting

EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")

Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command

EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")

Once you have it in Date format, you can use the subset command, or you can use brackets

WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]

Pass Arraylist as argument to function

It depends on how and where you declared your array list. If it is an instance variable in the same class like your AnalyseArray() method you don't have to pass it along. The method will know the list and you can simply use the A in whatever purpose you need.

If they don't know each other, e.g. beeing a local variable or declared in a different class, define that your AnalyseArray() method needs an ArrayList parameter

public void AnalyseArray(ArrayList<Integer> theList){}

and then work with theList inside that method. But don't forget to actually pass it on when calling the method.AnalyseArray(A);

PS: Some maybe helpful Information to Variables and parameters.

Intercept page exit event

Similar to Ghommey's answer, but this also supports old versions of IE and Firefox.

window.onbeforeunload = function (e) {
  var message = "Your confirmation message goes here.",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }

  // For Safari
  return message;
};

MySQL FULL JOIN?

Try This:

(SELECT p.LastName, p.FirstName, o.OrderNo
 FROM   Persons p
   LEFT JOIN Orders o
   ON o.OrderNo = p.P_id
)
UNION
(SELECT p.LastName, p.FirstName, o.OrderNo
 FROM   Persons p
   RIGHT JOIN Orders o
   ON o.OrderNo = p.P_id
);

+----------+-----------+---------+
| LastName | FirstName | OrderNo |
+----------+-----------+---------+
| Singh    | Shashi    |       1 |
| Yadav    | Sunil     |    NULL |
| Singh    | Satya     |    NULL |
| Jain     | Ankit     |    NULL |
| NULL     | NULL      |      11 |
| NULL     | NULL      |      12 |
| NULL     | NULL      |      13 |
+----------+-----------+---------+

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

I've solved the problem , and I will explain how :

  1. Download Github For Windows client and install it.
  2. After The client successfully installed , connect it with your github account.It should be easy , just follow the wizard.
  3. Then you should add git.exe location to your "Path Variable". The location you should add will probably be something like : C:\Users\Your_Username\AppData\Local\GitHub\PortableGit_ca477551eeb4aea0e4ae9fcd3358bd96720bb5c8\bin

Alternatively , if you don't want to add to environment variables. You can open the android studio and go to : Settings -> Version Control -> Git In text box next to "Path to Git Executable" you will see "git.exe" , just give it a full path like so : C:\Users\Your_Username\AppData\Local\GitHub\PortableGit_ca477551eeb4aea0e4ae9fcd3358bd96720bb5c8\bin\git.exe

Hope it saved your time . Happy coding :)

EDIT : For latest Github for windows versions some can find the git.exe under "...\cmd\git.exe" rather than "...\bin\git.exe".

Spring Security with roles and permissions

Just for sake of completeness (maybe someone else won't have to implement it from scratch):

We've implemented our own small library, as everyone else. It's supposed to make things easier, so that our developers don't have to reimplement it each time. It would be great if spring security would provide support of rbac out of the box, as this approach is much better than the default permission based one.

Have a look at Github (OSS, MIT license) to see if it suits your needs. It's basically only addressing the role <-> privileges mapping. The missing piece, you'll have to provide on your own is basically the user <-> roles mapping, e.g. by mapping groups (racf/ad groups) to roles (1:1) or by implementing an additional mapping. That one's different in each project, so it doesn't make sense to provide some implementation.

We've basically used this internally, so that we can start with rbac from the beginning. We can still replace it with some other implementation later on, if the application is growing, but it's important for us to get the setup right at the beginning.

If you don't use rbac, there's a good chance, that the permissions are scattered throughout the codebase and you'll have a hard time to extract/group those (into roles) later on. The generated graphs do also help to reason about it/restructure it later on.

SQL DELETE with JOIN another table for WHERE condition

How about:

DELETE guide_category  
  WHERE id_guide_category IN ( 

        SELECT id_guide_category 
          FROM guide_category AS gc
     LEFT JOIN guide AS g 
            ON g.id_guide = gc.id_guide
         WHERE g.title IS NULL

  )

How to implement band-pass Butterworth filter with Scipy.signal.butter

For a bandpass filter, ws is a tuple containing the lower and upper corner frequencies. These represent the digital frequency where the filter response is 3 dB less than the passband.

wp is a tuple containing the stop band digital frequencies. They represent the location where the maximum attenuation begins.

gpass is the maximum attenutation in the passband in dB while gstop is the attentuation in the stopbands.

Say, for example, you wanted to design a filter for a sampling rate of 8000 samples/sec having corner frequencies of 300 and 3100 Hz. The Nyquist frequency is the sample rate divided by two, or in this example, 4000 Hz. The equivalent digital frequency is 1.0. The two corner frequencies are then 300/4000 and 3100/4000.

Now lets say you wanted the stopbands to be down 30 dB +/- 100 Hz from the corner frequencies. Thus, your stopbands would start at 200 and 3200 Hz resulting in the digital frequencies of 200/4000 and 3200/4000.

To create your filter, you'd call buttord as

fs = 8000.0
fso2 = fs/2
N,wn = scipy.signal.buttord(ws=[300/fso2,3100/fso2], wp=[200/fs02,3200/fs02],
   gpass=0.0, gstop=30.0)

The length of the resulting filter will be dependent upon the depth of the stop bands and the steepness of the response curve which is determined by the difference between the corner frequency and stopband frequency.

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

I also had this problem today. Mine was caused by a cyclic dependency. Project A referenced Project B and vice versa.

Storing sex (gender) in database

I would go with Option 3 but multiple NON NULLABLE bit columns instead of one. IsMale (1=Yes / 0=No) IsFemale (1=Yes / 0=No)

if requried: IsUnknownGender (1=Yes / 0=No) and so on...

This makes for easy reading of the definitions, easy extensibility, easy programmability, no possibility of using values outside the domain and no requirement of a second lookup table+FK or CHECK constraints to lock down the values.

EDIT: Correction, you do need at least one constraint to ensure the set flags are valid.

How to redirect a page using onclick event in php?

you are using onclick which is javascript event. there is two ways

Javascript

<input type="button" value="Home" class="homebutton" id="btnHome" 
onClick="window.location = 'http://google.com'" />

Or PHP

create another page as redirect.php and put

<?php header('location : google.com') ?>

and insert this link on any page within the same directory

<a href="redirect.php">google<a/>

hope this helps its simplest!!

How do I delete virtual interface in Linux?

Have you tried:

ifconfig 10:35978f0 down

As the physical interface is 10 and the virtual aspect is after the colon :.

See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/

Verilog: How to instantiate a module

Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.

An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto and can afterwards be manually edited.

subcomponent subcomponent_instance_name(/*AUTOINST*/);

Expanded

subcomponent subcomponent_instance_name (/*AUTOINST*/
  //Inputs
  .clk,         (clk)           
  .rst_n,       (rst_n)
  .data_rx      (data_rx_1[9:0]),
  //Outputs
  .data_tx      (data_tx[9:0])
);

Implicit wires can be automated with /*AUTOWIRE*/. Check the link for further information.

encrypt and decrypt md5

Hashes can not be decrypted check this out.

If you want to encrypt-decrypt, use a two way encryption function of your database like - AES_ENCRYPT (in MySQL).

But I'll suggest CRYPT_BLOWFISH algorithm for storing password. Read this- http://php.net/manual/en/function.crypt.php and http://us2.php.net/manual/en/function.password-hash.php

For Blowfish by crypt() function -

crypt('String', '$2a$07$twentytwocharactersalt$');

password_hash will be introduced in PHP 5.5.

$options = [
    'cost' => 7,
    'salt' => 'BCryptRequires22Chrcts',
];
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);

Once you have stored the password, you can then check if the user has entered correct password by hashing it again and comparing it with the stored value.

Linq with group by having count

Below solution may help you.

var unmanagedDownloadcountwithfilter = from count in unmanagedDownloadCount.Where(d =>d.downloaddate >= startDate && d.downloaddate <= endDate)
group count by count.unmanagedassetregistryid into grouped
where grouped.Count() > request.Download
select new
{
   UnmanagedAssetRegistryID = grouped.Key,
   Count = grouped.Count()
};

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

Can't update data-attribute value

Had a similar problem, I propose this solution althought is not supported in IE 10 and under.

Given

<div id='example' data-example-update='1'></div>

The Javascript standard defines a property called dataset to update data-example-update.

document.getElementById('example').dataset.exampleUpdate = 2;

Note: use camel case notation to access the correct data attribute.

Source: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

Model backing a DB Context has changed; Consider Code First Migrations

You need to believe me. I got this error for the simple reason that I forgot to add the connection string in the App.Config(mine is a wpf project) of your startup project.

The entire config in my case

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="ZzaDbContext" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=ZaaDbInDepth;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

Manipulate a url string by adding GET parameters

$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

$queryString =  http_build_query($data);
//$queryString = foo=bar&baz=boom&cow=milk&php=hypertext+processor

echo 'http://domain.com?'.$queryString;
//output: http://domain.com?foo=bar&baz=boom&cow=milk&php=hypertext+processor

AutoComplete TextBox Control

    You can add a parameter in the query like @emailadd to be added in the aspx.cs file where the Stored Procedure is called with cmd.Parameter.AddWithValue.
    The trick is that the @emailadd parameter doesn't exist in the table design of the select query, but being added and inserted in the table.

    USE [DRDOULATINSTITUTE]
    GO
    /****** Object:  StoredProcedure [dbo].[ReikiInsertRow]    Script Date: 5/18/2016 11:12:33 AM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER procedure [dbo].[ReikiInsertRow]
    @Reiki varchar(100),
    @emailadd varchar(50)
    as
    insert into dbo.ReikiPowerDisplay
    select Reiki,ReikiDescription, @emailadd from ReikiPower
    where Reiki=@Reiki;

Posted By: Aneel Goplani. CIS. 2002. USA

Font awesome is not showing icon

I successfully installed Font Awesome using their CDN and javascript include (as described on this page). Then I tried to copy the HTML and CSS to some legacy pages and suddenly I saw empty square boxes instead of the icons.

I saw Daniel's answer (above) and because my legacy CSS file was huge (and years old) I suspected that was the issue. However when I looked in Chrome DevTools it really looked like Font Awesome was loaded:

Screenshot of CSS for Font Awesome Icon

I was expecting to see the font in strikeout if there was an issue... However I had really exhausted all my options so I checked the Computed Styles and saw clearly that the Font Awesome font was definitely not being used. (See the Rendered font at the bottom)

Font Awesome not being used

My legacy CSS file was a mess and I preferred not to touch it, so I cheated by doing this - please don't tell anyone :)

<a class="nav-link fa fa-instagram" style="font-family:FontAwesome;" href="//www.instagram.com/xxxx/" target="_blank"></a>

Also to note, when I upgraded from Font Awesome version 4.7.0 to version 5.4.1 this issue went away! I used this setup guide and this HTML

<a class="nav-link" href="//www.instagram.com/xxxx/" target="_blank"><i class="fab fa-instagram"></i></a>

How to give a Blob uploaded as FormData a file name?

It really depends on how the server on the other side is configured and with what modules for how it handles a blob post. You can try putting the desired name in the path for your post.

request.open(
    "POST",
    "/upload/myname.bmp",
    true
);

JBoss AS 7: How to clean up tmp?

Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :

-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache 
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440

error: request for member '..' in '..' which is of non-class type

If you want to declare a new substance with no parameter (knowing that the object have default parameters) don't write

 type substance1();

but

 type substance;

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

This can also be fixed by installing a node package manually.

npm install npm -g

The process of doing that will setup all the required directories.

Move existing, uncommitted work to a new branch in Git

If you have been making commits on your main branch while you coded, but you now want to move those commits to a different branch, this is a quick way:

  1. Copy your current history onto a new branch, bringing along any uncommitted changes too:

     git checkout -b <new-feature-branch>
    
  2. Now force the original "messy" branch to roll back: (without switching to it)

     git branch -f <previous-branch> <earlier-commit-id>
    

    For example:

     git branch -f master origin/master
    

    or if you had made 4 commits:

     git branch -f master HEAD~4
    

Warning: git branch -f master origin/master will reset the tracking information for that branch. So if you have configured your master branch to push to somewhere other than origin/master then that configuration will be lost.

Warning: If you rebase after branching, there is a danger that some commits may be lost, which is described here. The only way to avoid that is to create a new history using cherry-pick. That link describes the safest fool-proof method, although less convenient. (If you have uncommitted changes, you may need to git stash at the start and git stash pop at the end.)

find difference between two text files with one item per line

A tried a slight variation on Luca's answer and it worked for me.

diff file1 file2 | grep ">" | sed 's/^> //g' > diff_file

Note that the searched pattern in sed is a > followed by a space.

Reading *.wav files in Python

Using the struct module, you can take the wave frames (which are in 2's complementary binary between -32768 and 32767 (i.e. 0x8000 and 0x7FFF). This reads a MONO, 16-BIT, WAVE file. I found this webpage quite useful in formulating this:

import wave, struct

wavefile = wave.open('sine.wav', 'r')

length = wavefile.getnframes()
for i in range(0, length):
    wavedata = wavefile.readframes(1)
    data = struct.unpack("<h", wavedata)
    print(int(data[0]))

This snippet reads 1 frame. To read more than one frame (e.g., 13), use

wavedata = wavefile.readframes(13)
data = struct.unpack("<13h", wavedata)

Check if table exists and if it doesn't exist, create it in SQL Server 2008

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE  TABLE_NAME = 'd020915'))
BEGIN
  declare @result int
  set @result=1
  select @result as result
END

How do I import a .dmp file into Oracle?

I am Using Oracle Database Express Edition 11g Release 2.

Follow the Steps:

Open run SQl Command Line

Step 1: Login as system user

       SQL> connect system/tiger

Step 2 : SQL> CREATE USER UserName IDENTIFIED BY Password;

Step 3 : SQL> grant dba to UserName ;

Step 4 : SQL> GRANT UNLIMITED TABLESPACE TO UserName;

Step 5:

        SQL> CREATE BIGFILE TABLESPACE TSD_UserName
             DATAFILE 'tbs_perm_03.dat'
             SIZE 8G
             AUTOEXTEND ON;

Open Command Prompt in Windows or Terminal in Ubuntu. Then Type:

Note : if you Use Ubuntu then replace " \" to " /" in path.

Step 6: C:\> imp UserName/password@localhost file=D:\abc\xyz.dmp log=D:\abc\abc_1.log full=y;

Done....

I hope you Find Right solution here.

Thanks.

Fastest check if row exists in PostgreSQL

INSERT INTO target( userid, rightid, count )
  SELECT userid, rightid, count 
  FROM batch
  WHERE NOT EXISTS (
    SELECT * FROM target t2, batch b2
    WHERE t2.userid = b2.userid
    -- ... other keyfields ...
    )       
    ;

BTW: if you want the whole batch to fail in case of a duplicate, then (given a primary key constraint)

INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count 
FROM batch
    ;

will do exactly what you want: either it succeeds, or it fails.

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

Regex: match everything but specific pattern

Just match /^index\.php/ then reject whatever matches it.

How to return a part of an array in Ruby?

Yes, Ruby has very similar array-slicing syntax to Python. Here is the ri documentation for the array index method:

--------------------------------------------------------------- Array#[]
     array[index]                -> obj      or nil
     array[start, length]        -> an_array or nil
     array[range]                -> an_array or nil
     array.slice(index)          -> obj      or nil
     array.slice(start, length)  -> an_array or nil
     array.slice(range)          -> an_array or nil
------------------------------------------------------------------------
     Element Reference---Returns the element at index, or returns a 
     subarray starting at start and continuing for length elements, or 
     returns a subarray specified by range. Negative indices count 
     backward from the end of the array (-1 is the last element). 
     Returns nil if the index (or starting index) are out of range.

        a = [ "a", "b", "c", "d", "e" ]
        a[2] +  a[0] + a[1]    #=> "cab"
        a[6]                   #=> nil
        a[1, 2]                #=> [ "b", "c" ]
        a[1..3]                #=> [ "b", "c", "d" ]
        a[4..7]                #=> [ "e" ]
        a[6..10]               #=> nil
        a[-3, 3]               #=> [ "c", "d", "e" ]
        # special cases
        a[5]                   #=> nil
        a[6, 1]                #=> nil
        a[5, 1]                #=> []
        a[5..10]               #=> []

NumPy array initialization (fill with identical values)

You can use numpy.tile, e.g. :

v = 7
rows = 3
cols = 5
a = numpy.tile(v, (rows,cols))
a
Out[1]: 
array([[7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7]])

Although tile is meant to 'tile' an array (instead of a scalar, as in this case), it will do the job, creating pre-filled arrays of any size and dimension.

Postgres: How to do Composite keys?

The error you are getting is in line 3. i.e. it is not in

CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)

but earlier:

CREATE TABLE tags
     (
              (question_id, tag_id) NOT NULL,

Correct table definition is like pilcrow showed.

And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    UNIQUE (tag1, tag2, tag3)
);

or, if you want to have the constraint named according to your wish:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);

Checking something isEmpty in Javascript?

Empty check on a JSON's key depends on use-case. For a common use-case, we can test for following:

  1. Not null
  2. Not undefined
  3. Not an empty String ''
  4. Not an empty Object {} [] (Array is an Object)

Function:

function isEmpty(arg){
  return (
    arg == null || // Check for null or undefined
    arg.length === 0 || // Check for empty String (Bonus check for empty Array)
    (typeof arg === 'object' && Object.keys(arg).length === 0) // Check for empty Object or Array
  );
}

Return true for:

isEmpty(''); // Empty String
isEmpty(null); // null
isEmpty(); // undefined
isEmpty({}); // Empty Object
isEmpty([]); // Empty Array

How to cast List<Object> to List<MyClass>

You can do something like this

List<Customer> cusList = new ArrayList<Customer>();

for(Object o: list){        
    cusList.add((Customer)o);        
}

return cusList; 

Or the Java 8 way

list.stream().forEach(x->cusList.add((Customer)x))

return cuslist;

How to get mouse position in jQuery without mouse-events?

use window.event - it contains last event and as any event contains pageX, pageY etc. Works for Chrome, Safari, IE but not FF.

Method has the same erasure as another method in type

Java generics uses type erasure. The bit in the angle brackets (<Integer> and <String>) gets removed, so you'd end up with two methods that have an identical signature (the add(Set) you see in the error). That's not allowed because the runtime wouldn't know which to use for each case.

If Java ever gets reified generics, then you could do this, but that's probably unlikely now.

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

Simply use an image extension like .jpeg or .png.

Good beginners tutorial to socket.io?

To start with Socket.IO I suggest you read first the example on the main page:

http://socket.io/

On the server side, read the "How to use" on the GitHub source page:

https://github.com/Automattic/socket.io

And on the client side:

https://github.com/Automattic/socket.io-client

Finally you need to read this great tutorial:

http://howtonode.org/websockets-socketio

Hint: At the end of this blog post, you will have some links pointing on source code that could be some help.

CMD: Export all the screen content to a text file

How about this:

<command> > <filename.txt> & <filename.txt>

Example:

ipconfig /all > network.txt & network.txt

This will give the results in Notepad instead of the command prompt.

How to cancel a Task in await?

I just want to add to the already accepted answer. I was stuck on this, but I was going a different route on handling the complete event. Rather than running await, I add a completed handler to the task.

Comments.AsAsyncAction().Completed += new AsyncActionCompletedHandler(CommentLoadComplete);

Where the event handler looks like this

private void CommentLoadComplete(IAsyncAction sender, AsyncStatus status )
{
    if (status == AsyncStatus.Canceled)
    {
        return;
    }
    CommentsItemsControl.ItemsSource = Comments.Result;
    CommentScrollViewer.ScrollToVerticalOffset(0);
    CommentScrollViewer.Visibility = Visibility.Visible;
    CommentProgressRing.Visibility = Visibility.Collapsed;
}

With this route, all the handling is already done for you, when the task is cancelled it just triggers the event handler and you can see if it was cancelled there.

Splitting a dataframe string column into multiple different columns

A very direct way is to just use read.table on your character vector:

> read.table(text = text, sep = ".", colClasses = "character")
   V1 V2  V3  V4
1   F US CLE V13
2   F US CA6 U13
3   F US CA6 U13
4   F US CA6 U13
5   F US CA6 U13
6   F US CA6 U13
7   F US CA6 U13
8   F US CA6 U13
9   F US  DL U13
10  F US  DL U13
11  F US  DL U13
12  F US  DL Z13
13  F US  DL Z13

colClasses needs to be specified, otherwise F gets converted to FALSE (which is something I need to fix in "splitstackshape", otherwise I would have recommended that :) )


Update (> a year later)...

Alternatively, you can use my cSplit function, like this:

cSplit(as.data.table(text), "text", ".")
#     text_1 text_2 text_3 text_4
#  1:      F     US    CLE    V13
#  2:      F     US    CA6    U13
#  3:      F     US    CA6    U13
#  4:      F     US    CA6    U13
#  5:      F     US    CA6    U13
#  6:      F     US    CA6    U13
#  7:      F     US    CA6    U13
#  8:      F     US    CA6    U13
#  9:      F     US     DL    U13
# 10:      F     US     DL    U13
# 11:      F     US     DL    U13
# 12:      F     US     DL    Z13
# 13:      F     US     DL    Z13

Or, separate from "tidyr", like this:

library(dplyr)
library(tidyr)

as.data.frame(text) %>% separate(text, into = paste("V", 1:4, sep = "_"))
#    V_1 V_2 V_3 V_4
# 1    F  US CLE V13
# 2    F  US CA6 U13
# 3    F  US CA6 U13
# 4    F  US CA6 U13
# 5    F  US CA6 U13
# 6    F  US CA6 U13
# 7    F  US CA6 U13
# 8    F  US CA6 U13
# 9    F  US  DL U13
# 10   F  US  DL U13
# 11   F  US  DL U13
# 12   F  US  DL Z13
# 13   F  US  DL Z13

Most efficient way to check if a file is empty in Java on Windows

Try FileReader, this reader is meant to read stream of character, while FileInputStream is meant to read raw data.

From the Javadoc:

FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.

Since you wanna read a log file, FileReader is the class to use IMO.

How to iterate over rows in a DataFrame in Pandas

I was looking for How to iterate on rows and columns and ended here so:

for i, row in df.iterrows():
    for j, column in row.iteritems():
        print(column)

How to install multiple python packages at once using pip

You can simply place multiple name together separated by a white space like

C:\Users\Dell>pip install markdown django-filter

#c:\Users\Dell is path in my pc this can be anything on yours

this installed markdown and django-filter on my device. enter image description here

Can I install/update WordPress plugins without providing FTP access?

Yes, directly install the plugin in WordPress.

  1. Copy the plugin folder and paste in WordPress plugin folder.
  2. go to admin side (/test/wp-admin) then after go to on the plugin link and check the name of the plugin.
  3. Activate the plugin so Install the plugin easily.

other Option

  1. create the zip file for the plugin code.
  2. go to admin side (/test/wp-admin) then after go to on the plugin link and then click on the add new then browse the plugin zip folder and install the plugin then come out the option activate plugin so so do activate plugin and activate plugin.

What is the difference between a data flow diagram and a flow chart?

Data flow diagram: A modeling notation that represents a functional decomposition of a system.

Flow chart: Step by step flow of a programe.

Joining two table entities in Spring Data JPA

For a typical example of employees owning one or more phones, see this wikibook section.

For your specific example, if you want to do a one-to-one relationship, you should change the next code in ReleaseDateType model:

@Column(nullable = true) 
private Integer media_Id;

for:

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="CACHE_MEDIA_ID", nullable=true)
private CacheMedia cacheMedia ;

and in CacheMedia model you need to add:

@OneToOne(cascade=ALL, mappedBy="ReleaseDateType")
private ReleaseDateType releaseDateType;

then in your repository you should replace:

@Query("Select * from A a  left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();

by:

//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedia_Id(Integer id); 

or by:

@Query("FROM ReleaseDateType AS rdt WHERE cm.rdt.cacheMedia.id = ?1")    //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);

Or if you prefer to do a @OneToMany and @ManyToOne relation, you should change the next code in ReleaseDateType model:

@Column(nullable = true) 
private Integer media_Id;

for:

@OneToMany(cascade=ALL, mappedBy="ReleaseDateType")
private List<CacheMedia> cacheMedias ;

and in CacheMedia model you need to add:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="RELEASE_DATE_TYPE_ID", nullable=true)
private ReleaseDateType releaseDateType;

then in your repository you should replace:

@Query("Select * from A a  left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();

by:

//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedias_Id(Integer id); 

or by:

@Query("FROM ReleaseDateType AS rdt LEFT JOIN rdt.cacheMedias AS cm WHERE cm.id = ?1")    //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);

EntityType has no key defined error

i know that this post is late but this solution helped me:

    [Key]
    [Column(Order = 0)]
    public int RoleId { get; set; }

added [Column(Order = 0)] after [Key] can be added by increment by 1:

    [Key]
    [Column(Order = 1)]
    public int RoleIdName { get; set; }

etc...

Using JQuery hover with HTML image map

This question is old but I wanted to add an alternative to the accepted answer which didn't exist at the time.

Image Mapster is a jQuery plugin that I wrote to solve some of the shortcomings of Map Hilight (and it was initially an extension of that plugin, though it's since been almost completely rewritten). Initially, this was just the ability to maintain selection state for areas, fix browser compatibility problems. Since its initial release a few months ago, though, I have added a lot of features including the ability to use an alternate image as the source for the highlights.

It also has the ability to identify areas as "masks," meaning you can create areas with "holes", and additionally create complex groupings of areas. For example, area A could cause another area B to be highlighted, but area B itself would not respond to mouse events.

There are a few examples on the web site that show most of the features. The github repository also has more examples and complete documentation.

What does __FILE__ mean in Ruby?

The value of __FILE__ is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.chdir anywhere else in your application, this path will expand incorrectly.

puts __FILE__
Dir.chdir '../../'
puts __FILE__

One workaround to this problem is to store the expanded value of __FILE__ outside of any application code. As long as your require statements are at the top of your definitions (or at least before any calls to Dir.chdir), this value will continue to be useful after changing directories.

$MY_FILE_PATH = File.expand_path(File.dirname(__FILE__))

# open class and do some stuff that changes directory

puts $MY_FILE_PATH

Adding Counter in shell script

You may do this with a for loop instead of a while:

max_loop=20
for ((count = 0; count < max_loop; count++)); do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       break
  else
       echo "Sleeping for half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

if [ "$count" -eq "$max_loop" ]; then
  echo "Maximum number of trials reached" >&2
  exit 1
fi

How to register multiple implementations of the same interface in Asp.Net Core?

Why not use inheritance? This way we can have as many copies of the interface as we want and we can pick suitable names for each of them . And we have a benefit of type safety

public interface IReportGenerator
public interface IExcelReportGenerator : IReportGenerator
public interface IPdfReportGenerator : IReportGenerator

Concrete classes:

public class ExcelReportGenerator : IExcelReportGenerator
public class PdfReportGenerator : IPdfReportGenerator

Register:

instead of

services.AddScoped<IReportGenerator, PdfReportGenerator>();
services.AddScoped<IReportGenerator, ExcelReportGenerator>();

we have :

services.AddScoped<IPdfReportGenerator, PdfReportGenerator>();
services.AddScoped<IExcelReportGenerator, ExcelReportGenerator>();

Client:

public class ReportManager : IReportManager
{
    private readonly IExcelReportGenerator excelReportGenerator;
    private readonly IPdfReportGenerator pdfReportGenerator;

    public ReportManager(IExcelReportGenerator excelReportGenerator, 
                         IPdfReportGenerator pdfReportGenerator)
    {
        this.excelReportGenerator = excelReportGenerator;
        this.pdfReportGenerator = pdfReportGenerator;
    }

this approach also allows for louse coupled code, because we can move IReportGenerator to the core of the application and have child interfaces that will be declared at higher levels.

How to get docker-compose to always re-create containers from fresh images?

docker-compose up --force-recreate is one option, but if you're using it for CI, I would start the build with docker-compose rm -f to stop and remove the containers and volumes (then follow it with pull and up).

This is what I use:

docker-compose rm -f
docker-compose pull
docker-compose up --build -d
# Run some tests
./tests
docker-compose stop -t 1

The reason containers are recreated is to preserve any data volumes that might be used (and it also happens to make up a lot faster).

If you're doing CI you don't want that, so just removing everything should get you want you want.

Update: use up --build which was added in docker-compose 1.7

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

How do I loop through items in a list box and then remove those item?

You can't make modification to the collection being iterated within the ForEach block.

A quick fix is to iterate over a copy of the collection. An easy way to make this copy is through the ArrayList constructor. The DataRowView objects in the copied collection will refer to, and be able to modify, the same underlying data as your code.

For Each item As DataRowView In New System.Collections.ArrayList(lbOrdersNeedToBeVoided.Items)

please read http://social.msdn.microsoft.com/Forums/en-AU/vbgeneral/thread/b4d1f649-d78a-4e5b-8ad8-1940e3379bed

Parsing string as JSON with single quotes?

Using single quotes for keys are not allowed in JSON. You need to use double quotes.

For your use-case perhaps this would be the easiest solution:

str = '{"a":1}';

Source:

If a property requires quotes, double quotes must be used. All property names must be surrounded by double quotes.

How to get the file path from HTML input form in Firefox 3

Have a look at XPCOM, there might be something that you can use if Firefox 3 is used by a client.

How do I get the current mouse screen coordinates in WPF?

Or in pure WPF use PointToScreen.

Sample helper method:

// Gets the absolute mouse position, relative to screen
Point GetMousePos() => _window.PointToScreen(Mouse.GetPosition(_window));

How do I extract a substring from a string until the second space is encountered?

I would recommend a regular expression for this since it handles cases that you might not have considered.

var input = "o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467";
var regex = new Regex(@"^(.*? .*?) ");
var match = regex.Match(input);
if (match.Success)
{
    Console.WriteLine(string.Format("'{0}'", match.Groups[1].Value));
}

Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document

You also can use ng-attr-src="{{variable}}" instead of src="{{variable}}" and the attribute will only be generated once the compiler compiled the templates. This is mentioned here in the documentation: https://docs.angularjs.org/guide/directive#-ngattr-attribute-bindings