Programs & Examples On #Distributed algorithm

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

Great Explanation from the link : http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx

Let's First look at MVC

The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.

There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.

There is one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.

The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.

MVP – Model View Presenter

Now let’s look at the MVP pattern. It looks very similar to MVC, except for some key distinctions:

The input begins with the View, not the Presenter.

There is a one-to-one mapping between the View and the associated Presenter.

The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.

The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.

MVVM – Model View View Model

So with the MVC and MVP patterns in front of us, let’s look at the MVVM pattern and see what differences it holds:

The input begins with the View, not the View Model.

While the View holds a reference to the View Model, the View Model has no information about the View. This is why its possible to have a one-to-many mapping between various Views and one View Model…even across technologies. For example, a WPF View and a Silverlight View could share the same View Model.

Programmatic equivalent of default(Type)

  • In case of a value type use Activator.CreateInstance and it should work fine.
  • When using reference type just return null
public static object GetDefault(Type type)
{
   if(type.IsValueType)
   {
      return Activator.CreateInstance(type);
   }
   return null;
}

In the newer version of .net such as .net standard, type.IsValueType needs to be written as type.GetTypeInfo().IsValueType

How to center an element horizontally and vertically

Here is how to use 2 simple flex properties to center n divs on the 2 axis:

  • Set the height of your container: Here the body is set to be at least 100vh.
  • align-items: center will vertically center the blocks
  • justify-content: space-around will distribute the free horizontal space around the divs

_x000D_
_x000D_
body {_x000D_
  min-height: 100vh;_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: space-around;_x000D_
}
_x000D_
<div>foo</div>_x000D_
<div>bar</div>
_x000D_
_x000D_
_x000D_

How do I create a circle or square with just CSS - with a hollow center?

Try This

_x000D_
_x000D_
div.circle {_x000D_
  -moz-border-radius: 50px/50px;_x000D_
  -webkit-border-radius: 50px 50px;_x000D_
  border-radius: 50px/50px;_x000D_
  border: solid 21px #f00;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
div.square {_x000D_
  border: solid 21px #f0f;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
}
_x000D_
<div class="circle">_x000D_
  <img/>_x000D_
</div>_x000D_
 <hr/>_x000D_
<div class="square">_x000D_
  <img/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

More here

IDEA: javac: source release 1.7 requires target release 1.7

Have you looked at your build configuration it should like that if you use maven 3 and JDK 7

<build>
    <finalName>SpringApp</finalName>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        ...
    </plugins>
    ...
</build>

Validating with an XML schema in Python

There are two ways(actually there are more) that you could do this.
1. using lxml
pip install lxml

from lxml import etree, objectify
from lxml.etree import XMLSyntaxError

def xml_validator(some_xml_string, xsd_file='/path/to/my_schema_file.xsd'):
    try:
        schema = etree.XMLSchema(file=xsd_file)
        parser = objectify.makeparser(schema=schema)
        objectify.fromstring(some_xml_string, parser)
        print "YEAH!, my xml file has validated"
    except XMLSyntaxError:
        #handle exception here
        print "Oh NO!, my xml file does not validate"
        pass

xml_file = open('my_xml_file.xml', 'r')
xml_string = xml_file.read()
xml_file.close()

xml_validator(xml_string, '/path/to/my_schema_file.xsd')
  1. Use xmllint from the commandline. xmllint comes installed in many linux distributions.

>> xmllint --format --pretty 1 --load-trace --debug --schema /path/to/my_schema_file.xsd /path/to/my_xml_file.xml

Switch case with fallthrough?

Try this:

case $VAR in
normal)
    echo "This doesn't do fallthrough"
    ;;
special)
    echo -n "This does "
    ;&
fallthrough)
    echo "fall-through"
    ;;
esac

Selecting only first-level elements in jquery

$("ul > li a")

But you would need to set a class on the root ul if you specifically want to target the outermost ul:

<ul class="rootlist">
...

Then it's:

$("ul.rootlist > li a")....

Another way of making sure you only have the root li elements:

$("ul > li a").not("ul li ul a")

It looks kludgy, but it should do the trick

Replace String in all files in Eclipse

  • "Search"->"File"
  • Enter text, file pattern and projects
  • "Replace"
  • Enter new text

Voilà...

Find first element in a sequence that matches a predicate

I don't think there's anything wrong with either solutions you proposed in your question.

In my own code, I would implement it like this though:

(x for x in seq if predicate(x)).next()

The syntax with () creates a generator, which is more efficient than generating all the list at once with [].

How to zip a whole folder using PHP

I assume this is running on a server where the zip application is in the search path. Should be true for all unix-based and I guess most windows-based servers.

exec('zip -r archive.zip "My folder"');
unlink('My\ folder/index.html');
unlink('My\ folder/picture.jpg');

The archive will reside in archive.zip afterwards. Keep in mind that blanks in file or folder names are a common cause of errors and should be avoided where possible.

Formatting text in a TextBlock

You can do this in XAML easily enough:

<TextBlock>
  Hello <Bold>my</Bold> faithful <Underline>computer</Underline>.<Italic>You rock!</Italic>
</TextBlock>

How to apply a patch generated with git format-patch?

If you want to apply it as a commit, use git am.

How to hide iOS status bar

Add following line in viewdidload

  [[UIApplication sharedApplication] setStatusBarHidden:YES
                                        withAnimation:UIStatusBarAnimationFade];

and add new method

  - (BOOL)prefersStatusBarHidden {
          return YES;
  }

also change info.plist file View controller-based status bar appearance" = NO

its works for me

JTable How to refresh table model after insert delete or update the data.

The faster way for your case is:

    jTable.repaint(); // Repaint all the component (all Cells).

The optimized way when one or few cell change:

    ((AbstractTableModel) jTable.getModel()).fireTableCellUpdated(x, 0); // Repaint one cell.

Perform Segue programmatically and pass parameters to the destination view

I understand the problem of performing the segue at one place and maintaining the state to send parameters in prepare for segue.

I figured out a way to do this. I've added a property called userInfoDict to ViewControllers using a category. and I've override perform segue with identifier too, in such a way that If the sender is self(means the controller itself). It will pass this userInfoDict to the next ViewController.

Here instead of passing the whole UserInfoDict you can also pass the specific params, as sender and override accordingly.

1 thing you need to keep in mind. don't forget to call super method in ur performSegue method.

`React/RCTBridgeModule.h` file not found

I ran into this issue after doing a manual react-native link of a dependency which didn't support auto link on RN 0.59+

The solution was to select the xcodeproj file under the Libraries folder in Xcode and then in Build Settings, change Header Search Paths to add these two (recursive):

$(SRCROOT)/../../../ios/Pods/Headers/Public/React-Core
$(SRCROOT)/../../../ios/Pods/Headers/Public

How to get the azure account tenant Id?

The tenant id is also present in the management console URL when you browse to the given Active Directory instance, e.g.,

https://manage.windowsazure.com/<morestuffhere>/ActiveDirectoryExtension/Directory/BD848865-BE84-4134-91C6-B415927B3AB1

Azure Mgmt Console Active Directory

vertical divider between two columns in bootstrap

Assuming you have a column space, this is an option. Rebalance the columns depending on what you need.

<div class="col-1">
    <div class="col-6 vhr">
    </div>
</div>
.vhr{
  border-right: 1px solid #333;
  height:100%;
}

How do I update a GitHub forked repository?

In your local clone of your forked repository, you can add the original GitHub repository as a "remote". ("Remotes" are like nicknames for the URLs of repositories - origin is one, for example.) Then you can fetch all the branches from that upstream repository, and rebase your work to continue working on the upstream version. In terms of commands that might look like:

# Add the remote, call it "upstream":

git remote add upstream https://github.com/whoever/whatever.git

# Fetch all the branches of that remote into remote-tracking branches

git fetch upstream

# Make sure that you're on your master branch:

git checkout master

# Rewrite your master branch so that any commits of yours that
# aren't already in upstream/master are replayed on top of that
# other branch:

git rebase upstream/master

If you don't want to rewrite the history of your master branch, (for example because other people may have cloned it) then you should replace the last command with git merge upstream/master. However, for making further pull requests that are as clean as possible, it's probably better to rebase.


If you've rebased your branch onto upstream/master you may need to force the push in order to push it to your own forked repository on GitHub. You'd do that with:

git push -f origin master

You only need to use the -f the first time after you've rebased.

Change primary key column in SQL Server

Assuming that your current primary key constraint is called pk_history, you can replace the following lines:

ALTER TABLE history ADD PRIMARY KEY (id)

ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name

with these:

ALTER TABLE history DROP CONSTRAINT pk_history

ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)

If you don't know what the name of the PK is, you can find it with the following query:

SELECT * 
  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
 WHERE TABLE_NAME = 'history'

Counting Number of Letters in a string variable

myString.Length; //will get you your result
//alternatively, if you only want the count of letters:
myString.Count(char.IsLetter);
//however, if you want to display the words as ***_***** (where _ is a space)
//you can also use this:
//small note: that will fail with a repeated word, so check your repeats!
myString.Split(' ').ToDictionary(n => n, n => n.Length);
//or if you just want the strings and get the counts later:
myString.Split(' ');
//will not fail with repeats
//and neither will this, which will also get you the counts:
myString.Split(' ').Select(n => new KeyValuePair<string, int>(n, n.Length));

Grant all on a specific schema in the db to a group role in PostgreSQL

You found the shorthand to set privileges for all existing tables in the given schema. The manual clarifies:

(but note that ALL TABLES is considered to include views and foreign tables).

Bold emphasis mine. serial columns are implemented with nextval() on a sequence as column default and, quoting the manual:

For sequences, this privilege allows the use of the currval and nextval functions.

So if there are serial columns, you'll also want to grant USAGE (or ALL PRIVILEGES) on sequences

GRANT USAGE ON ALL SEQUENCES IN SCHEMA foo TO mygrp;

Note: identity columns in Postgres 10 or later use implicit sequences that don't require additional privileges. (Consider upgrading serial columns.)

What about new objects?

You'll also be interested in DEFAULT PRIVILEGES for users or schemas:

ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT ALL PRIVILEGES ON TABLES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT USAGE          ON SEQUENCES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo REVOKE ...;

This sets privileges for objects created in the future automatically - but not for pre-existing objects.

Default privileges are only applied to objects created by the targeted user (FOR ROLE my_creating_role). If that clause is omitted, it defaults to the current user executing ALTER DEFAULT PRIVILEGES. To be explicit:

ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo GRANT ...;
ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo REVOKE ...;

Note also that all versions of pgAdmin III have a subtle bug and display default privileges in the SQL pane, even if they do not apply to the current role. Be sure to adjust the FOR ROLE clause manually when copying the SQL script.

Using SED with wildcard

So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.

Get the IP Address of local computer

I was able to do it using DNS service under VS2013 with the following code:

#include <Windns.h>

WSADATA wsa_Data;

int wsa_ReturnCode = WSAStartup(0x101, &wsa_Data);

gethostname(hostName, 256);
PDNS_RECORD pDnsRecord;

DNS_STATUS statsus = DnsQuery(hostName, DNS_TYPE_A, DNS_QUERY_STANDARD, NULL, &pDnsRecord, NULL);
IN_ADDR ipaddr;
ipaddr.S_un.S_addr = (pDnsRecord->Data.A.IpAddress);
printf("The IP address of the host %s is %s \n", hostName, inet_ntoa(ipaddr));

DnsRecordListFree(&pDnsRecord, DnsFreeRecordList);

I had to add Dnsapi.lib as addictional dependency in linker option.

Reference here.

Firing events on CSS class changes in jQuery

change() does not fire when a CSS class is added or removed or the definition changes. It fires in circumstances like when a select box value is selected or unselected.

I'm not sure if you mean if the CSS class definition is changed (which can be done programmatically but is tedious and not generally recommended) or if a class is added or removed to an element. There is no way to reliably capture this happening in either case.

You could of course create your own event for this but this can only be described as advisory. It won't capture code that isn't yours doing it.

Alternatively you could override/replace the addClass() (etc) methods in jQuery but this won't capture when it's done via vanilla Javascript (although I guess you could replace those methods too).

Check for special characters (/*-+_@&$#%) in a string?

String test_string = "tesintg#$234524@#";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
  // Good-to-go
}

An example can be found here: http://ideone.com/B1HxA

How to read a HttpOnly cookie using JavaScript

Httponly cookies' purpose is being inaccessible by script, so you CAN NOT.

How to get root view controller?

Swift 3

let rootViewController = UIApplication.shared.keyWindow?.rootViewController

Bootstrap 3: Scroll bars

You need to use the overflow option, but with the following parameters:

.nav {
    max-height:300px;
    overflow-y:auto;  
}

Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.

If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.

Presumably you want something that adapts itself to the content rather then the the opposite.

Hope it may helpful

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

Array vs ArrayList in performance

Arrays are better in performance. ArrayList provides additional functionality such as "remove" at the cost of performance.

How can I pass command-line arguments to a Perl program?

If you just want some values, you can just use the @ARGV array. But if you are looking for something more powerful in order to do some command line options processing, you should use Getopt::Long.

How can I check if a string represents an int, without using try/except?

str.isdigit() should do the trick.

Examples:

str.isdigit("23") ## True
str.isdigit("abc") ## False
str.isdigit("23.4") ## False

EDIT: As @BuzzMoschetti pointed out, this way will fail for minus number (e.g, "-23"). In case your input_num can be less than 0, use re.sub(regex_search,regex_replace,contents) before applying str.isdigit(). For example:

import re
input_num = "-23"
input_num = re.sub("^-", "", input_num) ## "^" indicates to remove the first "-" only
str.isdigit(input_num) ## True

getOutputStream() has already been called for this response

This error was occuring in my program because the resultset was calling more columns to be displayed in the PDF Document than the database contained. For example, the table contains 30 fields but the program was calling 35 (resultset.getString(35))

Encoding conversion in java

It is a whole lot easier if you think of unicode as a character set (which it actually is - it is very basically the numbered set of all known characters). You can encode it as UTF-8 (1-3 bytes per character depending) or maybe UTF-16 (2 bytes per character or 4 bytes using surrogate pairs).

Back in the mist of time Java used to use UCS-2 to encode the unicode character set. This could only handle 2 bytes per character and is now obsolete. It was a fairly obvious hack to add surrogate pairs and move up to UTF-16.

A lot of people think they should have used UTF-8 in the first place. When Java was originally written unicode had far more than 65535 characters anyway...

Adding a directory to PATH in Ubuntu

Actually I would advocate .profile if you need it to work from scripts, and in particular, scripts run by /bin/sh instead of Bash. If this is just for your own private interactive use, .bashrc is fine, though.

How do I clone into a non-empty directory?

I had a similar problem with a new Apache web directory (account created with WHM) that I planned to use as a staging web server. I needed to initially clone my new project with the code base there and periodically deploy changes by pulling from repository.

The problem was that the account already contained web server files like:

.bash_history
.bash_logout
.bash_profile
.bashrc
.contactemail
.cpanel/
...

...that I did not want to either delete or commit to my repository. I needed them to just stay there unstaged and untracked.

What I did:

I went to my web folder (existing_folder):

cd /home/existing_folder

and then:

git init
git remote add origin PATH/TO/REPO
git pull origin master
git status

It displayed (as expected) a list of many not staged files - those that already existed initially from my cPanel web account.

Then, thanks to this article, I just added the list of those files to:

**.git/info/exclude**

This file, almost like the .gitignore file, allows you to ignore files from being staged. After this I had nothing to commit in the .git/ directory - it works like a personal .gitignore that no one else can see.

Now checking git status returns:

On branch master
nothing to commit, working tree clean

Now I can deploy changes to this web server by simply pulling from my git repository. Hope this helps some web developers to easily create a staging server.

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

If you are getting that error from Event Viewer, you should see another error event (at least one) from the Source ".NET Runtime". Look at that error message as it will contain the Exception info.

Where is Python language used?

Python is used for developing sites. It's more highlevel than php. Python is used for linux dekstop applications. For example, the most of Ubuntu configurations utilites are pythonic.

How to affect other elements when one element is hovered

Here is another idea that allow you to affect other elements without considering any specific selector and by only using the :hover state of the main element.

For this, I will rely on the use of custom properties (CSS variables). As we can read in the specification:

Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritance and cascade rules ...

The idea is to define custom properties within the main element and use them to style child elements and since these properties are inherited we simply need to change them within the main element on hover.

Here is an example:

_x000D_
_x000D_
#container {_x000D_
  width: 200px;_x000D_
  height: 30px;_x000D_
  border: 1px solid var(--c);_x000D_
  --c:red;_x000D_
}_x000D_
#container:hover {_x000D_
  --c:blue;_x000D_
}_x000D_
#container > div {_x000D_
  width: 30px;_x000D_
  height: 100%;_x000D_
  background-color: var(--c);_x000D_
}
_x000D_
<div id="container">_x000D_
  <div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why this can be better than using specific selector combined with hover?

I can provide at least 2 reasons that make this method a good one to consider:

  1. If we have many nested elements that share the same styles, this will avoid us complex selector to target all of them on hover. Using Custom properties, we simply change the value when hovering on the parent element.
  2. A custom property can be used to replace a value of any property and also a partial value of it. For example we can define a custom property for a color and we use it within a border, linear-gradient, background-color, box-shadow etc. This will avoid us reseting all these properties on hover.

Here is a more complex example:

_x000D_
_x000D_
.container {_x000D_
  --c:red;_x000D_
  width:400px;_x000D_
  display:flex;_x000D_
  border:1px solid var(--c);_x000D_
  justify-content:space-between;_x000D_
  padding:5px;_x000D_
  background:linear-gradient(var(--c),var(--c)) 0 50%/100% 3px no-repeat;_x000D_
}_x000D_
.box {_x000D_
  width:30%;_x000D_
  background:var(--c);_x000D_
  box-shadow:0px 0px 5px var(--c);_x000D_
  position:relative;_x000D_
}_x000D_
.box:before {_x000D_
  content:"A";_x000D_
  display:block;_x000D_
  width:15px;_x000D_
  margin:0 auto;_x000D_
  height:100%;_x000D_
  color:var(--c);_x000D_
  background:#fff;_x000D_
}_x000D_
_x000D_
/*Hover*/_x000D_
.container:hover {_x000D_
  --c:blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box"></div>_x000D_
<div class="box"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

As we can see above, we only need one CSS declaration in order to change many properties of different elements.

Watch multiple $scope attributes

$scope.$watch('age + name', function () {
  //called when name or age changed
});

Here function will get called when both age and name value get changed.

C# Example of AES256 encryption using System.Security.Cryptography.Aes

Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.

The finally implemented code started like this:

    try
    {
        // Create a new instance of the AesManaged class.  This generates a new key and initialization vector (IV).
        AesManaged myAes = new AesManaged();

        // Override the cipher mode, key and IV
        myAes.Mode = CipherMode.ECB;
        myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
        myAes.Key = CipherKey;  // Byte array representing the key
        myAes.Padding = PaddingMode.None;

        // Create a encryption object to perform the stream transform.
        ICryptoTransform encryptor = myAes.CreateEncryptor();

        // TODO: perform the encryption / decryption as required...

    }
    catch (Exception ex)
    {
        // TODO: Log the error 
        throw ex;
    }

set background color: Android

Color.parseColor("#rrggbb")

instead of #rrggbb you should be using hex values 0 to F for rr, gg and bb:

e.g. Color.parseColor("#000000") or Color.parseColor("#FFFFFF")

Source

From documentation:

public static int parseColor (String colorString):

Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. Supported formats are: #RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuschia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'

So I believe that if you are using #rrggbb you are getting IllegalArgumentException in your logcat

Source

Alternative:

Color mColor = new Color();
mColor.red(redvalue);
mColor.green(greenvalue);
mColor.blue(bluevalue);
li.setBackgroundColor(mColor);

Source

MySQL SELECT DISTINCT multiple columns

Both your queries are correct and should give you the right answer.

I would suggest the following query to troubleshoot your problem.

SELECT DISTINCT a,b,c,d,count(*) Count FROM my_table GROUP BY a,b,c,d
order by count(*) desc

That is add count(*) field. This will give you idea how many rows were eliminated using the group command.

How to view DLL functions?

Use dotPeek by JetBrains.

https://www.jetbrains.com/decompiler/

dotPeek is a free tool based on ReSharper. It can reliably decompile any .NET assembly into C# or IL code.

Pull new updates from original GitHub repository into forked GitHub repository

If you want to do it without cli, you can do it fully on Github website.

  1. Go to your fork repository.
  2. Click on New pull request.
  3. Make sure to set your fork as the base repository, and the original (upstream) repository as head repository. Usually you only want to sync the master branch.
  4. Create new pull request.
  5. Select the arrow to the right of the merging button, and make sure to choose rebase instead of merge. Then click the button. This way, it will not produce unnecessary merge commit.
  6. Done.

How to store a dataframe using Pandas

Pickle works good!

import pandas as pd
df.to_pickle('123.pkl')    #to save the dataframe, df to 123.pkl
df1 = pd.read_pickle('123.pkl') #to load 123.pkl back to the dataframe df

Converting json results to a date

I use this:

function parseJsonDate(jsonDateString){
    return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}

Update 2018:

This is an old question. Instead of still using this old non standard serialization format I would recommend to modify the server code to return better format for date. Either an ISO string containing time zone information, or only the milliseconds. If you use only the milliseconds for transport it should be UTC on server and client.

  • 2018-07-31T11:56:48Z - ISO string can be parsed using new Date("2018-07-31T11:56:48Z") and obtained from a Date object using dateObject.toISOString()
  • 1533038208000 - milliseconds since midnight January 1, 1970, UTC - can be parsed using new Date(1533038208000) and obtained from a Date object using dateObject.getTime()

Get values from other sheet using VBA

Usually I use this code (into a VBA macro) for getting a cell's value from another cell's value from another sheet:

Range("Y3") = ActiveWorkbook.Worksheets("Reference").Range("X4")

The cell Y3 is into a sheet that I called it "Calculate" The cell X4 is into a sheet that I called it "Reference" The VBA macro has been run when the "Calculate" in active sheet.

Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

use labelpad parameter:

pl.xlabel("...", labelpad=20)

or set it after:

ax.xaxis.labelpad = 20

How to use ArrayAdapter<myClass>

Here's a quick and dirty example of how to use an ArrayAdapter if you don't want to bother yourself with extending the mother class:

class MyClass extends Activity {
    private ArrayAdapter<String> mAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mAdapter = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_dropdown_item_1line, android.R.id.text1);

        final ListView list = (ListView) findViewById(R.id.list);
        list.setAdapter(mAdapter);

        //Add Some Items in your list:
        for (int i = 1; i <= 10; i++) {
            mAdapter.add("Item " + i);
        }

        // And if you want selection feedback:
        list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Do whatever you want with the selected item
                Log.d(TAG, mAdapter.getItem(position) + " has been selected!");
            }
        });
    }
}

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

TypeScript enum to object array

Simply this will return an array of enum values:

 Object.values(myEnum);

Reading data from XML

Alternatively, you can use XPathNavigator:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XPathNavigator navigator = doc.CreateNavigator();

string books = GetStringValues("Books: ", navigator, "//Book/Title");
string authors = GetStringValues("Authors: ", navigator, "//Book/Author");

..

/// <summary>
/// Gets the string values.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="navigator">The navigator.</param>
/// <param name="xpath">The xpath.</param>
/// <returns></returns>
private static string GetStringValues(string description,
                                      XPathNavigator navigator, string xpath) {
    StringBuilder sb = new StringBuilder();
    sb.Append(description);
    XPathNodeIterator bookNodesIterator = navigator.Select(xpath);
    while (bookNodesIterator.MoveNext())
       sb.Append(string.Format("{0} ", bookNodesIterator.Current.Value));
    return sb.ToString();
}

How do I parse a string with a decimal point to a double?

I couldn't write a comment, so I write here:

double.Parse("3.5", CultureInfo.InvariantCulture) is not a good idea, because in Canada we write 3,5 instead of 3.5 and this function gives us 35 as a result.

I tested both on my computer:

double.Parse("3.5", CultureInfo.InvariantCulture) --> 3.5 OK
double.Parse("3,5", CultureInfo.InvariantCulture) --> 35 not OK

This is a correct way that Pierre-Alain Vigeant mentioned

public static double GetDouble(string value, double defaultValue)
{
    double result;

    // Try parsing in the current culture
    if (!double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.CurrentCulture, out result) &&
        // Then try in US english
        !double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out result) &&
        // Then in neutral language
        !double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out result))
    {
        result = defaultValue;
    }
    return result;
}

Adding items to end of linked list

You want to navigate through the entire linked list using a loop and checking the "next" value for each node. The last node will be the one whose next value is null. Simply make this node's next value a new node which you create with the input data.

node temp = first; // starts with the first node.

    while (temp.next != null)
    {
       temp = temp.next;
    }

temp.next = new Node(header, x);

That's the basic idea. This is of course, pseudo code, but it should be simple enough to implement.

Where should my npm modules be installed on Mac OS X?

If you want to know the location of you NPM packages, you should:

which npm // locate a program file in the user's path SEE man which
// OUTPUT SAMPLE
/usr/local/bin/npm
la /usr/local/bin/npm // la: aliased to ls -lAh SEE which la THEN man ls
lrwxr-xr-x  1 t04435  admin    46B 18 Sep 10:37 /usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js

So given that npm is a NODE package itself, it is installed in the same location as other packages(EUREKA). So to confirm you should cd into node_modules and list the directory.

cd /usr/local/lib/node_modules/
ls
#SAMPLE OUTPUT
@angular npm .... all global npm packages installed

OR

npm root -g

As per @anthonygore 's comment

html table cell width for different rows

One solution would be to divide your table into 20 columns of 5% width each, then use colspan on each real column to get the desired width, like this:

_x000D_
_x000D_
<html>_x000D_
<body bgcolor="#14B3D9">_x000D_
<table width="100%" border="1" bgcolor="#ffffff">_x000D_
    <colgroup>_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
    </colgroup>_x000D_
    <tr>_x000D_
        <td colspan=5>25</td>_x000D_
        <td colspan=10>50</td>_x000D_
        <td colspan=5>25</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan=10>50</td>_x000D_
        <td colspan=6>30</td>_x000D_
        <td colspan=4>20</td>_x000D_
    </tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

JSFIDDLE

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

If you want to find interactively logged on users, I found a great tip here :https://p0w3rsh3ll.wordpress.com/2012/02/03/get-logged-on-users/ (Win32_ComputerSystem did not help me)

$explorerprocesses = @(Get-WmiObject -Query "Select * FROM Win32_Process WHERE Name='explorer.exe'" -ErrorAction SilentlyContinue)
If ($explorerprocesses.Count -eq 0)
{
    "No explorer process found / Nobody interactively logged on"
}
Else
{
    ForEach ($i in $explorerprocesses)
    {
        $Username = $i.GetOwner().User
        $Domain = $i.GetOwner().Domain
        Write-Host "$Domain\$Username logged on since: $($i.ConvertToDateTime($i.CreationDate))"
    }
}

Javascript: console.log to html

A little late to the party, but I took @Hristiyan Dodov's answer a bit further still.

All console methods are now rewired and in case of overflowing text, an optional autoscroll to bottom is included. Colors are now based on the logging method rather than the arguments.

_x000D_
_x000D_
rewireLoggingToElement(_x000D_
    () => document.getElementById("log"),_x000D_
    () => document.getElementById("log-container"), true);_x000D_
_x000D_
function rewireLoggingToElement(eleLocator, eleOverflowLocator, autoScroll) {_x000D_
    fixLoggingFunc('log');_x000D_
    fixLoggingFunc('debug');_x000D_
    fixLoggingFunc('warn');_x000D_
    fixLoggingFunc('error');_x000D_
    fixLoggingFunc('info');_x000D_
_x000D_
    function fixLoggingFunc(name) {_x000D_
        console['old' + name] = console[name];_x000D_
        console[name] = function(...arguments) {_x000D_
            const output = produceOutput(name, arguments);_x000D_
            const eleLog = eleLocator();_x000D_
_x000D_
            if (autoScroll) {_x000D_
                const eleContainerLog = eleOverflowLocator();_x000D_
                const isScrolledToBottom = eleContainerLog.scrollHeight - eleContainerLog.clientHeight <= eleContainerLog.scrollTop + 1;_x000D_
                eleLog.innerHTML += output + "<br>";_x000D_
                if (isScrolledToBottom) {_x000D_
                    eleContainerLog.scrollTop = eleContainerLog.scrollHeight - eleContainerLog.clientHeight;_x000D_
                }_x000D_
            } else {_x000D_
                eleLog.innerHTML += output + "<br>";_x000D_
            }_x000D_
_x000D_
            console['old' + name].apply(undefined, arguments);_x000D_
        };_x000D_
    }_x000D_
_x000D_
    function produceOutput(name, args) {_x000D_
        return args.reduce((output, arg) => {_x000D_
            return output +_x000D_
                "<span class=\"log-" + (typeof arg) + " log-" + name + "\">" +_x000D_
                    (typeof arg === "object" && (JSON || {}).stringify ? JSON.stringify(arg) : arg) +_x000D_
                "</span>&nbsp;";_x000D_
        }, '');_x000D_
    }_x000D_
}_x000D_
_x000D_
_x000D_
setInterval(() => {_x000D_
  const method = (['log', 'debug', 'warn', 'error', 'info'][Math.floor(Math.random() * 5)]);_x000D_
  console[method](method, 'logging something...');_x000D_
}, 200);
_x000D_
#log-container { overflow: auto; height: 150px; }_x000D_
_x000D_
.log-warn { color: orange }_x000D_
.log-error { color: red }_x000D_
.log-info { color: skyblue }_x000D_
.log-log { color: silver }_x000D_
_x000D_
.log-warn, .log-error { font-weight: bold; }
_x000D_
<div id="log-container">_x000D_
  <pre id="log"></pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Equivalent of typedef in C#

Here is the code for it, enjoy!, I picked that up from the dotNetReference type the "using" statement inside the namespace line 106 http://referencesource.microsoft.com/#mscorlib/microsoft/win32/win32native.cs

using System;
using System.Collections.Generic;
namespace UsingStatement
{
    using Typedeffed = System.Int32;
    using TypeDeffed2 = List<string>;
    class Program
    {
        static void Main(string[] args)
        {
        Typedeffed numericVal = 5;
        Console.WriteLine(numericVal++);

        TypeDeffed2 things = new TypeDeffed2 { "whatever"};
        }
    }
}

How to compare pointers?

The == operator on pointers will compare their numeric address and hence determine if they point to the same object.

Select query to remove non-numeric characters

Here is the answer:

DECLARE @t TABLE (tVal VARCHAR(100))

INSERT INTO @t VALUES('123')
INSERT INTO @t VALUES('123S')
INSERT INTO @t VALUES('A123,123')
INSERT INTO @t VALUES('a123..A123')


;WITH cte (original, tVal, n)
     AS
     (
         SELECT t.tVal AS original,
                LOWER(t.tVal)  AS tVal,
                65             AS n
         FROM   @t             AS t
         UNION ALL
         SELECT tVal AS original,
                CAST(REPLACE(LOWER(tVal), LOWER(CHAR(n)), '') AS VARCHAR(100)),
                n + 1
         FROM   cte
         WHERE  n <= 90
     )

SELECT t1.tVal  AS OldVal,
       t.tval   AS NewVal
FROM   (
           SELECT original,
                  tVal,
                  ROW_NUMBER() OVER(PARTITION BY tVal + original ORDER BY original) AS Sl
           FROM   cte
           WHERE  PATINDEX('%[a-z]%', tVal) = 0
       ) t
       INNER JOIN @t t1
            ON  t.original = t1.tVal
WHERE  t.sl = 1

Add and remove a class on click using jQuery?

you can try this along, it may help to give a shorter code on large function.

$('#menu li a').on('click', function(){
    $('li a.current').toggleClass('current');
});

Ng-model does not update controller value

Have a look at this fiddle http://jsfiddle.net/ganarajpr/MSjqL/

I have ( I assume! ) done exactly what you were doing and it seems to be working. Can you check what is not working here for you?

mysql select from n last rows

Starting from the answer given by @chaos, but with a few modifications:

  • You should always use ORDER BY if you use LIMIT. There is no implicit order guaranteed for an RDBMS table. You may usually get rows in the order of the primary key, but you can't rely on this, nor is it portable.

  • If you order by in the descending order, you don't need to know the number of rows in the table beforehand.

  • You must give a correlation name (aka table alias) to a derived table.

Here's my version of the query:

SELECT `id`
FROM (
    SELECT `id`, `val`
    FROM `big_table`
    ORDER BY `id` DESC
    LIMIT $n
) AS t
WHERE t.`val` = $certain_number;

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

Check Ayende post on the topic: Combating the Select N + 1 Problem In NHibernate.

Basically, when using an ORM like NHibernate or EntityFramework, if you have a one-to-many (master-detail) relationship, and want to list all the details per each master record, you have to make N + 1 query calls to the database, "N" being the number of master records: 1 query to get all the master records, and N queries, one per master record, to get all the details per master record.

More database query calls ? more latency time ? decreased application/database performance.

However, ORMs have options to avoid this problem, mainly using JOINs.

How do I make a composite key with SQL Server Management Studio?

Highlight both rows in the table design view and click on the key icon, they will now be a composite primary key.

I'm not sure of your question, but only one column per table may be an IDENTITY column, not both.

Sending simple message body + file attachment using Linux Mailx

The best way is to use mpack!

mpack -s "Subject" -d "./body.txt" "././image.png" mailadress

mpack - subject - body - attachment - mailadress

Stacked bar chart

You said :

Maybe my data.frame is not in a good format?

Yes this is true. Your data is in the wide format You need to put it in the long format. Generally speaking, long format is better for variables comparison.

Using reshape2 for example , you do this using melt:

dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work

Then you get your barplot:

ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) +
    geom_bar(stat='identity')

But using lattice and barchart smart formula notation , you don't need to reshape your data , just do this:

barchart(F1+F2+F3~Rank,data=dat)

What does the clearfix class do in css?

clearfix is the same as overflow:hidden. Both clear floated children of the parent, but clearfix will not cut off the element which overflow to it's parent. It also works in IE8 & above.

There is no need to define "." in content & .clearfix. Just write like this:

.clr:after {
    clear: both;
    content: "";
    display: block;
}

HTML

<div class="parent clr"></div>

Read these links for more

http://css-tricks.com/snippets/css/clear-fix/,

What methods of ‘clearfix’ can I use?

How do I install Python libraries in wheel format?

If you want to be relax for installing libraries for python.

You should using pip, that is python installer package.

To install pip:

  1. Download ez_setup.py and then run:

    python ez_setup.py
    
  2. Then download get-pip.py and run:

    python get-pip.py
    
  3. upgrade installed setuptools by pip:

    pip install setuptools --upgrade
    

    If you got this error:

    Wheel installs require setuptools >= 0.8 for dist-info support.
    pip's wheel support requires setuptools >= 0.8 for dist-info support.
    

    Add --no-use-wheel to above cmd:

    pip install setuptools --no-use-wheel --upgrade
    

Now, you can install libraries for python, just by:

pip install library_name

For example:

pip install requests

Note that to install some library may they need to compile, so you need to have compiler.

On windows there is a site for Unofficial Windows Binaries for Python Extension Packages that have huge python packages and complied python packages for windows.

For example to install pip using this site, just download and install setuptools and pip installer from that.

How to dynamically add and remove form fields in Angular 2

That is the HTML code. Anyone can use this:

<div class="card-header">Contact Information</div>
          <div class="card-body" formArrayName="funds">
            <div class="row">
              <div class="col-6" *ngFor="let contact of contactFormGroup.controls; let i = index;">
                <div [formGroupName]="i" class="row">
                  <div class="form-group col-6">
                    <label>Type of Contact</label>
                    <select class="form-control" formControlName="fundName" type="text">
                      <option value="01">Balance Fund</option>
                      <option value="02">Equity Fund</option>
                    </select> 
                  </div>
                  <div class="form-group col-12">
                    <label>Allocation</label>
                    <input class="form-control" formControlName="allocation" type="number">
                    <span class="text-danger" *ngIf="getContactsFormGroup(i).controls['allocation'].touched && 
                    getContactsFormGroup(i).controls['allocation'].hasError('required')">
                        Allocation % is required! </span>
                  </div>
                  <div class="form-group col-12 text-right">
                    <button class="btn btn-danger" type="button" (click)="removeContact(i)"> Remove </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <button class="btn btn-primary m-1" type="button" (click)="addContact()"> Add Contact </button>

Spring cron expression for every after 30 minutes

<property name="cronExpression" value="0 0/30 * * * ?" />

Swift - Remove " character from string

Here is the swift 3 updated answer

var editedText = myLabel.text?.replacingOccurrences(of: "\"", with: "")
Null Character (\0)
Backslash (\\)
Horizontal Tab (\t)
Line Feed (\n)
Carriage Return (\r)
Double Quote (\")
Single Quote (\')
Unicode scalar (\u{n})

Best practices for API versioning?

The URL should NOT contain the versions. The version has nothing to do with "idea" of the resource you are requesting. You should try to think of the URL as being a path to the concept you would like - not how you want the item returned. The version dictates the representation of the object, not the concept of the object. As other posters have said, you should be specifying the format (including version) in the request header.

If you look at the full HTTP request for the URLs which have versions, it looks like this:

(BAD WAY TO DO IT):

http://company.com/api/v3.0/customer/123
====>
GET v3.0/customer/123 HTTP/1.1
Accept: application/xml

<====
HTTP/1.1 200 OK
Content-Type: application/xml
<customer version="3.0">
  <name>Neil Armstrong</name>
</customer>

The header contains the line which contains the representation you are asking for ("Accept: application/xml"). That is where the version should go. Everyone seems to gloss over the fact that you may want the same thing in different formats and that the client should be able ask for what it wants. In the above example, the client is asking for ANY XML representation of the resource - not really the true representation of what it wants. The server could, in theory, return something completely unrelated to the request as long as it was XML and it would have to be parsed to realize it is wrong.

A better way is:

(GOOD WAY TO DO IT)

http://company.com/api/customer/123
===>
GET /customer/123 HTTP/1.1
Accept: application/vnd.company.myapp.customer-v3+xml

<===
HTTP/1.1 200 OK
Content-Type: application/vnd.company.myapp-v3+xml
<customer>
  <name>Neil Armstrong</name>
</customer>

Further, lets say the clients think the XML is too verbose and now they want JSON instead. In the other examples you would have to have a new URL for the same customer, so you would end up with:

(BAD)
http://company.com/api/JSONv3.0/customers/123
  or
http://company.com/api/v3.0/customers/123?format="JSON"

(or something similar). When in fact, every HTTP requests contains the format you are looking for:

(GOOD WAY TO DO IT)
===>
GET /customer/123 HTTP/1.1
Accept: application/vnd.company.myapp.customer-v3+json

<===
HTTP/1.1 200 OK
Content-Type: application/vnd.company.myapp-v3+json

{"customer":
  {"name":"Neil Armstrong"}
}

Using this method, you have much more freedom in design and are actually adhering to the original idea of REST. You can change versions without disrupting clients, or incrementally change clients as the APIs are changed. If you choose to stop supporting a representation, you can respond to the requests with HTTP status code or custom codes. The client can also verify the response is in the correct format, and validate the XML.

There are many other advantages and I discuss some of them here on my blog: http://thereisnorightway.blogspot.com/2011/02/versioning-and-types-in-resthttp-api.html

One last example to show how putting the version in the URL is bad. Lets say you want some piece of information inside the object, and you have versioned your various objects (customers are v3.0, orders are v2.0, and shipto object is v4.2). Here is the nasty URL you must supply in the client:

(Another reason why version in the URL sucks)
http://company.com/api/v3.0/customer/123/v2.0/orders/4321/

Writing a string to a cell in excel

try this instead

Set TxtRng = ActiveWorkbook.Sheets("Game").Range("A1")

ADDITION

Maybe the file is corrupt - this has happened to me several times before and the only solution is to copy everything out into a new file.

Please can you try the following:

  • Save a new xlsm file and call it "MyFullyQualified.xlsm"
  • Add a sheet with no protection and call it "mySheet"
  • Add a module to the workbook and add the following procedure

Does this run?

 Sub varchanger()

 With Excel.Application
    .ScreenUpdating = True
    .Calculation = Excel.xlCalculationAutomatic
    .EnableEvents = True
 End With

 On Error GoTo Whoa:

    Dim myBook As Excel.Workbook
    Dim mySheet As Excel.Worksheet
    Dim Rng  As Excel.Range

    Set myBook = Excel.Workbooks("MyFullyQualified.xlsm")
    Set mySheet = myBook.Worksheets("mySheet")
    Set Rng = mySheet.Range("A1")

    'ActiveSheet.Unprotect


    Rng.Value = "SubTotal"

    Excel.Workbooks("MyFullyQualified.xlsm").Worksheets("mySheet").Range("A1").Value = "Asdf"

LetsContinue:
        Exit Sub
Whoa:
        MsgBox Err.Number
        GoTo LetsContinue

End Sub

how to open a page in new tab on button click in asp.net?

Add_ supplier is name of the form

private void add_supplier_Load(object sender, EventArgs e)
{
    add_supplier childform = new add_supplier();
    childform.MdiParent = this;
    childform.Show();
}

How to Read and Write from the Serial Port

Note that usage of a SerialPort.DataReceived event is optional. You can set proper timeout using SerialPort.ReadTimeout and continuously call SerialPort.Read() after you wrote something to a port until you get a full response.

Moreover you can use SerialPort.BaseStream property to extract an underlying Stream instance. The benefit of using a Stream is that you can easily utilize various decorators with it:

var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and 
// overrides needen virtual methods. 
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.

For more information check:

how to read System environment variable in Spring applicationContext

You can mention your variable attributes in a property file and define environment specific property files like local.properties, production.propertied etc.

Now based on the environment, one of these property file can be read in one the listeners invoked at startup, like the ServletContextListener.

The property file will contain the the environment specific values for various keys.

Sample "local.propeties"

db.logsDataSource.url=jdbc:mysql://localhost:3306/logs
db.logsDataSource.username=root
db.logsDataSource.password=root

db.dataSource.url=jdbc:mysql://localhost:3306/main
db.dataSource.username=root
db.dataSource.password=root

Sample "production.properties"

db.logsDataSource.url=jdbc:mariadb://111.111.111.111:3306/logs
db.logsDataSource.username=admin
db.logsDataSource.password=xyzqer

db.dataSource.url=jdbc:mysql://111.111.111.111:3306/carsinfo
db.dataSource.username=admin
db.dataSource.password=safasf@mn

For using these properties file, you can make use of REsource as mentioned below

        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        ResourceLoader resourceLoader = new DefaultResourceLoader();

        Resource resource = resourceLoader.getResource("classpath:"+System.getenv("SERVER_TYPE")+"DB.properties");
        configurer.setLocation(resource);
        configurer.postProcessBeanFactory(beanFactory);

SERVER_TYPE can be defined as the environment variable with appropriate values for local and production environment.

With these changes the appplicationContext.xml will have the following changes

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
 <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="${db.dataSource.url}" />
  <property name="username" value="${db.dataSource.username}" />
  <property name="password" value="${db.dataSource.password}" />

Hope this helps .

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

I am also looking for an answer to this question, (to clarify, I want to be able to draw an image with user defined opacity such as how you can draw shapes with opacity) if you draw with primitive shapes you can set fill and stroke color with alpha to define the transparency. As far as I have concluded right now, this does not seem to affect image drawing.

//works with shapes but not with images
ctx.fillStyle = "rgba(255, 255, 255, 0.5)";

I have concluded that setting the globalCompositeOperation works with images.

//works with images
ctx.globalCompositeOperation = "lighter";

I wonder if there is some kind third way of setting color so that we can tint images and make them transparent easily.

EDIT:

After further digging I have concluded that you can set the transparency of an image by setting the globalAlpha parameter BEFORE you draw the image:

//works with images
ctx.globalAlpha = 0.5

If you want to achieve a fading effect over time you need some kind of loop that changes the alpha value, this is fairly easy, one way to achieve it is the setTimeout function, look that up to create a loop from which you alter the alpha over time.

Freeze the top row for an html table only (Fixed Table Header Scrolling)

It is possible using position:fixed on <th> (<th> being the top row).

Here's an example

Enum String Name from Value

You can convert the int back to an enumeration member with a simple cast, and then call ToString():

int value = GetValueFromDb();
var enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();

GROUP BY without aggregate function

I know you said you want to understand group by if you have data like this:

COL-A  COL-B  COL-C  COL-D
  1      Ac      C1     D1
  2      Bd      C2     D2
  3      Ba      C1     D3
  4      Ab      C1     D4
  5      C       C2     D5

And you want to make the data appear like:

COL-A  COL-B  COL-C  COL-D
  4      Ab      C1     D4
  1      Ac      C1     D1
  3      Ba      C1     D3
  2      Bd      C2     D2
  5      C       C2     D5

You use:

select * from table_name
order by col-c,colb

Because I think this is what you intend to do.

Go to first line in a file in vim?

In command mode (press Esc if you are not sure) you can use:

  • gg,
  • :1,
  • 1G,
  • or 1gg.

How to get difference between two dates in Year/Month/Week/Day?

I was trying to find a clear answer for Years, Months and Days, and I didn't find anything clear, If you are still looking check this method:

        public static string GetDifference(DateTime d1, DateTime d2)
        {
            int[] monthDay = new int[12] { 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
            DateTime fromDate;
            DateTime toDate;
            int year;
            int month;
            int day; 
            int increment = 0;

            if (d1 > d2)
            {
                fromDate = d2;
                toDate = d1;
            }
            else
            {
                fromDate = d1;
                toDate = d2;
            } 

            // Calculating Days
            if (fromDate.Day > toDate.Day)
            {
                increment = monthDay[fromDate.Month - 1];
            }

            if (increment == -1)
            {
                if (DateTime.IsLeapYear(fromDate.Year))
                {
                    increment = 29;
                }
                else
                {
                    increment = 28;
                }
            }

            if (increment != 0)
            {
                day = (toDate.Day + increment) - fromDate.Day;
                increment = 1;
            }
            else
            {
                day = toDate.Day - fromDate.Day;
            }

            // Month Calculation
            if ((fromDate.Month + increment) > toDate.Month)
            {
                month = (toDate.Month + 12) - (fromDate.Month + increment);
                increment = 1;
            }
            else
            {
                month = (toDate.Month) - (fromDate.Month + increment);
                increment = 0;
            }

            // Year Calculation
            year = toDate.Year - (fromDate.Year + increment);

            return year + " years " + month + " months " + day + " days";
        }

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

For those like me who are brand new to this, here is code with const and an actual way to compare the byte[]'s. I got all of this code from stackoverflow but defined consts so values could be changed and also

// 24 = 192 bits
    private const int SaltByteSize = 24;
    private const int HashByteSize = 24;
    private const int HasingIterationsCount = 10101;


    public static string HashPassword(string password)
    {
        // http://stackoverflow.com/questions/19957176/asp-net-identity-password-hashing

        byte[] salt;
        byte[] buffer2;
        if (password == null)
        {
            throw new ArgumentNullException("password");
        }
        using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, SaltByteSize, HasingIterationsCount))
        {
            salt = bytes.Salt;
            buffer2 = bytes.GetBytes(HashByteSize);
        }
        byte[] dst = new byte[(SaltByteSize + HashByteSize) + 1];
        Buffer.BlockCopy(salt, 0, dst, 1, SaltByteSize);
        Buffer.BlockCopy(buffer2, 0, dst, SaltByteSize + 1, HashByteSize);
        return Convert.ToBase64String(dst);
    }

    public static bool VerifyHashedPassword(string hashedPassword, string password)
    {
        byte[] _passwordHashBytes;

        int _arrayLen = (SaltByteSize + HashByteSize) + 1;

        if (hashedPassword == null)
        {
            return false;
        }

        if (password == null)
        {
            throw new ArgumentNullException("password");
        }

        byte[] src = Convert.FromBase64String(hashedPassword);

        if ((src.Length != _arrayLen) || (src[0] != 0))
        {
            return false;
        }

        byte[] _currentSaltBytes = new byte[SaltByteSize];
        Buffer.BlockCopy(src, 1, _currentSaltBytes, 0, SaltByteSize);

        byte[] _currentHashBytes = new byte[HashByteSize];
        Buffer.BlockCopy(src, SaltByteSize + 1, _currentHashBytes, 0, HashByteSize);

        using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, _currentSaltBytes, HasingIterationsCount))
        {
            _passwordHashBytes = bytes.GetBytes(SaltByteSize);
        }

        return AreHashesEqual(_currentHashBytes, _passwordHashBytes);

    }

    private static bool AreHashesEqual(byte[] firstHash, byte[] secondHash)
    {
        int _minHashLength = firstHash.Length <= secondHash.Length ? firstHash.Length : secondHash.Length;
        var xor = firstHash.Length ^ secondHash.Length;
        for (int i = 0; i < _minHashLength; i++)
            xor |= firstHash[i] ^ secondHash[i];
        return 0 == xor;
    }

In in your custom ApplicationUserManager, you set the PasswordHasher property the name of the class which contains the above code.

Loading cross-domain endpoint with AJAX

If the external site doesn't support JSONP or CORS, your only option is to use a proxy.

Build a script on your server that requests that content, then use jQuery ajax to hit the script on your server.

What is the best way to uninstall gems from a rails3 project?

Bundler now has a bundle remove GEM_NAME command (since v1.17.0, 25 October 2018).

Example of Named Pipes

Linux dotnet core doesn't support namedpipes!

Try TcpListener if you deploy to Linux

This NamedPipe Client/Server code round trips a byte to a server.

  • Client writes byte
  • Server reads byte
  • Server writes byte
  • Client reads byte

DotNet Core 2.0 Server ConsoleApp

using System;
using System.IO.Pipes;
using System.Threading.Tasks;

namespace Server
{
    class Program
    {
        static void Main(string[] args)
        {
            var server = new NamedPipeServerStream("A", PipeDirection.InOut);
            server.WaitForConnection();

            for (int i =0; i < 10000; i++)
            {
                var b = new byte[1];
                server.Read(b, 0, 1); 
                Console.WriteLine("Read Byte:" + b[0]);
                server.Write(b, 0, 1);
            }
        }
    }
}

DotNet Core 2.0 Client ConsoleApp

using System;
using System.IO.Pipes;
using System.Threading.Tasks;

namespace Client
{
    class Program
    {
        public static int threadcounter = 1;
        public static NamedPipeClientStream client;

        static void Main(string[] args)
        {
            client = new NamedPipeClientStream(".", "A", PipeDirection.InOut, PipeOptions.Asynchronous);
            client.Connect();

            var t1 = new System.Threading.Thread(StartSend);
            var t2 = new System.Threading.Thread(StartSend);

            t1.Start();
            t2.Start(); 
        }

        public static void StartSend()
        {
            int thisThread = threadcounter;
            threadcounter++;

            StartReadingAsync(client);

            for (int i = 0; i < 10000; i++)
            {
                var buf = new byte[1];
                buf[0] = (byte)i;
                client.WriteAsync(buf, 0, 1);

                Console.WriteLine($@"Thread{thisThread} Wrote: {buf[0]}");
            }
        }

        public static async Task StartReadingAsync(NamedPipeClientStream pipe)
        {
            var bufferLength = 1; 
            byte[] pBuffer = new byte[bufferLength];

            await pipe.ReadAsync(pBuffer, 0, bufferLength).ContinueWith(async c =>
            {
                Console.WriteLine($@"read data {pBuffer[0]}");
                await StartReadingAsync(pipe); // read the next data <-- 
            });
        }
    }
}

java.util.regex - importance of Pattern.compile()?

Pattern class is the entry point of the regex engine.You can use it through Pattern.matches() and Pattern.comiple(). #Difference between these two. matches()- for quickly check if a text (String) matches a given regular expression comiple()- create the reference of Pattern. So can use multiple times to match the regular expression against multiple texts.

For reference:

public static void main(String[] args) {
     //single time uses
     String text="The Moon is far away from the Earth";
     String pattern = ".*is.*";
     boolean matches=Pattern.matches(pattern,text);
     System.out.println("Matches::"+matches);

    //multiple time uses
     Pattern p= Pattern.compile("ab");
     Matcher  m=p.matcher("abaaaba");
     while(m.find()) {
         System.out.println(m.start()+ " ");
     }
}

Conversion hex string into ascii in bash command line

You can use something like this.

$ cat test_file.txt
54 68 69 73 20 69 73 20 74 65 78 74 20 64 61 74 61 2e 0a 4f 6e 65 20 6d 6f 72 65 20 6c 69 6e 65 20 6f 66 20 74 65 73 74 20 64 61 74 61 2e

$ for c in `cat test_file.txt`; do printf "\x$c"; done;
This is text data.
One more line of test data.

How do I use this JavaScript variable in HTML?

You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.

If you want to display a variable on the screen, this is done with JavaScript.

First, you need somewhere for it to write to:

<body>
    <p id="output"></p>
</body>

Then you need to update your JavaScript code to write to that <p> tag. Make sure you do so after the page is ready.

<script>
window.onload = function(){
    var name = prompt("What's your name?");
    var lengthOfName = name.length

    document.getElementById('output').innerHTML = lengthOfName;
};
</script>

_x000D_
_x000D_
window.onload = function() {_x000D_
  var name = prompt("What's your name?");_x000D_
  var lengthOfName = name.length_x000D_
_x000D_
  document.getElementById('output').innerHTML = lengthOfName;_x000D_
};
_x000D_
<p id="output"></p>
_x000D_
_x000D_
_x000D_

How do I display a ratio in Excel in the format A:B?

At work we only have Excel 2003 available and these two formulas seem to work perfectly for me:

=(ROUND(SUM(B3/C3),0))&":1"

or

=B3/GCD(B3,C3)&":"&C3/GCD(B3,C3)

unknown type name 'uint8_t', MinGW

I had to include "PROJECT_NAME/osdep.h" and that includes the os specific configurations.

I would look in other files using the types you are interested in and find where/how they are defined (by looking at includes).

Correct way to use get_or_create?

The issue you are encountering is a documented feature of get_or_create.

When using keyword arguments other than "defaults" the return value of get_or_create is an instance. That's why it is showing you the parens in the return value.

you could use customer.source = Source.objects.get_or_create(name="Website")[0] to get the correct value.

Here is a link for the documentation: http://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create-kwargs

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

How to import load a .sql or .csv file into SQLite?

Remember that the default delimiter for SQLite is the pipe "|"

sqlite> .separator ";"

sqlite> .import path/filename.txt tablename 

http://sqlite.awardspace.info/syntax/sqlitepg01.htm#sqlite010

What Content-Type value should I send for my XML sitemap?

As a rule of thumb, the safest bet towards making your document be treated properly by all web servers, proxies, and client browsers, is probably the following:

  1. Use the application/xml content type
  2. Include a character encoding in the content type, probably UTF-8
  3. Include a matching character encoding in the encoding attribute of the XML document itself.

In terms of the RFC 3023 spec, which some browsers fail to implement properly, the major difference in the content types is in how clients are supposed to treat the character encoding, as follows:

For application/xml, application/xml-dtd, application/xml-external-parsed-entity, or any one of the subtypes of application/xml such as application/atom+xml, application/rss+xml or application/rdf+xml, the character encoding is determined in this order:

  1. the encoding given in the charset parameter of the Content-Type HTTP header
  2. the encoding given in the encoding attribute of the XML declaration within the document,
  3. utf-8.

For text/xml, text/xml-external-parsed-entity, or a subtype like text/foo+xml, the encoding attribute of the XML declaration within the document is ignored, and the character encoding is:

  1. the encoding given in the charset parameter of the Content-Type HTTP header, or
  2. us-ascii.

Most parsers don't implement the spec; they ignore the HTTP Context-Type and just use the encoding in the document. With so many ill-formed documents out there, that's unlikely to change any time soon.

Javascript button to insert a big black dot (•) into a html textarea

Just access the element and append it to the value.

<input
     type="button" 
     onclick="document.getElementById('myTextArea').value += '•'" 
     value="Add •">

See a live demo.

For the sake of keeping things simple, I haven't written unobtrusive JS. For a production system you should.

Also it needs to be a UTF8 character.

Browsers generally submit forms using the encoding they received the page in. Serve your page as UTF-8 if you want UTF-8 data submitted back.

Logging framework incompatibility

SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log method has been changed (added Object[] p5):

SLF4J 1.5.11:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Throwable p5 )

SLF4J 1.6.0:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Object[] p5, Throwable p6 )

See compatibility reports for other SLF4J versions on this page.

You can generate such reports by the japi-compliance-checker tool.

enter image description here

How do you overcome the HTML form nesting limitation?

Well, if you submit a form, browser also sends a input submit name and value. So what yo can do is

<form   
 action="/post/dispatch/too_bad_the_action_url_is_in_the_form_tag_even_though_conceptually_every_submit_button_inside_it_may_need_to_post_to_a_diffent_distinct_url"  
method="post">  

    <input type="text" name="foo" /> <!-- several of those here -->  
    <div id="toolbar">
        <input type="submit" name="action:save" value="Save" />
        <input type="submit" name="action:delete" value="Delete" />
        <input type="submit" name="action:cancel" value="Cancel" />
    </div>
</form>

so on server side you just look for parameter that starts width string "action:" and the rest part tells you what action to take

so when you click on button Save browser sends you something like foo=asd&action:save=Save

How do I read a text file of about 2 GB?

Instead of loading / reading the complete file, you could use a tool to split the text file in smaller chunks. If you're using Linux, you could just use the split command (see this stackoverflow thread). For Windows, there are several tools available like HJSplit (see this superuser thread).

Microsoft.ACE.OLEDB.12.0 provider is not registered

Are you running a 64 bit system with the database running 32 bit but the console running 64 bit? There are no MS Access drivers that run 64 bit and would report an error identical to the one your reported.

UIView's frame, bounds, center, origin, when to use what?

The properties center, bounds and frame are interlocked: changing one will update the others, so use them however you want. For example, instead of modifying the x/y params of frame to recenter a view, just update the center property.

Global keyboard capture in C# application

private void buttonHook_Click(object sender, EventArgs e)
{
    // Hooks only into specified Keys (here "A" and "B").
    // (***) Use this constructor

    _globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });

    // Hooks into all keys.
    // (***) Or this - not both

    _globalKeyboardHook = new GlobalKeyboardHook();
    _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
}

And then is working fine.

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

i was trying to use airbnb deeplink dispatch and got this error. i had to also exlude the findbugs group from the annotationProcessor.

//airBnb
    compile ('com.airbnb:deeplinkdispatch:3.1.1'){
        exclude group:'com.google.code.findbugs'
    }
    annotationProcessor ('com.airbnb:deeplinkdispatch-processor:3.1.1'){
        exclude group:'com.google.code.findbugs'
    }

what do <form action="#"> and <form method="post" action="#"> do?

Apparently, action was required prior to HTML5 (and # was just a stand in), but you no longer have to use it.

See The Action Attribute:

When specified with no attributes, as below, the data is sent to the same page that the form is present on:

<form>

Replacing .NET WebBrowser control with a better browser, like Chrome?

Chrome uses (a fork of) Webkit if you didn't know, which is also used by Safari. Here's a few questions that are of the same vein:

The webkit one isn't great as the other answer states, one version no longer works (the google code one) and the Mono one is experimental. It'd be nice if someone made the effort to make a decent .NET wrapper for it but it's not something anyone seems to want to do - which is surprising given it now has support for HTML5 and so many other features that the IE(8) engine lacks.

Update (2014)

There's new dual-licensed project that allows you embed Chrome into your .NET applications called Awesomium. It comes with a .NET api but requires quite a few hacks for rendering (the examples draw the browser window to a buffer, paint the buffer as an image and refresh on a timer).

I think this is the browser used by Origin in Battlefield 3.

Update (2016)

There is now DotnetBrowser, a commercial alternative to Awesomium. It's based off Chromium.

What does the exclamation mark do before the function?

! is a logical NOT operator, it's a boolean operator that will invert something to its opposite.

Although you can bypass the parentheses of the invoked function by using the BANG (!) before the function, it will still invert the return, which might not be what you wanted. As in the case of an IEFE, it would return undefined, which when inverted becomes the boolean true.

Instead, use the closing parenthesis and the BANG (!) if needed.

// I'm going to leave the closing () in all examples as invoking the function with just ! and () takes away from what's happening.

(function(){ return false; }());
=> false

!(function(){ return false; }());
=> true

!!(function(){ return false; }());
=> false

!!!(function(){ return false; }());
=> true

Other Operators that work...

+(function(){ return false; }());
=> 0

-(function(){ return false; }());
=> -0

~(function(){ return false; }());
=> -1

Combined Operators...

+!(function(){ return false; }());
=> 1

-!(function(){ return false; }());
=> -1

!+(function(){ return false; }());
=> true

!-(function(){ return false; }());
=> true

~!(function(){ return false; }());
=> -2

~!!(function(){ return false; }());
=> -1

+~(function(){ return false; }());
+> -1

How to declare a static const char* in your header file?

You need to define static variables in a translation unit, unless they are of integral types.

In your header:

private:
    static const char *SOMETHING;
    static const int MyInt = 8; // would be ok

In the .cpp file:

const char *YourClass::SOMETHING = "something";

C++ standard, 9.4.2/4:

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression. In that case, the member can appear in integral constant expressions within its scope. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

Use multiple css stylesheets in the same html page

The one you include last will be the one that is used. Note however that if any rules has !important in the first stylesheet they will take priority.

Get an array of list element contents in jQuery

var optionTexts = [];
$("ul li").each(function() { optionTexts.push($(this).text()) });

...should do the trick. To get the final output you're looking for, join() plus some concatenation will do nicely:

var quotedCSV = '"' + optionTexts.join('", "') + '"';

How do I display a MySQL error in PHP for a long query that depends on the user input?

The suggestions don't work because they are for the standard MySQL driver, not for mysqli:

$this->db_link->error contains the error if one did occur

Or

mysqli_error($this->db_link)

will work.

How to use if - else structure in a batch file?

I believe you can use something such as

if ___ (

do this

) else if ___ (

do this

)

Try/catch does not seem to have an effect

Edit: As stated in the comments, the following solution applies to PowerShell V1 only.

See this blog post on "Technical Adventures of Adam Weigert" for details on how to implement this.

Example usage (copy/paste from Adam Weigert's blog):

Try {
    echo " ::Do some work..."
    echo " ::Try divide by zero: $(0/0)"
} -Catch {
    echo "  ::Cannot handle the error (will rethrow): $_"
    #throw $_
} -Finally {
    echo " ::Cleanup resources..."
}

Otherwise you'll have to use exception trapping.

How to write the Fibonacci Sequence?

Basically translated from Ruby:

def fib(n):
    a = 0
    b = 1
    for i in range(1,n+1):
            c = a + b
            print c
            a = b
            b = c

...

How to write a file with C in Linux?

You have to do write in the same loop as read.

What is float in Java?

Make it

float b= 3.6f;

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d

How to pass command line argument to gnuplot?

In the shell write

gnuplot -persist -e "plot filename1.dat,filename2.dat"

and consecutively the files you want. -persist is used to make the gnuplot screen stay as long as the user doesn't exit it manually.

Load local JSON file into variable

The built-in node.js module fs will do it either asynchronously or synchronously depending on your needs.

You can load it using var fs = require('fs');

Asynchronous

fs.readFile('./content.json', (err, data) => {
    if (err)
      console.log(err);
    else {
      var json = JSON.parse(data);
    //your code using json object
    }
})

Synchronous

var json = JSON.parse(fs.readFileSync('./content.json').toString());

How to use BOOLEAN type in SELECT statement

The BOOLEAN data type is a PL/SQL data type. Oracle does not provide an equivalent SQL data type (...) you can create a wrapper function which maps a SQL type to the BOOLEAN type.

Check this: http://forums.datadirect.com/ddforums/thread.jspa?threadID=1771&tstart=0&messageID=5284

SELECT where row value contains string MySQL

Use the % wildcard, which matches any number of characters.

SELECT * FROM Accounts WHERE Username LIKE '%query%'

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

This BFS-like solution is pretty straightforward. Simply jumps levels one-by-one.

def getHeight(self,root, method='links'):
    c_node = root
    cur_lvl_nodes = [root]
    nxt_lvl_nodes = []
    height = {'links': -1, 'nodes': 0}[method]

    while(cur_lvl_nodes or nxt_lvl_nodes):
        for c_node in cur_lvl_nodes:
            for n_node in filter(lambda x: x is not None, [c_node.left, c_node.right]):
                nxt_lvl_nodes.append(n_node)

        cur_lvl_nodes = nxt_lvl_nodes
        nxt_lvl_nodes = []
        height += 1

    return height

How does DISTINCT work when using JPA and Hibernate

I agree with kazanaki's answer, and it helped me. I wanted to select the whole entity, so I used

 select DISTINCT(c) from Customer c

In my case I have many-to-many relationship, and I want to load entities with collections in one query.

I used LEFT JOIN FETCH and at the end I had to make the result distinct.

Make EditText ReadOnly

This works for me:

EditText.setKeyListener(null);

Can Mockito capture arguments of a method called multiple times?

You can also use @Captor annotated ArgumentCaptor. For example:

@Mock
List<String> mockedList;

@Captor
ArgumentCaptor<String> argCaptor;

@BeforeTest
public void init() {
    //Initialize objects annotated with @Mock, @Captor and @Spy.
    MockitoAnnotations.initMocks(this);
}

@Test
public void shouldCallAddMethodTwice() {
    mockedList.add("one");
    mockedList.add("two");
    Mockito.verify(mockedList, times(2)).add(argCaptor.capture());

    assertEquals("one", argCaptor.getAllValues().get(0));
    assertEquals("two", argCaptor.getAllValues().get(1));
}

Hash String via SHA-256 in Java

You don't necessarily need the BouncyCastle library. The following code shows how to do so using the Integer.toHexString function

public static String sha256(String base) {
    try{
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(base.getBytes("UTF-8"));
        StringBuffer hexString = new StringBuffer();

        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }

        return hexString.toString();
    } catch(Exception ex){
       throw new RuntimeException(ex);
    }
}

Special thanks to user1452273 from this post: How to hash some string with sha256 in Java?

Keep up the good work !

Syntax of for-loop in SQL Server

Extra Info

Just to add as no-one has posted an answer that includes how to actually iterate though a dataset inside a loop, you can use the keywords OFFSET FETCH.

Usage

DECLARE @i INT = 0;
SELECT @count=  Count(*) FROM {TABLE}

WHILE @i <= @count
BEGIN

    SELECT * FROM {TABLE}
    ORDER BY {COLUMN}
    OFFSET @i ROWS   
    FETCH NEXT 1 ROWS ONLY  

    SET @i = @i + 1;

END

CSS Grid Layout not working in IE11 even with prefixes

Michael has given a very comprehensive answer, but I'd like to point out a few things which you can still do to be able to use grids in IE in a nearly painless way.

The repeat functionality is supported

You can still use the repeat functionality, it's just hiding behind a different syntax. Instead of writing repeat(4, 1fr), you have to write (1fr)[4]. That's it. See this series of articles for the current state of affairs: https://css-tricks.com/css-grid-in-ie-debunking-common-ie-grid-misconceptions/

Supporting grid-gap

Grid gaps are supported in all browsers except IE. So you can use the @supports at-rule to set the grid-gaps conditionally for all new browsers:

Example:

.grid {
  display: grid;
}
.item {
  margin-right: 1rem;
  margin-bottom: 1rem;
}
@supports (grid-gap: 1rem) {
  .grid {
    grid-gap: 1rem;
  }
  .item {
    margin-right: 0;
    margin-bottom: 0;
  }
}

It's a little verbose, but on the plus side, you don't have to give up grids altogether just to support IE.

Use Autoprefixer

I can't stress this enough - half the pain of grids is solved just be using autoprefixer in your build step. Write your CSS in a standards-complaint way, and just let autoprefixer do it's job transforming all older spec properties automatically. When you decide you don't want to support IE, just change one line in the browserlist config and you'll have removed all IE-specific code from your built files.

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I had the issue when I put jcenter() before google() in project level build.gradle. When I changed the order and put google() before jcenter() in build.gradle the problem disappeared

Here is my final build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.3'


        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Asp.net Hyperlink control equivalent to <a href="#"></a>

If you want to add the value on aspx page , Just enter <a href='your link'>clickhere</a>

If you are trying to achieve it via Code-Behind., Make use of the Hyperlink control

HyperLink hl1 = new HyperLink();
hl1.text="Click Here";
hl1.NavigateUrl="http://www.stackoverflow.com";

What is the difference between an interface and abstract class?

The main point is that:

  • Abstract is object oriented. It offers the basic data an 'object' should have and/or functions it should be able to do. It is concerned with the object's basic characteristics: what it has and what it can do. Hence objects which inherit from the same abstract class share the basic characteristics (generalization).
  • Interface is functionality oriented. It defines functionalities an object should have. Regardless what object it is, as long as it can do these functionalities, which are defined in the interface, it's fine. It ignores everything else. An object/class can contain several (groups of) functionalities; hence it is possible for a class to implement multiple interfaces.

adding 30 minutes to datetime php/mysql

If you are using MySQL you can do it like this:

SELECT '2008-12-31 23:59:59' + INTERVAL 30 MINUTE;


For a pure PHP solution use strtotime

strtotime('+ 30 minute',$yourdate);

2 "style" inline css img tags?

Do not use more than one style attribute. Just seperate styles in the style attribute with ; It is a block of inline CSS, so think of this as you would do CSS in a separate stylesheet.

So in this case its: style="height:100px;width:100px;"

You can use this for any CSS style, so if you wanted to change the colour of the text to white: style="height:100px;width:100px;color:#ffffff" and so on.

However, it is worth using inline CSS sparingly, as it can make code less manageable in future. Using an external stylesheet may be a better option for this. It depends really on your requirements. Inline CSS does make for quicker coding.

Concatenate two slices in Go

I think it's important to point out and to know that if the destination slice (the slice you append to) has sufficient capacity, the append will happen "in-place", by reslicing the destination (reslicing to increase its length in order to be able to accommodate the appendable elements).

This means that if the destination was created by slicing a bigger array or slice which has additional elements beyond the length of the resulting slice, they may get overwritten.

To demonstrate, see this example:

a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)

x, y := a[:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))

x = append(x, y...)
fmt.Printf("x: %v\n", x)

fmt.Printf("a: %v\n", a)

Output (try it on the Go Playground):

a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 10
x: [1 2 3 4]
a: [1 2 3 4 0 0 0 0 0 0]

We created a "backing" array a with length 10. Then we create the x destination slice by slicing this a array, y slice is created using the composite literal []int{3, 4}. Now when we append y to x, the result is the expected [1 2 3 4], but what may be surprising is that the backing array a also changed, because capacity of x is 10 which is sufficient to append y to it, so x is resliced which will also use the same a backing array, and append() will copy elements of y into there.

If you want to avoid this, you may use a full slice expression which has the form

a[low : high : max]

which constructs a slice and also controls the resulting slice's capacity by setting it to max - low.

See the modified example (the only difference is that we create x like this: x = a[:2:2]:

a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)

x, y := a[:2:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))

x = append(x, y...)
fmt.Printf("x: %v\n", x)

fmt.Printf("a: %v\n", a)

Output (try it on the Go Playground)

a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 2
x: [1 2 3 4]
a: [1 2 0 0 0 0 0 0 0 0]

As you can see, we get the same x result but the backing array a did not change, because capacity of x was "only" 2 (thanks to the full slice expression a[:2:2]). So to do the append, a new backing array is allocated that can store the elements of both x and y, which is distinct from a.

Cron job every three days

Run it every three days...

0 0 */3 * *

How about that?

If you want it to run on specific days of the month, like the 1st, 4th, 7th, etc... then you can just have a conditional in your script that checks for the current day of the month.

if (((date('j') - 1) % 3))
   exit();

or, as @mario points out, you can use date('k') to get the day of the year instead of doing it based on the day of the month.

Printing an array in C++?

Just iterate over the elements. Like this:

for (int i = numElements - 1; i >= 0; i--) 
    cout << array[i];

Note: As Maxim Egorushkin pointed out, this could overflow. See his comment below for a better solution.

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

For anyone having this problem with docker-compose. When you have more than one project (i.e. in different folders) with similar services you need to run docker-compose stop in each of your other projects.

How to save all console output to file in R?

  1. If you want to get error messages saved in a file

    zz <- file("Errors.txt", open="wt")
    sink(zz, type="message")
    

    the output will be:

    Error in print(errr) : object 'errr' not found
    Execution halted
    

    This output will be saved in a file named Errors.txt

  2. In case, you want printed values of console to a file you can use 'split' argument:

    zz <- file("console.txt", open="wt")
    sink(zz,  split=TRUE)
    print("cool")
    print(errr)
    

    output will be:

    [1] "cool"
    

    in console.txt file. So all your console output will be printed in a file named console.txt

How to find the array index with a value?

When the lists aren't extremely long, this is the best way I know:

function getIndex(val) {
    for (var i = 0; i < imageList.length; i++) {
        if (imageList[i] === val) {
            return i;
        }
    }
}

var imageList = [100, 200, 300, 400, 500];
var index = getIndex(200);

Replace X-axis with own values

Not sure if it's what you mean, but you can do this:

plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])

which then gives you the graph:

enter image description here

What is the difference between supervised learning and unsupervised learning?

Supervised learning

Applications in which the training data comprises examples of the input vectors along with their corresponding target vectors are known as supervised learning problems.

Unsupervised learning

In other pattern recognition problems, the training data consists of a set of input vectors x without any corresponding target values. The goal in such unsupervised learning problems may be to discover groups of similar examples within the data, where it is called clustering

Pattern Recognition and Machine Learning (Bishop, 2006)

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

I got this error message with vs2015, ssdt 14.1.xxx, ssrs. For me I think it was something different than described above with a 2 column, same name problem. I added this report, then deleted the report, then when I tried to add the query back in the ssrs wizard I got this message, " An error occurred while the query design method was being saved :invalid object name: tablename" . where tablename was the table on the query the wizard was reading. I tried cleaning the project, I tried rebuilding the project. In my opinion Microsoft isn't completing cleaning out the report when you delete it and as long as you try to add the original query back it won't add. The way I was able to fix it was to create the ssrs report in a whole new project (obviously nothing wrong with the query) and save it off to the side. Then I reopened my original ssrs project, right clicked on Reports, then Add, then add Existing Item. The report added back in just fine with no name conflict.

Socket.IO - how do I get a list of connected sockets/clients?

Socket.io 1.4

Object.keys(io.sockets.sockets); gives you all the connected sockets.

Socket.io 1.0 As of socket.io 1.0, the actual accepted answer isn't valid anymore. So I made a small function that I use as a temporary fix :

function findClientsSocket(roomId, namespace) {
    var res = []
    // the default namespace is "/"
    , ns = io.of(namespace ||"/");

    if (ns) {
        for (var id in ns.connected) {
            if(roomId) {
                var index = ns.connected[id].rooms.indexOf(roomId);
                if(index !== -1) {
                    res.push(ns.connected[id]);
                }
            } else {
                res.push(ns.connected[id]);
            }
        }
    }
    return res;
}

Api for No namespace becomes

// var clients = io.sockets.clients();
// becomes : 
var clients = findClientsSocket();

// var clients = io.sockets.clients('room');
// all users from room `room`
// becomes
var clients = findClientsSocket('room');

Api for a namespace becomes :

// var clients = io.of('/chat').clients();
// becomes
var clients = findClientsSocket(null, '/chat');

// var clients = io.of('/chat').clients('room');
// all users from room `room`
// becomes
var clients = findClientsSocket('room', '/chat');

Also see this related question, in which I give a function that returns the sockets for a given room.

function findClientsSocketByRoomId(roomId) {
var res = []
, room = io.sockets.adapter.rooms[roomId];
if (room) {
    for (var id in room) {
    res.push(io.sockets.adapter.nsp.connected[id]);
    }
}
return res;
}

Socket.io 0.7

API for no namespace:

var clients = io.sockets.clients();
var clients = io.sockets.clients('room'); // all users from room `room`

For a namespace

var clients = io.of('/chat').clients();
var clients = io.of('/chat').clients('room'); // all users from room `room`

Note: Since it seems the socket.io API is prone to breaking, and some solution rely on implementation details, it could be a matter of tracking the clients yourself:

var clients = [];

io.sockets.on('connect', function(client) {
    clients.push(client); 

    client.on('disconnect', function() {
        clients.splice(clients.indexOf(client), 1);
    });
});

Better way to set distance between flexbox items

It won't work in every case but if you have flexible child widths (%) and know the number of items per row you can very cleanly specify the margins of the necessary elements by using nth-child selector/s.

It depends largely on what you mean by "better". This way doesn't require additional wrapper markup for child elements or negative elements - but those things both have their place.

_x000D_
_x000D_
section {_x000D_
  display: block_x000D_
  width: 100vw;_x000D_
}_x000D_
.container {_x000D_
  align-content: flex-start;_x000D_
  align-items: stretch;_x000D_
  background-color: #ccc;_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
  justify-content: flex-start;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.child-item {_x000D_
  background-color: #c00;_x000D_
  margin-bottom: 2%;_x000D_
  min-height: 5em;_x000D_
  width: 32%;_x000D_
}_x000D_
_x000D_
.child-item:nth-child(3n-1) {_x000D_
  margin-left: 2%;_x000D_
  margin-right: 2%;_x000D_
}
_x000D_
<html>_x000D_
  <body>_x000D_
      <div class="container">_x000D_
        <div class="child-item"></div>_x000D_
        <div class="child-item"></div>_x000D_
        <div class="child-item"></div>_x000D_
        <div class="child-item"></div>_x000D_
        <div class="child-item"></div>_x000D_
        <div class="child-item"></div>_x000D_
        <div class="child-item"></div>_x000D_
      </div>_x000D_
   </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Cannot catch toolbar home button click event

This is how I do it to return to the right fragment otherwise if you have several fragments on the same level it would return to the first one if you don´t override the toolbar back button behavior.

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });

How to prettyprint a JSON file?

Use this function and don't sweat having to remember if your JSON is a str or dict again - just look at the pretty print:

import json

def pp_json(json_thing, sort=True, indents=4):
    if type(json_thing) is str:
        print(json.dumps(json.loads(json_thing), sort_keys=sort, indent=indents))
    else:
        print(json.dumps(json_thing, sort_keys=sort, indent=indents))
    return None

pp_json(your_json_string_or_dict)

Virtualbox shared folder permissions

The issue is that the shared folder's permissions are set to not allow symbolic links by default. You can enable them in a few easy steps.

  1. Shut down the virtual machine.
  2. Note your machine name at Machine > Settings > General > Name
  3. Note your shared folder name at 'Machine > Settings > Shared Folders`
  4. Find your VirtualBox root directory and execute the following command. VBoxManage setextradata "" VBoxInternal2/SharedFoldersEnableSymlinksCreate/ 1
  5. Start up the virtual machine and the shared folder will now allow symbolic links.

Insert Data Into Tables Linked by Foreign Key

You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:

insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

If the customer does not exist, you'll get an sql exception which text will be something like:

null value in column "customer_id" violates not-null constraint

(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:

insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.

tell pip to install the dependencies of packages listed in a requirement file

Any way to do this without manually re-installing the packages in a new virtualenv to get their dependencies ? This would be error-prone and I'd like to automate the process of cleaning the virtualenv from no-longer-needed old dependencies.

That's what pip-tools package is for (from https://github.com/jazzband/pip-tools):

Installation

$ pip install --upgrade pip  # pip-tools needs pip==6.1 or higher (!)
$ pip install pip-tools

Example usage for pip-compile

Suppose you have a Flask project, and want to pin it for production. Write the following line to a file:

# requirements.in
Flask

Now, run pip-compile requirements.in:

$ pip-compile requirements.in
#
# This file is autogenerated by pip-compile
# Make changes in requirements.in, then run this to update:
#
#    pip-compile requirements.in
#
flask==0.10.1
itsdangerous==0.24        # via flask
jinja2==2.7.3             # via flask
markupsafe==0.23          # via jinja2
werkzeug==0.10.4          # via flask

And it will produce your requirements.txt, with all the Flask dependencies (and all underlying dependencies) pinned. Put this file under version control as well and periodically re-run pip-compile to update the packages.

Example usage for pip-sync

Now that you have a requirements.txt, you can use pip-sync to update your virtual env to reflect exactly what's in there. Note: this will install/upgrade/uninstall everything necessary to match the requirements.txt contents.

$ pip-sync
Uninstalling flake8-2.4.1:
  Successfully uninstalled flake8-2.4.1
Collecting click==4.1
  Downloading click-4.1-py2.py3-none-any.whl (62kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 65kB 1.8MB/s
  Found existing installation: click 4.0
    Uninstalling click-4.0:
      Successfully uninstalled click-4.0
Successfully installed click-4.1

Exporting PDF with jspdf not rendering CSS

Slight change to @rejesh-yadav wonderful answer.

html2canvas now returns a promise.

html2canvas(document.body).then(function (canvas) {
    var img = canvas.toDataURL("image/png");
    var doc = new jsPDF();
    doc.addImage(img, 'JPEG', 10, 10);
    doc.save('test.pdf');        
});

Hope this helps some!

How to get MAC address of client using PHP?

//Simple & effective way to get client mac address
// Turn on output buffering
ob_start();
//Get the ipconfig details using system commond
system('ipconfig /all');

// Capture the output into a variable

    $mycom=ob_get_contents();

// Clean (erase) the output buffer

    ob_clean();

$findme = "Physical";
//Search the "Physical" | Find the position of Physical text
$pmac = strpos($mycom, $findme);

// Get Physical Address
$mac=substr($mycom,($pmac+36),17);
//Display Mac Address
echo $mac;

Forbidden :You don't have permission to access /phpmyadmin on this server

With the latest version of phpmyadmin 5.0.2+ at least

Check that the actual installation was completed correctly,

Mine had been copied over into a sub folder on a linux machine rather that being at the

/usr/share/phpmyadmin/

Dealing with multiple Python versions and PIP?

On Linux, Mac OS X and other POSIX systems, use the versioned Python commands in combination with the -m switch to run the appropriate copy of pip:

python2.7 -m pip install SomePackage
python3.4 -m pip install SomePackage

(appropriately versioned pip commands may also be available)

On Windows, use the py Python launcher in combination with the -m switch:

py -2.7 -m pip install SomePackage  # specifically Python 2.7
py -3.4 -m pip install SomePackage  # specifically Python 3.4

if you get an error for py -3.4 then try:

pip install SomePackage

Display filename before matching line

No trick necessary.

grep --with-filename 'pattern' file

With line numbers:

grep -n --with-filename 'pattern' file

There is already an object named in the database

"There is already an object named 'AboutUs' in the database."

This exception tells you that somebody has added an object named 'AboutUs' to the database already.

AutomaticMigrationsEnabled = true; can lead to it since data base versions are not controlled by you in this case. In order to avoid unpredictable migrations and make sure that every developer on the team works with the same data base structure I suggest you set AutomaticMigrationsEnabled = false;.

Automatic migrations and Coded migrations can live alongside if you are very careful and the only one developer on a project.

There is a quote from Automatic Code First Migrations post on Data Developer Center:

Automatic Migrations allows you to use Code First Migrations without having a code file in your project for each change you make. Not all changes can be applied automatically - for example column renames require the use of a code-based migration.

Recommendation for Team Environments

You can intersperse automatic and code-based migrations but this is not recommended in team development scenarios. If you are part of a team of developers that use source control you should either use purely automatic migrations or purely code-based migrations. Given the limitations of automatic migrations we recommend using code-based migrations in team environments.

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

What is a .pid file and what does it contain?

Pidfile contains pid of a process. It is a convention allowing long running processes to be more self-aware. Server process can inspect it to stop itself, or have heuristic that its other instance is already running. Pidfiles can also be used to conventiently kill risk manually, e.g. pkill -F <some.pid>

pthread_join() and pthread_exit()

It because every time

void pthread_exit(void *ret);

will be called from thread function so which ever you want to return simply its pointer pass with pthread_exit().

Now at

int pthread_join(pthread_t tid, void **ret);

will be always called from where thread is created so here to accept that returned pointer you need double pointer ..

i think this code will help you to understand this

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>

void* thread_function(void *ignoredInThisExample)
{
    char *a = malloc(10);
    strcpy(a,"hello world");
    pthread_exit((void*)a);
}
int main()
{
    pthread_t thread_id;
    char *b;

    pthread_create (&thread_id, NULL,&thread_function, NULL);

    pthread_join(thread_id,(void**)&b); //here we are reciving one pointer 
                                        value so to use that we need double pointer 
    printf("b is %s\n",b); 
    free(b); // lets free the memory

}

Get current controller in view

I have put this in my partial view:

@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()

in the same kind of situation you describe, and it shows the controller described in the URL (Category for you, Product for me), instead of the actual location of the partial view.

So use this alert instead:

alert('@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()');

How to compare only date components from DateTime in EF?

I think this could help you.

I made an extension since I have to compare dates in repositories filled with EF data and so .Date was not an option since it is not implemented in LinqToEntities translation.

Here is the code:

        /// <summary>
    /// Check if two dates are same
    /// </summary>
    /// <typeparam name="TElement">Type</typeparam>
    /// <param name="valueSelector">date field</param>
    /// <param name="value">date compared</param>
    /// <returns>bool</returns>
    public Expression<Func<TElement, bool>> IsSameDate<TElement>(Expression<Func<TElement, DateTime>> valueSelector, DateTime value)
    {
        ParameterExpression p = valueSelector.Parameters.Single();

        var antes = Expression.GreaterThanOrEqual(valueSelector.Body, Expression.Constant(value.Date, typeof(DateTime)));

        var despues = Expression.LessThan(valueSelector.Body, Expression.Constant(value.AddDays(1).Date, typeof(DateTime)));

        Expression body = Expression.And(antes, despues);

        return Expression.Lambda<Func<TElement, bool>>(body, p);
    }

then you can use it in this way.

 var today = DateTime.Now;
 var todayPosts = from t in turnos.Where(IsSameDate<Turno>(t => t.MyDate, today))
                                      select t);

PHP - Get array value with a numeric index

$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum');
$array = array_values($array);
echo $array[0]; //bar
echo $array[1]; //bin
echo $array[2]; //ipsum

How do I get rid of an element's offset using CSS?

This seems weird, but you can try setting vertical-align: top in the CSS for the inputs. That fixes it in IE8, at least.

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

If your date column is a string of the format '2017-01-01' you can use pandas astype to convert it to datetime.

df['date'] = df['date'].astype('datetime64[ns]')

or use datetime64[D] if you want Day precision and not nanoseconds

print(type(df_launath['date'].iloc[0]))

yields

<class 'pandas._libs.tslib.Timestamp'> the same as when you use pandas.to_datetime

You can try it with other formats then '%Y-%m-%d' but at least this works.

What is correct media query for IPad Pro?

I tried several of the proposed answers but the problem is that the media queries conflicted with other queries and instead of displaying the mobile CSS on the iPad Pro, it was displaying the desktop CSS. So instead of using max and min for dimensions, I used the EXACT VALUES and it works because on the iPad pro you can't resize the browser.

Note that I added a query for mobile CSS that I use for devices with less than 900px width; feel free to remove it if needed.

This is the query, it combines both landscape and portrait, it works for the 12.9" and if you need to target the 10.5" you can simply add the queries for these dimensions:

@media only screen and (max-width: 900px), 
(height: 1024px) and (width: 1366px) and (-webkit-min-device-pixel-ratio: 1.5) and (orientation: landscape), 
(width: 1024px) and (height: 1366px) and (-webkit-min-device-pixel-ratio: 1.5) and (orientation: portrait)  {

     // insert mobile and iPad Pro 12.9" CSS here    
}

Why can't I display a pound (£) symbol in HTML?

Use &#163;. I had the same problem and solved it using jQuery:

$(this).text('&amp;#163;');
  • If you try this and it does not work, just change the jQuery methods,
$(this).html('&amp;#163;');
  • This always work in all contexts...

How to remove carriage return and newline from a variable in shell script

You can use sed as follows:

MY_NEW_VAR=$(echo $testVar | sed -e 's/\r//g')
echo ${MY_NEW_VAR} got it

By the way, try to do a dos2unix on your data file.

How to downgrade Xcode to previous version?

I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.

Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.

What does the colon (:) operator do?

Since most for loops are very similar, Java provides a shortcut to reduce the amount of code required to write the loop called the for each loop.

Here is an example of the concise for each loop:

for (Integer grade : quizGrades){
      System.out.println(grade);
 }    

In the example above, the colon (:) can be read as "in". The for each loop altogether can be read as "for each Integer element (called grade) in quizGrades, print out the value of grade."

Arraylist swap elements

You can use Collections.swap(List<?> list, int i, int j);

How to check if object property exists with a variable holding the property name?

Thank you for everyone's assistance and pushing to get rid of the eval statement. Variables needed to be in brackets, not dot notation. This works and is clean, proper code.

Each of these are variables: appChoice, underI, underObstr.

if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
    //enter code here
}

SSL InsecurePlatform error when using Requests package

if you just want to stopping insecure warning like:

/usr/lib/python3/dist-packages/urllib3/connectionpool.py:794: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html InsecureRequestWarning)

do:

requests.METHOD("https://www.google.com", verify=False)

verify=False

is the key, followings are not good at it:

requests.packages.urllib3.disable_warnings()

or

urllib3.disable_warnings()

but, you HAVE TO know, that might cause potential security risks.

This version of the application is not configured for billing through Google Play

Conclusions in 2021

For all of you who concerned about debugging - You CAN run and debug and test the code in debug mode

Here's how you can test the process:

(This of course relies on the fact that you have already added and activated your products, and your code is ready for integration with those products)

  1. Add com.android.vending.BILLING to the manifest
  2. Upload signed apk to internal testing
  3. Add license testers (Play console -> Settings -> License testing) - If you use multiple accounts on your device and you're not sure which one to use, just add all of them as testers.
  4. Run the application, as you normally would, from Android Studio (* The application should have the same version code as the one you just uploaded to internal testing)

I did the above and it is working just fine.

How to include header files in GCC search path?

Using environment variable is sometimes more convenient when you do not control the build scripts / process.

For C includes use C_INCLUDE_PATH.

For C++ includes use CPLUS_INCLUDE_PATH.

See this link for other gcc environment variables.

Example usage in MacOS / Linux

# `pip install` will automatically run `gcc` using parameters
# specified in the `asyncpg` package (that I do not control)

C_INCLUDE_PATH=/home/scott/.pyenv/versions/3.7.9/include/python3.7m pip install asyncpg

Example usage in Windows

set C_INCLUDE_PATH="C:\Users\Scott\.pyenv\versions\3.7.9\include\python3.7m"

pip install asyncpg

# clear the environment variable so it doesn't affect other builds
set C_INCLUDE_PATH=

Add items in array angular 4

Yes there is a way to do it.

First declare a class.

//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

Then in your component import the class

import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
 name: string;
 empoloyeeID : number;
 empList: Array<Custom> = [];
 constructor() {

 }

 ngOnInit() {
 }
 onEmpCreate(){
   //console.log(this.name,this.empoloyeeID);
   let customObj = new Custom();
   customObj.name = "something";
   customObj.employeeId = 12; 
   this.empList.push(customObj);
   this.name ="";
   this.empoloyeeID = 0; 
 }
}

Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html

Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2

type checking in javascript

A number is an integer if its modulo %1 is 0-

function isInt(n){
    return (typeof n== 'number' && n%1== 0);
}

This is only as good as javascript gets- say +- ten to the 15th.

isInt(Math.pow(2,50)+.1) returns true, as does Math.pow(2,50)+.1 == Math.pow(2,50)

Remove padding from columns in Bootstrap 3

Bootstrap 4 has a native class to do this : add the class .no-gutters to the parent .row

Generate .pem file used to set up Apple Push Notifications

According to Troubleshooting Push Certificate Problems

The SSL certificate available in your Apple Developer Program account contains a public key but not a private key. The private key exists only on the Mac that created the Certificate Signing Request uploaded to Apple. Both the public and private keys are necessary to export the Privacy Enhanced Mail (PEM) file.

Chances are the reason you can't export a working PEM from the certificate provided by the client is that you do not have the private key. The certificate contains the public key, while the private key probably only exists on the Mac that created the original CSR.

You can either:

  1. Try to get the private key from the Mac that originally created the CSR. Exporting the PEM can be done from that Mac or you can copy the private key to another Mac.

or

  1. Create a new CSR, new SSL certificate, and this time back up the private key.

Switching a DIV background image with jQuery

One way to do this is to put both images in the HTML, inside a SPAN or DIV, you can hide the default either with CSS, or with JS on page load. Then you can toggle on click. Here is a similar example I am using to put left/down icons on a list:

$(document).ready(function(){
    $(".button").click(function () {
        $(this).children(".arrow").toggle();
            return false;
    });
});

<a href="#" class="button">
    <span class="arrow">
        <img src="/images/icons/left.png" alt="+" />
    </span>
    <span class="arrow" style="display: none;">
        <img src="/images/down.png" alt="-" />
    </span>
</a>

Git commit date

The show command may be what you want. Try

git show -s --format=%ci <commit>

Other formats for the date string are available as well. Check the manual page for details.

SQL Server format decimal places with commas

Thankfully(?), in SQL Server 2012+, you can now use FORMAT() to achieve this:

FORMAT(@s,'#,0.0000')


In prior versions, at the risk of looking real ugly

[Query]:

declare @s decimal(18,10);
set @s = 1234.1234567;
select replace(convert(varchar,cast(floor(@s) as money),1),'.00',
    '.'+right(cast(@s * 10000 +10000.5 as int),4))

In the first part, we use MONEY->VARCHAR to produce the commas, but FLOOR() is used to ensure the decimals go to .00. This is easily identifiable and replaced with the 4 digits after the decimal place using a mixture of shifting (*10000) and CAST as INT (truncation) to derive the digits.

[Results]:

|   COLUMN_0 |
--------------
| 1,234.1235 |

But unless you have to deliver business reports using SQL Server Management Studio or SQLCMD, this is NEVER the correct solution, even if it can be done. Any front-end or reporting environment has proper functions to handle display formatting.

How to clear form after submit in Angular 2?

To reset your form after submitting, you can just simply invoke this.form.reset(). By calling reset() it will:

  1. Mark the control and child controls as pristine.
  2. Mark the control and child controls as untouched.
  3. Set the value of control and child controls to custom value or null.
  4. Update value/validity/errors of affected parties.

Please find this pull request for a detailed answer. FYI, this PR has already been merged to 2.0.0.

Hopefully this can be helpful and let me know if you have any other questions in regards to Angular2 Forms.

"The public type <<classname>> must be defined in its own file" error in Eclipse

Cant have two public classes in same file

   public class StaticDemo{

Change to

   class StaticDemo{

Custom CSS for <audio> tag?

Besides the box-shadow, transform and border options mentioned in other answers, WebKit browsers currently also obey -webkit-text-fill-color to set the colour of the "time elapsed" numbers, but since there is no way to set their background (which might vary with platform, e.g. inverted high-contrast modes on some operating systems), you would be advised to set -webkit-text-fill-color to the value "initial" if you've used it elsewhere and the audio element is inheriting this, otherwise some users might find those numbers unreadable.

Can I pass an array as arguments to a method with variable arguments in Java?

Yes, a T... is only a syntactic sugar for a T[].

JLS 8.4.1 Format parameters

The last formal parameter in a list is special; it may be a variable arity parameter, indicated by an elipsis following the type.

If the last formal parameter is a variable arity parameter of type T, it is considered to define a formal parameter of type T[]. The method is then a variable arity method. Otherwise, it is a fixed arity method. Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation.

Here's an example to illustrate:

public static String ezFormat(Object... args) {
    String format = new String(new char[args.length])
        .replace("\0", "[ %s ]");
    return String.format(format, args);
}
public static void main(String... args) {
    System.out.println(ezFormat("A", "B", "C"));
    // prints "[ A ][ B ][ C ]"
}

And yes, the above main method is valid, because again, String... is just String[]. Also, because arrays are covariant, a String[] is an Object[], so you can also call ezFormat(args) either way.

See also


Varargs gotchas #1: passing null

How varargs are resolved is quite complicated, and sometimes it does things that may surprise you.

Consider this example:

static void count(Object... objs) {
    System.out.println(objs.length);
}

count(null, null, null); // prints "3"
count(null, null); // prints "2"
count(null); // throws java.lang.NullPointerException!!!

Due to how varargs are resolved, the last statement invokes with objs = null, which of course would cause NullPointerException with objs.length. If you want to give one null argument to a varargs parameter, you can do either of the following:

count(new Object[] { null }); // prints "1"
count((Object) null); // prints "1"

Related questions

The following is a sample of some of the questions people have asked when dealing with varargs:


Vararg gotchas #2: adding extra arguments

As you've found out, the following doesn't "work":

    String[] myArgs = { "A", "B", "C" };
    System.out.println(ezFormat(myArgs, "Z"));
    // prints "[ [Ljava.lang.String;@13c5982 ][ Z ]"

Because of the way varargs work, ezFormat actually gets 2 arguments, the first being a String[], the second being a String. If you're passing an array to varargs, and you want its elements to be recognized as individual arguments, and you also need to add an extra argument, then you have no choice but to create another array that accommodates the extra element.

Here are some useful helper methods:

static <T> T[] append(T[] arr, T lastElement) {
    final int N = arr.length;
    arr = java.util.Arrays.copyOf(arr, N+1);
    arr[N] = lastElement;
    return arr;
}
static <T> T[] prepend(T[] arr, T firstElement) {
    final int N = arr.length;
    arr = java.util.Arrays.copyOf(arr, N+1);
    System.arraycopy(arr, 0, arr, 1, N);
    arr[0] = firstElement;
    return arr;
}

Now you can do the following:

    String[] myArgs = { "A", "B", "C" };
    System.out.println(ezFormat(append(myArgs, "Z")));
    // prints "[ A ][ B ][ C ][ Z ]"

    System.out.println(ezFormat(prepend(myArgs, "Z")));
    // prints "[ Z ][ A ][ B ][ C ]"

Varargs gotchas #3: passing an array of primitives

It doesn't "work":

    int[] myNumbers = { 1, 2, 3 };
    System.out.println(ezFormat(myNumbers));
    // prints "[ [I@13c5982 ]"

Varargs only works with reference types. Autoboxing does not apply to array of primitives. The following works:

    Integer[] myNumbers = { 1, 2, 3 };
    System.out.println(ezFormat(myNumbers));
    // prints "[ 1 ][ 2 ][ 3 ]"

Explicitly select items from a list or tuple

Another possible solution:

sek=[]
L=[1,2,3,4,5,6,7,8,9,0]
for i in [2, 4, 7, 0, 3]:
   a=[L[i]]
   sek=sek+a
print (sek)

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

I had this error running against a webserver with url like:

a.b.domain.com

but there was no certificate for it, so I got a DNS called

a_b.domain.com

Just putting hint to this solution here since this came up top in google.

How to emulate GPS location in the Android Emulator?

First go in DDMS section in your eclipse Than open emulator Control .... Go To Manual Section set lat and long and then press Send Button

Twitter bootstrap modal-backdrop doesn't disappear

for me, the best answer is this.

<body>
<!-- All other HTML -->
<div>
    ...
</div>

<!-- Modal -->
<div class="modal fade" id="myModal">
    ...
</div>

Modal Markup Placement Always try to place a modal's HTML code in a top-level position in your document to avoid other components affecting the modal's appearance and/or functionality.

from this SO answer

join list of lists in python

If you need a list, not a generator, use list():

from itertools import chain
x = [["a","b"], ["c"]]
y = list(chain(*x))

JPA - Persisting a One to Many relationship

You have to set the associatedEmployee on the Vehicle before persisting the Employee.

Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);

newEmployee.setVehicles(vehicles);

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

You're confusing PATH and PYTHONPATH. You need to do this:

export PATH=$PATH:/home/randy/lib/python 

PYTHONPATH is used by the python interpreter to determine which modules to load.

PATH is used by the shell to determine which executables to run.

Angular ng-class if else

Just make a rule for each case:

<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1)  }">

Or use the ternary operator:

<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'">