Programs & Examples On #Hamiltonian cycle

How to add one day to a date?

U can try java.util.Date library like this way-

int no_of_day_to_add = 1;

Date today = new Date();
Date tomorrow = new Date( today.getYear(), today.getMonth(), today.getDate() + no_of_day_to_add );

Change value of no_of_day_to_add as you want.

I have set value of no_of_day_to_add to 1 because u wanted only one day to add.

More can be found in this documentation.

How to "perfectly" override a dict?

All you will have to do is

class BatchCollection(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(*args, **kwargs)

OR

class BatchCollection(dict):
    def __init__(self, inpt={}):
        super(BatchCollection, self).__init__(inpt)

A sample usage for my personal use

### EXAMPLE
class BatchCollection(dict):
    def __init__(self, inpt={}):
        dict.__init__(*args, **kwargs)

    def __setitem__(self, key, item):
        if (isinstance(key, tuple) and len(key) == 2
                and isinstance(item, collections.Iterable)):
            # self.__dict__[key] = item
            super(BatchCollection, self).__setitem__(key, item)
        else:
            raise Exception(
                "Valid key should be a tuple (database_name, table_name) "
                "and value should be iterable")

Note: tested only in python3

Required attribute HTML5

Just put the following below your form. Make sure your input fields are required.

<script>
    var forms = document.getElementsByTagName('form');
    for (var i = 0; i < forms.length; i++) {
        forms[i].noValidate = true;
        forms[i].addEventListener('submit', function(event) {
            if (!event.target.checkValidity()) {
                event.preventDefault();
                alert("Please complete all fields and accept the terms.");
            }
        }, false);
    }
</script>

How do I force make/GCC to show me the commands?

Use make V=1

Other suggestions here:

  • make VERBOSE=1 - did not work at least from my trials.
  • make -n - displays only logical operation, not command line being executed. E.g. CC source.cpp

  • make --debug=j - works as well, but might also enable multi threaded building, causing extra output.

IndexOf function in T-SQL

One very small nit to pick:

The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:

"john@work"@myemployer.com

This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:

SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1

More information:

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

How to use onClick() or onSelect() on option tag in a JSP page?

Change onClick() from with onChange() in the . You can send the option value to a javascript function.

<select id="selector" onChange="doSomething(document.getElementById(this).options[document.getElementById(this).selectedIndex].value);"> 
<option value="option1"> Option1 </option>
<option value="option2"> Option2 </option>
<option value="optionN"> OptionN </option>
</select>

How to do HTTP authentication in android?

For my Android projects I've used the Base64 library from here:

http://iharder.net/base64

It's a very extensive library and so far I've had no problems with it.

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

Had the same problem. Here's how I solved it: Go to Package Explorer. Right click on JRE System Library and go to Properties. In the Classpath Container > Select JRE for the project build path select the third option (Workspace default JRE).

Source : https://thenewboston.com/forum/topic.php?id=3917

How do you declare an interface in C++?

My answer is basically the same as the others but I think there are two other important things to do:

  1. Declare a virtual destructor in your interface or make a protected non-virtual one to avoid undefined behaviours if someone tries to delete an object of type IDemo.

  2. Use virtual inheritance to avoid problems whith multiple inheritance. (There is more often multiple inheritance when we use interfaces.)

And like other answers:

  • Make a class with pure virtual methods.
  • Use the interface by creating another class that overrides those virtual methods.

    class IDemo
    {
        public:
            virtual void OverrideMe() = 0;
            virtual ~IDemo() {}
    }
    

    Or

    class IDemo
    {
        public:
            virtual void OverrideMe() = 0;
        protected:
            ~IDemo() {}
    }
    

    And

    class Child : virtual public IDemo
    {
        public:
            virtual void OverrideMe()
            {
                //do stuff
            }
    }
    

What is an optional value in Swift?

Here is an equivalent optional declaration in Swift:

var middleName: String?

This declaration creates a variable named middleName of type String. The question mark (?) after the String variable type indicates that the middleName variable can contain a value that can either be a String or nil. Anyone looking at this code immediately knows that middleName can be nil. It's self-documenting!

If you don't specify an initial value for an optional constant or variable (as shown above) the value is automatically set to nil for you. If you prefer, you can explicitly set the initial value to nil:

var middleName: String? = nil

for more detail for optional read below link

http://www.iphonelife.com/blog/31369/swift-101-working-swifts-new-optional-values

Why can't I push to this bare repository?

Try this in your alice repository (before pushing):

git config push.default tracking

Or, configure it as the default for your user with git config --global ….


git push does default to the origin repository (which is normally the repository from which you cloned the current repository), but it does not default to pushing the current branch—it defaults to pushing only branches that exist in both the source repository and the destination repository.

The push.default configuration variable (see git-config(1)) controls what git push will push when it is not given any “refspec” arguments (i.e. something after a repository name). The default value gives the behavior described above.

Here are possible values for push.default:

  • nothing
    This forces you to supply a “refspec”.

  • matching (the default)
    This pushes all branches that exist in both the source repository and the destination repository.
    This is completely independent of the branch that is currently checked out.

  • upstream or tracking
    (Both values mean the same thing. The later was deprecated to avoid confusion with “remote-tracking” branches. The former was introduced in 1.7.4.2, so you will have to use the latter if you are using Git 1.7.3.1.)
    These push the current branch to the branch specified by its “upstream” configuration.

  • current
    This pushes the current branch to the branch of the same name at the destination repository.

    These last two end up being the same for common cases (e.g. working on local master which uses origin/master as its upstream), but they are different when the local branch has a different name from its “upstream” branch:

    git checkout master
    # hack, commit, hack, commit
    
    # bug report comes in, we want a fix on master without the above commits
    
    git checkout -b quickfix origin/master  # "upstream" is master on origin
    # fix, commit
    git push
    

    With push.default equal to upstream (or tracking), the push would go to origin’s master branch. When it is equal to current, the push would go to origin’s quickfix branch.

The matching setting will update bare’s master in your scenario once it has been established. To establish it, you could use git push origin master once.

However, the upstream setting (or maybe current) seems like it might be a better match for what you expect to happen, so you might want to try it:

# try it once (in Git 1.7.2 and later)
git -c push.default=upstream push

# configure it for only this repository
git config push.default upstream

# configure it for all repositories that do not override it themselves
git config --global push.default upstream

(Again, if you are still using a Git before 1.7.4.2, you will need to use tracking instead of upstream).

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

Your app's manifest.xml having these permission to access information from your's device but you don't have privacy policy link while submitting on the play store. so you getting this warning.

Need privacy policy for the app If your app handles personal or sensitive user data

Adding a privacy policy to your app's store listing helps provide transparency about how you treat sensitive user and device data.

******Update
The privacy policy setting in Google Play Console has changed locations.

In Google Play Console,
Select Store presence > App content.
Under "Privacy Policy".

How do I display the current value of an Android Preference in the Preference summary?

The concise solution by 1 line of code:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    bindPreferenceSummaryToValue(findPreference("mySetting"));

    // initialize summary
    sBindPreferenceSummaryToValueListener.onPreferenceChange(findPreference("mySetting"), 
        ((ListPreference) findPreference("mySetting")).getEntry());
}

java.io.FileNotFoundException: (Access is denied)

Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.

It worked for me so here's hoping it helps someone else, too.

Inheritance and init method in Python

A simple change in Num2 class like this:

super().__init__(num) 

It works in python3.

class Num:
        def __init__(self,num):
                self.n1 = num

class Num2(Num):
        def __init__(self,num):
                super().__init__(num)
                self.n2 = num*2
        def show(self):
                print (self.n1,self.n2)

mynumber = Num2(8)
mynumber.show()

Laravel Eloquent LEFT JOIN WHERE NULL

This can be resolved by specifying the specific column names desired from the specific table like so:

$c = Customer::leftJoin('orders', function($join) {
      $join->on('customers.id', '=', 'orders.customer_id');
    })
    ->whereNull('orders.customer_id')
    ->first([
        'customers.id',
        'customers.first_name',
        'customers.last_name',
        'customers.email',
        'customers.phone',
        'customers.address1',
        'customers.address2',
        'customers.city',
        'customers.state',
        'customers.county',
        'customers.district',
        'customers.postal_code',
        'customers.country'
    ]);

C++ for each, pulling from vector elements

For next examples assumed that you use C++11. Example with ranged-based for loops:

for (auto &attack : m_attack) // access by reference to avoid copying
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

You should use const auto &attack depending on the behavior of makeDamage().

You can use std::for_each from standard library + lambdas:

std::for_each(m_attack.begin(), m_attack.end(),
        [](Attack * attack)
        {
            if (attack->m_num == input)
            {
                attack->makeDamage();
            }
        }
);

If you are uncomfortable using std::for_each, you can loop over m_attack using iterators:

for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

Use m_attack.cbegin() and m_attack.cend() to get const iterators.

Reload activity in Android

for me it's working it's not creating another Intents and on same the Intents new data loaded.

    overridePendingTransition(0, 0);
    finish();
    overridePendingTransition(0, 0);
    startActivity(getIntent());
    overridePendingTransition(0, 0);

Permission denied error on Github Push

In could able to resolve this issue with giving username and password in below url.

Please replace username and password with your Github credentials:

git remote set-url origin https://<username>:<password>@github.com/<username>/FirstRepository.git

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

System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.CurrentCulture;

string _pos = dblstr.Replace(".",
    ci.NumberFormat.NumberDecimalSeparator).Replace(",",
        ci.NumberFormat.NumberDecimalSeparator);

double _dbl = double.Parse(_pos);

Android ADB devices unauthorized

This worked for me

1- Go to ~/.android/ and remove “adbkey”
2- Disconnect USB connection
3- adb kill-server
4- Revoke USB debugging authorizations (in developer option)
5- Reconnect the device to the Ma
6- adb devices

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

Update (2016-11-01)

I was using AmplifyJS mentioned below to work around this issue. However, for Safari in Private browsing, it was falling back to a memory-based storage. In my case, it was not appropriate because it means the storage is cleared on refresh, even if the user is still in private browsing.

Also, I have noticed a number of users who are always browsing in Private mode on iOS Safari. For that reason, a better fallback for Safari is to use cookies (if available). By default, cookies are still accessible even in private browsing. Of course, they are cleared when exiting the private browsing, but they are not cleared on refresh.

I found the local-storage-fallback library. From the documentation:

Purpose

With browser settings like "Private Browsing" it has become a problem to rely on a working window.localStorage, even in newer browsers. Even though it may exist, it will throw exceptions when trying to use setItem or getItem. This module will run appropriate checks to see what browser storage mechanism might be available, and then expose it. It uses the same API as localStorage so it should work as a drop-in replacement in most cases.

Beware of the gotchas:

  • CookieStorage has storage limits. Be careful here.
  • MemoryStorage will not persist between page loads. This is more or less a stop-gap to prevent page crashes, but may be sufficient for websites that don't do full page loads.

TL;DR:

Use local-storage-fallback (unified API with .getItem(prop) and .setItem(prop, val)):

Check and use appropriate storage adapter for browser (localStorage, sessionStorage, cookies, memory)

Original answer

To add upon previous answers, one possible workaround would be to change the storage method. There are a few librairies such as AmplifyJS and PersistJS which can help. Both libs allow persistent client-side storage through several backends.

For AmplifyJS

localStorage

  • IE 8+
  • Firefox 3.5+
  • Safari 4+
  • Chrome
  • Opera 10.5+
  • iPhone 2+
  • Android 2+

sessionStorage

  • IE 8+
  • Firefox 2+
  • Safari 4+
  • Chrome
  • Opera 10.5+
  • iPhone 2+
  • Android 2+

globalStorage

  • Firefox 2+

userData

  • IE 5 - 7
  • userData exists in newer versions of IE as well, but due to quirks in IE 9's implementation, we don't register userData if localStorage is supported.

memory

  • An in-memory store is provided as a fallback if none of the other storage types are available.

For PersistentJS

  • flash: Flash 8 persistent storage.
  • gears: Google Gears-based persistent storage.
  • localstorage: HTML5 draft storage.
  • globalstorage: HTML5 draft storage (old spec).
  • ie: Internet Explorer userdata behaviors.
  • cookie: Cookie-based persistent storage.

They offer an abstraction layer so you don't have to worry about choosing the storage type. Keep in mind there might be some limitations (such as size limits) depending on the storage type though. Right now, I am using AmplifyJS, but I still have to do some more testing on iOS 7/Safari/etc. to see if it actually solves the problem.

Join a list of items with different types as string in Python

Maybe you do not need numbers as strings, just do:

functaulu = [munfunc(arg) for arg in range(loppu)]

Later if you need it as string you can do it with string or with format string:

print "Vastaus5 = %s" % functaulu[5]

How to get the PID of a process by giving the process name in Mac OS X ?

You can try this

pid=$(ps -o pid=,comm= | grep -m1 $procname | cut -d' ' -f1)

Error 6 (net::ERR_FILE_NOT_FOUND): The files c or directory could not be found

Big one I see that causes this is filename. If you have a SPACE then any number such as 'Site 2' the file path with look like something/Site%202/index.html This is because spaces or rendered as %20, and if another number is immediately following that it will try to read it as %202. Fix is you never use spaces in your filenames.

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

If the shell scripts start with #!/bin/bash, they will always run with bash from /bin. If they however start with #!/usr/bin/env bash, they will search for bash in $PATH and then start with the first one they can find.

Why would this be useful? Assume you want to run bash scripts, that require bash 4.x or newer, yet your system only has bash 3.x installed and currently your distribution doesn't offer a newer version or you are no administrator and cannot change what is installed on that system.

Of course, you can download bash source code and build your own bash from scratch, placing it to ~/bin for example. And you can also modify your $PATH variable in your .bash_profile file to include ~/bin as the first entry (PATH=$HOME/bin:$PATH as ~ will not expand in $PATH). If you now call bash, the shell will first look for it in $PATH in order, so it starts with ~/bin, where it will find your bash. Same thing happens if scripts search for bash using #!/usr/bin/env bash, so these scripts would now be working on your system using your custom bash build.

One downside is, that this can lead to unexpected behavior, e.g. same script on the same machine may run with different interpreters for different environments or users with different search paths, causing all kind of headaches.

The biggest downside with env is that some systems will only allow one argument, so you cannot do this #!/usr/bin/env <interpreter> <arg>, as the systems will see <interpreter> <arg> as one argument (they will treat it as if the expression was quoted) and thus env will search for an interpreter named <interpreter> <arg>. Note that this is not a problem of the env command itself, which always allowed multiple parameters to be passed through but with the shebang parser of the system that parses this line before even calling env. Meanwhile this has been fixed on most systems but if your script wants to be ultra portable, you cannot rely that this has been fixed on the system you will be running.

It can even have security implications, e.g. if sudo was not configured to clean environment or $PATH was excluded from clean up. Let me demonstrate this:

Usually /bin is a well protected place, only root is able to change anything there. Your home directory is not, though, any program you run is able to make changes to it. That means malicious code could place a fake bash into some hidden directory, modify your .bash_profile to include that directory in your $PATH, so all scripts using #!/usr/bin/env bash will end up running with that fake bash. If sudo keeps $PATH, you are in big trouble.

E.g. consider a tool creates a file ~/.evil/bash with the following content:

#!/bin/bash

if [ $EUID -eq 0 ]; then
  echo "All your base are belong to us..."
  # We are root - do whatever you want to do
fi

/bin/bash "$@"

Let's make a simple script sample.sh:

#!/usr/bin/env bash

echo "Hello World"

Proof of concept (on a system where sudo keeps $PATH):

$ ./sample.sh
Hello World

$ sudo ./sample.sh
Hello World

$ export PATH="$HOME/.evil:$PATH"

$ ./sample.sh
Hello World

$ sudo ./sample.sh
All your base are belong to us...
Hello World

Usually the classic shells should all be located in /bin and if you don't want to place them there for whatever reason, it's really not an issue to place a symlink in /bin that points to their real locations (or maybe /bin itself is a symlink), so I would always go with #!/bin/sh and #!/bin/bash. There's just too much that would break if these wouldn't work anymore. It's not that POSIX would require these position (POSIX does not standardize path names and thus it doesn't even standardize the shebang feature at all) but they are so common, that even if a system would not offer a /bin/sh, it would probably still understand #!/bin/sh and know what to do with it and may it only be for compatibility with existing code.

But for more modern, non standard, optional interpreters like Perl, PHP, Python, or Ruby, it's not really specified anywhere where they should be located. They may be in /usr/bin but they may as well be in /usr/local/bin or in a completely different hierarchy branch (/opt/..., /Applications/..., etc.). That's why these often use the #!/usr/bin/env xxx shebang syntax.

How to send parameters with jquery $.get()

I got this working : -

$.get('api.php', 'client=mikescafe', function(data) {
...
});

It sends via get the string ?client=mikescafe then collect this variable in api.php, and use it in your mysql statement.

urlencode vs rawurlencode?

simple * rawurlencode the path - path is the part before the "?" - spaces must be encoded as %20 * urlencode the query string - Query string is the part after the "?" -spaces are better encoded as "+" = rawurlencode is more compatible generally

How can I pull from remote Git repository and override the changes in my local repository?

Provided that the remote repository is origin, and that you're interested in master:

git fetch origin
git reset --hard origin/master

This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.

All your local commits not common to the remote will be gone.

What is the Simplest Way to Reverse an ArrayList?

Another recursive solution

 public static String reverse(ArrayList<Float> list) {
   if (list.size() == 1) {
       return " " +list.get(0);
   }
   else {
       return " "+ list.remove(list.size() - 1) + reverse(list);
   } 
 }

Getting the base url of the website and globally passing it to twig in Symfony 2

In one situation involving a multi-domain application, app.request.getHttpHost helped me out. It returns something like example.com or subdomain.example.com (or example.com:8000 when the port is not standard). This was in Symfony 3.4.

Manually put files to Android emulator SD card

I am using Android Studio 3.3.

Go to View -> Tools Window -> Device File Explorer. Or you can find it on the Bottom Right corner of the Android Studio.

If the Emulator is running, the Device File Explorer will display the File structure on Emulator Storage.

Here you can right click on a Folder and select "Upload" to place the file

enter image description here

Creating a class object in c++

1) What is the difference between both the way of creating class objects.

a) pointer

Example* example=new Example();
// you get a pointer, and when you finish it use, you have to delete it:

delete example;

b) Simple declaration

Example example;

you get a variable, not a pointer, and it will be destroyed out of scope it was declared.

2) Singleton C++

This SO question may helps you

Update one MySQL table with values from another

It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.

What to do on TransactionTooLargeException

There isn't one specific cause of this problem.For me, in my Fragment class I was doing this:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View rootView = inflater.inflate(R.layout.snacks_layout, container); //<-- notice the absence of the false argument
    return rootView;
}

instead of this:

View rootView = inflater.inflate(R.layout.softs_layout, container, false);

SQL Server principal "dbo" does not exist,

enter image description here

Do Graphically.

Database right click-->properties-->files-->select database owner-->select [sa]-- ok

When is layoutSubviews called?

Some of the points in BadPirate's answer are only partially true:

  1. For addSubView point

    addSubview causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target.

    It depends on the view's (target view) autoresize mask. If it has autoresize mask ON, layoutSubview will be called on each addSubview. If it has no autoresize mask then layoutSubview will be called only when the view's (target View) frame size changes.

    Example: if you created UIView programmatically (it has no autoresize mask by default), LayoutSubview will be called only when UIView frame changes not on every addSubview.

    It is through this technique that the performance of the application also increases.

  2. For the device rotation point

    Rotating a device only calls layoutSubview on the parent view (the responding viewController's primary view)

    This can be true only when your VC is in the VC hierarchy (root at window.rootViewController), well this is most common case. In iOS 5, if you create a VC, but it is not added into any another VC, then this VC would not get any noticed when device rotate. Therefore its view would not get noticed by calling layoutSubviews.

Reading file line by line (with space) in Unix Shell scripting - Issue

Try this,

IFS=''
while read line
do
    echo $line
done < file.txt

EDIT:

From man bash

IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with  the  read  builtin  command. The default value is
``<space><tab><newline>''

How to show shadow around the linearlayout in Android?

For lollipop and above you can use elevation.

For older versions:

Here is a lazy hack from: http://odedhb.blogspot.com/2013/05/android-layout-shadow-without-9-patch.html

(toast_frame does not work on KitKat, shadow was removed from toasts)

just use:

android:background="@android:drawable/toast_frame"

or:

android:background="@android:drawable/dialog_frame"

as a background

examples:

<TextView
        android:layout_width="fill_parent"
        android:text="I am a simple textview with a shadow"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:padding="16dp"
        android:textColor="#fff"
        android:background="@android:drawable/toast_frame"
        />

and with different bg color:

<LinearLayout
        android:layout_height="64dp"
        android:layout_width="fill_parent"
        android:gravity="center"
        android:background="@android:drawable/toast_frame"
        android:padding="4dp"
        >
    <Button
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="Button shadow"
            android:background="#33b5e5"
            android:textSize="24sp"
            android:textStyle="bold"
            android:textColor="#fff"
            android:layout_gravity="center|bottom"
            />

</LinearLayout>

Getting the encoding of a Postgres database

If you want to get database encodings:

psql  -U postgres -h somehost --list

You'll see something like:

List of databases
           Name         |  Owner   | Encoding
------------------------+----------+----------
db1                     | postgres | UTF8

Python readlines() usage and efficient practice for reading

Read line by line, not the whole file:

for line in open(file_name, 'rb'):
    # process line here

Even better use with for automatically closing the file:

with open(file_name, 'rb') as f:
    for line in f:
        # process line here

The above will read the file object using an iterator, one line at a time.

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

I managed to hit this error when simply creating a table! There was obviously no contention problem on a table that didn't yet exist. The CREATE TABLE statement contained a CONSTRAINT fk_name FOREIGN KEY clause referencing a well-populated table. I had to:

  • Remove the FOREIGN KEY clause from the CREATE TABLE statement
  • Create an INDEX on the FK column
  • Create the FK

Could not open input file: composer.phar

The composer.phar install is not working but without .phar this is working.

We need to enable the openssl module in php before installing the zendframe work.

We have to uncomment the line ;extension=php_openssl.dll from php.ini file.

composer use different php.ini file which is located at the wamp\bin\php\php-<version number>\php.ini

After enabling the openssl we need to restart the server.

The execute the following comments.

I can install successfully using these commands -

composer self-update
composer install --prefer-dist

enter image description here

Sublime Text 2 multiple line edit

It's fine to manually select each number for a small set of numbers like in your example, but for larger collections you can do a regex search which will do the work for you.

Ctrl + F will open the search bar.

Regex searches are enabled by clicking the ".*" button on the far left.

Type in "\d+" to search for all occurrences of 1 or more digits. Clicking the "Find All" button will select each of these numbers separately.

Then you can use Ctrl + Shift + L to convert the selection into multiple cursors. From here you can do as you like.

How to remove all listeners in an element?

Here's a function that is also based on cloneNode, but with an option to clone only the parent node and move all the children (to preserve their event listeners):

function recreateNode(el, withChildren) {
  if (withChildren) {
    el.parentNode.replaceChild(el.cloneNode(true), el);
  }
  else {
    var newEl = el.cloneNode(false);
    while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
    el.parentNode.replaceChild(newEl, el);
  }
}

Remove event listeners on one element:

recreateNode(document.getElementById("btn"));

Remove event listeners on an element and all of its children:

recreateNode(document.getElementById("list"), true);

If you need to keep the object itself and therefore can't use cloneNode, then you have to wrap the addEventListener function and track the listener list by yourself, like in this answer.

Outlets cannot be connected to repeating content iOS

With me I have a UIViewcontroller, and into it I have a tableview with a custom cell on it. I map my outlet of UILabel into UItableviewcell to the UIViewController then got the error.

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

Based on this page:

  • Run regedit (remember to run it as the administrator)
  • Expand HKEY_LOCAL_MACHINE
  • Expand SOFTWARE
  • Expand Microsoft
  • Expand Windows
  • Expand CurrentVersion
  • Expand App Paths
  • At App Paths, add a new KEY called sqldeveloper.exe
  • Expand sqldeveloper.exe
  • Modify the (DEFAULT) value to the full pathway to the sqldeveloper executable (See example below step 11)
  • Create a new STRING VALUE called PATH and set it value to the sqldeveloper pathway + \jdk\jre\bin

The import com.google.android.gms cannot be resolved

In my case only after I added gcm.jar to lib folder, it started to work. It was here: C:\adt-bundle-windows-x86_64-20131030\sdk\extras\google\gcm\gcm-client\dist

So the google-play-services.jar didn't work...

What is the difference between JSF, Servlet and JSP?

See http://www.oracle.com/technetwork/java/faq-137059.html

JSP technology is part of the Java technology family. JSP pages are compiled into servlets and may call JavaBeans components (beans) or Enterprise JavaBeans components (enterprise beans) to perform processing on the server. As such, JSP technology is a key component in a highly scalable architecture for web-based applications.

See https://jcp.org/en/introduction/faq

A: JavaServer Faces technology is a framework for building user interfaces for web applications. JavaServer Faces technology includes:

A set of APIs for: representing UI components and managing their state, handling events and input validation, defining page navigation, and supporting internationalization and accessibility.

A JavaServer Pages (JSP) custom tag library for expressing a JavaServer Faces interface within a JSP page.

JSP is a specialized kind of servlet.

JSF is a set of tags you can use with JSP.

What is the standard exception to throw in Java for not supported/implemented operations?

If you create a new (not yet implemented) function in NetBeans, then it generates a method body with the following statement:

throw new java.lang.UnsupportedOperationException("Not supported yet.");

Therefore, I recommend to use the UnsupportedOperationException.

How to order citations by appearance using BibTeX?

I'm a bit new to Bibtex (and to Latex in general) and I'd like to revive this old post since I found it came up in many of my Google search inquiries about the ordering of a bibliography in Latex.

I'm providing a more verbose answer to this question in the hope that it might help some novices out there facing the same difficulties as me.

Here is an example of the main .tex file in which the bibliography is called:

\documentclass{article}
\begin{document}

So basically this is where the body of your document goes.

``FreeBSD is easy to install,'' said no one ever \cite{drugtrafficker88}.

``Yeah well at least I've got chicken,'' said Leeroy Jenkins \cite{goodenough04}.

\newpage
\bibliographystyle{ieeetr} % Use ieeetr to list refs in the order they're cited
\bibliography{references} % Or whatever your .bib file is called
\end{document}

...and an example of the .bib file itself:

@ARTICLE{ goodenough04,
AUTHOR    = "G. D. Goodenough and others", 
TITLE     = "What it's like to have a sick-nasty last name",
JOURNAL   = "IEEE Trans. Geosci. Rem. Sens.",
YEAR      = "xxxx",
volume    = "xx",
number    = "xx",
pages     = "xx--xx"
}
@BOOK{ drugtrafficker88,
AUTHOR    = "G. Drugtrafficker", 
TITLE     = "What it's Like to Have a Misleading Last Name",
YEAR      = "xxxx",
PUBLISHER = "Harcourt Brace Jovanovich, Inc."
ADDRESS   = "The Florida Alps, FL, USA"
}

Note the references in the .bib file are listed in reverse order but the references are listed in the order they are cited in the paper.

More information on the formatting of your .bib file can be found here: http://en.wikibooks.org/wiki/LaTeX/Bibliography_Management

Programmatically navigate using react router V4

I think that @rgommezz covers most of the cases minus one that I think it's quite important.

// history is already a dependency or React Router, but if don't have it then try npm install save-dev history

import createHistory from "history/createBrowserHistory"

// in your function then call add the below 
const history = createHistory();
// Use push, replace, and go to navigate around.
history.push("/home");

This allows me to write a simple service with actions/calls that I can call to do the navigation from any component I want without doing a lot HoC on my components...

It is not clear why nobody has provided this solution before. I hope it helps, and if you see any issue with it please let me know.

How do I get video durations with YouTube API version 3?

You can get the duration from the 'contentDetails' field in the json response.

enter image description here

Set value to an entire column of a pandas dataframe

I had a similar issue before even with this approach df.loc[:,'industry'] = 'yyy', but once I refreshed the notebook, it ran well.

You may want to try refreshing the cells after you have df.loc[:,'industry'] = 'yyy'.

CSS media queries: max-width OR max-height

CSS Media Queries & Logical Operators: A Brief Overview ;)

The quick answer.

Separate rules with commas: @media handheld, (min-width: 650px), (orientation: landscape) { ... }

The long answer.

There's a lot here, but I've tried to make it information dense, not just fluffy writing. It's been a good chance to learn myself! Take the time to systematically read though and I hope it will be helpful.


Media Queries

Media queries essentially are used in web design to create device- or situation-specific browsing experiences; this is done using the @media declaration within a page's CSS. This can be used to display a webpage differently under a large number of circumstances: whether you are on a tablet or TV with different aspect ratios, whether your device has a color or black-and-white screen, or, perhaps most frequently, when a user changes the size of their browser or switches between browsing devices with varying screen sizes (very generally speaking, designing like this is referred to as Responsive Web Design)

Logical Operators

In designing for these situations, there appear to be four Logical Operators that can be used to require more complex combinations of requirements when targeting a variety of devices or viewport sizes.

(Note: If you don't understand the the differences between media rules, media queries, and feature queries, browse the bottom section of this answer first to get a bit better acquainted with the terminology associated with media query syntax

1. AND (and keyword)

Requires that all conditions specified must be met before the styling rules will take effect.

@media screen and (min-width: 700px) and (orientation: landscape) { ... }

The specified styling rules won't go into place unless all of the following evaluate as true:

  • The media type is 'screen' and
  • The viewport is at least 700px wide and
  • Screen orientation is currently landscape.

Note: I believe that used together, these three feature queries make up a single media query.

2. OR (Comma-separated lists)

Rather than an or keyword, comma-separated lists are used in chaining multiple media queries together to form a more complex media rule

@media handheld, (min-width: 650px), (orientation: landscape) { ... }

The specified styling rules will go into effect once any one media query evaluates as true:

  1. The media type is 'handheld' or
  2. The viewport is at least 650px wide or
  3. Screen orientation is currently landscape.

3. NOT (not keyword)

The not keyword can be used to negate a single media query (and NOT a full media rule--meaning that it only negates entries between a set of commas and not the full media rule following the @media declaration).

Similarly, note that the not keyword negates media queries, it cannot be used to negate an individual feature query within a media query.*

@media not screen and (min-resolution: 300dpi), (min-width: 800px) { ... }

The styling specified here will go into effect if

  1. The media type AND min-resolution don't both meet their requirements ('screen' and '300dpi' respectively) or
  2. The viewport is at least 800 pixels wide.

In other words, if the media type is 'screen' and the min-resolution is 300 dpi, the rule will not go into effect unless the min-width of the viewport is at least 800 pixels.

(The not keyword can be a little funky to state. Let me know if I can do better. ;)

4. ONLY (only keyword)

As I understand it, the only keyword is used to prevent older browsers from misinterpreting newer media queries as the earlier-used, narrower media type. When used correctly, older/non-compliant browsers should just ignore the styling altogether.

<link rel="stylesheet" media="only screen and (color)" href="example.css" />

An older / non-compliant browser would just ignore this line of code altogether, I believe as it would read the only keyword and consider it an incorrect media type. (See here and here for more info from smarter people)

FOR MORE INFO

For more info (including more features that can be queried), see: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries#Logical_operators


Understanding Media Query Terminology

Note: I needed to learn the following terminology for everything here to make sense, particularly concerning the not keyword. Here it is as I understand it:

A media rule (MDN also seems to call these media statements) includes the term @media with all of its ensuing media queries

@media all and (min-width: 800px)

@media only screen and (max-resolution:800dpi), not print

@media screen and (min-width: 700px), (orientation: landscape)

@media handheld, (min-width: 650px), (min-aspect-ratio: 1/1)

A media query is a set of feature queries. They can be as simple as one feature query or they can use the and keyword to form a more complex query. Media queries can be comma-separated to form more complex media rules (see the or keyword above).

screen (Note: Only one feature query in use here.)

only screen

only screen and (max-resolution:800dpi)

only tv and (device-aspect-ratio: 16/9) and (color)

NOT handheld, (min-width: 650px). (Note the comma: there are two media queries here.)

A feature query is the most basic portion of a media rule and simply concerns a given feature and its status in a given browsing situation.

screen

(min-width: 650px)

(orientation: landscape)

(device-aspect-ratio: 16/9)


Code snippets and information derived from:

CSS media queries by Mozilla Contributors (licensed under CC-BY-SA 2.5). Some code samples were used with minor alterations to (hopefully) increase clarity of explanation.

Declaring variables in Excel Cells

You can use (hidden) cells as variables. E.g., you could hide Column C, set C1 to

=20

and use it as

=c1*20

Alternatively you can write VBA Macros which set and read a global variable.

Edit: AKX renders my Answer partially incorrect. I had no idea you could name cells in Excel.

Can I set state inside a useEffect hook

? 1. Can I set state inside a useEffect hook?

In principle, you can set state freely where you need it - including inside useEffect and even during rendering. Just make sure to avoid infinite loops by settting Hook deps properly and/or state conditionally.


? 2. Lets say I have some state that is dependent on some other state. Is it appropriate to create a hook that observes A and sets B inside the useEffect hook?

You just described the classic use case for useReducer:

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. (React docs)

When setting a state variable depends on the current value of another state variable, you might want to try replacing them both with useReducer. [...] When you find yourself writing setSomething(something => ...), it’s a good time to consider using a reducer instead. (Dan Abramov, Overreacted blog)

_x000D_
_x000D_
let MyComponent = () => {_x000D_
  let [state, dispatch] = useReducer(reducer, { a: 1, b: 2 });_x000D_
_x000D_
  useEffect(() => {_x000D_
    console.log("Some effect with B");_x000D_
  }, [state.b]);_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <p>A: {state.a}, B: {state.b}</p>_x000D_
      <button onClick={() => dispatch({ type: "SET_A", payload: 5 })}>_x000D_
        Set A to 5 and Check B_x000D_
      </button>_x000D_
      <button onClick={() => dispatch({ type: "INCREMENT_B" })}>_x000D_
        Increment B_x000D_
      </button>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
// B depends on A. If B >= A, then reset B to 1._x000D_
function reducer(state, { type, payload }) {_x000D_
  const someCondition = state.b >= state.a;_x000D_
_x000D_
  if (type === "SET_A")_x000D_
    return someCondition ? { a: payload, b: 1 } : { ...state, a: payload };_x000D_
  else if (type === "INCREMENT_B") return { ...state, b: state.b + 1 };_x000D_
  return state;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect } = React</script>
_x000D_
_x000D_
_x000D_


? 3. Will the effects cascade such that, when I click the button, the first effect will fire, causing b to change, causing the second effect to fire, before the next render?

useEffect always runs after the render is committed and DOM changes are applied. The first effect fires, changes b and causes a re-render. After this render has completed, second effect will run due to b changes.

_x000D_
_x000D_
let MyComponent = props => {_x000D_
  console.log("render");_x000D_
  let [a, setA] = useState(1);_x000D_
  let [b, setB] = useState(2);_x000D_
_x000D_
  let isFirstRender = useRef(true);_x000D_
_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect a, value:", a);_x000D_
    if (isFirstRender.current) isFirstRender.current = false;_x000D_
    else setB(3);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect a, value:", a);_x000D_
    };_x000D_
  }, [a]);_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect b, value:", b);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect b, value:", b);_x000D_
    };_x000D_
  }, [b]);_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <p>a: {a}, b: {b}</p>_x000D_
      <button_x000D_
        onClick={() => {_x000D_
          console.log("Clicked!");_x000D_
          setA(5);_x000D_
        }}_x000D_
      >_x000D_
        click me_x000D_
      </button>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
_x000D_
_x000D_


? 4. Are there any performance downsides to structuring code like this?

Yes. By wrapping the state change of b in a separate useEffect for a, the browser has an additional layout/paint phase - these effects are potentially visible for the user. If there is no way you want give useReducer a try, you could change b state together with a directly:

_x000D_
_x000D_
let MyComponent = () => {_x000D_
  console.log("render");_x000D_
  let [a, setA] = useState(1);_x000D_
  let [b, setB] = useState(2);_x000D_
_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect b, value:", b);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect b, value:", b);_x000D_
    };_x000D_
  }, [b]);_x000D_
_x000D_
  const handleClick = () => {_x000D_
    console.log("Clicked!");_x000D_
    setA(5);_x000D_
    b >= 5 ? setB(1) : setB(b + 1);_x000D_
  };_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <p>_x000D_
        a: {a}, b: {b}_x000D_
      </p>_x000D_
      <button onClick={handleClick}>click me</button>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
_x000D_
_x000D_

How to select all instances of a variable and edit variable name in Sublime

This worked for me. Put your cursor at the beginning of the word you want to replace, then

CtrlK, CtrlD, CtrlD ...

That should select as many instances of the word as you like, then you can just type the replacement.

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

convert string into array of integers

If the numbers can be separated by more than one space, it is safest to split the string on one or more consecutive whitespace characters (which includes tabs and regular spaces). With a regular expression, this would be \s+.

You can then map each element using the Number function to convert it. Note that parseInt will not work (i.e. arr.map(parseInt)) because map passes three arguments to the mapping function: the element, the index, and the original array. parseInt accepts the base or radix as the second parameter, so it will end up taking the index as the base, often resulting in many NaNs in the result. However, Number ignores any arguments other than the first, so it works directly.

const str = '1\t\t2   3 4';
const result = str.split(/\s+/).map(Number); //[1,2,3,4]

You could also use an anonymous function for the mapping callback with the unary plus operator to convert each element to a number.

const str = '1\t\t2   3 4';
const result = str.split(/\s+/).map(x => +x); //[1,2,3,4]

With an anonymous function for the callback, you can decide what parameters to use, so parseInt can also work.

const str = '1\t\t2   3 4';
const result = str.split(/\s+/).map(x => parseInt(x)); //[1,2,3,4]

How to dynamic new Anonymous Class?

You can create an ExpandoObject like this:

IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;

And after casting it to dynamic, those values will look like properties:

dynamic d = expando;
Console.WriteLine(d.Name);

However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:

d.GetType().GetProperty("Name") 

Creating a "Hello World" WebSocket example

WebSockets are implemented with a protocol that involves handshake between client and server. I don't imagine they work very much like normal sockets. Read up on the protocol, and get your application to talk it. Alternatively, use an existing WebSocket library, or .Net4.5beta which has a WebSocket API.

MySQL direct INSERT INTO with WHERE clause

If I understand the goal is to insert a new record to a table but if the data is already on the table: skip it! Here is my answer:

INSERT INTO tbl_member 
(Field1,Field2,Field3,...) 
SELECT a.Field1,a.Field2,a.Field3,... 
FROM (SELECT Field1 = [NewValueField1], Field2 = [NewValueField2], Field3 = [NewValueField3], ...) AS a 
LEFT JOIN tbl_member AS b 
ON a.Field1 = b.Field1 
WHERE b.Field1 IS NULL

The record to be inserted is in the new value fields.

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

Validation is easy, text them a little code to type in. A CharField is a great way to store it. I wouldn't worry too much about canonicalizing phone numbers.

How to add files/folders to .gitignore in IntelliJ IDEA?

Intellij had .ignore plugin to support this. https://plugins.jetbrains.com/plugin/7495?pr=idea

After you install the plugin, you right click on the project and select new -> .ignore file -> .gitignore file (Git) enter image description here

Then, select the type of project you have to generate a template and click Generate. enter image description here

Today`s date in an excel macro

Here's an example that puts the Now() value in column A.

Sub move()
    Dim i As Integer
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim nextRow As Long
    Dim copyRange As Range
    Dim destRange As Range

    Application.ScreenUpdating = False

        Set sh1 = ActiveWorkbook.Worksheets("Sheet1")
        Set sh2 = ActiveWorkbook.Worksheets("Sheet2")
        Set copyRange = sh1.Range("A1:A5")

        i = Application.WorksheetFunction.CountA(sh2.Range("B:B")) + 4

        Set destRange = sh2.Range("B" & i)

        destRange.Resize(1, copyRange.Rows.Count).Value = Application.Transpose(copyRange.Value)
        destRange.Offset(0, -1).Value = Format(Now(), "MMM-DD-YYYY")

        copyRange.Clear

    Application.ScreenUpdating = True

End Sub

There are better ways of getting the last row in column B than using a While loop, plenty of examples around here. Some are better than others but depend on what you're doing and what your worksheet structure looks like. I used one here which assumes that column B is ALL empty except the rows/records you're moving. If that's not the case, or if B1:B3 have some values in them, you'd need to modify or use another method. Or you could just use your loop, but I'd search for alternatives :)

Hiding a password in a python script (insecure obfuscation only)

for python3 obfuscation using base64 is done differently:

import base64
base64.b64encode(b'PasswordStringAsStreamOfBytes')

which results in

b'UGFzc3dvcmRTdHJpbmdBc1N0cmVhbU9mQnl0ZXM='

note the informal string representation, the actual string is in quotes

and decoding back to the original string

base64.b64decode(b'UGFzc3dvcmRTdHJpbmdBc1N0cmVhbU9mQnl0ZXM=')
b'PasswordStringAsStreamOfBytes'

to use this result where string objects are required the bytes object can be translated

repr = base64.b64decode(b'UGFzc3dvcmRTdHJpbmdBc1N0cmVhbU9mQnl0ZXM=')
secret = repr.decode('utf-8')
print(secret)

for more information on how python3 handles bytes (and strings accordingly) please see the official documentation.

How to import a new font into a project - Angular 5

You can try creating a css for your font with font-face (like explained here)

Step #1

Create a css file with font face and place it somewhere, like in assets/fonts

customfont.css

@font-face {
    font-family: YourFontFamily;
    src: url("/assets/font/yourFont.otf") format("truetype");
}

Step #2

Add the css to your .angular-cli.json in the styles config

"styles":[
 //...your other styles
 "assets/fonts/customFonts.css"
 ]

Do not forget to restart ng serve after doing this

Step #3

Use the font in your code

component.css

span {font-family: YourFontFamily; }

AngularJS $watch window resize inside directive

You can listen resize event and fire where some dimension change

directive

(function() {
'use strict';

    angular
    .module('myApp.directives')
    .directive('resize', ['$window', function ($window) {
        return {
            link: link,
            restrict: 'A'
        };

        function link(scope, element, attrs){
            scope.width = $window.innerWidth;
            function onResize(){
                // uncomment for only fire when $window.innerWidth change   
                // if (scope.width !== $window.innerWidth)
                {
                    scope.width = $window.innerWidth;
                    scope.$digest();
                }
            };

            function cleanUp() {
                angular.element($window).off('resize', onResize);
            }

            angular.element($window).on('resize', onResize);
            scope.$on('$destroy', cleanUp);
        }
    }]);
})();

In html

<div class="row" resize> ,
    <div class="col-sm-2 col-xs-6" ng-repeat="v in tag.vod"> 
        <h4 ng-bind="::v.known_as"></h4>
    </div> 
</div> 

Controller :

$scope.$watch('width', function(old, newv){
     console.log(old, newv);
 })

Could not establish secure channel for SSL/TLS with authority '*'

This was exact the problem I was facing. At some other article I got a hint to change the configuration. For me this works:

<bindings>
  <basicHttpBinding>
    <binding name="xxxBinding">
      <security mode="Transport">
        <transport clientCredentialType="Certificate"/>
      </security>
    </binding>
  </basicHttpBinding>
</bindings>

Convert array to JSON string in swift

If you're already using SwiftyJSON:

https://github.com/SwiftyJSON/SwiftyJSON

You can do this:

// this works with dictionaries too
let paramsDictionary = [
    "title": "foo",
    "description": "bar"
]
let paramsArray = [ "one", "two" ]
let paramsJSON = JSON(paramsArray)
let paramsString = paramsJSON.rawString(encoding: NSUTF8StringEncoding, options: nil)

SWIFT 3 UPDATE

 let paramsJSON = JSON(paramsArray)
 let paramsString = paramsJSON.rawString(String.Encoding.utf8, options: JSONSerialization.WritingOptions.prettyPrinted)!

JSON strings, which are good for transport, don't come up often because you can JSON encode an HTTP body. But one potential use-case for JSON stringify is Multipart Post, which AlamoFire nows supports.

Wireshark vs Firebug vs Fiddler - pros and cons?

The benefit of WireShark is that it could possibly show you errors in levels below the HTTP protocol. Fiddler will show you errors in the HTTP protocol.

If you think the problem is somewhere in the HTTP request issued by the browser, or you are just looking for more information in regards to what the server is responding with, or how long it is taking to respond, Fiddler should do.

If you suspect something may be wrong in the TCP/IP protocol used by your browser and the server (or in other layers below that), go with WireShark.

Interfaces with static fields in java for sharing 'constants'

There is a lot of hate for this pattern in Java. However, an interface of static constants does sometimes have value. You need to basically fulfill the following conditions:

  1. The concepts are part of the public interface of several classes.

  2. Their values might change in future releases.

  3. Its critical that all implementations use the same values.

For example, suppose that you are writing an extension to a hypothetical query language. In this extension you are going to expand the language syntax with some new operations, which are supported by an index. E.g. You are going to have a R-Tree supporting geospatial queries.

So you write a public interface with the static constant:

public interface SyntaxExtensions {
     // query type
     String NEAR_TO_QUERY = "nearTo";

     // params for query
     String POINT = "coordinate";
     String DISTANCE_KM = "distanceInKm";
}

Now later, a new developer thinks he needs to build a better index, so he comes and builds an R* implementation. By implementing this interface in his new tree he guarantees that the different indexes will have identical syntax in the query language. Moreover, if you later decided that "nearTo" was a confusing name, you could change it to "withinDistanceInKm", and know that the new syntax would be respected by all your index implementations.

PS: The inspiration for this example is drawn from the Neo4j spatial code.

How to make an image center (vertically & horizontally) inside a bigger div

Personally, I'd place it as the background image within the div, the CSS for that being:

#demo {
    background: url(bg_apple_little.gif) no-repeat center center;
    height: 200px;
    width: 200px;
}

(Assumes a div with id="demo" as you are already specifying height and width adding a background shouldn't be an issue)

Let the browser take the strain.

Table is marked as crashed and should be repaired

Run this from your server's command line:

 mysqlcheck --repair --all-databases

javac: file not found: first.java Usage: javac <options> <source files>

Sometimes this issue occurs, If you are creating a java file for the first time in your system. The Extension of your Java file gets saved as the text file.

e.g Example.java.txt (wrong extension)

You need to change the text file extension to java file.

It should be like:

Example.java (right extension)

Delay/Wait in a test case of Xcode UI testing

Asynchronous UI Testing was introduced in Xcode 7 Beta 4. To wait for a label with the text "Hello, world!" to appear you can do the following:

let app = XCUIApplication()
app.launch()

let label = app.staticTexts["Hello, world!"]
let exists = NSPredicate(format: "exists == 1")

expectationForPredicate(exists, evaluatedWithObject: label, handler: nil)
waitForExpectationsWithTimeout(5, handler: nil)

More details about UI Testing can be found on my blog.

Eclipse doesn't stop at breakpoints

  1. Go to (eclipse-workspace)\.metadata\.plugins\org.eclipse.wst.server.core and delete all tmp folders.
  2. Clean and Restart server.

Setting Windows PATH for Postgres tools

Incase any one still wondering how to add environment variables then please use this link to add variables. Link: https://sqlbackupandftp.com/blog/setting-windows-path-for-postgres-tools

SOAP client in .NET - references or examples?

Take a look at "using WCF Services with PHP". It explains the basics of what you need.

As a theory summary:

WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.

The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.

You have the first part of the article here, explaining how to create a very basic WCF Service.

More resources:

Using WCF with PHP5.

Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

If you remove [DataType(DataType.Date)] from your model, the input field in Chrome is rendered as type="datetime" and won't show the datepicker either.

Java Equivalent of C# async/await?

AsynHelper Java library includes a set of utility classes/methods for such asynchronous calls (and wait).

If it is desired to run a set of method calls or code blocks asynchronously, the It includes an useful helper method AsyncTask.submitTasks as in below snippet.

AsyncTask.submitTasks(
    () -> getMethodParam1(arg1, arg2),
    () -> getMethodParam2(arg2, arg3)
    () -> getMethodParam3(arg3, arg4),
    () -> {
             //Some other code to run asynchronously
          }
    );

If it is desired to wait till all asynchronous codes are completed running, the AsyncTask.submitTasksAndWait varient can be used.

Also if it is desired to obtain a return value from each of the asynchronous method call or code block, the AsyncSupplier.submitSuppliers can be used so that the result can be then obtained by from the result suppliers array returned by the method. Below is the sample snippet:

Supplier<Object>[] resultSuppliers = 
   AsyncSupplier.submitSuppliers(
     () -> getMethodParam1(arg1, arg2),
     () -> getMethodParam2(arg3, arg4),
     () -> getMethodParam3(arg5, arg6)
   );

Object a = resultSuppliers[0].get();
Object b = resultSuppliers[1].get();
Object c = resultSuppliers[2].get();

myBigMethod(a,b,c);

If the return type of each method differ, use the below kind of snippet.

Supplier<String> aResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam1(arg1, arg2));
Supplier<Integer> bResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam2(arg3, arg4));
Supplier<Object> cResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam3(arg5, arg6));

myBigMethod(aResultSupplier.get(), bResultSupplier.get(), cResultSupplier.get());

The result of the asynchronous method calls/code blocks can also be obtained at a different point of code in the same thread or a different thread as in the below snippet.

AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam1(arg1, arg2), "a");
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam2(arg3, arg4), "b");
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam3(arg5, arg6), "c");


//Following can be in the same thread or a different thread
Optional<String> aResult = AsyncSupplier.waitAndGetFromSupplier(String.class, "a");
Optional<Integer> bResult = AsyncSupplier.waitAndGetFromSupplier(Integer.class, "b");
Optional<Object> cResult = AsyncSupplier.waitAndGetFromSupplier(Object.class, "c");

 myBigMethod(aResult.get(),bResult.get(),cResult.get());

Can't change table design in SQL Server 2008

The answer is on the MSDN site:

The Save (Not Permitted) dialog box warns you that saving changes is not permitted because the changes you have made require the listed tables to be dropped and re-created.

The following actions might require a table to be re-created:

  • Adding a new column to the middle of the table
  • Dropping a column
  • Changing column nullability
  • Changing the order of the columns
  • Changing the data type of a column

EDIT 1:

Additional useful informations from here:

To change the Prevent saving changes that require the table re-creation option, follow these steps:

  1. Open SQL Server Management Studio (SSMS).
  2. On the Tools menu, click Options.
  3. In the navigation pane of the Options window, click Designers.
  4. Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.

Note If you disable this option, you are not warned when you save the table that the changes that you made have changed the metadata structure of the table. In this case, data loss may occur when you save the table.

Risk of turning off the "Prevent saving changes that require table re-creation" option

Although turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore, we recommend that you do not work around this problem by turning off the option.

Settings, screen shot

Python error: "IndexError: string index out of range"

There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):

word = 'hello'
so_far = "-" * len(word)       # Create variable so_far to contain the current guess

while word != so_far:          # if still not complete
    print(so_far)
    guess = input('>> ')       # get a char guess

    if guess in word:
        print("\nYes!", guess, "is in the word!")

        new = ""
        for i in range(len(word)):  
            if guess == word[i]:
                new += guess        # fill the position with new value
            else:
                new += so_far[i]    # same value as before
        so_far = new
    else:
        print("try_again")

print('finish')

I tried to write it for py3k with a py2k ide, be careful with errors.

How do I convert an Array to a List<object> in C#?

another way

List<YourClass> list = (arrayList.ToArray() as YourClass[]).ToList();

Retrieve filename from file descriptor in C

In Windows, with GetFileInformationByHandleEx, passing FileNameInfo, you can retrieve the file name.

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

Apart from very good responses here, you could try this as well if you want to use your sub query as is.

Approach:

1) Select the desired column (Only 1) from your sub query

2) Use where to map the column name

Code:

 SELECT count(distinct dNum)
 FROM myDB.dbo.AQ
 WHERE A_ID in 
   (
    SELECT A_ID 
    FROM (SELECT DISTINCT TOP (0.1) PERCENT A_ID, COUNT(DISTINCT dNum) AS ud 
          FROM         myDB.dbo.AQ
          WHERE     M > 1 and B = 0 
          GROUP BY A_ID ORDER BY ud DESC
         ) a 
   )

How do I set the time zone of MySQL?

On Windows (IIS) in order to be able to SET GLOBAL time_zone = 'Europe/Helsinki' (or whatever) the MySQL time_zone description tables need to be populated first.

I downloaded these from this link https://dev.mysql.com/downloads/timezones.html

After running the downloaded SQL query I was able to set the GLOBAL time_zone and resolve the issue I had where SELECT NOW(); was returning GMT rather than BST.

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

FWIW, sp_test will not be returning anything but an integer (all SQL Server stored procs just return an integer) and no result sets on the wire (since no SELECT statements). To get the output of the PRINT statements, you normally use the InfoMessage event on the connection (not the command) in ADO.NET.

How to iterate through a table rows and get the cell values using jQuery

$(this) instead of $this

$("tr.item").each(function() {
        var quantity1 = $(this).find("input.name").val(),
            quantity2 = $(this).find("input.id").val();
});

Proof_1:

proof_2:

How do I check to see if my array includes an object?

#include? should work, it works for general objects, not only strings. Your problem in example code is this test:

unless @suggested_horses.exists?(horse.id)
  @suggested_horses<< horse
end

(even assuming using #include?). You try to search for specific object, not for id. So it should be like this:

unless @suggested_horses.include?(horse)
  @suggested_horses << horse
end

ActiveRecord has redefined comparision operator for objects to take a look only for its state (new/created) and id

How to get a Char from an ASCII Character Code in c#

You can simply write:

char c = (char) 2;

or

char c = Convert.ToChar(2);

or more complex option for ASCII encoding only

char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];

How to update and order by using ms sql

UPDATE messages SET 
 status=10 
WHERE ID in (SELECT TOP (10) Id FROM Table WHERE status=0 ORDER BY priority DESC);

MySQL Join Where Not Exists

I'd probably use a LEFT JOIN, which will return rows even if there's no match, and then you can select only the rows with no match by checking for NULLs.

So, something like:

SELECT V.*
FROM voter V LEFT JOIN elimination E ON V.id = E.voter_id
WHERE E.voter_id IS NULL

Whether that's more or less efficient than using a subquery depends on optimization, indexes, whether its possible to have more than one elimination per voter, etc.

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

You can write your query like this.

var query = from t1 in myTABLE1List // List<TABLE_1>
            join t2 in myTABLE1List
               on t1.ColumnA equals t2.ColumnA
               and t1.ColumnB equals t2.ColumnA

If you want to compare your column with multiple columns.

Pointers in Python?

>> id(1)
1923344848  # identity of the location in memory where 1 is stored
>> id(1)
1923344848  # always the same
>> a = 1
>> b = a  # or equivalently b = 1, because 1 is immutable
>> id(a)
1923344848
>> id(b)  # equal to id(a)
1923344848

As you can see a and b are just two different names that reference to the same immutable object (int) 1. If later you write a = 2, you reassign the name a to a different object (int) 2, but the b continues referencing to 1:

>> id(2)
1923344880
>> a = 2
>> id(a)
1923344880  # equal to id(2)
>> b
1           # b hasn't changed
>> id(b)
1923344848  # equal to id(1)

What would happen if you had a mutable object instead, such as a list [1]?

>> id([1])
328817608
>> id([1])
328664968  # different from the previous id, because each time a new list is created
>> a = [1]
>> id(a)
328817800
>> id(a)
328817800 # now same as before
>> b = a
>> id(b)
328817800  # same as id(a)

Again, we are referencing to the same object (list) [1] by two different names a and b. However now we can mutate this list while it remains the same object, and a, b will both continue referencing to it

>> a[0] = 2
>> a
[2]
>> b
[2]
>> id(a)
328817800  # same as before
>> id(b)
328817800  # same as before

Copy every nth line from one sheet to another

Add new column and fill it with ascending numbers. Then filter by ([column] mod 7 = 0) or something like that (don't have Excel in front of me to actually try this);

If you can't filter by formula, add one more column and use the formula =MOD([column; 7]) in it then filter zeros and you'll get all seventh rows.

Python 3: EOF when reading a line (Sublime Text 2 is angry)

I had the same problem. The problem with the Sublime Text's default console is that it does not support input.

To solve it, you have to install a package called SublimeREPL. SublimeREPL provides a Python interpreter which accepts input.

There is an article that explains the solution in detail.

GitHub page for SublimeREPL

How to compile .c file with OpenSSL includes?

You need to include the library path (-L/usr/local/lib/)

gcc -o Opentest Opentest.c -L/usr/local/lib/ -lssl -lcrypto

It works for me.

How to test that a registered variable is not empty?

- name: set pkg copy dir name
  set_fact:
    PKG_DIR: >-
      {% if ansible_os_family == "RedHat" %}centos/*.rpm
      {%- elif ansible_distribution == "Ubuntu" %}ubuntu/*.deb
      {%- elif ansible_distribution == "Kylin Linux Advanced Server" %}kylin/*.deb
      {%- else %}{%- endif %}

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

Maybe the current user is not root,try sudo mysql -uroot -p ,I successed just now.

Reading a text file and splitting it into single words in python

with open(filename) as file:
    words = file.read().split()

Its a List of all words in your file.

import re
with open(filename) as file:
    words = re.findall(r"([a-zA-Z\-]+)", file.read())

javascript: detect scroll end

This will actually be the correct answer:

function scrolled(event) {
   const container = event.target.body
   const {clientHeight, scrollHeight, scrollY: scrollTop} = container

   if (clientHeight + scrollY >= scrollHeight) {
    scrolledToBottom(event);
   }
}

The reason for using the event is up-to-date data, if you'll use a direct reference to the div you'll get outdated scrollY and will fail to detect the position correctly.

additional way is to wrap it in a setTimeout and wait till the data updates.

Set width of a "Position: fixed" div relative to parent div

You need to give the same style of the fixed element and its parent element. One of these examples is created with max widths and in the other example with paddings.

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box_x000D_
}_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
.container {_x000D_
  max-width: 500px;_x000D_
  height: 100px;_x000D_
  width: 100%;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
  background-color: lightgray;_x000D_
}_x000D_
.content {_x000D_
  max-width: 500px;_x000D_
  width: 100%;_x000D_
  position: fixed;_x000D_
}_x000D_
h2 {_x000D_
  border: 1px dotted black;_x000D_
  padding: 10px;_x000D_
}_x000D_
.container-2 {_x000D_
  height: 100px;_x000D_
  padding-left: 32px;_x000D_
  padding-right: 32px;_x000D_
  margin-top: 10px;_x000D_
  background-color: lightgray;_x000D_
}_x000D_
.content-2 {_x000D_
  width: 100%;_x000D_
  position: fixed;_x000D_
  left: 0;_x000D_
  padding-left: 32px;_x000D_
  padding-right: 32px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="content">_x000D_
    <h2>container with max widths</h2>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div class="container-2">_x000D_
  <div class="content-2">_x000D_
    <div>_x000D_
      <h2>container with paddings</h2>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Negative matching using grep (match lines that do not contain foo)

grep -v is your friend:

grep --help | grep invert  

-v, --invert-match select non-matching lines

Also check out the related -L (the complement of -l).

-L, --files-without-match only print FILE names containing no match

jQuery addClass onClick

Try to make your css more specific so that the new (green) style is more specific than the previous one, so that it worked for me!

For example, you might use in css:

button:active {/*your style here*/}

Instead of (probably not working):

.active {/*style*/} (.active is not a pseudo-class)

Hope it helps!

Axios handling errors

Actually, it's not possible with axios as of now. The status codes which falls in the range of 2xx only, can be caught in .then().

A conventional approach is to catch errors in the catch() block like below:

axios.get('/api/xyz/abcd')
  .catch(function (error) {
    if (error.response) {
      // Request made and server responded
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }

  });

Another approach can be intercepting requests or responses before they are handled by then or catch.

axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

Xcode "Device Locked" When iPhone is unlocked

there are two solution worked for me. 1) disconnect your device from the mac and reattach it. 2) disconnect your device from the mac and restart it and then connect it with mac it'll work

Retrieving parameters from a URL

There is a nice library w3lib.url

from w3lib.url import url_query_parameter
url = "/abc?def=ghi"
print url_query_parameter(url, 'def')
ghi

Read from database and fill DataTable

Private Function LoaderData(ByVal strSql As String) As DataTable
    Dim cnn As SqlConnection
    Dim dad As SqlDataAdapter

    Dim dtb As New DataTable
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        dad = New SqlDataAdapter(strSql, cnn)
        dad.Fill(dtb)
        cnn.Close()
        dad.Dispose()
    Catch ex As Exception
        cnn.Close()
        MsgBox(ex.Message)
    End Try
    Return dtb
End Function

How do I convert Int/Decimal to float in C#?

It is just:

float f = (float)6;

Remove multiple items from a Python list in just one statement

You can do it in one line by converting your lists to sets and using set.difference:

item_list = ['item', 5, 'foo', 3.14, True]
list_to_remove = ['item', 5, 'foo']

final_list = list(set(item_list) - set(list_to_remove))

Would give you the following output:

final_list = [3.14, True]

Note: this will remove duplicates in your input list and the elements in the output can be in any order (because sets don't preserve order). It also requires all elements in both of your lists to be hashable.

make: *** [ ] Error 1 error

Sometimes you will get lots of compiler outputs with many warnings and no line of output that says "error: you did something wrong here" but there was still an error. An example of this is a missing header file - the compiler says something like "no such file" but not "error: no such file", then it exits with non-zero exit code some time later (perhaps after many more warnings). Make will bomb out with an error message in these cases!

How to use basic authorization in PHP curl

Can you try this,

 $ch = curl_init($url);
 ...
 curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  
 ...

REF: http://php.net/manual/en/function.curl-setopt.php

Declare variable in SQLite and use it

SQLite doesn't support native variable syntax, but you can achieve virtually the same using an in-memory temp table.

I've used the below approach for large projects and works like a charm.

/* Create in-memory temp table for variables */
BEGIN;

PRAGMA temp_store = 2;
CREATE TEMP TABLE _Variables(Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT);

/* Declaring a variable */
INSERT INTO _Variables (Name) VALUES ('VariableName');

/* Assigning a variable (pick the right storage class) */
UPDATE _Variables SET IntegerValue = ... WHERE Name = 'VariableName';

/* Getting variable value (use within expression) */
... (SELECT coalesce(RealValue, IntegerValue, BlobValue, TextValue) FROM _Variables WHERE Name = 'VariableName' LIMIT 1) ...

DROP TABLE _Variables;
END;

How to use Console.WriteLine in ASP.NET (C#) during debug?

Trace.Write("Error Message") and Trace.Warn("Error Message") are the methods to use in web, need to decorate the page header trace=true and in config file to hide the error message text to go to end-user and so as to stay in iis itself for programmer debug.

How to verify if nginx is running or not?

You could use lsof to see what application is listening on port 80:

sudo lsof -i TCP:80

IndentationError: unindent does not match any outer indentation level

Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.

Try this:

import sys

def Factorial(n): # return factorial
    result = 1
    for i in range (1,n):
        result = result * i
    print "factorial is ",result
    return result

print Factorial(10)

How do I capture the output into a variable from an external process in PowerShell?

I tried the answers, but in my case I did not get the raw output. Instead it was converted to a PowerShell exception.

The raw result I got with:

$rawOutput = (cmd /c <command> 2`>`&1)

PHP - Session destroy after closing browser

There's one more "hack" by using HTTP Referer (we asume that browser window was closed current referer's domain name and curent page's domain name do not match):

session_start();
$_SESSION['somevariable'] = 'somevalue';

if(parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST) != $_SERVER["SERVER_NAME"]){
    session_destroy();
}

This also has some drawbacks, but it helped me few times.

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

A key issue here is that this loop iterates over the rows (1st dimension) of B:

In [258]: B
Out[258]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])
In [259]: for b in B:
     ...:     print(b,'=>',end='')
     ...:     b += 1
     ...:     print(b)
     ...:     
[0 1 2] =>[1 2 3]
[3 4 5] =>[4 5 6]
[6 7 8] =>[7 8 9]
[ 9 10 11] =>[10 11 12]

Thus the += is acting on a mutable object, an array.

This is implied in the other answers, but easily missed if your focus is on the a = a+1 reassignment.

I could also make an in-place change to b with [:] indexing, or even something fancier, b[1:]=0:

In [260]: for b in B:
     ...:     print(b,'=>',end='')
     ...:     b[:] = b * 2

[1 2 3] =>[2 4 6]
[4 5 6] =>[ 8 10 12]
[7 8 9] =>[14 16 18]
[10 11 12] =>[20 22 24]

Of course with a 2d array like B we usually don't need to iterate on the rows. Many operations that work on a single of B also work on the whole thing. B += 1, B[1:] = 0, etc.

Python - Using regex to find multiple matches and print them out

Do not use regular expressions to parse HTML.

But if you ever need to find all regexp matches in a string, use the findall function.

import re
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
matches = re.findall('<form>(.*?)</form>', line, re.DOTALL)
print(matches)

# Output: ['Form 1', 'Form 2']

How to combine GROUP BY and ROW_NUMBER?

;with C as
(
  select Rel.t2ID,
         Rel.t1ID,
         t1.Price,
         row_number() over(partition by Rel.t2ID order by t1.Price desc) as rn
  from @t1 as T1
    inner join @relation as Rel
      on T1.ID = Rel.t1ID
)
select T2.ID as T2ID,
       T2.Name as T2Name,
       T2.Orders,
       T1.ID as T1ID,
       T1.Name as T1Name,
       T1Sum.Price
from @t2 as T2
  inner join (
              select C1.t2ID,
                     sum(C1.Price) as Price,
                     C2.t1ID
              from C as C1
                inner join C as C2 
                  on C1.t2ID = C2.t2ID and
                     C2.rn = 1
              group by C1.t2ID, C2.t1ID
             ) as T1Sum
    on T2.ID = T1Sum.t2ID
  inner join @t1 as T1
    on T1.ID = T1Sum.t1ID

How can I check a C# variable is an empty string "" or null?

Cheap trick:

Convert.ToString((object)stringVar) == “”

This works because Convert.ToString(object) returns an empty string if object is null. Convert.ToString(string) returns null if string is null.

(Or, if you're using .NET 2.0 you could always using String.IsNullOrEmpty.)

How to get query params from url in Angular 2?

You can get the query parameters when passed in URL using ActivatedRoute as stated below:-

url:- http:/domain.com?test=abc

import { Component } from '@angular/core';
import { ActivatedRoute }     from '@angular/router';

@Component({
  selector: 'my-home'
})
export class HomeComponent {

  constructor(private sharedServices : SharedService,private route: ActivatedRoute) { 
    route.queryParams.subscribe(
      data => console.log('queryParams', data['test']));
  }

}

How do you change the document font in LaTeX?

As second says, most of the "design" decisions made for TeX documents are backed up by well researched usability studies, so changing them should be undertaken with care. It is, however, relatively common to replace Computer Modern with Times (also a serif face).

Try \usepackage{times}.

Can I get "&&" or "-and" to work in PowerShell?

In CMD, '&&' means "execute command 1, and if it succeeds, execute command 2". I have used it for things like:

build && run_tests

In PowerShell, the closest thing you can do is:

(build) -and (run_tests)

It has the same logic, but the output text from the commands is lost. Maybe it is good enough for you, though.

If you're doing this in a script, you will probably be better off separating the statements, like this:

build
if ($?) {
    run_tests
}

2019/11/27: The &&operator is now available for PowerShell 7 Preview 5+:

PS > echo "Hello!" && echo "World!"
Hello!
World!

CSS grid wrapping

Here's my attempt. Excuse the fluff, I was feeling extra creative.

My method is a parent div with fixed dimensions. The rest is just fitting the content inside that div accordingly.

This will rescale the images regardless of the aspect ratio. There will be no hard cropping either.

_x000D_
_x000D_
body {_x000D_
    background: #131418;_x000D_
    text-align: center;_x000D_
    margin: 0 auto;_x000D_
}_x000D_
_x000D_
.my-image-parent {_x000D_
    display: inline-block;_x000D_
    width: 300px;_x000D_
    height: 300px;_x000D_
    line-height: 300px; /* Should match your div height */_x000D_
    text-align: center;_x000D_
    font-size: 0;_x000D_
}_x000D_
_x000D_
/* Start demonstration background fluff */_x000D_
    .bg1 {background: url(https://unsplash.it/801/799);}_x000D_
    .bg2 {background: url(https://unsplash.it/799/800);}_x000D_
    .bg3 {background: url(https://unsplash.it/800/799);}_x000D_
    .bg4 {background: url(https://unsplash.it/801/801);}_x000D_
    .bg5 {background: url(https://unsplash.it/802/800);}_x000D_
    .bg6 {background: url(https://unsplash.it/800/802);}_x000D_
    .bg7 {background: url(https://unsplash.it/802/802);}_x000D_
    .bg8 {background: url(https://unsplash.it/803/800);}_x000D_
    .bg9 {background: url(https://unsplash.it/800/803);}_x000D_
    .bg10 {background: url(https://unsplash.it/803/803);}_x000D_
    .bg11 {background: url(https://unsplash.it/803/799);}_x000D_
    .bg12 {background: url(https://unsplash.it/799/803);}_x000D_
    .bg13 {background: url(https://unsplash.it/806/799);}_x000D_
    .bg14 {background: url(https://unsplash.it/805/799);}_x000D_
    .bg15 {background: url(https://unsplash.it/798/804);}_x000D_
    .bg16 {background: url(https://unsplash.it/804/799);}_x000D_
    .bg17 {background: url(https://unsplash.it/804/804);}_x000D_
    .bg18 {background: url(https://unsplash.it/799/804);}_x000D_
    .bg19 {background: url(https://unsplash.it/798/803);}_x000D_
    .bg20 {background: url(https://unsplash.it/803/797);}_x000D_
/* end demonstration background fluff */_x000D_
_x000D_
.my-image {_x000D_
    width: auto;_x000D_
    height: 100%;_x000D_
    vertical-align: middle;_x000D_
    background-size: contain;_x000D_
    background-position: center;_x000D_
    background-repeat: no-repeat;_x000D_
}
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg1"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg2"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg3"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg4"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg5"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg6"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg7"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg8"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg9"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg10"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg11"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg12"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg13"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg14"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg15"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg16"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg17"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg18"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg19"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg20"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Remove trailing comma from comma-separated string

For more than one commas

            String names = "Hello,World,,,";
    System.out.println(names.replaceAll("(,)*$", ""));

Output: Hello,World

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

http://msdn.microsoft.com/en-us/library/ms157328.aspx

Get a DataTable Columns DataType

You can get column type of DataTable with DataType attribute of datatable column like below:

var type = dt.Columns[0].DataType

dt : DataTable object.

0 : DataTable column index.

Hope It Helps

Ty :)

jQuery UI Sortable Position

As per the official documentation of the jquery sortable UI: http://api.jqueryui.com/sortable/#method-toArray

In update event. use:

var sortedIDs = $( ".selector" ).sortable( "toArray" );

and if you alert or console this var (sortedIDs). You'll get your sequence. Please choose as the "Right Answer" if it is a right one.

How to use double or single brackets, parentheses, curly braces

Parentheses in function definition

Parentheses () are being used in function definition:

function_name () { command1 ; command2 ; }

That is the reason you have to escape parentheses even in command parameters:

$ echo (
bash: syntax error near unexpected token `newline'

$ echo \(
(

$ echo () { command echo The command echo was redefined. ; }
$ echo anything
The command echo was redefined.

How to set variable from a SQL query?

To ASSIGN variables using a SQL select the best practice is as shown below

->DECLARE co_id INT ;
->DECLARE sname VARCHAR(10) ;

->SELECT course_id INTO co_id FROM course_details ;
->SELECT student_name INTO sname FROM course_details;

IF you have to assign more than one variable in a single line you can use this same SELECT INTO

->DECLARE val1 int;
->DECLARE val2 int;

->SELECT student__id,student_name INTO val1,val2 FROM student_details;

--HAPPY CODING-- 

Create list of single item repeated N times

You can also write:

[e] * n

You should note that if e is for example an empty list you get a list with n references to the same list, not n independent empty lists.

Performance testing

At first glance it seems that repeat is the fastest way to create a list with n identical elements:

>>> timeit.timeit('itertools.repeat(0, 10)', 'import itertools', number = 1000000)
0.37095273281943264
>>> timeit.timeit('[0] * 10', 'import itertools', number = 1000000)
0.5577236771712819

But wait - it's not a fair test...

>>> itertools.repeat(0, 10)
repeat(0, 10)  # Not a list!!!

The function itertools.repeat doesn't actually create the list, it just creates an object that can be used to create a list if you wish! Let's try that again, but converting to a list:

>>> timeit.timeit('list(itertools.repeat(0, 10))', 'import itertools', number = 1000000)
1.7508119747063233

So if you want a list, use [e] * n. If you want to generate the elements lazily, use repeat.

How can I retrieve the remote git address of a repo?

If you have the name of the remote, you will be able with git 2.7 (Q4 2015), to use the new git remote get-url command:

git remote get-url origin

(nice pendant of git remote set-url origin <newurl>)

See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf).
(Merged by Junio C Hamano -- gitster -- in commit e437cbd, 05 Oct 2015)

remote: add get-url subcommand

Expanding insteadOf is a part of ls-remote --url and there is no way to expand pushInsteadOf as well.
Add a get-url subcommand to be able to query both as well as a way to get all configured urls.

How to set connection timeout with OkHttp

For Retrofit 2.0.0-beta1 or beta2, the code goes as follows:

OkHttpClient client = new OkHttpClient();

client.setConnectTimeout(30, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
client.setWriteTimeout(30, TimeUnit.SECONDS);

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://api.yourapp.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();

Rolling back bad changes with svn in Eclipse

I have written a couple of blog posts on this subject. One that is Subclipse centric: http://markphip.blogspot.com/2007/01/how-to-undo-commit-in-subversion.html and one that is command-line centric: http://blogs.collab.net/subversion/2007/07/second-chances/

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

Using .text() to retrieve only text not nested in child tags

Try this:

$('#listItem').not($('#listItem').children()).text()

Not unique table/alias

 select persons.personsid,name,info.id,address
    -> from persons
    -> inner join persons on info.infoid = info.info.id;

Concatenating two one-dimensional NumPy arrays

There are several possibilities for concatenating 1D arrays, e.g.,

numpy.r_[a, a],
numpy.stack([a, a]).reshape(-1),
numpy.hstack([a, a]),
numpy.concatenate([a, a])

All those options are equally fast for large arrays; for small ones, concatenate has a slight edge:

enter image description here

The plot was created with perfplot:

import numpy
import perfplot

perfplot.show(
    setup=lambda n: numpy.random.rand(n),
    kernels=[
        lambda a: numpy.r_[a, a],
        lambda a: numpy.stack([a, a]).reshape(-1),
        lambda a: numpy.hstack([a, a]),
        lambda a: numpy.concatenate([a, a]),
    ],
    labels=["r_", "stack+reshape", "hstack", "concatenate"],
    n_range=[2 ** k for k in range(19)],
    xlabel="len(a)",
)

Is there a vr (vertical rule) in html?

An <hr> inside a display:flex will make it display vertically.

JSFiddle: https://jsfiddle.net/w6y5t1kL/

Example:

<div style="display:flex;">
  <div>
    Content
    <ul>
      <li>Continued content...</li>
    </ul>
  </div>
  <hr>
  <div>
    Content
    <ul>
      <li>Continued content...</li>
    </ul>
  </div>
</div>

VS 2017 Metadata file '.dll could not be found

In my case I run the tests and got error CS0006. It turned out that I run tests in Release mode. Switch to Debug mode fixed this error.

HTML5 validation when the input type is not "submit"

I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):

<input type="text" id="example" name="example" value="" required>
<button type="button"  onclick="submitform()" id="save">Save</button>
<input id="submit_handle" type="submit" style="display: none">

<script>
function submitform() {
    $('#submit_handle').click();
}
</script>

How set maximum date in datepicker dialog in android?

private void selectDOB() {

    final Calendar calendar = Calendar.getInstance();
    mYear = calendar.get(Calendar.YEAR);
    mDay = calendar.get(Calendar.DATE);
    mMonth = calendar.get(Calendar.MONTH);

    DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
        @SuppressLint("LongLogTag")
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            strDateOfBirth = (month + 1) + "-" + dayOfMonth + "-" + year;

            //********************** check and set date with append 0 at starting***************************
            if (dayOfMonth < 10) {
                strNewDay = "0" + dayOfMonth;
            } else {
                strNewDay = dayOfMonth + "";
            }
            if (month + 1 < 10) {
                strNewMonth = "0" + (month + 1);
            } else {
                strNewMonth = (month + 1) + "";
            }

            Log.e("strnewDay *****************", strNewDay + "");
            Log.e("strNewMonth *****************", strNewMonth + "");

            //    etDateOfBirth.setText(dayOfMonth + " / " + (month + 1) + " / " + year);
            etDateOfBirth.setText(strNewDay + " / " + strNewMonth + " / " + year);

            Log.e("strDateOfBirth *******************", strDateOfBirth + "");

        }
    }, mYear, mMonth, mDay);

    datePickerDialog.show();

    //*************** input date of birth must be greater than or equal to 18 ************************************

    Calendar maxDate = Calendar.getInstance();
    maxDate.set(Calendar.DAY_OF_MONTH, mDay);
    maxDate.set(Calendar.MONTH, mMonth);
    maxDate.set(Calendar.YEAR, mYear - 18);
    datePickerDialog.getDatePicker().setMaxDate(maxDate.getTimeInMillis());

    //*************** input date of birth must be less than today date ************************************
    //   datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());

}

How to name variables on the fly?

And this option?

list_name<-list()
for(i in 1:100){
    paste("orca",i,sep="")->list_name[[i]]
}

It works perfectly. In the example you put, first line is missing, and then gives you the error message.

How do I check if an HTML element is empty using jQuery?

If by "empty", you mean with no HTML content,

if($('#element').html() == "") {
  //call function
}

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

Subtle, but this error got me because I forgot to declare a smallint column as unsigned to match the referenced, existing table which was "smallint unsigned." Having one unsigned and one not unsigned caused MySQL to prevent the foreign key from being created on the new table.

id smallint(3) not null

does not match, for the sake of foreign keys,

id smallint(3) unsigned not null

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INT representation:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

How can I decrypt a password hash in PHP?

it seems someone finally has created a script to decrypt password_hash. checkout this one: https://pastebin.com/Sn19ShVX

<?php
error_reporting(0);

# Coded by L0c4lh34rtz - IndoXploit

# \n -> linux
# \r\n -> windows
$list = explode("\n", file_get_contents($argv[1])); # change \n to \r\n if you're using windows
# ------------------- #

$hash = '$2y$10$BxO1iVD3HYjVO83NJ58VgeM4wNc7gd3gpggEV8OoHzB1dOCThBpb6'; # hash here, NB: use single quote (') , don't use double quote (")

if(isset($argv[1])) {
    foreach($list as $wordlist) {
        print " [+]"; print (password_verify($wordlist, $hash)) ? "$hash -> $wordlist (OK)\n" : "$hash -> $wordlist (SALAH)\n";
    }
} else {
    print "usage: php ".$argv[0]." wordlist.txt\n";
}
?>

How to get the groups of a user in Active Directory? (c#, asp.net)

This works for me

public string[] GetGroupNames(string domainName, string userName)
    {
        List<string> result = new List<string>();

        using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domainName))
        {
            using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(principalContext, userName).GetGroups())
            {
                src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
            }
        }

        return result.ToArray();
    }

React Native absolute positioning horizontal centre

<View style={{...StyleSheet.absoluteFillObject, justifyContent: 'center', alignItems: 'center'}}>
  <Text>CENTERD TEXT</Text>
</View>

And add this

import {StyleSheet} from 'react-native';

jQuery select change show/hide div event

change your jquery method to

$(function () { /* DOM ready */
    $("#type").change(function () {
        alert('The option with value ' + $(this).val());
        //hide the element you want to hide here with
        //("id").attr("display","block"); // to show
        //("id").attr("display","none"); // to hide
    });
});

parse html string with jquery

I'm not a 100% sure, but won't

$(data)

produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.

EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)

$("img", data).attr ("src")

if you want to access the src-attribute. If your data is just text, it would probably work to do

$("img", $(data)).attr ("src")

How to set Java environment path in Ubuntu

  1. Update bashrc file to add JAVA_HOME

    sudo nano ~/.bashrc

  2. Add JAVA_HOME to bashrc file.

    export JAVA_HOME=/usr/java/<your version of java>
    export PATH=${PATH}:${JAVA_HOME}/bin

  3. Ensure Java is accessible

    java -version

  4. In Case of Manual installation of JDK, If you got an error as shown below

    Error occurred during initialization of VM
    java/lang/NoClassDefFoundError: java/lang/Object
    
  5. Execute the following command in your JAVA_HOME/lib directory:

    unpack200 -r -v -l "" tools.pack tools.jar

  6. Execute the following commands in your JAVA_HOME/jre/lib

    ../../bin/unpack200 rt.pack rt.jar ../../bin/unpack200 jsse.pack jsse.rar ../../bin/unpack200 charsets.pack charsets.jar

  7. Ensure Java is accessible

    java -version

How to run function in AngularJS controller on document ready?

The answer

$scope.$watch('$viewContentLoaded', 
    function() { 
        $timeout(function() {
            //do something
        },0);    
});

is the only one that works in most scenarios I tested. In a sample page with 4 components all of which build HTML from a template, the order of events was

$document ready
$onInit
$postLink
(and these 3 were repeated 3 more times in the same order for the other 3 components)
$viewContentLoaded (repeated 3 more times)
$timeout execution (repeated 3 more times)

So a $document.ready() is useless in most cases since the DOM being constructed in angular may be nowhere near ready.

But more interesting, even after $viewContentLoaded fired, the element of interest still could not be found.

Only after the $timeout executed was it found. Note that even though the $timeout was a value of 0, nearly 200 milliseconds elapsed before it executed, indicating that this thread was held off for quite a while, presumably while the DOM had angular templates added on a main thread. The total time from the first $document.ready() to the last $timeout execution was nearly 500 milliseconds.

In one extraordinary case where the value of a component was set and then the text() value was changed later in the $timeout, the $timeout value had to be increased until it worked (even though the element could be found during the $timeout). Something async within the 3rd party component caused a value to take precedence over the text until sufficient time passed. Another possibility is $scope.$evalAsync, but was not tried.

I am still looking for that one event that tells me the DOM has completely settled down and can be manipulated so that all cases work. So far an arbitrary timeout value is necessary, meaning at best this is a kludge that may not work on a slow browser. I have not tried JQuery options like liveQuery and publish/subscribe which may work, but certainly aren't pure angular.

Pass a string parameter in an onclick function

Here is a jQuery solution that I'm using.

jQuery

$("#slideshow button").click(function(){
    var val = $(this).val();
    console.log(val);
});

HTML

<div id="slideshow">
    <img src="image1.jpg">
    <button class="left" value="back">&#10094;</button>
    <button class="right" value="next">&#10095;</button>
</div>

JSON Invalid UTF-8 middle byte

On the off chance it may help others I'll share a related anecdote.

I encountered this exact error (Invalid UTF-8 middle byte 0x3f) running a PowerShell script via the PowerShell Integrated Script Environment (ISE). The identical script, executed outside the ISE, works fine. The code uses the Confluence v3 and v5.x REST APIs and this error is logged on the Confluence v5.x server - presumably because the ISE somehow mucks with the request.

How do I return JSON without using a template in Django?

from django.utils import simplejson 
from django.core import serializers 

def pagina_json(request): 
   misdatos = misdatos.objects.all()
   data = serializers.serialize('json', misdatos) 
   return HttpResponse(data, mimetype='application/json')

Can Mysql Split a column?

You may get what you want by using the MySQL REGEXP or LIKE.

See the MySQL Docs on Pattern Matching

change directory in batch file using variable

simple way to do this... here are the example

cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause

this will mount the ISO image to the specific drive...use

AngularJs: Reload page

I would suggest to refer the page. Official suggestion

https://docs.angularjs.org/guide/$location

enter image description here

How to add a border just on the top side of a UIView

//MARK:- Add LeftBorder For View

(void)prefix_addLeftBorder:(UIView *) viewName
{
    CALayer *leftBorder = [CALayer layer];
    leftBorder.backgroundColor = [UIColor colorWithRed:221/255.0f green:221/255.0f blue:221/255.0f alpha:1.0f].CGColor;
    leftBorder.frame = CGRectMake(0,0,1.0,viewName.frame.size.height);
    [viewName.layer addSublayer:leftBorder];
}

//MARK:- Add RightBorder For View

(void)prefix_addRightBorder:(UIView *) viewName
{
    CALayer *rightBorder = [CALayer layer];
    rightBorder.backgroundColor = [UIColor colorWithRed:221/255.0f green:221/255.0f blue:221/255.0f alpha:1.0f].CGColor;
    rightBorder.frame = CGRectMake(viewName.frame.size.width - 1.0,0,1.0,viewName.frame.size.height);
    [viewName.layer addSublayer:rightBorder];
}

//MARK:- Add Bottom Border For View

(void)prefix_addbottomBorder:(UIView *) viewName
{
    CALayer *bottomBorder = [CALayer layer];
    bottomBorder.backgroundColor = [UIColor colorWithRed:221/255.0f green:221/255.0f blue:221/255.0f alpha:1.0f].CGColor;
    bottomBorder.frame = CGRectMake(0,viewName.frame.size.height - 1.0,viewName.frame.size.width,1.0);
    [viewName.layer addSublayer:bottomBorder];
}

How can I plot separate Pandas DataFrames as subplots?

You can plot multiple subplots of multiple pandas data frames using matplotlib with a simple trick of making a list of all data frame. Then using the for loop for plotting subplots.

Working code:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# dataframe sample data
df1 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df2 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df3 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df4 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df5 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
df6 = pd.DataFrame(np.random.rand(10,2)*100, columns=['A', 'B'])
#define number of rows and columns for subplots
nrow=3
ncol=2
# make a list of all dataframes 
df_list = [df1 ,df2, df3, df4, df5, df6]
fig, axes = plt.subplots(nrow, ncol)
# plot counter
count=0
for r in range(nrow):
    for c in range(ncol):
        df_list[count].plot(ax=axes[r,c])
        count=+1

enter image description here

Using this code you can plot subplots in any configuration. You need to just define number of rows nrow and number of columns ncol. Also, you need to make list of data frames df_list which you wanted to plot.

View contents of database file in Android Studio

Finally, i found a simplest solution which do not need to open the DDMS.

Actually, the solution is based on what @Distwo mentioned, but it don't have to be that complicated.

First, remember the path of your database file in the device, it should aways the same. For example mine is:/data/data/com.XXX.module/databases/com.XXX.module.database

Second, execute this command which pulls your database file onto you PC

 adb pull /data/data/com.XXX.module/databases/com.XXX.module.database /Users/somePathOnYourPC/

What you need to do is just copy and store this command, then you can use it again and again.

Third, if you got Permission Denied or something like that, just run adb root before the previous command.

How to blur background images in Android

You can have a view with Background color as black and set alpha for the view as 0.7 or whatever as per your requirement.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/onboardingimg1">
    <View
        android:id="@+id/opacityFilter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/black"
        android:layout_alignParentBottom="true"
        android:alpha="0.7">
    </View>


</RelativeLayout>

How to shift a column in Pandas DataFrame

You need to use df.shift here.
df.shift(i) shifts the entire dataframe by i units down.

So, for i = 1:

Input:

    x1   x2  
0  206  214  
1  226  234  
2  245  253  
3  265  272    
4  283  291

Output:

    x1   x2
0  Nan  Nan   
1  206  214  
2  226  234  
3  245  253  
4  265  272 

So, run this script to get the expected output:

import pandas as pd

df = pd.DataFrame({'x1': ['206', '226', '245',' 265', '283'],
                   'x2': ['214', '234', '253', '272', '291']})

print(df)
df['x2'] = df['x2'].shift(1)
print(df)

.htaccess mod_rewrite - how to exclude directory from rewrite rule

What you could also do is put a .htaccess file containing

RewriteEngine Off

In the folders you want to exclude from being rewritten (by the rules in a .htaccess file that's higher up in the tree). Simple but effective.

Disable beep of Linux Bash on Windows 10

In addition to what jgr208 said, you may have a ~/.profile file already and ~/.bash_profile may not be present, as was the case with me.

In this case, add setterm -blength 0 to the .profile.

If you create a .bash_profile, your .profile will be ignored and anything Windows wrote there will not work.

UEFA/FIFA scores API

http://api.football-data.org/index is free and useful. The API is in active development, stable and recently the first versioned release called alpha was put online. Check the blog section to follow updates and changes.

Javascript string replace with regex to strip off illegal characters

You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");

How to convert BigInteger to String in java

Why don't you use the BigInteger(String) constructor ? That way, round-tripping via toString() should work fine.

(note also that your conversion to bytes doesn't explicitly specify a character-encoding and is platform-dependent - that could be source of grief further down the line)

How to find tag with particular text with Beautiful Soup?

With bs4 4.7.1+ you can use :contains pseudo class to specify the td containing your search string

from bs4 import BeautifulSoup
html = '''
<tr>
  <td class="pos">\n
      "Some text:"\n
      <br>\n
      <strong>some value</strong>\n
  </td>
</tr>
<tr>
  <td class="pos">\n
      "Fixed text:"\n
      <br>\n
      <strong>text I am looking for</strong>\n
  </td>
</tr>
<tr>
  <td class="pos">\n
      "Some other text:"\n
      <br>\n
      <strong>some other value</strong>\n
  </td>
</tr>'''
soup = bs(html, 'lxml')
print(soup.select_one('td:contains("Fixed text:")'))

Is there a way to automatically build the package.json file for Node.js projects

use command npm init -f to generate package.json file and after that use --save after each command so that each module will automatically get updated inside your package.json for ex: npm install express --save

Remove quotes from a character vector in R

I think I was trying something very similar to the original poster. the get() worked for me, although the name inside the chart was not inherited. Here is the code that worked for me.

#install it if you dont have it
library(quantmod)

# a list of stock tickers
myStocks <- c("INTC", "AAPL", "GOOG", "LTD")

# get some stock prices from default service
getSymbols(myStocks)

# to pause in between plots
par(ask=TRUE)

# plot all symbols
for (i in 1:length(myStocks)) {
    chartSeries(get(myStocks[i]), subset="last 26 weeks")
}

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How do I generate random number for each row in a TSQL Select?

When called multiple times in a single batch, rand() returns the same number.

I'd suggest using convert(varbinary,newid()) as the seed argument:

SELECT table_name, 1.0 + floor(14 * RAND(convert(varbinary, newid()))) magic_number 
FROM information_schema.tables

newid() is guaranteed to return a different value each time it's called, even within the same batch, so using it as a seed will prompt rand() to give a different value each time.

Edited to get a random whole number from 1 to 14.

How to iterate over array of objects in Handlebars?

I had a similar issue I was getting the entire object in this but the value was displaying while doing #each.

Solution: I re-structure my array of object like this:

let list = results.map((item)=>{
    return { name:item.name, author:item.author }
});

and then in template file:

{{#each list}}
    <tr>
        <td>{{name }}</td>
        <td>{{author}}</td>      
    </tr>
{{/each}} 

minimize app to system tray

At the click on the image in System tray, you can verify if the frame is visible and then you have to set Visible = true or false

*ngIf else if in template

You can also use this old trick for converting complex if/then/else blocks into a slightly cleaner switch statement:

<div [ngSwitch]="true">
    <button (click)="foo=(++foo%3)+1">Switch!</button>

    <div *ngSwitchCase="foo === 1">one</div>
    <div *ngSwitchCase="foo === 2">two</div>
    <div *ngSwitchCase="foo === 3">three</div>
</div>

Eclipse gives “Java was started but returned exit code 13”

In your eclipse.ini file simply put

–vm
/home/aniket/jdk1.7.0_11/bin(Your path to JDK 7)

before -vmargs line.

How can I set a custom date time format in Oracle SQL Developer?

You can change this in preferences:

  1. From Oracle SQL Developer's menu go to: Tools > Preferences.
  2. From the Preferences dialog, select Database > NLS from the left panel.
  3. From the list of NLS parameters, enter DD-MON-RR HH24:MI:SS into the Date Format field.
  4. Save and close the dialog, done!

Here is a screenshot:

Changing Date Format preferences in Oracle SQL Developer

How to use \n new line in VB msgbox() ...?

Add a vbNewLine as:

"text1" & vbNewLine & "text2"

How to retrieve an element from a set without removing it?

Seemingly the most compact (6 symbols) though very slow way to get a set element (made possible by PEP 3132):

e,*_=s

With Python 3.5+ you can also use this 7-symbol expression (thanks to PEP 448):

[*s][0]

Both options are roughly 1000 times slower on my machine than the for-loop method.

Default visibility for C# classes and members (fields, methods, etc.)?

By default, the access modifier for a class is internal. That means to say, a class is accessible within the same assembly. But if we want the class to be accessed from other assemblies then it has to be made public.

How to tell when UITableView has completed ReloadData?

It appears folks are still reading this question and the answers. B/c of that, I'm editing my answer to remove the word Synchronous which is really irrelevant to this.

When [tableView reloadData] returns, the internal data structures behind the tableView have been updated. Therefore, when the method completes you can safely scroll to the bottom. I verified this in my own app. The widely accepted answer by @rob-mayoff, while also confusing in terminology, acknowledges the same in his last update.

If your tableView isn't scrolling to the bottom you may have an issue in other code you haven't posted. Perhaps you are changing data after scrolling is complete and you're not reloading and/or scrolling to the bottom then?

Add some logging as follows to verify that the table data is correct after reloadData. I have the following code in a sample app and it works perfectly.

// change the data source

NSLog(@"Before reload / sections = %d, last row = %d",
      [self.tableView numberOfSections],
      [self.tableView numberOfRowsInSection:[self.tableView numberOfSections]-1]);

[self.tableView reloadData];

NSLog(@"After reload / sections = %d, last row = %d",
      [self.tableView numberOfSections],
      [self.tableView numberOfRowsInSection:[self.tableView numberOfSections]-1]);

[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.tableView numberOfRowsInSection:[self.tableView numberOfSections]-1]-1
                                                          inSection:[self.tableView numberOfSections] - 1]
                      atScrollPosition:UITableViewScrollPositionBottom
                              animated:YES];

What does the Java assert keyword do, and when should it be used?

Assertions are checks which may get switched off. They're rarely used. Why?

  • They must not be used for checking public method arguments as you have no control over them.
  • They should not be used for simple checks like result != null as such checks are very fast and there's hardly anything to save.

So, what's left? Expensive checks for conditions really expected to be true. A good example would be the invariants of a data structure like RB-tree. Actually, in ConcurrentHashMap of JDK8, there are a few such meaningful asserts for the TreeNodes.

  • You really don't want to switch them on in production as they could easily dominate the run time.
  • You may want to switch them on or off during tests.
  • You definitely want to switch them on when working on the code.

Sometimes, the check is not really expensive, but at the same time, you're pretty sure, it'll pass. In my code, there's e.g.,

assert Sets.newHashSet(userIds).size() == userIds.size();

where I'm pretty sure that the list I just created has unique elements, but I wanted to document and double check it.

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

display Java.util.Date in a specific format

This will help you. DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); print (df.format(new Date());

How to make a div with a circular shape?

You can do following

FIDDLE

<div id="circle"></div>

CSS

#circle {
    width: 100px;
    height: 100px;
    background: red;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px;
}

Other shape SOURCE

Simple example of threading in C++

When searching for an example of a C++ class that calls one of its own instance methods in a new thread, this question comes up, but we were not able to use any of these answers that way. Here's an example that does that:

Class.h

class DataManager
{
public:
    bool hasData;
    void getData();
    bool dataAvailable();
};

Class.cpp

#include "DataManager.h"

void DataManager::getData()
{
    // perform background data munging
    hasData = true;
    // be sure to notify on the main thread
}

bool DataManager::dataAvailable()
{
    if (hasData)
    {
        return true;
    }
    else
    {
        std::thread t(&DataManager::getData, this);
        t.detach(); // as opposed to .join, which runs on the current thread
    }
}

Note that this example doesn't get into mutex or locking.

Finishing current activity from a fragment

You should use getActivity() method in order to finish the activity from the fragment.

getActivity().finish();

How to make custom error pages work in ASP.NET MVC 4

My current setup (on MVC3, but I think it still applies) relies on having an ErrorController, so I use:

<system.web>
    <customErrors mode="On" defaultRedirect="~/Error">
      <error redirect="~/Error/NotFound" statusCode="404" />
    </customErrors>
</system.web>

And the controller contains the following:

public class ErrorController : Controller
{
    public ViewResult Index()
    {
        return View("Error");
    }
    public ViewResult NotFound()
    {
        Response.StatusCode = 404;  //you may want to set this to 200
        return View("NotFound");
    }
}

And the views just the way you implement them. I tend to add a bit of logic though, to show the stack trace and error information if the application is in debug mode. So Error.cshtml looks something like this:

@model System.Web.Mvc.HandleErrorInfo
@{
    Layout = "_Layout.cshtml";
    ViewBag.Title = "Error";
}
<div class="list-header clearfix">
    <span>Error</span>
</div>
<div class="list-sfs-holder">
    <div class="alert alert-error">
        An unexpected error has occurred. Please contact the system administrator.
    </div>
    @if (Model != null && HttpContext.Current.IsDebuggingEnabled)
    {
        <div>
            <p>
                <b>Exception:</b> @Model.Exception.Message<br />
                <b>Controller:</b> @Model.ControllerName<br />
                <b>Action:</b> @Model.ActionName
            </p>
            <div style="overflow:scroll">
                <pre>
                    @Model.Exception.StackTrace
                </pre>
            </div>
        </div>
    }
</div>

How to Create simple drag and Drop in angularjs

Using HTML 5 Drag and Drop
You can easily archive this using HTML 5 drag and drop feature along with angular directives.

  1. Enable drag by setting draggable = true.
  2. Add directives for parent container and child items.
  3. Override drag and drop functions - 'ondragstart' for parent and 'ondrop' for child.

Find the example below in which list is array of items.
HTML code:

    <div class="item_content" ng-repeat="item in list" draggrble-container>
        <div class="item" draggable-item draggable="true">{{item}}</div>
    </div>

Javascript:

    module.directive("draggableItem",function(){
     return {
      link:function(scope,elem,attr){
        elem[0].ondragstart = function(event){
            scope.$parent.selectedItem = scope.item;
        };
      }
     };
    });


    module.directive("draggrbleContainer",function(){
     return {
        link:function(scope,elem,attr){
            elem[0].ondrop = function(event){
                event.preventDefault();
                let selectedIndex = scope.list.indexOf(scope.$parent.selectedItem);
                let newPosition = scope.list.indexOf(scope.item);
                scope.$parent.list.splice(selectedIndex,1);
                scope.$parent.list.splice(newPosition,0,scope.$parent.selectedItem);
                scope.$apply();
            };
            elem[0].ondragover = function(event){
                event.preventDefault();

            };
        }
     };
    });

Find the complete code here https://github.com/raghavendrarai/SimpleDragAndDrop

How to convert a table to a data frame

If you are using the tidyverse, you can use

as_data_frame(table(myvector))

to get a tibble (i.e. a data frame with some minor variations from the base class)