Programs & Examples On #Pbs

PBS stands for portable batch system, and describes a family of software products for high performance computing.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

From comments:

But, this code never stops (because of integer overflow) !?! Yves Daoust

For many numbers it will not overflow.

If it will overflow - for one of those unlucky initial seeds, the overflown number will very likely converge toward 1 without another overflow.

Still this poses interesting question, is there some overflow-cyclic seed number?

Any simple final converging series starts with power of two value (obvious enough?).

2^64 will overflow to zero, which is undefined infinite loop according to algorithm (ends only with 1), but the most optimal solution in answer will finish due to shr rax producing ZF=1.

Can we produce 2^64? If the starting number is 0x5555555555555555, it's odd number, next number is then 3n+1, which is 0xFFFFFFFFFFFFFFFF + 1 = 0. Theoretically in undefined state of algorithm, but the optimized answer of johnfound will recover by exiting on ZF=1. The cmp rax,1 of Peter Cordes will end in infinite loop (QED variant 1, "cheapo" through undefined 0 number).

How about some more complex number, which will create cycle without 0? Frankly, I'm not sure, my Math theory is too hazy to get any serious idea, how to deal with it in serious way. But intuitively I would say the series will converge to 1 for every number : 0 < number, as the 3n+1 formula will slowly turn every non-2 prime factor of original number (or intermediate) into some power of 2, sooner or later. So we don't need to worry about infinite loop for original series, only overflow can hamper us.

So I just put few numbers into sheet and took a look on 8 bit truncated numbers.

There are three values overflowing to 0: 227, 170 and 85 (85 going directly to 0, other two progressing toward 85).

But there's no value creating cyclic overflow seed.

Funnily enough I did a check, which is the first number to suffer from 8 bit truncation, and already 27 is affected! It does reach value 9232 in proper non-truncated series (first truncated value is 322 in 12th step), and the maximum value reached for any of the 2-255 input numbers in non-truncated way is 13120 (for the 255 itself), maximum number of steps to converge to 1 is about 128 (+-2, not sure if "1" is to count, etc...).

Interestingly enough (for me) the number 9232 is maximum for many other source numbers, what's so special about it? :-O 9232 = 0x2410 ... hmmm.. no idea.

Unfortunately I can't get any deep grasp of this series, why does it converge and what are the implications of truncating them to k bits, but with cmp number,1 terminating condition it's certainly possible to put the algorithm into infinite loop with particular input value ending as 0 after truncation.

But the value 27 overflowing for 8 bit case is sort of alerting, this looks like if you count the number of steps to reach value 1, you will get wrong result for majority of numbers from the total k-bit set of integers. For the 8 bit integers the 146 numbers out of 256 have affected series by truncation (some of them may still hit the correct number of steps by accident maybe, I'm too lazy to check).

How to get user's high resolution profile picture on Twitter?

use this URL : "https://twitter.com/(userName)/profile_image?size=original"

If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient, using TWTRAuthSession.

This is the code snipe for iOS:

if let twitterId = session.userID{
   let twitterClient = TWTRAPIClient(userID: twitterId)
   twitterClient.loadUser(withID: twitterId) {(user, error) in
       if let userName = user?.screenName{
          let url = "https://twitter.com/\(userName)/profile_image?size=original")
       }
   }
}

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

In my case, I decided to remove the homebrew python installation from my mac as I already had two other versions of python installed on my mac through MacPorts. This caused the error message.

Reinstalling python through brew solved my issue.

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

I faced this exception for a long time and was not able to pinpoint the problem. The exception says line 1 column 9. The mistake I did is to get the first line of the file which flume is processing.

Apache flume process the content of the file in patches. So, when flume throws this exception and says line 1, it means the first line in the current patch.

If your flume agent is configured to use batch size = 100, and (for example) the file contains 400 lines, this means the exception is thrown in one of the following lines 1, 101, 201,301.

How to discover the line which causes the problem?

You have three ways to do that.

1- pull the source code and run the agent in debug mode. If you are an average developer like me and do not know how to make this, check the other two options.

2- Try to split the file based on the batch size and run the flume agent again. If you split the file into 4 files, and the invalid json exists between lines 301 and 400, the flume agent will process the first 3 files and stop at the fourth file. Take the fourth file and again split it into more smaller files. continue the process until you reach a file with only one line and flume fails while processing it.

3- Reduce the batch size of the flume agent to only one and compare the number of processed events in the output of the sink you are using. For example, in my case I am using Solr sink. The file contains 400 lines. The flume agent is configured with batch size=100. When I run the flume agent, it fails at some point and throw that exception. At this point check how many documents are ingested in Solr. If the invalid json exists at line 346, the number of documents indexed into Solr will be 345, so the next line is the line which causes the problem.

In my case I followed the third option and fortunately I pinpoint the line which causes the problem.

This is a long answer but it actually does not solve the exception. How I overcome this exception?

I have no idea why Jackson library complain while parsing a json string contains escaped characters \n \r \t. I think (but I am not sure) the Jackson parser is by default escaping these characters which cases the json string to be split into two lines (in case of \n) and then it deals each line as a separate json string.

In my case we used a customized interceptor to remove these characters before being processed by the flume agent. This is the way we solved this problem.

Python json.loads shows ValueError: Extra data

You can just read from a file, jsonifying each line as you go:

tweets = []
for line in open('tweets.json', 'r'):
    tweets.append(json.loads(line))

This avoids storing intermediate python objects. As long as your write one full tweet per append() call, this should work.

Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

data to load:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>

get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

Twitter - share button, but with image

To create a Twitter share link with a photo, you first need to tweet out the photo from your Twitter account. Once you've tweeted it out, you need to grab the pic.twitter.com link and place that inside your twitter share url.

note: You won't be able to see the pic.twitter.com url so what I do is use a separate account and hit the retweet button. A modal will pop up with the link inside.

You Twitter share link will look something like this:

<a href="https://twitter.com/home?status=This%20photo%20is%20awesome!%20Check%20it%20out:%20pic.twitter.com/9Ee63f7aVp">Share on Twitter</a>

Get unique values from a list in python

Same order unique list using only a list compression.

> my_list = [1, 2, 1, 3, 2, 4, 3, 5, 4, 3, 2, 3, 1]
> unique_list = [
>    e
>    for i, e in enumerate(my_list)
>    if my_list.index(e) == i
> ]
> unique_list
[1, 2, 3, 4, 5]

enumerates gives the index i and element e as a tuple.

my_list.index returns the first index of e. If the first index isn't i then the current iteration's e is not the first e in the list.

Edit

I should note that this isn't a good way to do it, performance-wise. This is just a way that achieves it using only a list compression.

How do you echo a 4-digit Unicode character in Bash?

In Bash:

UnicodePointToUtf8()
{
    local x="$1"               # ok if '0x2620'
    x=${x/\\u/0x}              # '\u2620' -> '0x2620'
    x=${x/U+/0x}; x=${x/u+/0x} # 'U-2620' -> '0x2620'
    x=$((x)) # from hex to decimal
    local y=$x n=0
    [ $x -ge 0 ] || return 1
    while [ $y -gt 0 ]; do y=$((y>>1)); n=$((n+1)); done
    if [ $n -le 7 ]; then       # 7
        y=$x
    elif [ $n -le 11 ]; then    # 5+6
        y=" $(( ((x>> 6)&0x1F)+0xC0 )) \
            $(( (x&0x3F)+0x80 ))" 
    elif [ $n -le 16 ]; then    # 4+6+6
        y=" $(( ((x>>12)&0x0F)+0xE0 )) \
            $(( ((x>> 6)&0x3F)+0x80 )) \
            $(( (x&0x3F)+0x80 ))"
    else                        # 3+6+6+6
        y=" $(( ((x>>18)&0x07)+0xF0 )) \
            $(( ((x>>12)&0x3F)+0x80 )) \
            $(( ((x>> 6)&0x3F)+0x80 )) \
            $(( (x&0x3F)+0x80 ))"
    fi
    printf -v y '\\x%x' $y
    echo -n -e $y
}

# test
for (( i=0x2500; i<0x2600; i++ )); do
    UnicodePointToUtf8 $i
    [ "$(( i+1 & 0x1f ))" != 0 ] || echo ""
done
x='U+2620'
echo "$x -> $(UnicodePointToUtf8 $x)"

Output:

-?¦?????????+???+???+???+???+???
????¦???????-???????-???????+???
????????????????-¦++++++++++++¦¦
¦¦¦¦------+++???????????????????
¯???_???¦???¦???¦¦¦¦????????????
¦???????????????????????????????
????????????????????????????????
????????????????????????????????
U+2620 -> ?

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

fopen deprecated warning

I'am using VisualStdio 2008. In this case I often set Preprocessor Definitions

Menu \ Project \ [ProjectName] Properties... Alt+F7

If click this menu or press Alt + F7 in project window, you can see "Property Pages" window.

Then see menu on left of window.

Configuration Properties \ C/C++ \ Preprocessor

Then add _CRT_SECURE_NO_WARNINGS to \ Preprocessor Definitions.

Limiting the output of PHP's echo to 200 characters

echo strlen($row['style-info'])<=200 ? $row['style-info'] : substr($row['style-info'],0,200).'...';

Connecting to local SQL Server database using C#

You try with this string connection

Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database1.mdf;Database=dbname; Trusted_Connection=Yes;

Difference between window.location.href and top.location.href

top object makes more sense inside frames. Inside a frame, window refers to current frame's window while top refers to the outermost window that contains the frame(s). So:

window.location.href = 'somepage.html'; means loading somepage.html inside the frame.

top.location.href = 'somepage.html'; means loading somepage.html in the main browser window.

Two other interesting objects are self and parent.

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

If you came here searching OpenID Connect (OIDC): OAuth 2.0 != OIDC

I recognize that this is tagged for oauth 2.0 and NOT OIDC, however there is frequently a conflation between the 2 standards since both standards can use JWTs and the aud claim. And one (OIDC) is basically an extension of the other (OAUTH 2.0). (I stumbled across this question looking for OIDC myself.)

OAuth 2.0 Access Tokens##

For OAuth 2.0 Access tokens, existing answers pretty well cover it. Additionally here is one relevant section from OAuth 2.0 Framework (RFC 6749)

For public clients using implicit flows, this specification does not provide any method for the client to determine what client an access token was issued to.
...
Authenticating resource owners to clients is out of scope for this specification. Any specification that uses the authorization process as a form of delegated end-user authentication to the client (e.g., third-party sign-in service) MUST NOT use the implicit flow without additional security mechanisms that would enable the client to determine if the access token was issued for its use (e.g., audience- restricting the access token).

OIDC ID Tokens##

OIDC has ID Tokens in addition to Access tokens. The OIDC spec is explicit on the use of the aud claim in ID Tokens. (openid-connect-core-1.0)

aud
REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.

furthermore OIDC specifies the azp claim that is used in conjunction with aud when aud has more than one value.

azp
OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.

Does the Java &= operator apply & or &&?

i came across a similar situation using booleans where I wanted to avoid calling b() if a was already false.

This worked for me:

a &= a && b()

findAll() in yii

This is your safest way to do it:

$id =101;
//$user_id=25;
$criteria=new CDbCriteria;
$criteria->condition="email_id < :email_id";
//$criteria->addCondition("user_id=:user_id");
$criteria->params=array(
  ':email_id' => $id,
  //':user_id' => $user_id,
);
$comments=EmailArchive::model()->findAll($criteria);

Note that if you comment out the commented lines you get a way to add more filtering to your search.

After this it is recommend to check if there is any data returned like:

if (isset($comments)) { // We found some comments, we can sleep well tonight
  // do comments process or whatever
}

Switch statement with returns -- code correctness

Remove the break statements. They aren't needed and perhaps some compilers will issue "Unreachable code" warnings.

MS Excel showing the formula in a cell instead of the resulting value

Check for spaces in your formula before the "=". example' =A1' instean '=A1'

Oracle - How to create a readonly user

A user in an Oracle database only has the privileges you grant. So you can create a read-only user by simply not granting any other privileges.

When you create a user

CREATE USER ro_user
 IDENTIFIED BY ro_user
 DEFAULT TABLESPACE users
 TEMPORARY TABLESPACE temp;

the user doesn't even have permission to log in to the database. You can grant that

GRANT CREATE SESSION to ro_user

and then you can go about granting whatever read privileges you want. For example, if you want RO_USER to be able to query SCHEMA_NAME.TABLE_NAME, you would do something like

GRANT SELECT ON schema_name.table_name TO ro_user

Generally, you're better off creating a role, however, and granting the object privileges to the role so that you can then grant the role to different users. Something like

Create the role

CREATE ROLE ro_role;

Grant the role SELECT access on every table in a particular schema

BEGIN
  FOR x IN (SELECT * FROM dba_tables WHERE owner='SCHEMA_NAME')
  LOOP
    EXECUTE IMMEDIATE 'GRANT SELECT ON schema_name.' || x.table_name || 
                                  ' TO ro_role';
  END LOOP;
END;

And then grant the role to the user

GRANT ro_role TO ro_user;

Keeping it simple and how to do multiple CTE in a query

You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts and the second is named ProductsOverTenDollars.

WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
   SELECT
      CategoryID,
      CategoryName,
      (SELECT COUNT(1) FROM Products p
       WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
   FROM Categories c
),

ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
   SELECT
      ProductID,
      CategoryID,
      ProductName,
      UnitPrice
   FROM Products p
   WHERE UnitPrice > 10.0
)

SELECT c.CategoryName, c.NumberOfProducts,
      p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
   INNER JOIN CategoryAndNumberOfProducts c ON
      p.CategoryID = c.CategoryID
ORDER BY ProductName

php multidimensional array get values

This is the way to iterate on this array:

foreach($hotels as $row) {
       foreach($row['rooms'] as $k) {
             echo $k['boards']['board_id'];
             echo $k['boards']['price'];
       }
}

You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.

Ruby get object keys as array

Use the keys method: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]

Start new Activity and finish current one in Android?

Use finish like this:

Intent i = new Intent(Main_Menu.this, NextActivity.class);
finish();  //Kill the activity from which you will go to next activity 
startActivity(i);

FLAG_ACTIVITY_NO_HISTORY you can use in case for the activity you want to finish. For exampe you are going from A-->B--C. You want to finish activity B when you go from B-->C so when you go from A-->B you can use this flag. When you go to some other activity this activity will be automatically finished.

To learn more on using Intent.FLAG_ACTIVITY_NO_HISTORY read: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NO_HISTORY

Django CharField vs TextField

For eg.,. 2 fields are added in a model like below..

description = models.TextField(blank=True, null=True)
title = models.CharField(max_length=64, blank=True, null=True)

Below are the mysql queries executed when migrations are applied.


for TextField(description) the field is defined as a longtext

ALTER TABLE `sometable_sometable` ADD COLUMN `description` longtext NULL;

The maximum length of TextField of MySQL is 4GB according to string-type-overview.


for CharField(title) the max_length(required) is defined as varchar(64)

ALTER TABLE `sometable_sometable` ADD COLUMN `title` varchar(64) NULL;
ALTER TABLE `sometable_sometable` ALTER COLUMN `title` DROP DEFAULT;

Is there a unique Android device ID?

It's a simple question, with no simple answer.

More over, all of the existing answers here are whether out of date or unreliable.

So if you're searching for a solution in 2020.

Here are a few things to take in mind:

All the hardware based identifiers (SSAID, IMEI, MAC, etc) are unreliable for non-google's devices (Everything except Pixels and Nexuses), which are more than 50% of active devices worldwide. Therefore official Android identifiers best practices clearly states:

Avoid using hardware identifiers, such as SSAID (Android ID), IMEI, MAC address, etc...

That makes most of the answers above invalid. Also due to different android security updates, some of them require newer and stricter runtime permissions, which can be simply denied by user.

As example CVE-2018-9489 which affects all the WIFI based techniques mentioned above.

That makes those identifiers not only unreliable, but also unaccessible in many cases.

So in simpler words: don't use those techniques.

Many other answers here are suggesting to use the AdvertisingIdClient, which is also incompatible, as its by design should be used only for ads profiling. It's also stated in the official reference

Only use an Advertising ID for user profiling or ads use cases

It's not only unreliable for device identification, but you also must follow the user privacy regarding ad tracking policy, which states clearly that user can reset or block it at any moment.

So don't use it either.

Since you cannot have the desired static globally unique and reliable device identifier. Android's official reference suggest:

Use a FirebaseInstanceId or a privately stored GUID whenever possible for all other use cases, except for payment fraud prevention and telephony.

It's unique for the application installation on the device, so when the user uninstall the app - it's wiped out, so it's not 100% reliable, but it's the next best thing.

To use FirebaseInstanceId add the latest firebase-messaging dependency into your gradle

implementation 'com.google.firebase:firebase-messaging:20.2.4'

And use the code below in a background thread:

String reliableIdentifier = FirebaseInstanceId.getInstance().getId();

If you need to store the device identification on your remote server, then don't store it as is (plain text), but a hash with salt.

Today it's not only a best practice, you actually must to do it by law according to GDPR - identifiers and similar regulations.

Git add and commit in one command

I use the following (both are work in progress, so I'll try to remember to update this):

# Add All and Commit
  aac = !echo "Enter commit message:" && read MSG && echo "" && echo "Status before chagnes:" && echo "======================" && git status && echo "" && echo "Adding all..." && echo "=============" && git add . && echo "" && echo "Committing..." && echo "=============" && git commit -m \"$MSG\" && echo "" && echo "New status:" && echo "===========" && git status

# Add All and Commit with bumpted Version number
  aacv = !echo "Status before chagnes:" && echo "======================" && git status && echo "" && echo "Adding all..." && echo "=============" && git add . && echo "" && echo "Committing..." && echo "=============" && git commit -m \"Bumped to version $(head -n 1 VERSION)\" && echo "" && echo "New status:" && echo "===========" && git status

With the echo "Enter commit message:" && read MSG part inspired by Sojan V Jose

I'd love to get an if else statement in there so I can get aacv to ask me if I want to deploy when it's done and do that for me if I type 'y', but I guess I should put that in my .zshrc file

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

Remove element should clear out such errors. The reason behind this is the inherited settings. Your application will inherit some settings from its parent's config file and machine's (server) config files.
You can either remove such duplicates with the remove tag before adding them or make these tags non-inheritable in the upper level config files.

How can I convert an RGB image into grayscale in Python?

Using this formula

Y' = 0.299 R + 0.587 G + 0.114 B 

We can do

import imageio
import numpy as np
import matplotlib.pyplot as plt

pic = imageio.imread('(image)')
gray = lambda rgb : np.dot(rgb[... , :3] , [0.299 , 0.587, 0.114]) 
gray = gray(pic)  
plt.imshow(gray, cmap = plt.get_cmap(name = 'gray'))

However, the GIMP converting color to grayscale image software has three algorithms to do the task.

Shorten string without cutting words in JavaScript

If you (already) using a lodash library, there is a function called truncate which can be used for trimming the string.

Based on the example on the docs page

_.truncate('hi-diddly-ho there, neighborino', {
  'length': 24,
  'separator': ' '
});
// => 'hi-diddly-ho there,...'

Deleting row from datatable in C#

I see a number of answers using the Remove method and others using the Delete method.

Remove (according to the docs) will immediately remove the record from the (local) table, and on Update, will not remove a missing record.

Delete in comparison changes the RowState to Deleted, and will update the server table on Update. Likewise, calling the AcceptChanges method before the Update to the server table will reset all your RowState(s) to Unchanged and nothing will flow to the server. (Still nursing my thumb after hitting this a number of times).

One liner for If string is not null or empty else

There is a null coalescing operator (??), but it would not handle empty strings.

If you were only interested in dealing with null strings, you would use it like

string output = somePossiblyNullString ?? "0";

For your need specifically, there is the conditional operator bool expr ? true_value : false_value that you can use to simplify if/else statement blocks that set or return a value.

string output = string.IsNullOrEmpty(someString) ? "0" : someString;

Change image source in code behind - Wpf

None of the above solutions worked for me. But this did:

myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative));

C# Convert List<string> to Dictionary<string, string>

By using ToDictionary:

var dictionary = list.ToDictionary(s => s);

If it is possible that any string could be repeated, either do a Distinct call first on the list (to remove duplicates), or use ToLookup which allows for multiple values per key.

Why is there no ForEach extension method on IEnumerable?

You could use the (chainable, but lazily evaluated) Select, first doing your operation, and then returning identity (or something else if you prefer)

IEnumerable<string> people = new List<string>(){"alica", "bob", "john", "pete"};
people.Select(p => { Console.WriteLine(p); return p; });

You will need to make sure it is still evaluated, either with Count() (the cheapest operation to enumerate afaik) or another operation you needed anyway.

I would love to see it brought in to the standard library though:

static IEnumerable<T> WithLazySideEffect(this IEnumerable<T> src, Action<T> action) {
  return src.Select(i => { action(i); return i; } );
}

The above code then becomes people.WithLazySideEffect(p => Console.WriteLine(p)) which is effectively equivalent to foreach, but lazy and chainable.

'pip' is not recognized as an internal or external command

I was having the same problem just now.

After adding the proper folder (C:\Python33\Scripts) to the path, I still could not get pip to run. All it took was running pip.exe install -package- instead of pip install -package-.

How do I see which version of Swift I'm using?

Updated answer for how to find which version of Swift your project is using in a few click in Xcode 12 to help out rookies like me.

  1. Click on your Project (top level Blue Icon in the left hand pane)
  2. Click on Build Settings (5th item in the Project > Header)
  3. Scroll down to Swift Compiler - Language, and look at the dropdown.

enter image description here

Autocompletion in Vim

There’s also clang_complete which uses the clang compiler to provide code completion for C++ projects. There’s another question with troubleshooting hints for this plugin.

The plugin seems to work fairly well as long as the project compiles, but is prohibitively slow for large projects (since it attempts a full compilation to generate the tags list).

Is there a minlength validation attribute in HTML5?

The minLength attribute (unlike maxLength) does not exist natively in HTML5. However, there a some ways to validate a field if it contains less than x characters.

An example is given using jQuery at this link: http://docs.jquery.com/Plugins/Validation/Methods/minlength

<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
        <script type="text/javascript">
            jQuery.validator.setDefaults({
                debug: true,
                success: "valid"
            });;
        </script>

        <script>
            $(document).ready(function(){
                $("#myform").validate({
                    rules: {
                        field: {
                            required: true,
                            minlength: 3
                        }
                    }
                });
            });
        </script>
    </head>

    <body>
        <form id="myform">
            <label for="field">Required, Minimum length 3: </label>
            <input class="left" id="field" name="field" />
            <br/>
            <input type="submit" value="Validate!" />
        </form>
    </body>

</html>

Functional, Declarative, and Imperative Programming

imperative - expressions describe sequence of actions to perform (associative)

declarative - expressions are declarations that contribute to behavior of program (associative, commutative, idempotent, monotonic)

functional - expressions have value as only effect; semantics support equational reasoning

Correct location of openssl.cnf file

RHEL: /etc/pki/tls/openssl.cnf

How to open new browser window on button click event?

Or write to the response stream:

Response.Write("<script>");
Response.Write("window.open('page.html','_blank')");
Response.Write("</script>");

Change the maximum upload file size

To locate the ini file, first run

php -i | grep -i "loaded configuration file"

Then open the file and change

upload_max_filesize = 2M
post_max_size = 2M

replacing the 2M with the size you want, for instance 100M.

I've got a blog post about with a little more info too http://www.seanbehan.com/how-to-increase-or-change-the-file-upload-size-in-the-php-ini-file-for-wordpress

Is there any difference between GROUP BY and DISTINCT

For the query you posted, they are identical. But for other queries that may not be true.

For example, it's not the same as:

SELECT C FROM myTbl GROUP BY C, D

MySQL: Insert record if not exists in table

You are inserting not Updating the result. You can define the name column in primary column or set it is unique.

Difference between Running and Starting a Docker container

This is a very important question and the answer is very simple, but fundamental:

  1. Run: create a new container of an image, and execute the container. You can create N clones of the same image. The command is: docker run IMAGE_ID and not docker run CONTAINER_ID

enter image description here

  1. Start: Launch a container previously stopped. For example, if you had stopped a database with the command docker stop CONTAINER_ID, you can relaunch the same container with the command docker start CONTAINER_ID, and the data and settings will be the same.

enter image description here

Export to CSV using jQuery and html

I am not sure if the above CSV generation code is so great as it appears to skip th cells and also did not appear to allow for commas in the value. So here is my CSV generation code that might be useful.

It does assume you have the $table variable which is a jQuery object (eg. var $table = $('#yourtable');)

$rows = $table.find('tr');

var csvData = "";

for(var i=0;i<$rows.length;i++){
                var $cells = $($rows[i]).children('th,td'); //header or content cells

                for(var y=0;y<$cells.length;y++){
                    if(y>0){
                      csvData += ",";
                    }
                    var txt = ($($cells[y]).text()).toString().trim();
                    if(txt.indexOf(',')>=0 || txt.indexOf('\"')>=0 || txt.indexOf('\n')>=0){
                        txt = "\"" + txt.replace(/\"/g, "\"\"") + "\"";
                    }
                    csvData += txt;
                }
                csvData += '\n';
 }

How to know if two arrays have the same values

Simple solution for shallow equality using ES6:

const arr1test = arr1.slice().sort()
const arr2test = arr2.slice().sort()
const equal = !arr1test.some((val, idx) => val !== arr2test[idx])

Creates shallow copies of each array and sorts them. Then uses some() to loop through arr1test values, checking each value against the value in arr2test with the same index. If all values are equal, some() returns false, and in turn equal evaluates to true.

Could also use every(), but it would have to cycle through every element in the array to satisfy a true result, whereas some() will bail as soon as it finds a value that is not equal:

const equal = arr1test.every((val, idx) => val === arr2test[idx])

How to parse month full form string using DateFormat in Java?

You are probably using a locale where the month names are not "January", "February", etc. but some other words in your local language.

Try specifying the locale you wish to use, for example Locale.US:

DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
Date d = fmt.parse("June 27,  2007");

Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.

Tuples( or arrays ) as Dictionary keys in C#

If you are on .NET 4.0 use a Tuple:

lookup = new Dictionary<Tuple<TypeA, TypeB, TypeC>, string>();

If not you can define a Tuple and use that as the key. The Tuple needs to override GetHashCode, Equals and IEquatable:

struct Tuple<T, U, W> : IEquatable<Tuple<T,U,W>>
{
    readonly T first;
    readonly U second;
    readonly W third;

    public Tuple(T first, U second, W third)
    {
        this.first = first;
        this.second = second;
        this.third = third;
    }

    public T First { get { return first; } }
    public U Second { get { return second; } }
    public W Third { get { return third; } }

    public override int GetHashCode()
    {
        return first.GetHashCode() ^ second.GetHashCode() ^ third.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return false;
        }
        return Equals((Tuple<T, U, W>)obj);
    }

    public bool Equals(Tuple<T, U, W> other)
    {
        return other.first.Equals(first) && other.second.Equals(second) && other.third.Equals(third);
    }
}

Celery Received unregistered task of type (run example)

app = Celery('proj',
             broker='amqp://',
             backend='amqp://',
             include=['proj.tasks'])

please include=['proj.tasks'] You need go to the top dir, then exec this

celery -A app.celery_module.celeryapp worker --loglevel=info

not

celery -A celeryapp worker --loglevel=info

in your celeryconfig.py input imports = ("path.ptah.tasks",)

please in other module invoke task!!!!!!!!

grep a file, but show several surrounding lines?

If you search code often, AG the silver searcher is much more efficient (ie faster) than grep.

You show context lines by using -C option.

Eg:

ag -C 3 "foo" myFile

line 1
line 2
line 3
line that has "foo"
line 5
line 6
line 7

How can I show line numbers in Eclipse?

Open Eclipse

goto -> Windows -> Preferences -> Editor -> Text Editors -> Show Line No

Tick the Show Line No checkbox

Is there a Google Sheets formula to put the name of the sheet into a cell?

Here is my proposal for a script which returns the name of the sheet from its position in the sheet list in parameter. If no parameter is provided, the current sheet name is returned.

function sheetName(idx) {
  if (!idx)
    return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
  else {
    var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
    var idx = parseInt(idx);
    if (isNaN(idx) || idx < 1 || sheets.length < idx)
      throw "Invalid parameter (it should be a number from 0 to "+sheets.length+")";
    return sheets[idx-1].getName();
  }
}

You can then use it in a cell like any function

=sheetName() // display current sheet name
=sheetName(1) // display first sheet name
=sheetName(5) // display 5th sheet name

As described by other answers, you need to add this code in a script with :

Tools > Script editor

How do I decode a base64 encoded string?

Simple:

byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);

Single line if statement with 2 actions

userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";

should do the trick.

"&" meaning after variable type

The & means that the function accepts the address (or reference) to a variable, instead of the value of the variable.

For example, note the difference between this:

void af(int& g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

And this (without the &):

void af(int g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

How to send string from one activity to another?

 Intent intent = new Intent(activity1.this, activity2.class);
 intent.putExtra("message", message);
 startActivity(intent);

In activity2, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :

  Bundle bundle = getIntent().getExtras();
  String message = bundle.getString("message");

Numpy - Replace a number with NaN

A[A==NDV]=numpy.nan

A==NDV will produce a boolean array that can be used as an index for A

How can I parse a CSV string with JavaScript, which contains comma in data?

No regexp, readable, and according to https://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules:

function csv2arr(str: string) {
    let line = ["",];
    const ret = [line,];
    let quote = false;

    for (let i = 0; i < str.length; i++) {
        const cur = str[i];
        const next = str[i + 1];

        if (!quote) {
            const cellIsEmpty = line[line.length - 1].length === 0;
            if (cur === '"' && cellIsEmpty) quote = true;
            else if (cur === ",") line.push("");
            else if (cur === "\r" && next === "\n") { line = ["",]; ret.push(line); i++; }
            else if (cur === "\n" || cur === "\r") { line = ["",]; ret.push(line); }
            else line[line.length - 1] += cur;
        } else {
            if (cur === '"' && next === '"') { line[line.length - 1] += cur; i++; }
            else if (cur === '"') quote = false;
            else line[line.length - 1] += cur;
        }
    }
    return ret;
}

How to change letter spacing in a Textview?

This answer is based on Pedro's answer but adjusted so it also works if text attribute is already set:

package nl.raakict.android.spc.widget;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ScaleXSpan;
import android.util.AttributeSet;
import android.widget.TextView;


public class LetterSpacingTextView extends TextView {
    private float letterSpacing = LetterSpacing.BIGGEST;
    private CharSequence originalText = "";


    public LetterSpacingTextView(Context context) {
        super(context);
    }

    public LetterSpacingTextView(Context context, AttributeSet attrs){
        super(context, attrs);
        originalText = super.getText();
        applyLetterSpacing();
        this.invalidate();
    }

    public LetterSpacingTextView(Context context, AttributeSet attrs, int defStyle){
        super(context, attrs, defStyle);
    }

    public float getLetterSpacing() {
        return letterSpacing;
    }

    public void setLetterSpacing(float letterSpacing) {
        this.letterSpacing = letterSpacing;
        applyLetterSpacing();
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        originalText = text;
        applyLetterSpacing();
    }

    @Override
    public CharSequence getText() {
        return originalText;
    }

    private void applyLetterSpacing() {
        if (this == null || this.originalText == null) return;
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < originalText.length(); i++) {
            String c = ""+ originalText.charAt(i);
            builder.append(c.toLowerCase());
            if(i+1 < originalText.length()) {
                builder.append("\u00A0");
            }
        }
        SpannableString finalText = new SpannableString(builder.toString());
        if(builder.toString().length() > 1) {
            for(int i = 1; i < builder.toString().length(); i+=2) {
                finalText.setSpan(new ScaleXSpan((letterSpacing+1)/10), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        super.setText(finalText, BufferType.SPANNABLE);
    }

    public class LetterSpacing {
        public final static float NORMAL = 0;
        public final static float NORMALBIG = (float)0.025;
        public final static float BIG = (float)0.05;
        public final static float BIGGEST = (float)0.2;
    }
}

If you want to use it programatically:

LetterSpacingTextView textView = new LetterSpacingTextView(context);
textView.setSpacing(10); //Or any float. To reset to normal, use 0 or LetterSpacingTextView.Spacing.NORMAL
textView.setText("My text");
//Add the textView in a layout, for instance:
((LinearLayout) findViewById(R.id.myLinearLayout)).addView(textView);

How can I get new selection in "select" in Angular 2?

Just use [ngValue] instead of [value]!!

export class Organisation {
  description: string;
  id: string;
  name: string;
}
export class ScheduleComponent implements OnInit {
  selectedOrg: Organisation;
  orgs: Organisation[] = [];

  constructor(private organisationService: OrganisationService) {}

  get selectedOrgMod() {
    return this.selectedOrg;
  }

  set selectedOrgMod(value) {
    this.selectedOrg = value;
  }
}


<div class="form-group">
      <label for="organisation">Organisation
      <select id="organisation" class="form-control" [(ngModel)]="selectedOrgMod" required>
        <option *ngFor="let org of orgs" [ngValue]="org">{{org.name}}</option>
      </select>
      </label>
</div>

How to find row number of a value in R code

If you want to know the row and column of a value in a matrix or data.frame, consider using the arr.ind=TRUE argument to which:

> which(mydata_2 == 1578, arr.ind=TRUE)
  row col
7   7   3

So 1578 is in column 3 (which you already know) and row 7.

return results from a function (javascript, nodejs)

You are trying to execute an asynchronous function in a synchronous way, which is unfortunately not possible in Javascript.

As you guessed correctly, the roomId=results.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.

Look at this article, it talks about .insert and not .find, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html

make: *** [ ] Error 1 error

From GNU Make error appendix, as you see this is not a Make error but an error coming from gcc.

‘[foo] Error NN’ ‘[foo] signal description’ These errors are not really make errors at all. They mean that a program that make invoked as part of a recipe returned a non-0 error code (‘Error NN’), which make interprets as failure, or it exited in some other abnormal fashion (with a signal of some type). See Errors in Recipes. If no *** is attached to the message, then the subprocess failed but the rule in the makefile was prefixed with the - special character, so make ignored the error.

So in order to attack the problem, the error message from gcc is required. Paste the command in the Makefile directly to the command line and see what gcc says. For more details on Make errors click here.

How to post query parameters with Axios?

axios signature for post is axios.post(url[, data[, config]]). So you want to send params object within the third argument:

.post(`/mails/users/sendVerificationMail`, null, { params: {
  mail,
  firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));

This will POST an empty body with the two query params:

POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName

href="file://" doesn't work

Share your folder for "everyone" or some specific group and try this:

_x000D_
_x000D_
<a href="file://YOURSERVERNAME/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf"> Download PDF </a> 
_x000D_
_x000D_
_x000D_

Extract digits from string - StringUtils Java

try this :

String s = "helloThisIsA1234Sample";
s = s.replaceAll("\\D+","");

This means: replace all occurrences of digital characters (0 -9) by an empty string !

How to handle Pop-up in Selenium WebDriver using Java

String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
String subWindowHandler = null;

Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();

subWindowHandler = iterator.next();

driver.switchTo().window(subWindowHandler); // switch to popup window

// Now you are in the popup window, perform necessary actions here

driver.switchTo().window(parentWindowHandler);  // switch back to parent window

npm ERR! Error: EPERM: operation not permitted, rename

For me i just closed the Code editor (VS Code) and then run the same command. And that solves the issue for me.

Create a temporary table in a SELECT statement without a separate CREATE TABLE

In addition to psparrow's answer if you need to add an index to your temporary table do:

CREATE TEMPORARY TABLE IF NOT EXISTS 
  temp_table ( INDEX(col_2) ) 
ENGINE=MyISAM 
AS (
  SELECT col_1, coll_2, coll_3
  FROM mytable
)

It also works with PRIMARY KEY

How to convert an NSTimeInterval (seconds) into minutes

Swift 2 version

extension NSTimeInterval {
            func toMM_SS() -> String {
                let interval = self
                let componentFormatter = NSDateComponentsFormatter()

                componentFormatter.unitsStyle = .Positional
                componentFormatter.zeroFormattingBehavior = .Pad
                componentFormatter.allowedUnits = [.Minute, .Second]
                return componentFormatter.stringFromTimeInterval(interval) ?? ""
            }
        }
    let duration = 326.4.toMM_SS()
    print(duration)    //"5:26"

Add querystring parameters to link_to

If you want to keep existing params and not expose yourself to XSS attacks, be sure to clean the params hash, leaving only the params that your app can be sending:

# inline
<%= link_to 'Link', params.slice(:sort).merge(per_page: 20) %>

 

If you use it in multiple places, clean the params in the controller:

# your_controller.rb
@params = params.slice(:sort, :per_page)

# view
<%= link_to 'Link', @params.merge(per_page: 20) %>

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

you can use lftp, the swish army knife of downloading if you have bigger files you can add --use-pget-n=10 to command

lftp -c 'mirror --parallel=100 https://example.com/files/ ;exit'

How to remove unused imports in Intellij IDEA on commit?

In IntelliJ, select the project you want to optimize imports on, go to Code menu and choose Optimize imports and a small Optimize Imports popup window will appear. On the popup window you need to click on Run button. Or alternatively, on IntelliJ on Mac, you can use a keyboard short cut Option + Command + O

HTTP POST with URL query parameters -- good idea or not?

Everyone is right: stick with POST for non-idempotent requests.

What about using both an URI query string and request content? Well it's valid HTTP (see note 1), so why not?!

It is also perfectly logical: URLs, including their query string part, are for locating resources. Whereas HTTP method verbs (POST - and its optional request content) are for specifying actions, or what to do with resources. Those should be orthogonal concerns. (But, they are not beautifully orthogonal concerns for the special case of ContentType=application/x-www-form-urlencoded, see note 2 below.)

Note 1: HTTP specification (1.1) does not state that query parameters and content are mutually exclusive for a HTTP server that accepts POST or PUT requests. So any server is free to accept both. I.e. if you write the server there's nothing to stop you choosing to accept both (except maybe an inflexible framework). Generally, the server can interpret query strings according to whatever rules it wants. It can even interpret them with conditional logic that refers to other headers like Content-Type too, which leads to Note 2:

Note 2: if a web browser is the primary way people are accessing your web application, and application/x-www-form-urlencoded is the Content-Type they are posting, then you should follow the rules for that Content-Type. And the rules for application/x-www-form-urlencoded are much more specific (and frankly, unusual): in this case you must interpret the URI as a set of parameters, and not a resource location. [This is the same point of usefulness Powerlord raised; that it may be hard to use web forms to POST content to your server. Just explained a little differently.]

Note 3: what are query strings originally for? RFC 3986 defines HTTP query strings as an URI part that works as a non-hierarchical way of locating a resource.

In case readers asking this question wish to ask what is good RESTful architecture: the RESTful architecture pattern doesn't require URI schemes to work a specific way. RESTful architecture concerns itself with other properties of the system, like cacheability of resources, the design of the resources themselves (their behavior, capabilities, and representations), and whether idempotence is satisfied. Or in other words, achieving a design which is highly compatible with HTTP protocol and its set of HTTP method verbs. :-) (In other words, RESTful architecture is not very presciptive with how the resources are located.)

Final note: sometimes query parameters get used for yet other things, which are neither locating resources nor encoding content. Ever seen a query parameter like 'PUT=true' or 'POST=true'? These are workarounds for browsers that don't allow you to use PUT and POST methods. While such parameters are seen as part of the URL query string (on the wire), I argue that they are not part of the URL's query in spirit.

MySQL Error 1215: Cannot add foreign key constraint

For me it was the column types. BigINT != INT.

But then it still didn't work.

So I checked the engines. Make sure Table1 = InnoDB and Table = InnoDB

CSS scale down image to fit in containing div, without specifing original size

You can use a background image to accomplish this;

From MDN - Background Size: Contain:

This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.

Demo

CSS:

#im {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url("path/to/img");
    background-repeat: no-repeat;
    background-size: contain;
}

HTML:

<div id="wrapper">
    <div id="im">
    </div>
</div>

LISTAGG in Oracle to return distinct values

Further refining @YoYo's correction to @a_horse_with_no_name's row_number() based approach using DECODE vs CASE (i saw here). I see that @Martin Vrbovsky also has this case approach answer.

select
  col1, 
  listagg(col2, ',') within group (order by col2) AS col2_list,
  listagg(col3, ',') within group (order by col3) AS col3_list,
  SUM(col4) AS col4
from (
  select
    col1, 
    decode(row_number() over (partition by col1, col2 order by null),1,col2) as col2,
    decode(row_number() over (partition by col1, col3 order by null),1,col3) as col3
  from foo
)
group by col1;

Get checkbox list values with jQuery

var nameCheckBoxList = "myCheckListName";
var selectedValues = $("[name=" + nameCheckBoxList + "]:checked").map(function(){return this.value;});

How to use target in location.href

If you are using an <a/> to trigger the report, you can try this approach. Instead of attempting to spawn a new window when window.open() fails, make the default scenario to open a new window via target (and prevent it if window.open() succeeds).

HTML

<a href="http://my/url" target="_blank" id="myLink">Link</a>

JS

var spawn = function (e) {
    try {
        window.open(this.href, "","width=1002,height=700,location=0,menubar=0,scrollbars=1,status=1,resizable=0")
        e.preventDefault(); // Or: return false;
    } catch(e) {
    // Allow the default event handler to take place
    }
}

document.getElementById("myLink").onclick = spawn;

Appending to an existing string

Can I ask why this is important?

I know that this is not a direct answer to your question, but the fact that you are trying to preserve the object ID of a string might indicate that you should look again at what you are trying to do.

You might find, for instance, that relying on the object ID of a string will lead to bugs that are quite hard to track down.

Read/write to file using jQuery

Use javascript's execCommand('SaveAs', false, filename); functionality

Edit: No longer works. This Javascript function used to work across all browsers, but now only on IE, due to browser security considerations. It presented a "Save As" Dialog to the user who runs this function through their browser, the user presses OK and the file is saved by javascript on the server side.

Now this code is an rare antique zero day collectible.

// content is the data (a string) you'll write to file.
// filename is a string filename to write to on server side.
// This function uses iFrame as a buffer, it fills it up with your content
// and prompts the user to save it out.
function save_content_to_file(content, filename){
    var dlg = false;
    with(document){
     ir=createElement('iframe');
     ir.id='ifr';
     ir.location='about.blank';
     ir.style.display='none';
     body.appendChild(ir);
      with(getElementById('ifr').contentWindow.document){
           open("text/plain", "replace");
           charset = "utf-8";
           write(content);
           close();
           document.charset = "utf-8";
           dlg = execCommand('SaveAs', false, filename);
       }
       body.removeChild(ir);
     }
    return dlg;
}

Invoke the function like this:

msg =  "I am the president of tautology club.";
save_content_to_file(msg, "C:\\test");

Initializing a struct to 0

I also thought this would work but it's misleading:

myStruct _m1 = {0};

When I tried this:

myStruct _m1 = {0xff};

Only the 1st byte was set to 0xff, the remaining ones were set to 0. So I wouldn't get into the habit of using this.

How to lock orientation of one view controller to portrait mode only in Swift

Here is a simple way that works for me with Swift 4.2 (iOS 12.2), put this in a UIViewController for which you want to disable shouldAutorotate:

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

The .portrait part tells it in which orientation(s) to remain, you can change this as you like. Choices are: .portrait, .all, .allButUpsideDown, .landscape, .landscapeLeft, .landscapeRight, .portraitUpsideDown.

.prop() vs .attr()

attributes -> HTML

properties -> DOM

Get everything after the dash in a string in JavaScript

You can use split method for it. And if you should take string from specific pattern you can use split with req. exp.:

_x000D_
_x000D_
var string = "sometext-20202";
console.log(string.split(/-(.*)/)[1])
_x000D_
_x000D_
_x000D_

Using File.listFiles with FileNameExtensionFilter

With java lambdas (available since java 8) you can simply convert javax.swing.filechooser.FileFilter to java.io.FileFilter in one line.

javax.swing.filechooser.FileFilter swingFilter = new FileNameExtensionFilter("jpeg files", "jpeg");
java.io.FileFilter ioFilter = file -> swingFilter.accept(file);
new File("myDirectory").listFiles(ioFilter);

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

https://fettblog.eu/gulp-4-parallel-and-series/

Because gulp.task(name, deps, func) was replaced by gulp.task(name, gulp.{series|parallel}(deps, func)).

You are using the latest version of gulp but older code. Modify the code or downgrade.

Show a message box from a class in c#?

using System.Windows.Forms;

public class message
{
    static void Main()
    {  
        MessageBox.Show("Hello World!"); 
    }
}

Mongoimport of json file

Using mongoimport you can able to achieve the same

mongoimport --db test --collection user --drop --file ~/downloads/user.json

where,

test - Database name
user - collection name
user.json - dataset file

--drop is drop the collection if already exist.

resize2fs: Bad magic number in super-block while trying to open

I ran into the same exact problem around noon today and finally found a solution here --> Trying to resize2fs EB volume fails

I skipped mounting, since the partition was already mounted.

Apparently CentOS 7 uses XFS as the default file system and as a result resize2fs will fail.

I took a look in /etc/fstab, and guess what, XFS was staring me in the face... Hope this helps.

How can I determine if an image has loaded, using Javascript/jQuery?

May I suggest a pure CSS solution altogether?

Just have a Div that you want to show the image in. Set the image as background. Then have the property background-size: cover or background-size: contain depending on how you want it.

cover will crop the image until smaller sides cover the box. contain will keep the entire image inside the div, leaving you with spaces on sides.

Check the snippet below.

_x000D_
_x000D_
div {_x000D_
  height: 300px;_x000D_
  width: 300px;_x000D_
  border: 3px dashed grey;_x000D_
  background-position: center;_x000D_
  background-repeat: no-repeat;_x000D_
}_x000D_
_x000D_
.cover-image {_x000D_
  background-size: cover;_x000D_
}_x000D_
_x000D_
.contain-image {_x000D_
  background-size: contain;_x000D_
}
_x000D_
<div class="cover-image" style="background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)">_x000D_
</div>_x000D_
<br/>_x000D_
<div class="contain-image" style="background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)">_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I delete all of my Git stashes at once?

There are two ways to delete a stash:

  1. If you no longer need a particular stash, you can delete it with: $ git stash drop <stash_id>.
  2. You can delete all of your stashes from the repo with: $ git stash clear.

Use both of them with caution, it maybe is difficult to revert the once deleted stashes.

Here is the reference article.

How to copy a row and insert in same table with a autoincrement field in MySQL?

For a quick, clean solution that doesn't require you to name columns, you can use a prepared statement as described here: https://stackoverflow.com/a/23964285/292677

If you need a complex solution so you can do this often, you can use this procedure:

DELIMITER $$

CREATE PROCEDURE `duplicateRows`(_schemaName text, _tableName text, _whereClause text, _omitColumns text)
SQL SECURITY INVOKER
BEGIN
  SELECT IF(TRIM(_omitColumns) <> '', CONCAT('id', ',', TRIM(_omitColumns)), 'id') INTO @omitColumns;

  SELECT GROUP_CONCAT(COLUMN_NAME) FROM information_schema.columns 
  WHERE table_schema = _schemaName AND table_name = _tableName AND FIND_IN_SET(COLUMN_NAME,@omitColumns) = 0 ORDER BY ORDINAL_POSITION INTO @columns;

  SET @sql = CONCAT('INSERT INTO ', _tableName, '(', @columns, ')',
  'SELECT ', @columns, 
  ' FROM ', _schemaName, '.', _tableName, ' ',  _whereClause);

  PREPARE stmt1 FROM @sql;
  EXECUTE stmt1;
END

You can run it with:

CALL duplicateRows('database', 'table', 'WHERE condition = optional', 'omit_columns_optional');

Examples

duplicateRows('acl', 'users', 'WHERE id = 200'); -- will duplicate the row for the user with id 200
duplicateRows('acl', 'users', 'WHERE id = 200', 'created_ts'); -- same as above but will not copy the created_ts column value    
duplicateRows('acl', 'users', 'WHERE id = 200', 'created_ts,updated_ts'); -- same as above but also omits the updated_ts column
duplicateRows('acl', 'users'); -- will duplicate all records in the table

DISCLAIMER: This solution is only for someone who will be repeatedly duplicating rows in many tables, often. It could be dangerous in the hands of a rogue user.

JavaScript: Upload file

Pure JS

You can use fetch optionally with await-try-catch

let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
     
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});

_x000D_
_x000D_
async function SavePhoto(inp) 
{
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
         
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user)); 
    
    const ctrl = new AbortController()    // timeout
    setTimeout(() => ctrl.abort(), 5000);
    
    try {
       let r = await fetch('/upload/image', 
         {method: "POST", body: formData, signal: ctrl.signal}); 
       console.log('HTTP response code:',r.status); 
    } catch(e) {
       console.log('Huston we have problem...:', e);
    }
    
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Before selecting the file open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)
_x000D_
_x000D_
_x000D_

Old school approach - xhr

let photo = document.getElementById("image-file").files[0];  // file from input
let req = new XMLHttpRequest();
let formData = new FormData();

formData.append("photo", photo);                                
req.open("POST", '/upload/image');
req.send(formData);

_x000D_
_x000D_
function SavePhoto(e) 
{
    let user = { name:'john', age:34 };
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    let photo = e.files[0];      
    
    formData.append("user", JSON.stringify(user));   
    formData.append("photo", photo);
    
    xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
    xhr.timeout = 5000;
    xhr.open("POST", '/upload/image'); 
    xhr.send(formData);
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Choose file and open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)
_x000D_
_x000D_
_x000D_

SUMMARY

  • In server side you can read original file name (and other info) which is automatically included to request by browser in filename formData parameter.
  • You do NOT need to set request header Content-Type to multipart/form-data - this will be set automatically by browser.
  • Instead of /upload/image you can use full address like http://.../upload/image.
  • If you want to send many files in single request use multiple attribute: <input multiple type=... />, and attach all chosen files to formData in similar way (e.g. photo2=...files[2];... formData.append("photo2", photo2);)
  • You can include additional data (json) to request e.g. let user = {name:'john', age:34} in this way: formData.append("user", JSON.stringify(user));
  • You can set timeout: for fetch using AbortController, for old approach by xhr.timeout= milisec
  • This solutions should work on all major browsers.

Convert java.time.LocalDate into java.util.Date type

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

That assumes your date chooser uses the system default timezone to transform dates into strings.

Transpose a range in VBA

Something like this should do it for you.

Sub CombineColumns1()
    Dim xRng As Range
    Dim i As Long, j As Integer
    Dim xNextRow As Long
    Dim xTxt As String
    On Error Resume Next
    With ActiveSheet
        xTxt = .RangeSelection.Address
        Set xRng = Application.InputBox("please select the data range", "Kutools for Excel", xTxt, , , , , 8)
        If xRng Is Nothing Then Exit Sub
        j = xRng.Columns(1).Column
        For i = 4 To xRng.Columns.Count Step 3
            'Need to recalculate the last row, as some of the final columns may not have data in all rows
            xNextRow = .Cells(.Rows.Count, j).End(xlUp).Row + 1

            .Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Copy .Cells(xNextRow, j)
            .Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Clear
        Next
    End With
End Sub

You could do this too.

Sub TransposeFormulas()
    Dim vFormulas As Variant
    Dim oSel As Range
    If TypeName(Selection) <> "Range" Then
        MsgBox "Please select a range of cells first.", _
                vbOKOnly + vbInformation, "Transpose formulas"
        Exit Sub
    End If
    Set oSel = Selection
    vFormulas = oSel.Formula
    vFormulas = Application.WorksheetFunction.Transpose(vFormulas)
    oSel.Offset(oSel.Rows.Count + 2).Resize(oSel.Columns.Count, oSel.Rows.Count).Formula = vFormulas
End Sub

See this for more info.

http://bettersolutions.com/vba/arrays/transposing.htm

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

This solution is Only for local system / localhost on windows:

The simplest way to install xampp 5.6.X version as per your requirement in other windows drive then run xampp 5.6.X services from it's control panel for php 5.6 version.

NOTE: If you already have xampp (any other version) on your system then please close that xampp's services then start xampp 5.6.x services otherwise this solution will not work.

You can download your required (xampp 5.6 as per question) xampp version from below link:

https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/

I have used this solution many times, it worked like charm. I hope this will also help you. Thank you to ask this question.

document.getElementById('btnid').disabled is not working in firefox and chrome

Another alternative :

document.formname.elementname.disabled=true

Work on FF and IE ! :)

Failed to install Python Cryptography package with PIP and setup.py

I noticed the original poster was clearly using a windows installation... and the best answers above are all for other OSs... so here goes. This assumes you have installed Python 2.7 which is the most widely supported (though old) version.

  1. Install the "Visual C++ Compiler for Python"
  2. Open an Administrative command prompt window
  3. Re-run pip install (package) e.g.

    cd C:\Python27\Scripts
    pip install cryptography  (or pycrypto, fabric, etc)
    

how to use JSON.stringify and json_decode() properly

jsonText = $_REQUEST['myJSON'];

$decodedText = html_entity_decode($jsonText);

$myArray = json_decode($decodedText, true);`

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

From the jQuery docs for processData:

processData Boolean
Default: true
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

Source: http://api.jquery.com/jquery.ajax

Looks like you are going to have to use processData to send your data to the server, or modify your php script to support querystring encoded parameters.

SQL Server : check if variable is Empty or NULL for WHERE clause

Just use

If @searchType is null means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType is NULL

If @searchType is an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType = ''

If @searchType is null or an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR Coalesce(@SearchType,'') = ''

download a file from Spring boot rest service

    @GetMapping("/downloadfile/{productId}/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable(value = "productId") String productId,
        @PathVariable String fileName, HttpServletRequest request) {
    // Load file as Resource
    Resource resource;

    String fileBasePath = "C:\\Users\\v_fzhang\\mobileid\\src\\main\\resources\\data\\Filesdown\\" + productId
            + "\\";
    Path path = Paths.get(fileBasePath + fileName);
    try {
        resource = new UrlResource(path.toUri());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }

    // Try to determine file's content type
    String contentType = null;
    try {
        contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
    } catch (IOException ex) {
        System.out.println("Could not determine file type.");
    }

    // Fallback to the default content type if type could not be determined
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
            .body(resource);
}

To test it, use postman

http://localhost:8080/api/downloadfile/GDD/1.zip

Mapping many-to-many association table with extra column(s)

As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.

For instance, the implementation code of the extra class should look like that:

@Entity
@Table(name = "USER_SERVICES")
public class UserService{

    // example of auto-generated ID
    @Id
    @Column(name = "USER_SERVICES_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long userServiceID;



    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SERVICE_ID")
    private Service service;



    // example of extra column
    @Column(name="VISIBILITY")    
    private boolean visibility;



    public long getUserServiceID() {
        return userServiceID;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public boolean getVisibility() {
        return visibility;
    }

    public void setVisibility(boolean visibility) {
        this.visibility = visibility;
    }

}

How to format numbers by prepending 0 to single-digit numbers?

My Example like this

         var n =9;
         var checkval=('00'+n).slice(-2);
         console.log(checkval)

and the output is 09

jQuery UI autocomplete with item and id

Just want to share what worked on my end, in case it would be able to help someone else too. Alternatively based on Paty Lustosa's answer above, please allow me to add another approach derived from this site where he used an ajax approach for the source method

http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3

The kicker is the resulting "string" or json format from your php script (listing.php below) that derives the result set to be shown in the autocomplete field should follow something like this:

    {"list":[
     {"value": 1, "label": "abc"},
     {"value": 2, "label": "def"},
     {"value": 3, "label": "ghi"}
    ]}

Then on the source portion of the autocomplete method:

    source: function(request, response) {
        $.getJSON("listing.php", {
            term: request.term
        }, function(data) {                     
            var array = data.error ? [] : $.map(data.list, function(m) {
                return {
                    label: m.label,
                    value: m.value
                };
            });
            response(array);
        });
    },
    select: function (event, ui) {
        $("#autocomplete_field").val(ui.item.label); // display the selected text
        $("#field_id").val(ui.item.value); // save selected id to hidden input
        return false;
    }

Hope this helps... all the best!

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

Use the backslash before db on the header and you can use it then typically as you wrote it before.

Here is the example:

Use \DB;

Then inside your controller class you can use as you did before, like that ie :

$item = DB::table('items')->get();

VSCode single to double quote automatic replace

It looks like it is a bug open for this issue: Prettier Bug

None of above solution worked for me. The only thing that worked was, adding this line of code in package.json:

"prettier": {
    "singleQuote": true
  },

Is Secure.ANDROID_ID unique for each device?

There are multiple solution exist but none of them perfect. let's go one by one.

1. Unique Telephony Number (IMEI, MEID, ESN, IMSI)

  • This solution needs to request for android.permission.READ_PHONE_STATE to your user which can be hard to justify following the type of application you have made.

  • Furthermore, this solution is limited to smartphones because tablets don’t have telephony services. One advantage is that the value survives to factory resets on devices.

2. MAC Address

  • You can also try to get a MAC Address from a device having a Wi-Fi or Bluetooth hardware. But, this solution is not recommended because not all of the device have Wi-Fi connection. Even if the user have a Wi-Fi connection, it must be turned on to retrieve the data. Otherwise, the call doesn’t report the MAC Address.

3. Serial Number

  • Devices without telephony services like tablets must report a unique device ID that is available via android.os.Build.SERIAL since Android 2.3 Gingerbread. Some phones having telephony services can also define a serial number. Like not all Android devices have a Serial Number, this solution is not reliable.

4. Secure Android ID

  • On a device first boot, a randomly value is generated and stored. This value is available via Settings.Secure.ANDROID_ID . It’s a 64-bit number that should remain constant for the lifetime of a device. ANDROID_ID seems a good choice for a unique device identifier because it’s available for smartphones and tablets.

    String androidId = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);
    
  • However, the value may change if a factory reset is performed on the device. There is also a known bug with a popular handset from a manufacturer where every instance have the same ANDROID_ID. Clearly, the solution is not 100% reliable.

5. Use UUID

  • As the requirement for most of applications is to identify a particular installation and not a physical device, a good solution to get unique id for an user if to use UUID class. The following solution has been presented by Reto Meier from Google in a Google I/O presentation :

    private static String uniqueID = null;
    private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
    public synchronized static String id(Context context) {
       if (uniqueID == null) {
           SharedPreferences sharedPrefs = context.getSharedPreferences(
                   PREF_UNIQUE_ID, Context.MODE_PRIVATE);
           uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
           if (uniqueID == null) {
               uniqueID = UUID.randomUUID().toString();
               Editor editor = sharedPrefs.edit();
               editor.putString(PREF_UNIQUE_ID, uniqueID);
               editor.commit();
           }
       }    return uniqueID;
    }
    

Identify a particular device on Android is not an easy thing. There are many good reasons to avoid that. Best solution is probably to identify a particular installation by using UUID solution. credit : blog

Convert array values from string to int?

Not sure if this is faster but flipping an array twice will cast numeric strings to integers:

$string = "1,2,3,bla";
$ids = array_flip(array_flip(explode(',', $string)));
var_dump($ids);

Important: Do not use this if you are dealing with duplicate values!

How to submit form on change of dropdown list?

To those in the answer above. It's definitely JavaScript. It's just inline.

BTW the jQuery equivalent if you want to apply to all selects:

$('form select').on('change', function(){
    $(this).closest('form').submit();
});

UIView with rounded corners and drop shadow?

var shadows = UIView()
shadows.frame = view.frame
shadows.clipsToBounds = false
view.addSubview(shadows)


let shadowPath0 = UIBezierPath(roundedRect: shadows.bounds, cornerRadius: 10)
let layer0 = CALayer()
layer0.shadowPath = shadowPath0.cgPath
layer0.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.23).cgColor
layer0.shadowOpacity = 1
layer0.shadowRadius = 6
layer0.shadowOffset = CGSize(width: 0, height: 3)
layer0.bounds = shadows.bounds
layer0.position = shadows.center

shadows.layer.addSublayer(layer0)

Why am I getting InputMismatchException?

Are you providing write input to the console ?

Scanner reader = new Scanner(System.in);
num = reader.nextDouble();  

This is return double if you just enter number like 456. In case you enter a string or character instead,it will throw java.util.InputMismatchException when it tries to do num = reader.nextDouble() .

Could not find a part of the path ... bin\roslyn\csc.exe

In my situation, our team don't want to keep 'packages' folder, so we put all dlls in other directory like 'sharedlib'.

I used build event to solve this problem.

if "$(ConfigurationName)" == "Release" (
goto :release
) else (
goto:exit
)

:release
if not exist $(TargetDir)\roslyn mkdir $(TargetDir)\roslyn

copy /Y "$(ProjectDir)..\..\Shared Lib\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\tools\Roslyn45\*" "$(TargetDir)\roslyn"
goto :exit

:exit

How can I solve equations in Python?

There are two ways to approach this problem: numerically and symbolically.

To solve it numerically, you have to first encode it as a "runnable" function - stick a value in, get a value out. For example,

def my_function(x):
    return 2*x + 6

It is quite possible to parse a string to automatically create such a function; say you parse 2x + 6 into a list, [6, 2] (where the list index corresponds to the power of x - so 6*x^0 + 2*x^1). Then:

def makePoly(arr):
    def fn(x):
        return sum(c*x**p for p,c in enumerate(arr))
    return fn

my_func = makePoly([6, 2])
my_func(3)    # returns 12

You then need another function which repeatedly plugs an x-value into your function, looks at the difference between the result and what it wants to find, and tweaks its x-value to (hopefully) minimize the difference.

def dx(fn, x, delta=0.001):
    return (fn(x+delta) - fn(x))/delta

def solve(fn, value, x=0.5, maxtries=1000, maxerr=0.00001):
    for tries in xrange(maxtries):
        err = fn(x) - value
        if abs(err) < maxerr:
            return x
        slope = dx(fn, x)
        x -= err/slope
    raise ValueError('no solution found')

There are lots of potential problems here - finding a good starting x-value, assuming that the function actually has a solution (ie there are no real-valued answers to x^2 + 2 = 0), hitting the limits of computational accuracy, etc. But in this case, the error minimization function is suitable and we get a good result:

solve(my_func, 16)    # returns (x =) 5.000000000000496

Note that this solution is not absolutely, exactly correct. If you need it to be perfect, or if you want to try solving families of equations analytically, you have to turn to a more complicated beast: a symbolic solver.

A symbolic solver, like Mathematica or Maple, is an expert system with a lot of built-in rules ("knowledge") about algebra, calculus, etc; it "knows" that the derivative of sin is cos, that the derivative of kx^p is kpx^(p-1), and so on. When you give it an equation, it tries to find a path, a set of rule-applications, from where it is (the equation) to where you want to be (the simplest possible form of the equation, which is hopefully the solution).

Your example equation is quite simple; a symbolic solution might look like:

=> LHS([6, 2]) RHS([16])

# rule: pull all coefficients into LHS
LHS, RHS = [lh-rh for lh,rh in izip_longest(LHS, RHS, 0)], [0]

=> LHS([-10,2]) RHS([0])

# rule: solve first-degree poly
if RHS==[0] and len(LHS)==2:
    LHS, RHS = [0,1], [-LHS[0]/LHS[1]]

=> LHS([0,1]) RHS([5])

and there is your solution: x = 5.

I hope this gives the flavor of the idea; the details of implementation (finding a good, complete set of rules and deciding when each rule should be applied) can easily consume many man-years of effort.

Replacing &nbsp; from javascript dom text node

for me replace doesn't work... try this code:

str = str.split("&quot;").join('"');

Using PHP with Socket.io

We are now in 2018 and hoola, there is a way to implement WS and WAMPServer on php. It 's Called Ratchet.

Access parent URL from iframe

The following line will work: document.location.ancestorOrigins[0] this one returns the ancestor domain name.

Which comment style should I use in batch files?

There are a number of ways to comment in a batch file

1)Using rem

This is the official way. It apparently takes longer to execute than ::, although it apparently stops parsing early, before the carets are processed. Percent expansion happens before rem and :: are identified, so incorrect percent usage i.e. %~ will cause errors if percents are present. Safe to use anywhere in code blocks.

2)Using labels :, :: or :; etc.

For :: comment, ': comment' is an invalid label name because it begins with an invalid character. It is okay to use a colon in the middle of a label though. If a space begins at the start of label, it is removed : label becomes :label. If a space or a colon appears in the middle of the label, the rest of the name is not interpreted meaning that if there are two labels :f:oo and :f rr, both will be interpreted as :f and only the later defined label in the file will be jumped to. The rest of the label is effectively a comment. There are multiple alternatives to ::, listed here. You can never goto or call a ::foo label. goto :foo and goto ::foo will not work.

They work fine outside of code blocks but after a label in a code block, invalid or not, there has to be a valid command line. :: comment is indeed another valid command. It interprets it as a command and not a label; the command has precedence. Which is the command to cd to the :: volume, which will work if you have executed subst :: C:\, otherwise you get a cannot find the volume error. That's why :; is arguably better because it cannot be interpreted in this way, and therefore is interpreted as a label instead, which serves as the valid command. This is not recursive, i.e, the next label does not need a command after it. That's why they come in twos.

You need to provide a valid command after the label e.g. echo something. A label in a code block has to come with at least one valid command, so the lines come in pairs of two. You will get an unexpected ) error if there is a space or a closing parenthesis on the next line. If there is a space between the two :: lines you will get an invalid syntax error.

You can also use the caret operator in the :: comment like so:

@echo off

echo hello
(
   :;(^
   this^
   is^
   a^
   comment^
   )
   :;
)
   :;^
   this^
   is^
   a^
   comment
   :;
) 

But you need the trailing :; for the reason stated above.

@echo off

(
echo hello
:;
:; comment
:; comment
:;
)
echo hello

It is fine as long as there is an even number. This is undoubtedly the best way to comment -- with 4 lines and :;. With :; you don't get any errors that need to be suppressed using 2> nul or subst :: C:\. You could use subst :: C:\ to make the volume not found error go away but it means you will have to also put C: in the code to prevent your working directory from becoming ::\.

To comment at the end of a line you can do command &:: or command & rem comment, but there still has to be an even number, like so:

@echo off

(
echo hello & :;yes
echo hello & :;yes
:;
)

echo hello

The first echo hello & :;yes has a valid command on the next line but the second & :;yes does not, so it needs one i.e. the :;.

3)Using an invalid environment variable

%= comment =%. In a batch file, environment variables that are not defined are removed from the script. This makes it possible to use them at the end of a line without using &. It is custom to use an invalid environment variable i.e. one that contains an equals sign. The extra equals is not required but makes it look symmetrical. Also, variable names starting with "=" are reserved for undocumented dynamic variables. Those dynamic variables never end with "=", so by using an "=" at both the start and end of the comment, there is no possibility of a name clash. The comment cannot contain % or :.

@echo off 
echo This is an example of an %= Inline Comment =% in the middle of a line.

4)As a command, redirecting stderr to nul

@echo off
(
echo hello
;this is a comment 2> nul
;this is another comment  2> nul
)

5)At the end of a file, everything after an unclosed parenthesis is a comment

@echo off
(
echo hello
)

(this is a comment
this is a comment
this is a comment

Visualizing decision tree in scikit-learn

I copy and change a part of your code as the below:

from pandas import read_csv, DataFrame
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
from os import system

data = read_csv('D:/training.csv')
Y = data.Y
X = data.ix[:,"X0":"X33"]

dtree = tree.DecisionTreeClassifier(criterion = "entropy")
dtree = dtree.fit(X, Y)

After making sure you have dtree, which means that the above code runs well, you add the below code to visualize decision tree:

Remember to install graphviz first: pip install graphviz

import graphviz 
from graphviz import Source
dot_data = tree.export_graphviz(dtree, out_file=None, feature_names=X.columns)
graph = graphviz.Source(dot_data) 
graph.render("name of file",view = True)

I tried with my data, visualization worked well and I got a pdf file viewed immediately.

Hide Twitter Bootstrap nav collapse on click

I think it's better to use default Bootstrap 3's collapse.js methods using the .navbar-collapse as the collapsible element you wish to hide as shown below.

Other solutions may cause other undesired problems with the way elements display or function in your web page. Therefore, while some solutions may appear to fix your initial problem it may very well introduce others, so make sure you run thorough testing of your site after any fix.

To see this code in action:

  1. Press "Run This Code Snippet" below.
  2. Press "Full Page" button.
  3. Scale window until drop-down activates.
  4. Then select a menu option and voila!

Cheers!

_x000D_
_x000D_
$('.nav a').click(function() {_x000D_
  $('.navbar-collapse').collapse('hide');  _x000D_
});
_x000D_
<html lang="en">_x000D_
  <head>_x000D_
    <meta charset="utf-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="author" content="Franciscus Agnew">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->_x000D_
    <title>Bootstrap Navbar Collapse Function</title>_x000D_
_x000D_
    <!-- Latest compiled and minified CSS -->_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">_x000D_
_x000D_
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->_x000D_
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
    <!--[if lt IE 9]>_x000D_
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>_x000D_
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>_x000D_
    <![endif]-->_x000D_
  </head>_x000D_
  _x000D_
  <body>_x000D_
    <header>_x000D_
      <nav class="navbar navbar-default navbar-fixed-top" role="navigation">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-expanded="navbar"><span class="sr-only">Toggle navigation</span>Menu <span class="glyphicon glyphicon-chevron-down"></span></button>_x000D_
            <a class="navbar-brand" href="#">Brand Logo</a>_x000D_
          </div><!-- navbar-header -->_x000D_
    _x000D_
          <div class="collapse navbar-collapse" id="navbar">_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li class="active"><a href="#">Home</a></li>_x000D_
              <li><a href="#about">About</a></li>_x000D_
              <li><a href="#portfolio">Portfolio</a></li>_x000D_
              <li><a href="#services">Services</a></li>_x000D_
              <li><a href="#staff">Staff</a></li>_x000D_
              <li><a href="#contact">Contact</a></li>_x000D_
            </ul><!-- navbar-right -->_x000D_
          </div><!-- navbar-collapse -->_x000D_
          _x000D_
        </div><!-- container -->_x000D_
      </nav><!-- navbar-fixed-top -->_x000D_
    </header>_x000D_
    _x000D_
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
    _x000D_
    _x000D_
    <!-- Include all compiled plugins (below), or include individual files as needed -->_x000D_
    <!-- Latest compiled and minified JavaScript -->_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>_x000D_
    _x000D_
    <!-- Custom Navbar Collapse Script Solution -->_x000D_
    <script>_x000D_
      $('.nav a').click(function() {_x000D_
        $('.navbar-collapse').collapse('hide');  _x000D_
      });_x000D_
    </script>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Configure hibernate to connect to database via JNDI Datasource

Apparently, you did it right. But here is a list of things you'll need with examples from a working application:

1) A context.xml file in META-INF, specifying your data source:

<Context>
    <Resource 
        name="jdbc/DsWebAppDB" 
        auth="Container" 
        type="javax.sql.DataSource" 
        username="sa" 
        password="" 
        driverClassName="org.h2.Driver" 
        url="jdbc:h2:mem:target/test/db/h2/hibernate" 
        maxActive="8" 
        maxIdle="4"/>
</Context>

2) web.xml which tells the container that you are using this resource:

<resource-env-ref>
    <resource-env-ref-name>jdbc/DsWebAppDB</resource-env-ref-name>
    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>

3) Hibernate configuration which consumes the data source. In this case, it's a persistence.xml, but it's similar in hibernate.cfg.xml

<persistence-unit name="dswebapp">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
        <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/DsWebAppDB"/>
    </properties>
</persistence-unit>

What is the Swift equivalent of respondsToSelector?

Functions are first-class types in Swift, so you can check whether an optional function defined in a protocol has been implemented by comparing it to nil:

if (someObject.someMethod != nil) {
    someObject.someMethod!(someArgument)
} else {
    // do something else
}

Compare two objects in Java with possible null values

This is what Java internal code uses (on other compare methods):

public static boolean compare(String str1, String str2) {
    return (str1 == null ? str2 == null : str1.equals(str2));
}

WAMP Server doesn't load localhost

Change the port 80 to port 8080 and restart all services and access like localhost:8080/

It will work fine.

Validate phone number using javascript

Add a $ to the end of the regex to signify the end of the pattern:

var regExp = /^(\([0-9]{3}\)\s?|[0-9]{3}-)[0-9]{3}-[0-9]{4}$/;

Counting repeated characters in a string in Python

this will show a dict of characters with occurrence count

str = 'aabcdefghijklmnopqrstuvwxyz'
mydict = {}
for char in str:
    mydict[char]=mydict.get(char,0)+1
 print mydict

How to check if an excel cell is empty using Apache POI?

As of Apache POI 3.17 you will have to check if the cell is empty using enumerations:

import org.apache.poi.ss.usermodel.CellType;

if(cell == null || cell.getCellTypeEnum() == CellType.BLANK) { ... }

Set 4 Space Indent in Emacs in Text Mode

This is the only solution that keeps a tab from ever getting inserted for me, without a sequence or conversion of tabs to spaces. Both of those seemed adequate, but wasteful:

(setq-default
    indent-tabs-mode nil
    tab-width 4
    tab-stop-list (quote (4 8))
)

Note that quote needs two numbers to work (but not more!).

Also, in most major modes (Python for instance), indentation is automatic in Emacs. If you need to indent outside of the auto indent, use:

M-i

In Oracle SQL: How do you insert the current date + time into a table?

It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:

insert into errortable (dateupdated, table1id)
    values (sysdate, 1083);

It seems silly to convert the system date to a string just to convert it back to a date.

If you want to see the full date, then you can do:

select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;

Properly embedding Youtube video into bootstrap 3.0 page

I use bootstrap 3.x as well and the following code fore responsive youtube video embedding works like charm for me:

.videoWrapperOuter {
  max-width:640px; 
  margin-left:auto;
  margin-right:auto;
}
.videoWrapperInner {
  float: none;
  clear: both;
  width: 100%;
  position: relative;
  padding-bottom: 50%;
  padding-top: 25px;
  height: 0;
}
.videoWrapperInner iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<div class="videoWrapperOuter">
  <div class="videoWrapperInner">
    <iframe src="//www.youtube.com/embed/C6-TWRn0k4I" 
      frameborder="0" allowfullscreen></iframe>
  </div>
</div>

I gave a similiar answer on another thread (Shrink a YouTube video to responsive width), but I guess my answers can help here as well.

c - warning: implicit declaration of function ‘printf’

the warning or error of kind IMPLICIT DECLARATION is that the compiler is expecting a Function Declaration/Prototype..

It might either be a header file or your own function Declaration..

How to use NSURLConnection to connect with SSL for an untrusted cert?

NSURLRequest has a private method called setAllowsAnyHTTPSCertificate:forHost:, which will do exactly what you'd like. You could define the allowsAnyHTTPSCertificateForHost: method on NSURLRequest via a category, and set it to return YES for the host that you'd like to override.

How to get to a particular element in a List in java?

You have about 98% right. The only issue is that you're trying to print out an String[] which does not print the way you'd like. Instead try this...

for (String[] s : myEntries) {
    System.out.print("Next item: " + s[0]);
    for(int i = 1; i < s.length; i++) {
        System.out.print(", " + s[i]);
    }
    System.out.println("");
}

This way you're accessing each string in the array instead of the array itself.

Hope this helps!

Determine the number of NA values in a column

A quick and easy Tidyverse solution to get a NA count for all columns is to use summarise_all() which I think makes a much easier to read solution than using purrr or sapply

library(tidyverse)
# Example data
df <- tibble(col1 = c(1, 2, 3, NA), 
             col2 = c(NA, NA, "a", "b"))

df %>% summarise_all(~ sum(is.na(.)))
#> # A tibble: 1 x 2
#>    col1  col2
#>   <int> <int>
#> 1     1     2

Install Chrome extension form outside the Chrome Web Store

For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.

Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.

Extensions can be loaded in unpacked mode by following the following steps:

  1. Visit chrome://extensions (via omnibox or menu -> Tools -> Extensions).
  2. Enable Developer mode by ticking the checkbox in the upper-right corner.
  3. Click on the "Load unpacked extension..." button.
  4. Select the directory containing your unpacked extension.

If you have a crx file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.

These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.

python: Appending a dictionary to a list - I see a pointer like behavior

You are correct in that your list contains a reference to the original dictionary.

a.append(b.copy()) should do the trick.

Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b), which makes a deep copy.

How to remove leading and trailing whitespace in a MySQL field?

You can use the following sql, UPDATE TABLE SET Column= replace(Column , ' ','')

How to take the nth digit of a number in python

I'm very sorry for necro-threading but I wanted to provide a solution without converting the integer to a string. Also I wanted to work with more computer-like thinking so that's why the answer from Chris Mueller wasn't good enough for me.

So without further ado,

import math

def count_number(number):
    counter = 0
    counter_number = number
    while counter_number > 0:
        counter_number //= 10
        counter += 1
    return counter


def digit_selector(number, selected_digit, total):
    total_counter = total
    calculated_select = total_counter - selected_digit
    number_selected = int(number / math.pow(10, calculated_select))
    while number_selected > 10:
        number_selected -= 10
    return number_selected


def main():
    x = 1548731588
    total_digits = count_number(x)
    digit_2 = digit_selector(x, 2, total_digits)
    return print(digit_2)


if __name__ == '__main__':
    main()

which will print:

5

Hopefully someone else might need this specific kind of code. Would love to have feedback on this aswell!

This should find any digit in a integer.

Flaws:

Works pretty ok but if you use this for long numbers then it'll take more and more time. I think that it would be possible to see if there are multiple thousands etc and then substract those from number_selected but that's maybe for another time ;)

Usage:

You need every line from 1-21. Then you can call first count_number to make it count your integer.

x = 1548731588
total_digits = count_number(x)

Then read/use the digit_selector function as follows:

digit_selector('insert your integer here', 'which digit do you want to have? (starting from the most left digit as 1)', 'How many digits are there in total?')

If we have 1234567890, and we need 4 selected, that is the 4th digit counting from left so we type '4'.

We know how many digits there are due to using total_digits. So that's pretty easy.

Hope that explains everything!

Han

PS: Special thanks for CodeVsColor for providing the count_number function. I used this link: https://www.codevscolor.com/count-number-digits-number-python to help me make the digit_selector work.

Is it correct to use DIV inside FORM?

No, its not

<div> tags are always abused to create a web layout. Its symbolic purpose is to divide a section/portion in the page so that separate style can be added or applied to it. [w3schools Doc] [W3C]

It highly depends on what your some and another has.

HTML5, has more logical meaning tags, instead of having plain layout tags. The section, header, nav, aside everything have their own semantic meaning to it. And are used against <div>

What is /dev/null 2>&1?

This is the way to execute a program quietly, and hide all its output.

/dev/null is a special filesystem object that discards everything written into it. Redirecting a stream into it means hiding your program's output.

The 2>&1 part means "redirect the error stream into the output stream", so when you redirect the output stream, error stream gets redirected as well. Even if your program writes to stderr now, that output would be discarded as well.

C# how to create a Guid value?

There are two ways

var guid = Guid.NewGuid();

or

var guid = Guid.NewGuid().ToString();

both use the Guid class, the first creates a Guid Object, the second a Guid string.

How to determine the installed webpack version

webpack 4 now offers a version property that can be used!

How to convert upper case letters to lower case

You can find more methods and functions related to Python strings in section 5.6.1. String Methods of the documentation.

w.strip(',.').lower()

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)

Duration column = End - Start

  1. Once done, plot your stacked bar chart using the entire data.
  2. Mark start and end range to no fill.
  3. Right click on the X Axis and change Axis options manually. (This did cause me some issues, till I realized I couldn't manipulate them to enter dates, :) yeah I am newbie, excel masters! :))

enter image description here

Volatile Vs Atomic

The volatile keyword is used:

  • to make non atomic 64-bit operations atomic: long and double. (all other, primitive accesses are already guaranteed to be atomic!)
  • to make variable updates guaranteed to be seen by other threads + visibility effects: after writing to a volatile variable, all the variables that where visible before writing that variable become visible to another thread after reading the same volatile variable (happen-before ordering).

The java.util.concurrent.atomic.* classes are, according to the java docs:

A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:

boolean compareAndSet(expectedValue, updateValue);

The atomic classes are built around the atomic compareAndSet(...) function that maps to an atomic CPU instruction. The atomic classes introduce the happen-before ordering as the volatile variables do. (with one exception: weakCompareAndSet(...)).

From the java docs:

When a thread sees an update to an atomic variable caused by a weakCompareAndSet, it does not necessarily see updates to any other variables that occurred before the weakCompareAndSet.

To your question:

Does this mean that whosoever takes lock on it, that will be setting its value first. And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?

You don't lock anything, what you are describing is a typical race condition that will happen eventually if threads access shared data without proper synchronization. As already mentioned declaring a variable volatile in this case will only ensure that other threads will see the change of the variable (the value will not be cached in a register of some cache that is only seen by one thread).

What is the difference between AtomicInteger and volatile int?

AtomicInteger provides atomic operations on an int with proper synchronization (eg. incrementAndGet(), getAndAdd(...), ...), volatile int will just ensure the visibility of the int to other threads.

Changing iframe src with Javascript

change onselect to onchange in inputs and use

calendar.src = loc

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
_x000D_
<head>_x000D_
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />_x000D_
  <title>Untitled 1</title>_x000D_
_x000D_
  <script>_x000D_
  function go(loc) {_x000D_
    calendar.src = loc;_x000D_
  }_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe>_x000D_
_x000D_
  <form method="post">_x000D_
    <input name="calendarSelection" type="radio" onchange="go('https://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day_x000D_
    <input name="calendarSelection" type="radio" onchange="go('https://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Week_x000D_
    <input name="calendarSelection" type="radio" onchange="go('https://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Month_x000D_
  </form>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Saving the PuTTY session logging

This is a bit confusing, but follow these steps to save the session.

  1. Category -> Session -> enter public IP in Host and 22 in port.
  2. Connection -> SSH -> Auth -> select the .ppk file
  3. Category -> Session -> enter a name in Saved Session -> Click Save

To open the session, double click on particular saved session.

Adding data attribute to DOM

in Jquery "data" doesn't refresh by default :

alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data("myval","20"); //setter
alert($('#outer').html());

You'd use "attr" instead for live update:

alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());

mingw-w64 threads: posix vs win32

Parts of the GCC runtime (the exception handling, in particular) are dependent on the threading model being used. So, if you're using the version of the runtime that was built with POSIX threads, but decide to create threads in your own code with the Win32 APIs, you're likely to have problems at some point.

Even if you're using the Win32 threading version of the runtime you probably shouldn't be calling the Win32 APIs directly. Quoting from the MinGW FAQ:

As MinGW uses the standard Microsoft C runtime library which comes with Windows, you should be careful and use the correct function to generate a new thread. In particular, the CreateThread function will not setup the stack correctly for the C runtime library. You should use _beginthreadex instead, which is (almost) completely compatible with CreateThread.

How to export query result to csv in Oracle SQL Developer?

Not exactly "exporting," but you can select the rows (or Ctrl-A to select all of them) in the grid you'd like to export, and then copy with Ctrl-C.

The default is tab-delimited. You can paste that into Excel or some other editor and manipulate the delimiters all you like.

Also, if you use Ctrl-Shift-C instead of Ctrl-C, you'll also copy the column headers.

Number of rows affected by an UPDATE in PL/SQL

You use the sql%rowcount variable.

You need to call it straight after the statement which you need to find the affected row count for.

For example:

set serveroutput ON; 
DECLARE 
    i NUMBER; 
BEGIN 
    UPDATE employees 
    SET    status = 'fired' 
    WHERE  name LIKE '%Bloggs'; 
    i := SQL%rowcount; 
    --note that assignment has to precede COMMIT
    COMMIT; 
    dbms_output.Put_line(i); 
END; 

What's the difference between ngOnInit and ngAfterViewInit of Angular2?

ngOnInit() is called after ngOnChanges() was called the first time. ngOnChanges() is called every time inputs are updated by change detection.

ngAfterViewInit() is called after the view is initially rendered. This is why @ViewChild() depends on it. You can't access view members before they are rendered.

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

tl;dr:

concat and append currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True to silence it. In the future the default will change to not sort, so it's best to specify either sort=True or False now, or better yet ensure that your non-concatenation indices match.


The warning is new in pandas 0.23.0:

In a future version of pandas pandas.concat() and DataFrame.append() will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned, link.

More information from linked very old github issue, comment by smcinerney :

When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.

This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.

After some time the parameter sort was implemented in pandas.concat and DataFrame.append:

sort : boolean, default None

Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.

Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.

This has no effect when join='inner', which already preserves the order of the non-concatenation axis.

So if both DataFrames have the same columns in the same order, there is no warning and no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])

print (pd.concat([df1, df2]))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort is explicitly set (sort=None is the default value):

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=True))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=False))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a and b from df1 with a and b from df2 in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.

Lastly, if you pass sort=True, columns are sorted alphanumerically. If sort=False and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]}, 
                    columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]}, 
                    columns=['c','b','a','d'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=True))
   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=False))

   b  a    e    c    d
0  0  1  5.0  NaN  NaN
1  8  2  0.0  NaN  NaN
0  7  4  NaN  2.0  7.0
1  3  5  NaN  8.0  0.0

In your code:

placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
                                                       .append(placement_by_video_summary_new, sort=True)
                                                       .sort_index()

Does WhatsApp offer an open API?

  1. is the correct answer. WhatsApp is intentionally a closed system without an API for external access.

There were several projects available that reverse engineered the WhatsApp webservice interfaces. However, to my knowledge all of them are now discontinued/defunct due to legal action against them from WhatsApp.

For mobile phone applications there is a limited URL-Scheme-API available on IPhone and Android (Android-intent possible as well).

Find the day of a week

Look up ?strftime:

%A Full weekday name in the current locale

df$day = strftime(df$date,'%A')

How to export data to CSV in PowerShell?

simply use the Out-File cmd but DON'T forget to give an encoding type: -Encoding UTF8

so use it so:

$log | Out-File -Append C:\as\whatever.csv -Encoding UTF8

-Append is required if you want to write in the file more then once.

Invoking JavaScript code in an iframe from the parent page

The IFRAME should be in the frames[] collection. Use something like

frames['iframeid'].method();

Android Studio - Unable to find valid certification path to requested target

jcenter() equals to https://bintray.com/bintray/jcenter

You need import jcenter's cerficate into your java keystore.

Steps:

  1. Visit jcenter using your browser and export the certificate as .crt file. (lock icon on the left of Firefox address bar, or Chrome developer tool secuity tab)
  2. Download this tool and run it.
  3. Select "Open an existing KeyStore" button to open JDKPATH/jre/lib/security/cacerts, the password is "changeit"
  4. Use the "Import Trusted Certificate" button to import the .crt file, then save and exist

If you are behind proxy, in gradle.properties, besides setting

systemProp.http.proxyHost and systemProp.http.proxyPort

also set

systemProp.https.proxyHost and systemProp.https.proxyPort

By now it should be fine.

How to access child's state in React?

If you already have onChange handler for the individual FieldEditors I don't see why you couldn't just move the state up to the FormEditor component and just pass down a callback from there to the FieldEditors that will update the parent state. That seems like a more React-y way to do it, to me.

Something along the line of this perhaps:

const FieldEditor = ({ value, onChange, id }) => {
  const handleChange = event => {
    const text = event.target.value;
    onChange(id, text);
  };

  return (
    <div className="field-editor">
      <input onChange={handleChange} value={value} />
    </div>
  );
};

const FormEditor = props => {
  const [values, setValues] = useState({});
  const handleFieldChange = (fieldId, value) => {
    setValues({ ...values, [fieldId]: value });
  };

  const fields = props.fields.map(field => (
    <FieldEditor
      key={field}
      id={field}
      onChange={handleFieldChange}
      value={values[field]}
    />
  ));

  return (
    <div>
      {fields}
      <pre>{JSON.stringify(values, null, 2)}</pre>
    </div>
  );
};

// To add abillity to dynamically add/remove fields keep the list in state
const App = () => {
  const fields = ["field1", "field2", "anotherField"];

  return <FormEditor fields={fields} />;
};

Original - pre-hooks version:

_x000D_
_x000D_
class FieldEditor extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.handleChange = this.handleChange.bind(this);_x000D_
  }_x000D_
_x000D_
  handleChange(event) {_x000D_
    const text = event.target.value;_x000D_
    this.props.onChange(this.props.id, text);_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div className="field-editor">_x000D_
        <input onChange={this.handleChange} value={this.props.value} />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
class FormEditor extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.state = {};_x000D_
_x000D_
    this.handleFieldChange = this.handleFieldChange.bind(this);_x000D_
  }_x000D_
_x000D_
  handleFieldChange(fieldId, value) {_x000D_
    this.setState({ [fieldId]: value });_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    const fields = this.props.fields.map(field => (_x000D_
      <FieldEditor_x000D_
        key={field}_x000D_
        id={field}_x000D_
        onChange={this.handleFieldChange}_x000D_
        value={this.state[field]}_x000D_
      />_x000D_
    ));_x000D_
_x000D_
    return (_x000D_
      <div>_x000D_
        {fields}_x000D_
        <div>{JSON.stringify(this.state)}</div>_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
// Convert to class component and add ability to dynamically add/remove fields by having it in state_x000D_
const App = () => {_x000D_
  const fields = ["field1", "field2", "anotherField"];_x000D_
_x000D_
  return <FormEditor fields={fields} />;_x000D_
};_x000D_
_x000D_
ReactDOM.render(<App />, document.body);
_x000D_
_x000D_
_x000D_

How do I get the HTTP status code with jQuery?

I have had major issues with ajax + jQuery v3 getting both the response status code and data from JSON APIs. jQuery.ajax only decodes JSON data if the status is a successful one, and it also swaps around the ordering of the callback parameters depending on the status code. Ugghhh.

The best way to combat this is to call the .always chain method and do a bit of cleaning up. Here is my code.

$.ajax({
        ...
    }).always(function(data, textStatus, xhr) {
        var responseCode = null;
        if (textStatus === "error") {
            // data variable is actually xhr
            responseCode = data.status;
            if (data.responseText) {
                try {
                    data = JSON.parse(data.responseText);
                } catch (e) {
                    // Ignore
                }
            }
        } else {
            responseCode = xhr.status;
        }

        console.log("Response code", responseCode);
        console.log("JSON Data", data);
    });

How to open CSV file in R when R says "no such file or directory"?

I had the same problem and when I checked the properties of the file on file explorer, it shows me the next message:

"Security: This file came from another computer and might be blocked to help protect this computer"

You click on the "Unblock" button and... you can access to the file from R without any problem, just using read.csv() function and from the directory specified as your working directory, even if is not the same as the file’s directory you are accessing to.

How to pass data from child component to its parent in ReactJS?

You can even avoid the function at the parent updating the state directly

In Parent Component:

render(){
 return(<Child sendData={ v => this.setState({item: v}) } />);
}

In the Child Component:

demoMethod(){
   this.props.sendData(value);
}

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

If you really want to insert this record, remove the `abuse_id` field and the corresponding value from the INSERTstatement :

INSERT INTO  `abuses` (  `user_id` ,  `abuser_username` ,  `comment` ,  `reg_date` , `auction_id` ) 
VALUES ( 100020,  'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;

How can I change the width and height of slides on Slick Carousel?

I found good solution myself. Since slick slider is still used nowadays i'll post my approach.

@RuivBoas answer is partly correct. - It can change the width of the slide but it can break the slider. Why?

Slick slider may exceed browser width. Actual container width is set to value that can accomodate all it's slides.

The best solution for setting slide width is to use width of the actual browser window. It works best with responsive design.

For example 2 slides with absorbed width

CSS

.slick-slide {
    width: 50vw;
    // for absorbing width from @Ken Wheeler answer
    box-sizing: border-box;
}

JS

$(document).on('ready', function () {
            $("#container").slick({
                variableWidth: true,
                slidesToShow: 2,
                slidesToScroll: 2
            });
        });

HTML markup

<div id="container">
    <div><img/></div>
    <div><img/></div>
    <div><img/></div>
</div>

Display progress bar while doing some work in C#?

And another example that BackgroundWorker is the right way to do it...

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace SerialSample
{
    public partial class Form1 : Form
    {
        private BackgroundWorker _BackgroundWorker;
        private Random _Random;

        public Form1()
        {
            InitializeComponent();
            _ProgressBar.Style = ProgressBarStyle.Marquee;
            _ProgressBar.Visible = false;
            _Random = new Random();

            InitializeBackgroundWorker();
        }

        private void InitializeBackgroundWorker()
        {
            _BackgroundWorker = new BackgroundWorker();
            _BackgroundWorker.WorkerReportsProgress = true;

            _BackgroundWorker.DoWork += (sender, e) => ((MethodInvoker)e.Argument).Invoke();
            _BackgroundWorker.ProgressChanged += (sender, e) =>
                {
                    _ProgressBar.Style = ProgressBarStyle.Continuous;
                    _ProgressBar.Value = e.ProgressPercentage;
                };
            _BackgroundWorker.RunWorkerCompleted += (sender, e) =>
            {
                if (_ProgressBar.Style == ProgressBarStyle.Marquee)
                {
                    _ProgressBar.Visible = false;
                }
            };
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            _BackgroundWorker.RunWorkerAsync(new MethodInvoker(() =>
                {
                    _ProgressBar.BeginInvoke(new MethodInvoker(() => _ProgressBar.Visible = true));
                    for (int i = 0; i < 1000; i++)
                    {
                        Thread.Sleep(10);
                        _BackgroundWorker.ReportProgress(i / 10);
                    }
                }));
        }
    }
}

Should IBOutlets be strong or weak under ARC?

I think that most important information is: Elements in xib are automatically in subviews of view. Subviews is NSArray. NSArray owns it's elements. etc have strong pointers on them. So in most cases you don't want to create another strong pointer (IBOutlet)

And with ARC you don't need to do anything in viewDidUnload

Replace all spaces in a string with '+'

You can also do it like:

str = str.replace(/\s/g, "+");

Have a look at this fiddle.

java.util.NoSuchElementException: No line found

I also encounter with that problem. In my case the problem was that i closed the scanner inside one of the funcs..

_x000D_
_x000D_
public class Main _x000D_
{_x000D_
 public static void main(String[] args) _x000D_
 {_x000D_
  Scanner menu = new Scanner(System.in);_x000D_
        boolean exit = new Boolean(false);_x000D_
    while(!exit){_x000D_
  String choose = menu.nextLine();_x000D_
        Part1 t=new Part1()_x000D_
        t.start();_x000D_
     System.out.println("Noooooo Come back!!!"+choose);_x000D_
  }_x000D_
 menu.close();_x000D_
 }_x000D_
}_x000D_
_x000D_
public class Part1 extends Thread _x000D_
{_x000D_
public void run()_x000D_
  { _x000D_
     Scanner s = new Scanner(System.in);_x000D_
     String st = s.nextLine();_x000D_
     System.out.print("bllaaaaaaa\n"+st);_x000D_
     s.close();_x000D_
 }_x000D_
}_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

The code above made the same exaption, the solution was to close the scanner only once at the main.

Where is SQL Profiler in my SQL Server 2008?

Also ensure that "client tools" are selected in the install options. However if SQL Managment Studio 2008 exists then it is likely that you installed the express edition.

How can I convert ArrayList<Object> to ArrayList<String>?

Using Java 8 lambda:

ArrayList<Object> obj = new ArrayList<>();
obj.add(1);
obj.add("Java");
obj.add(3.14);

ArrayList<String> list = new ArrayList<>();
obj.forEach((xx) -> list.add(String.valueOf(xx)));

Python: list of lists

Lists are a mutable type - in order to create a copy (rather than just passing the same list around), you need to do so explicitly:

listoflists.append((list[:], list[0]))

However, list is already the name of a Python built-in - it'd be better not to use that name for your variable. Here's a version that doesn't use list as a variable name, and makes a copy:

listoflists = []
a_list = []
for i in range(0,10):
    a_list.append(i)
    if len(a_list)>3:
        a_list.remove(a_list[0])
        listoflists.append((list(a_list), a_list[0]))
print listoflists

Note that I demonstrated two different ways to make a copy of a list above: [:] and list().

The first, [:], is creating a slice (normally often used for getting just part of a list), which happens to contain the entire list, and thus is effectively a copy of the list.

The second, list(), is using the actual list type constructor to create a new list which has contents equal to the first list. (I didn't use it in the first example because you were overwriting that name in your code - which is a good example of why you don't want to do that!)

What is the difference between "screen" and "only screen" in media queries?

The answer by @hybrid is quite informative, except it doesn't explain the purpose as mentioned by @ashitaka "What if you use the Mobile First approach? So, we have the mobile CSS first and then use min-width to target larger sites. We shouldn't use the only keyword in that context, right? "

Want to add in here that the purpose is simply to prevent non supporting browsers to use that Other device style as if it starts from "screen" without it will take it for a screen whereas if it starts from "only" style will be ignored.

Answering to ashitaka consider this example

<link rel="stylesheet" type="text/css" 
  href="android.css" media="only screen and (max-width: 480px)" />
<link rel="stylesheet" type="text/css" 
  href="desktop.css" media="screen and (min-width: 481px)" />

If we don't use "only" it will still work as desktop-style will also be used striking android styles but with unnecessary overhead. In this case, IF a browser is non-supporting it will fallback to the second Style-sheet ignoring the first.

Changing cell color using apache poi

For apache POI 3.9 you can use the code bellow:

HSSFCellStyle style = workbook.createCellStyle()
style.setFillForegroundColor(HSSFColor.YELLOW.index)
style.setFillPattern((short) FillPatternType.SOLID_FOREGROUND.ordinal())

The methods for 3.9 version accept short and you should pay attention to the inputs.

How to empty a list in C#?

It's really easy:

myList.Clear();

Getting All Variables In Scope

You can't.

Variables, identifiers of function declarations and arguments for function code, are bound as properties of the Variable Object, which is not accesible.

See also:

adb command not found in linux environment

updating the $PATH did not work for me, therefore I added a symbolic link to adb to make it work, as follows:

ln -s <android-sdk-folder>/platform-tools/adb <android-sdk-folder>/tools/adb

What does O(log n) mean exactly?

O(log n) is a bit misleading, more precisely it's O(log2 n), i.e. (logarithm with base 2).

The height of a balanced binary tree is O(log2 n), since every node has two (note the "two" as in log2 n) child nodes. So, a tree with n nodes has a height of log2 n.

Another example is binary search, which has a running time of O(log2 n) because at every step you divide the search space by 2.

How to assign colors to categorical variables in ggplot2 that have stable mapping?

This is an old post, but I was looking for answer to this same question,

Why not try something like:

scale_color_manual(values = c("foo" = "#999999", "bar" = "#E69F00"))

If you have categorical values, I don't see a reason why this should not work.

How to remove default chrome style for select Input?

-webkit-appearance: none;

and add your own style

Tensorflow installation error: not a supported wheel on this platform

I was trying to do the windows-based install and kept getting this error.

Turns out you have to have python 3.5.2. Not 2.7, not 3.6.x-- nothing other than 3.5.2.

After installing python 3.5.2 the pip install worked.

Download JSON object as a file from browser

If you prefer console snippet, raser, than filename, you can do this:

window.open(URL.createObjectURL(
    new Blob([JSON.stringify(JSON)], {
      type: 'application/binary'}
    )
))

How do I set default values for functions parameters in Matlab?

This is my simple way to set default values to a function, using "try":

function z = myfun (a,varargin)

%% Default values
b = 1;
c = 1;
d = 1;
e = 1;

try 
    b = varargin{1};
    c = varargin{2};
    d = varargin{3};
    e = varargin{4};
end

%% Calculation
z = a * b * c * d * e ;
end

Regards!

Float vs Decimal in ActiveRecord

In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.

  def change
    change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13
    change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13
  end

Procedure expects parameter which was not supplied

I come across similar problem while calling stored procedure

CREATE PROCEDURE UserPreference_Search
    @UserPreferencesId int,
    @SpecialOfferMails char(1),
    @NewsLetters char(1),
    @UserLoginId int,
    @Currency varchar(50)
AS
DECLARE @QueryString nvarchar(4000)

SET @QueryString = 'SELECT UserPreferencesId,SpecialOfferMails,NewsLetters,UserLoginId,Currency FROM UserPreference'
IF(@UserPreferencesId IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE UserPreferencesId = @DummyUserPreferencesId';
END

IF(@SpecialOfferMails IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE SpecialOfferMails = @DummySpecialOfferMails';
END

IF(@NewsLetters IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE NewsLetters = @DummyNewsLetters';
END

IF(@UserLoginId IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE UserLoginId = @DummyUserLoginId';
END

IF(@Currency IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE Currency = @DummyCurrency';
END

EXECUTE SP_EXECUTESQL @QueryString
                     ,N'@DummyUserPreferencesId int, @DummySpecialOfferMails char(1), @DummyNewsLetters char(1), @DummyUserLoginId int, @DummyCurrency varchar(50)'
                     ,@DummyUserPreferencesId=@UserPreferencesId
                     ,@DummySpecialOfferMails=@SpecialOfferMails
                     ,@DummyNewsLetters=@NewsLetters
                     ,@DummyUserLoginId=@UserLoginId
                     ,@DummyCurrency=@Currency;

Which dynamically constructing the query for search I was calling above one by:

public DataSet Search(int? AccessRightId, int? RoleId, int? ModuleId, char? CanAdd, char? CanEdit, char? CanDelete, DateTime? CreatedDatetime, DateTime? LastAccessDatetime, char? Deleted)
    {
        dbManager.ConnectionString = ConfigurationManager.ConnectionStrings["MSSQL"].ToString();
        DataSet ds = new DataSet();
        try
        {
            dbManager.Open();
            dbManager.CreateParameters(9);
            dbManager.AddParameters(0, "@AccessRightId", AccessRightId, ParameterDirection.Input);
            dbManager.AddParameters(1, "@RoleId", RoleId, ParameterDirection.Input);
            dbManager.AddParameters(2, "@ModuleId", ModuleId, ParameterDirection.Input);
            dbManager.AddParameters(3, "@CanAdd", CanAdd, ParameterDirection.Input);
            dbManager.AddParameters(4, "@CanEdit", CanEdit, ParameterDirection.Input);
            dbManager.AddParameters(5, "@CanDelete", CanDelete, ParameterDirection.Input);
            dbManager.AddParameters(6, "@CreatedDatetime", CreatedDatetime, ParameterDirection.Input);
            dbManager.AddParameters(7, "@LastAccessDatetime", LastAccessDatetime, ParameterDirection.Input);
            dbManager.AddParameters(8, "@Deleted", Deleted, ParameterDirection.Input);
            ds = dbManager.ExecuteDataSet(CommandType.StoredProcedure, "AccessRight_Search");
            return ds;
        }
        catch (Exception ex)
        {
        }
        finally
        {
            dbManager.Dispose();
        }
        return ds;
    }

Then after lot of head scratching I modified stored procedure to:

ALTER PROCEDURE [dbo].[AccessRight_Search]
    @AccessRightId int=null,
    @RoleId int=null,
    @ModuleId int=null,
    @CanAdd char(1)=null,
    @CanEdit char(1)=null,
    @CanDelete char(1)=null,
    @CreatedDatetime datetime=null,
    @LastAccessDatetime datetime=null,
    @Deleted char(1)=null
AS
DECLARE @QueryString nvarchar(4000)
DECLARE @HasWhere bit
SET @HasWhere=0

SET @QueryString = 'SELECT a.AccessRightId, a.RoleId,a.ModuleId, a.CanAdd, a.CanEdit, a.CanDelete, a.CreatedDatetime, a.LastAccessDatetime, a.Deleted, b.RoleName, c.ModuleName FROM AccessRight a, Role b, Module c WHERE a.RoleId = b.RoleId AND a.ModuleId = c.ModuleId'

SET @HasWhere=1;

IF(@AccessRightId IS NOT NULL)
    BEGIN
        IF(@HasWhere=0) 
            BEGIN
                SET @QueryString = @QueryString + ' WHERE a.AccessRightId = @DummyAccessRightId';
                SET @HasWhere=1;
            END
        ELSE                SET @QueryString = @QueryString + ' AND a.AccessRightId = @DummyAccessRightId';
    END

IF(@RoleId IS NOT NULL)
    BEGIN
        IF(@HasWhere=0)
            BEGIN   
                SET @QueryString = @QueryString + ' WHERE a.RoleId = @DummyRoleId';
                SET @HasWhere=1;
            END
        ELSE            SET @QueryString = @QueryString + ' AND a.RoleId = @DummyRoleId';
    END

IF(@ModuleId IS NOT NULL)
BEGIN
    IF(@HasWhere=0) 
            BEGIN   
                SET @QueryString = @QueryString + ' WHERE a.ModuleId = @DummyModuleId';
                SET @HasWhere=1;
            END
    ELSE SET @QueryString = @QueryString + ' AND a.ModuleId = @DummyModuleId';
END

IF(@CanAdd IS NOT NULL)
BEGIN
    IF(@HasWhere=0) 
            BEGIN       
                SET @QueryString = @QueryString + ' WHERE a.CanAdd = @DummyCanAdd';
                SET @HasWhere=1;
            END
    ELSE SET @QueryString = @QueryString + ' AND a.CanAdd = @DummyCanAdd';
END

IF(@CanEdit IS NOT NULL)
BEGIN
    IF(@HasWhere=0) 
        BEGIN
            SET @QueryString = @QueryString + ' WHERE a.CanEdit = @DummyCanEdit';
            SET @HasWhere=1;
        END
    ELSE SET @QueryString = @QueryString + ' AND a.CanEdit = @DummyCanEdit';
END

IF(@CanDelete IS NOT NULL)
BEGIN
    IF(@HasWhere=0) 
        BEGIN
            SET @QueryString = @QueryString + ' WHERE a.CanDelete = @DummyCanDelete';
            SET @HasWhere=1;
        END
    ELSE SET @QueryString = @QueryString + ' AND a.CanDelete = @DummyCanDelete';
END

IF(@CreatedDatetime IS NOT NULL)
BEGIN
    IF(@HasWhere=0) 
    BEGIN
        SET @QueryString = @QueryString + ' WHERE a.CreatedDatetime = @DummyCreatedDatetime';
        SET @HasWhere=1;
    END
    ELSE SET @QueryString = @QueryString + ' AND a.CreatedDatetime = @DummyCreatedDatetime';
END

IF(@LastAccessDatetime IS NOT NULL)
BEGIN
    IF(@HasWhere=0) 
        BEGIN
            SET @QueryString = @QueryString + ' WHERE a.LastAccessDatetime = @DummyLastAccessDatetime';
            SET @HasWhere=1;
        END
    ELSE SET @QueryString = @QueryString + ' AND a.LastAccessDatetime = @DummyLastAccessDatetime';
END

IF(@Deleted IS NOT NULL)
BEGIN
  IF(@HasWhere=0)   
    BEGIN
        SET @QueryString = @QueryString + ' WHERE a.Deleted = @DummyDeleted';
        SET @HasWhere=1;
    END
  ELSE SET @QueryString = @QueryString + ' AND a.Deleted = @DummyDeleted';
END

PRINT @QueryString

EXECUTE SP_EXECUTESQL @QueryString
                      ,N'@DummyAccessRightId int, @DummyRoleId int, @DummyModuleId int, @DummyCanAdd char(1), @DummyCanEdit char(1), @DummyCanDelete char(1), @DummyCreatedDatetime datetime, @DummyLastAccessDatetime datetime, @DummyDeleted char(1)'
                      ,@DummyAccessRightId=@AccessRightId
                      ,@DummyRoleId=@RoleId
                      ,@DummyModuleId=@ModuleId
                      ,@DummyCanAdd=@CanAdd
                      ,@DummyCanEdit=@CanEdit
                      ,@DummyCanDelete=@CanDelete
                      ,@DummyCreatedDatetime=@CreatedDatetime
                      ,@DummyLastAccessDatetime=@LastAccessDatetime
                      ,@DummyDeleted=@Deleted;

HERE I am Initializing the Input Params of Stored Procedure to null as Follows

    @AccessRightId int=null,
@RoleId int=null,
@ModuleId int=null,
@CanAdd char(1)=null,
@CanEdit char(1)=null,
@CanDelete char(1)=null,
@CreatedDatetime datetime=null,
@LastAccessDatetime datetime=null,
@Deleted char(1)=null

that did the trick for Me.

I hope this will be helpfull to someone who fall in similar trap.

How to obtain values of request variables using Python and Flask

Adding more to Jason's more generalized way of retrieving the POST data or GET data

from flask_restful import reqparse

def parse_arg_from_requests(arg, **kwargs):
    parse = reqparse.RequestParser()
    parse.add_argument(arg, **kwargs)
    args = parse.parse_args()
    return args[arg]

form_field_value = parse_arg_from_requests('FormFieldValue')

Resetting a form in Angular 2 after submit

Use NgForm's .resetForm() rather than .reset() because it is the method that is officially documented in NgForm's public api. (Ref [1])

<form (ngSubmit)="mySubmitHandler(); myNgForm.resetForm()" #myNgForm="ngForm">

The .resetForm() method will reset the NgForm's FormGroup and set it's submit flag to false (See [2]).

Tested in @angular versions 2.4.8 and 4.0.0-rc3

newline in <td title="">

I use the jQuery clueTip plugin for this.

How to combine GROUP BY and ROW_NUMBER?

The deduplication (to select the max T1) and the aggregation need to be done as distinct steps. I've used a CTE since I think this makes it clearer:

;WITH sumCTE
AS
(
    SELECT  Rel.t2ID, SUM(Price) price
    FROM    @t1         AS T1
    JOIN    @relation   AS Rel 
    ON      Rel.t1ID=T1.ID
    GROUP 
    BY      Rel.t2ID
)
,maxCTE
AS
(
    SELECT  Rel.t2ID, Rel.t1ID, 
            ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
    FROM    @t1         AS T1
    JOIN    @relation   AS Rel 
    ON      Rel.t1ID=T1.ID
)
SELECT T2.ID AS T2ID
,T2.Name as T2Name
,T2.Orders
,T1.ID AS T1ID
,T1.Name As T1Name
,sumT1.Price
FROM    @t2 AS T2
JOIN    sumCTE AS sumT1
ON      sumT1.t2ID = t2.ID
JOIN    maxCTE AS maxT1
ON      maxT1.t2ID = t2.ID
JOIN    @t1 AS T1
ON      T1.ID = maxT1.t1ID
WHERE   maxT1.PriceList = 1

C# event with custom arguments

I might be late in the game, but how about:

public event Action<MyEvent> EventTriggered = delegate { }; 

private void Trigger(MyEvent e) 
{ 
     EventTriggered(e);
} 

Setting the event to an anonymous delegate avoids for me to check to see if the event isn't null.

I find this comes in handy when using MVVM, like when using ICommand.CanExecute Method.

What is VanillaJS?

The plain and simple answer is yes, VanillaJS === JavaScript, as prescribed by Dr B. Eich.

Printing a char with printf

This is supposed to print the ASCII value of the character, as %d is the escape sequence for an integer. So the value given as argument of printf is taken as integer when printed.

char ch = 'a';
printf("%d", ch);

Same holds for printf("%d", '\0');, where the NULL character is interpreted as the 0 integer.

Finally, sizeof('\n') is 4 because in C, this notation for characters stands for the corresponding ASCII integer. So '\n' is the same as 10 as an integer.

It all depends on the interpretation you give to the bytes.

Regex to replace multiple spaces with a single space

More robust:

function trim(word)
{
    word = word.replace(/[^\x21-\x7E]+/g, ' '); // change non-printing chars to spaces
    return word.replace(/^\s+|\s+$/g, '');      // remove leading/trailing spaces
}

Retrofit 2 - URL Query Parameter

If you specify @GET("foobar?a=5"), then any @Query("b") must be appended using &, producing something like foobar?a=5&b=7.

If you specify @GET("foobar"), then the first @Query must be appended using ?, producing something like foobar?b=7.

That's how Retrofit works.

When you specify @GET("foobar?"), Retrofit thinks you already gave some query parameter, and appends more query parameters using &.

Remove the ?, and you will get the desired result.

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

Solution (Updated: 24-may-2016): Change build.gradle (project)

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:X.X.X-lastVersionGradle'
    classpath 'com.google.gms:google-services:X.X.X-lastVersionGServices' // If use google-services

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

X.X.X-lastVersionGradle: For example: 2.1.0

X.X.X-lastVersionGServices: For example: 3.0.0 (support Firebase Analytics)

Note: if you're using the google-services plugin has to be the same version (if there)

Warning!! -> 2.2.0-alpha throws Unsupported major.minor version 52.0 if you don't use java JDK 8u91 and NetBeans 8.1

List all column except for one in R

In addition to tcash21's numeric indexing if OP may have been looking for negative indexing by name. Here's a few ways I know, some are risky than others to use:

mtcars[, -which(names(mtcars) == "carb")]  #only works on a single column
mtcars[, names(mtcars) != "carb"]          #only works on a single column
mtcars[, !names(mtcars) %in% c("carb", "mpg")] 
mtcars[, -match(c("carb", "mpg"), names(mtcars))] 
mtcars2 <- mtcars; mtcars2$hp <- NULL         #lost column (risky)


library(gdata) 
remove.vars(mtcars2, names=c("mpg", "carb"), info=TRUE) 

Generally I use:

mtcars[, !names(mtcars) %in% c("carb", "mpg")] 

because I feel it's safe and efficient.

Permutation of array

There are n! total permutations for the given array size n. Here is code written in Java using DFS.

public List<List<Integer>> permute(int[] nums) {
    List<List<Integer>> results = new ArrayList<List<Integer>>();
    if (nums == null || nums.length == 0) {
        return results;
    }
    List<Integer> result = new ArrayList<>();
    dfs(nums, results, result);
    return results;
}

public void dfs(int[] nums, List<List<Integer>> results, List<Integer> result) {
    if (nums.length == result.size()) {
        List<Integer> temp = new ArrayList<>(result);
        results.add(temp);
    }        
    for (int i=0; i<nums.length; i++) {
        if (!result.contains(nums[i])) {
            result.add(nums[i]);
            dfs(nums, results, result);
            result.remove(result.size() - 1);
        }
    }
}

For input array [3,2,1,4,6], there are totally 5! = 120 possible permutations which are:

[[3,4,6,2,1],[3,4,6,1,2],[3,4,2,6,1],[3,4,2,1,6],[3,4,1,6,2],[3,4,1,2,6],[3,6,4,2,1],[3,6,4,1,2],[3,6,2,4,1],[3,6,2,1,4],[3,6,1,4,2],[3,6,1,2,4],[3,2,4,6,1],[3,2,4,1,6],[3,2,6,4,1],[3,2,6,1,4],[3,2,1,4,6],[3,2,1,6,4],[3,1,4,6,2],[3,1,4,2,6],[3,1,6,4,2],[3,1,6,2,4],[3,1,2,4,6],[3,1,2,6,4],[4,3,6,2,1],[4,3,6,1,2],[4,3,2,6,1],[4,3,2,1,6],[4,3,1,6,2],[4,3,1,2,6],[4,6,3,2,1],[4,6,3,1,2],[4,6,2,3,1],[4,6,2,1,3],[4,6,1,3,2],[4,6,1,2,3],[4,2,3,6,1],[4,2,3,1,6],[4,2,6,3,1],[4,2,6,1,3],[4,2,1,3,6],[4,2,1,6,3],[4,1,3,6,2],[4,1,3,2,6],[4,1,6,3,2],[4,1,6,2,3],[4,1,2,3,6],[4,1,2,6,3],[6,3,4,2,1],[6,3,4,1,2],[6,3,2,4,1],[6,3,2,1,4],[6,3,1,4,2],[6,3,1,2,4],[6,4,3,2,1],[6,4,3,1,2],[6,4,2,3,1],[6,4,2,1,3],[6,4,1,3,2],[6,4,1,2,3],[6,2,3,4,1],[6,2,3,1,4],[6,2,4,3,1],[6,2,4,1,3],[6,2,1,3,4],[6,2,1,4,3],[6,1,3,4,2],[6,1,3,2,4],[6,1,4,3,2],[6,1,4,2,3],[6,1,2,3,4],[6,1,2,4,3],[2,3,4,6,1],[2,3,4,1,6],[2,3,6,4,1],[2,3,6,1,4],[2,3,1,4,6],[2,3,1,6,4],[2,4,3,6,1],[2,4,3,1,6],[2,4,6,3,1],[2,4,6,1,3],[2,4,1,3,6],[2,4,1,6,3],[2,6,3,4,1],[2,6,3,1,4],[2,6,4,3,1],[2,6,4,1,3],[2,6,1,3,4],[2,6,1,4,3],[2,1,3,4,6],[2,1,3,6,4],[2,1,4,3,6],[2,1,4,6,3],[2,1,6,3,4],[2,1,6,4,3],[1,3,4,6,2],[1,3,4,2,6],[1,3,6,4,2],[1,3,6,2,4],[1,3,2,4,6],[1,3,2,6,4],[1,4,3,6,2],[1,4,3,2,6],[1,4,6,3,2],[1,4,6,2,3],[1,4,2,3,6],[1,4,2,6,3],[1,6,3,4,2],[1,6,3,2,4],[1,6,4,3,2],[1,6,4,2,3],[1,6,2,3,4],[1,6,2,4,3],[1,2,3,4,6],[1,2,3,6,4],[1,2,4,3,6],[1,2,4,6,3],[1,2,6,3,4],[1,2,6,4,3]]

Hope this helps.

Failed to serialize the response in Web API with Json

I don't like this code:

foreach(var user in db.Users)

As an alternative, one might do something like this, which worked for me:

var listOfUsers = db.Users.Select(r => new UserModel
                         {
                             userModel.FirstName = r.FirstName;
                             userModel.LastName = r.LastName;

                         });

return listOfUsers.ToList();

However, I ended up using Lucas Roselli's solution.

Update: Simplified by returning an anonymous object:

var listOfUsers = db.Users.Select(r => new 
                         {
                             FirstName = r.FirstName;
                             LastName = r.LastName;
                         });

return listOfUsers.ToList();