Programs & Examples On #Visualworks

VisualWorks is a cross-platform implementation of the Smalltalk language.

How can I save application settings in a Windows Forms application?

The registry/configurationSettings/XML argument still seems very active. I've used them all, as the technology has progressed, but my favourite is based on Threed's system combined with Isolated Storage.

The following sample allows storage of an objects named properties to a file in isolated storage. Such as:

AppSettings.Save(myobject, "Prop1,Prop2", "myFile.jsn");

Properties may be recovered using:

AppSettings.Load(myobject, "myFile.jsn");

It is just a sample, not suggestive of best practices.

internal static class AppSettings
{
    internal static void Save(object src, string targ, string fileName)
    {
        Dictionary<string, object> items = new Dictionary<string, object>();
        Type type = src.GetType();

        string[] paramList = targ.Split(new char[] { ',' });
        foreach (string paramName in paramList)
            items.Add(paramName, type.GetProperty(paramName.Trim()).GetValue(src, null));

        try
        {
            // GetUserStoreForApplication doesn't work - can't identify.
            // application unless published by ClickOnce or Silverlight
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly();
            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.Write((new JavaScriptSerializer()).Serialize(items));
            }

        }
        catch (Exception) { }   // If fails - just don't use preferences
    }

    internal static void Load(object tar, string fileName)
    {
        Dictionary<string, object> items = new Dictionary<string, object>();
        Type type = tar.GetType();

        try
        {
            // GetUserStoreForApplication doesn't work - can't identify
            // application unless published by ClickOnce or Silverlight
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly();
            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
            using (StreamReader reader = new StreamReader(stream))
            {
                items = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(reader.ReadToEnd());
            }
        }
        catch (Exception) { return; }   // If fails - just don't use preferences.

        foreach (KeyValuePair<string, object> obj in items)
        {
            try
            {
                tar.GetType().GetProperty(obj.Key).SetValue(tar, obj.Value, null);
            }
            catch (Exception) { }
        }
    }
}

What's the difference between a method and a function?

A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.

A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:

  1. A method is implicitly passed the object on which it was called.
  2. A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).

(this is a simplified explanation, ignoring issues of scope etc.)

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

Call to your bank and ask them to activate your card to internet-use. Thats what helped me.

Perform commands over ssh with Python

#Reading the Host,username,password,port from excel file
import paramiko 
import xlrd

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

loc = ('/Users/harshgow/Documents/PYTHON_WORK/labcred.xlsx')
wo = xlrd.open_workbook(loc)
sheet = wo.sheet_by_index(0)
Host = sheet.cell_value(0,1)
Port = int(sheet.cell_value(3,1))
User = sheet.cell_value(1,1)
Pass = sheet.cell_value(2,1)

def details(Host,Port,User,Pass):
    ssh.connect(Host, Port, User, Pass)
    print('connected to ip ',Host)
    stdin, stdout, stderr = ssh.exec_command("")
    stdin.write('xcommand SystemUnit Boot Action: Restart\n')
    print('success')

details(Host,Port,User,Pass)

What is the exact meaning of Git Bash?

I think the question asker is (was) thinking that git bash is a command like git init or git checkout. Git bash is not a command, it is an interface. I will also assume the asker is not a linux user because bash is very popular the unix/linux world. The name "bash" is an acronym for "Bourne Again SHell". Bash is a text-only command interface that has features which allow automated scripts to be run. A good analogy would be to compare bash to the new PowerShell interface in Windows7/8. A poor analogy (but one likely to be more readily understood by more people) is the combination of the command prompt and .BAT (batch) command files from the days of DOS and early versions of Windows.

REFERENCES:

python object() takes no parameters error

You've mixed tabs and spaces. __init__ is actually defined nested inside another method, so your class doesn't have its own __init__ method, and it inherits object.__init__ instead. Open your code in Notepad instead of whatever editor you're using, and you'll see your code as Python's tab-handling rules see it.

This is why you should never mix tabs and spaces. Stick to one or the other. Spaces are recommended.

Peak-finding algorithm for Python/SciPy

There is a function in scipy named scipy.signal.find_peaks_cwt which sounds like is suitable for your needs, however I don't have experience with it so I cannot recommend..

http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks_cwt.html

How can I pass a member function where a free function is expected?

You can stop banging your heads now. Here is the wrapper for the member function to support existing functions taking in plain C functions as arguments. thread_local directive is the key here.

http://cpp.sh/9jhk3

// Example program
#include <iostream>
#include <string>

using namespace std;

typedef int FooCooker_ (int);

// Existing function
extern "C" void cook_10_foo (FooCooker_ FooCooker) {
    cout << "Cooking 10 Foo ..." << endl;
    cout << "FooCooker:" << endl;
    FooCooker (10);
}

struct Bar_ {
    Bar_ (int Foo = 0) : Foo (Foo) {};
    int cook (int Foo) {
        cout << "This Bar got " << this->Foo << endl;
        if (this->Foo >= Foo) {
            this->Foo -= Foo;
            cout << Foo << " cooked" << endl;
            return Foo;
        } else {
            cout << "Can't cook " <<  Foo << endl;
            return 0;
        }
    }
    int Foo = 0;
};

// Each Bar_ object and a member function need to define
// their own wrapper with a global thread_local object ptr
// to be called as a plain C function.
thread_local static Bar_* BarPtr = NULL;
static int cook_in_Bar (int Foo) {
    return BarPtr->cook (Foo);
}

thread_local static Bar_* Bar2Ptr = NULL;
static int cook_in_Bar2 (int Foo) {
    return Bar2Ptr->cook (Foo);
}

int main () {
  BarPtr = new Bar_ (20);
  cook_10_foo (cook_in_Bar);

  Bar2Ptr = new Bar_ (40);
  cook_10_foo (cook_in_Bar2);

  delete BarPtr;
  delete Bar2Ptr;
  return 0;
}

Please comment on any issues with this approach.

Other answers fail to call existing plain C functions: http://cpp.sh/8exun

Java count occurrence of each item in an array

It can be done in a very simple way using collections please find the code below

String[] array = {"name1","name1","name2","name2", "name2"};
List<String> sampleList=(List<String>) Arrays.asList(array);
for(String inpt:array){
int frequency=Collections.frequency(sampleList,inpt);
System.out.println(inpt+" "+frequency);
}

Here the output will be like name1 2 name1 2 name2 3 name2 3 name2 3

To avoid printing redundant keys use HashMap and get your desired output

Open soft keyboard programmatically

There are already too many answers but nothing worked for me apart from this

inputMethodManager.showSoftInput(emailET,InputMethodManager.SHOW_FORCED);

I used showSoftInput with SHOW_FORCED

And my activity has

 android:windowSoftInputMode="stateVisible|adjustResize"

hope this helps someone

How to replace a whole line with sed?

This might work for you:

cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]
!
aaa=bbb
aaa=ccc
aaa=ddd
aaa=xxx

RecyclerView: Inconsistency detected. Invalid item position

Most of the answers are disabling animations or creating new copies of data which is an overkill in my opinion. They do work but they don't address the root cause of the issue. In my case it was due to using DiffUtils in a wrong way. In the areItemsTheSame(old, new) method I did not properly implement the equality check, that, in turn cased the adapter to be notified by notifyItemRangeInserted() even though the same number of items are in the new list. So pay close attention to how you implement the DiffUtils callbacks!

.toLowerCase not working, replacement function?

It is a number, not a string. Numbers don't have a toLowerCase() function because numbers do not have case in the first place.

To make the function run without error, run it on a string.

var ans = "334";

Of course, the output will be the same as the input since, as mentioned, numbers don't have case in the first place.

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

For anyone getting this using ServiceStack backend; add "Authorization" to allowed headers in the Cors plugin:

Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type,Authorization"));

Angular2 multiple router-outlet in the same template

You can not use multiple router outlets in the same template with ngIf condition. But you can use it in the way shown below:

<div *ngIf="loading">
  <span>loading true</span>
  <ng-container *ngTemplateOutlet="template"></ng-container>
</div>

<div *ngIf="!loading">
  <span>loading false</span>
  <ng-container *ngTemplateOutlet="template"></ng-container>
  </div>

  <ng-template #template>
    <router-outlet> </router-outlet>
  </ng-template>

How do I get the fragment identifier (value after hash #) from a URL?

You may do it by using following code:

var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);

SEE DEMO

Why I get 'list' object has no attribute 'items'?

You have a dictionary within a list. You must first extract the dictionary from the list and then process the items in the dictionary.

If your list contained multiple dictionaries and you wanted the value from each dictionary stored in a list as you have shown do this:

result_list = [[int(v) for k,v in d.items()] for d in qs]

Which is the same as:

result_list = []
for d in qs:
    result_list.append([int(v) for k,v in d.items()])

The above will keep the values from each dictionary in their own separate list. If you just want all the values in one big list you can do this:

result_list = [int(v) for d in qs for k,v in d.items()]

jQuery Datepicker close datepicker after selected date

There is another code that's works for me (jQuery).

_x000D_
_x000D_
$(".datepicker").datepicker({_x000D_
    format: "dd/mm/yyyy",_x000D_
    autoHide: true_x000D_
    })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.css" />_x000D_
Date: <input type="text" readonly="true" class="datepicker">
_x000D_
_x000D_
_x000D_

Is key-value pair available in Typescript?

Is key-value pair available in Typescript?

If you think of a C# KeyValuePair<string, string>: No, but you can easily define one yourself:

interface KeyValuePair {
    key: string;
    value: string;
}

Usage:

let foo: KeyValuePair = { key: "k", value: "val" };

Laravel Request getting current path with query string

Similar to Yada's answer: $request->url() will also work if you are injecting Illuminate\Http\Request

Edit: The difference between fullUrl and url is the fullUrl includes your query parameters

How to read HDF5 files in Python

Reading the file

import h5py

f = h5py.File(file_name, mode)

Studying the structure of the file by printing what HDF5 groups are present

for key in f.keys():
    print(key) #Names of the groups in HDF5 file.

Extracting the data

#Get the HDF5 group
group = f[key]

#Checkout what keys are inside that group.
for key in group.keys():
    print(key)

data = group[some_key_inside_the_group].value
#Do whatever you want with data

#After you are done
f.close()

Why is "throws Exception" necessary when calling a function?

void show() throws Exception
{
    throw new Exception("my.own.Exception");
}

As there is checked exception in show() method , which is not being handled in that method so we use throws keyword for propagating the Exception.

void show2() throws Exception //Why throws is necessary here ?
{
show();
}

Since you are using the show() method in show2() method and you have propagated the exception atleast you should be handling here. If you are not handling the Exception here , then you are using throws keyword. So that is the reason for using throws keyword at the method signature.

Is it possible to put a ConstraintLayout inside a ScrollView?

PROBLEM:

I had a problem with ConstraintLayout and ScrollView when i wanted to include it in another layout.

DECISION:

The solution to my problem was to use dataBinding.

dataBinding (layout)

How to find text in a column and saving the row number where it is first found - Excel VBA

Check for "projtemp" and then check if the previous one is a number entry (like 19,18..etc..) if that is so then get the row no of that proj temp ....

and if that is not so ..then re-check that the previous entry is projtemp or a number entry ...

Getting all documents from one collection in Firestore

The example in the other answer is unnecessarily complex. This would be more straightforward, if all you want to do is return the raw data objects for each document in a query or collection:

async getMarker() {
    const snapshot = await firebase.firestore().collection('events').get()
    return snapshot.docs.map(doc => doc.data());
}

Copy file or directories recursively in Python

shutil.copy and shutil.copy2 are copying files.

shutil.copytree copies a folder with all the files and all subfolders. shutil.copytree is using shutil.copy2 to copy the files.

So the analog to cp -r you are saying is the shutil.copytree because cp -r targets and copies a folder and its files/subfolders like shutil.copytree. Without the -r cp copies files like shutil.copy and shutil.copy2 do.

How to reverse apply a stash?

You can follow the image i shared to unstash if u accidentally tapped stashing.

Checkbox Check Event Listener

If you have a checkbox in your html something like:

<input id="conducted" type = "checkbox" name="party" value="0">

and you want to add an EventListener to this checkbox using javascript, in your associated js file, you can do as follows:

checkbox = document.getElementById('conducted');

checkbox.addEventListener('change', e => {

    if(e.target.checked){
        //do something
    }

});

Split an NSString to access one particular piece

Either of these 2:

NSString *subString = [dateString subStringWithRange:NSMakeRange(0,2)];
NSString *subString = [[dateString componentsSeparatedByString:@"/"] objectAtIndex:0];

Though keep in mind that sometimes a date string is not formatted properly and a day ( or a month for that matter ) is shown as 8, rather than 08 so the first one might be the worst of the 2 solutions.

The latter should be put into a separate array so you can actually check for the length of the thing returned, so you do not get any exceptions thrown in the case of a corrupt or invalid date string from whatever source you have.

Can I write native iPhone apps using Python?

Yes, nowadays you can develop apps for iOS in Python.

There are two frameworks that you may want to checkout: Kivy and PyMob.

Please consider the answers to this question too, as they are more up-to-date than this one.

datetime datatype in java

Depends on the RDBMS or even the JDBC driver.

Most of the times you can use java.sql.Timestamp most of the times along with a prepared statement:

pstmt.setTimestamp( index, new Timestamp( yourJavaUtilDateInstance.getTime() );

Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)

I was trying to up the limit Wordpress sets on media uploads. I followed advice from some blog I’m not going to mention to raise the limit from 64MB to 2GB.

I did the following:

Created a (php.ini) file in WP ADMIN with the following integers:

upload_max_filesize = 2000MB
post_max_size = 2100MV
memory_limit = 2300MB

I immediately received this error when trying to log into my Wordpress dashboard to check if it worked:

“Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)"

The above information in this chain helped me tremendously. (Stack usually does BTW)

I modified the PHP.ini file to the following:

upload_max_filesize = 2000M
post_max_size = 2100M
memory_limit = 536870912M

The major difference was only use M, not MB, and set that memory limit high.

As soon as I saved the changed the PHP.ini file, I saved it, went to login again and the login screen reappeared.

I went in and checked media uploads, ands bang:

Image showing twordpress media folder “Add New” box, with limits stated as “MAXIMUM UPLOAD FILE SIZE: 2 GB”

I haven't restarted Apache yet… but all looks good.

Thanks everyone.

CertificateException: No name matching ssl.someUrl.de found

In case, it helps someone:

Use case: i am using a self-signed certificate for my development on localhost.

Error: Caused by: java.security.cert.CertificateException: No name matching localhost found

Solution: When you generate your self-signed certicate, make sure you answer this question like that(See Bruno's answer for the why):

What is your first and last name?
  [Unknown]:  localhost



As a bonus, here are my steps:
1. Generate self-signed certificate:

keytool -genkeypair -alias netty -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 4000
Enter keystore password: ***
Re-enter new password: ***
What is your first and last name?
  [Unknown]:  localhost
...

2. Copy the certificate in src/main/resources(if necessary)

3. Update the cacerts
keytool -v -importkeystore -srckeystore keystore.p12 -srcstoretype pkcs12 -destkeystore "%JAVA_HOME%\jre\lib\security\cacerts" -deststoretype jks

4. Update your config(in my case application.properties):

server.port=8443
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=jumping_monkey
server.ssl.key-store-type=pkcs12
server.ssl.key-alias=netty



Cheers

C# Form.Close vs Form.Dispose

Using usingis a pretty good way:

using (MyForm foo = new MyForm())
{
    if (foo.ShowDialog() == DialogResult.OK)
    {
        // your code
    }
}

Bootstrap 4 align navbar items to the right

Find the 69 line in the verndor-prefixes.less and write it following:

_x000D_
_x000D_
.panel {_x000D_
    margin-bottom: 20px;_x000D_
    height: 100px;_x000D_
    background-color: #fff;_x000D_
    border: 1px solid transparent;_x000D_
    border-radius: 4px;_x000D_
    -webkit-box-shadow: 0 1px 1px rgba(0,0,0,.05);_x000D_
    box-shadow: 0 1px 1px rgba(0,0,0,.05);_x000D_
}
_x000D_
_x000D_
_x000D_

Render HTML in React Native

 <WebView ref={'webview'} automaticallyAdjustContentInsets={false} source={require('../Assets/aboutus.html')} />

This worked for me :) I have html text aboutus file.

Conditionally Remove Dataframe Rows with R

Subset is your safest and easiest answer.

subset(dataframe, A==B & E!=0)

Real data example with mtcars

subset(mtcars, cyl==6 & am!=0)

How to make a GridLayout fit screen size

Starting in API 21 the notion of weight was added to GridLayout.

To support older android devices, you can use the GridLayout from the v7 support library.

compile 'com.android.support:gridlayout-v7:22.2.1'

The following XML gives an example of how you can use weights to fill the screen width.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:grid="http://schemas.android.com/apk/res-auto"

    android:id="@+id/choice_grid"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:padding="4dp"

    grid:alignmentMode="alignBounds"
    grid:columnCount="2"
    grid:rowOrderPreserved="false"
    grid:useDefaultMargins="true">

    <TextView
        android:layout_width="0dp"
        android:layout_height="100dp"
        grid:layout_columnWeight="1"
        grid:layout_gravity="fill_horizontal"
        android:gravity="center"
        android:background="#FF33B5E5"
        android:text="Tile1" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="100dp"
        grid:layout_columnWeight="1"
        grid:layout_gravity="fill_horizontal"
        android:gravity="center"
        android:background="#FF33B5E5"
        android:text="Tile2" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="100dp"
        grid:layout_columnWeight="1"
        grid:layout_gravity="fill_horizontal"
        android:gravity="center"
        android:background="#FF33B5E5"
        android:text="Tile3" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="100dp"
        grid:layout_columnWeight="1"
        grid:layout_gravity="fill_horizontal"
        android:gravity="center"
        android:background="#FF33B5E5"
        android:text="Tile4" />

</android.support.v7.widget.GridLayout>

Unable to compile simple Java 10 / Java 11 project with Maven

As of 30Jul, 2018 to fix the above issue, one can configure the java version used within maven to any up to JDK/11 and make use of the maven-compiler-plugin:3.8.0 to specify a release of either 9,10,11 without any explicit dependencies.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <release>11</release>  <!--or <release>10</release>-->
    </configuration>
</plugin>

Note:- The default value for source/target has been lifted from 1.5 to 1.6 with this version. -- release notes.


Edit [30.12.2018]

In fact, you can make use of the same version of maven-compiler-plugin while compiling the code against JDK/12 as well.

More details and a sample configuration in how to Compile and execute a JDK preview feature with Maven.

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

You can also do

t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')

as in the Ruby on Rails API.

SQL grouping by month and year

For mariaDB you can:

SELECT DATE_FORMAT(date, '%m-%Y')
FROM [Order]
GROUP BY 
DATE_FORMAT(date, '%m-%Y')

Link: https://mariadb.com/kb/en/library/date_format/

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

Answer offered by @faham is a nice one-liner, but it doesn't return the index to the dictionary containing the value. Instead it returns the dictionary itself. Here is a simple way to get: A list of indexes one or more if there are more than one, or an empty list if there are none:

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

[i for i, d in enumerate(list) if 'Tom' in d.values()]

Output:

>>> [1]

What I like about this approach is that with a simple edit you can get a list of both the indexes and the dictionaries as tuples. This is the problem I needed to solve and found these answers. In the following, I added a duplicate value in a different dictionary to show how it works:

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

[(i, d) for i, d in enumerate(list) if 'Tom' in d.values()]

Output:

>>> [(1, {'id': '2345', 'name': 'Tom'}), (3, {'id': '4567', 'name': 'Tom'})]

This solution finds all dictionaries containing 'Tom' in any of their values.

Select all from table with Laravel and Eloquent

Well, to do it with eloquent you would do:

Blog:all();

From within your Model you do:

return DB::table('posts')->get();

http://laravel.com/docs/queries

What does the "undefined reference to varName" in C mean?

You need to link both a.o and b.o:

gcc -o program a.c b.c

If you have a main() in each file, you cannot link them together.

However, your a.c file contains a reference to doSomething() and expects to be linked with a source file that defines doSomething() and does not define any function that is defined in a.c (such as main()).

You cannot call a function in Process B from Process A. You cannot send a signal to a function; you send signals to processes, using the kill() system call.

The signal() function specifies which function in your current process (program) is going to handle the signal when your process receives the signal.

You have some serious work to do understanding how this is going to work - how ProgramA is going to know which process ID to send the signal to. The code in b.c is going to need to call signal() with dosomething as the signal handler. The code in a.c is simply going to send the signal to the other process.

Removing html5 required attribute with jQuery

If you want to set required to true

$(document).ready(function(){
$('#edit-submitted-first-name').prop('required',true);
});

if you want to set required to false

$(document).ready(function(){
$('#edit-submitted-first-name').prop('required',false);
});

How to convert an integer to a string in any base?

Well I personally use this function, written by me

import string

def to_base(value, base, digits=string.digits+string.ascii_letters):    # converts decimal to base n

    digits_slice = digits[0:base]

    temporary_var = value
    data = [temporary_var]

    while True:
        temporary_var = temporary_var // base
        data.append(temporary_var)
        if temporary_var < base:
            break

    result = ''
    for each_data in data:
        result += digits_slice[each_data % base]
    result = result[::-1]

    return result

This is how you can use it

print(to_base(7, base=2))

Output: "111"

print(to_base(23, base=3))

Output: "212"

Please feel free to suggest improvements in my code.

How do I get java logging output to appear on a single line?

if you're using java.util.logging, then there is a configuration file that is doing this to log contents (unless you're using programmatic configuration). So, your options are
1) run post -processor that removes the line breaks
2) change the log configuration AND remove the line breaks from it. Restart your application (server) and you should be good.

How to call a RESTful web service from Android?

Perhaps am late or maybe you've already used it before but there is another one called ksoap and its pretty amazing.. It also includes timeouts and can parse any SOAP based webservice efficiently. I also made a few changes to suit my parsing.. Look it up

Oracle PL/SQL - How to create a simple array variable?

Sample programs as follows and provided on link also https://oracle-concepts-learning.blogspot.com/

plsql table or associated array.

        DECLARE 
            TYPE salary IS TABLE OF NUMBER INDEX BY VARCHAR2(20); 
            salary_list salary; 
            name VARCHAR2(20); 
        BEGIN 
           -- adding elements to the table 
           salary_list('Rajnish') := 62000; salary_list('Minakshi') := 75000; 
           salary_list('Martin') := 100000; salary_list('James') := 78000; 
           -- printing the table name := salary_list.FIRST; WHILE name IS NOT null 
            LOOP 
               dbms_output.put_line ('Salary of ' || name || ' is ' || 
               TO_CHAR(salary_list(name))); 
               name := salary_list.NEXT(name); 
            END LOOP; 
        END; 
        /

How to send email from MySQL 5.1

I agree with Jim Blizard. The database is not the part of your technology stack that should send emails. For example, what if you send an email but then roll back the change that triggered that email? You can't take the email back.

It's better to send the email in your application code layer, after your app has confirmed that the SQL change was made successfully and committed.

What is a clean, Pythonic way to have multiple constructors in Python?

All of these answers are excellent if you want to use optional parameters, but another Pythonic possibility is to use a classmethod to generate a factory-style pseudo-constructor:

def __init__(self, num_holes):

  # do stuff with the number

@classmethod
def fromRandom(cls):

  return cls( # some-random-number )

How can I use Timer (formerly NSTimer) in Swift?

SimpleTimer (Swift 3.1)

Why?

This is a simple timer class in swift that enables you to:

  • Local scoped timer
  • Chainable
  • One liners
  • Use regular callbacks

Usage:

SimpleTimer(interval: 3,repeats: true){print("tick")}.start()//Ticks every 3 secs

Code:

class SimpleTimer {/*<--was named Timer, but since swift 3, NSTimer is now Timer*/
    typealias Tick = ()->Void
    var timer:Timer?
    var interval:TimeInterval /*in seconds*/
    var repeats:Bool
    var tick:Tick

    init( interval:TimeInterval, repeats:Bool = false, onTick:@escaping Tick){
        self.interval = interval
        self.repeats = repeats
        self.tick = onTick
    }
    func start(){
        timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(update), userInfo: nil, repeats: true)//swift 3 upgrade
    }
    func stop(){
        if(timer != nil){timer!.invalidate()}
    }
    /**
     * This method must be in the public or scope
     */
    @objc func update() {
        tick()
    }
}

What does __FILE__ mean in Ruby?

In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.

In PHP __FILE__ is the full path (which in my opinion is preferable). This is why, in order to make your paths portable in Ruby, you really need to use this:

File.expand_path(File.dirname(__FILE__) + "relative/path/to/file")

I should note that in Ruby 1.9.1 __FILE__ contains the full path to the file, the above description was for when I used Ruby 1.8.7.

In order to be compatible with both Ruby 1.8.7 and 1.9.1 (not sure about 1.9) you should require files by using the construct I showed above.

Find and replace in file and overwrite file doesn't work, it empties the file

I was searching for the option where I can define the line range and found the answer. For example I want to change host1 to host2 from line 36-57.

sed '36,57 s/host1/host2/g' myfile.txt > myfile1.txt

You can use gi option as well to ignore the character case.

sed '30,40 s/version/story/gi' myfile.txt > myfile1.txt

Doctrine and LIKE query

you can also do it like that :

$ver = $em->getRepository('GedDocumentBundle:version')->search($val);

$tail = sizeof($ver);

C++ display stack trace on exception

I would like to add a standard library option (i.e. cross-platform) how to generate exception backtraces, which has become available with C++11:

Use std::nested_exception and std::throw_with_nested

This won't give you a stack unwind, but in my opinion the next best thing. It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.

Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"

How do I reset the scale/zoom of a web app on an orientation change on the iPhone?

Jeremy Keith (@adactio) has a good solution for this on his blog Orientation and scale

Keep the Markup scalable by not setting a maximum-scale in markup.

<meta name="viewport" content="width=device-width, initial-scale=1">

Then disable scalability with javascript on load until gesturestart when you allow scalability again with this script:

if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) {
    var viewportmeta = document.querySelector('meta[name="viewport"]');
    if (viewportmeta) {
        viewportmeta.content = 'width=device-width, minimum-scale=1.0, maximum-scale=1.0, initial-scale=1.0';
        document.body.addEventListener('gesturestart', function () {
            viewportmeta.content = 'width=device-width, minimum-scale=0.25, maximum-scale=1.6';
        }, false);
    }
}

Update 22-12-2014:
On an iPad 1 this doesnt work, it fails on the eventlistener. I've found that removing .body fixes that:

document.addEventListener('gesturestart', function() { /* */ });

correct way of comparing string jquery operator =

First of all you should use double "==" instead of "=" to compare two values. Using "=" You assigning value to variable in this case "somevar"

How to encrypt and decrypt file in Android?

You could use java-aes-crypto or Facebook's Conceal

java-aes-crypto

Quoting from the repo

A simple Android class for encrypting & decrypting strings, aiming to avoid the classic mistakes that most such classes suffer from.

Facebook's conceal

Quoting from the repo

Conceal provides easy Android APIs for performing fast encryption and authentication of data

Create a zip file and download it

// http headers for zip downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filepath.$filename));
ob_end_flush();
@readfile($filepath.$filename);

I found this soludtion here and it work for me

Format date as dd/MM/yyyy using pipes

Import DatePipe from angular/common and then use the below code:

var datePipe = new DatePipe();
    this.setDob = datePipe.transform(userdate, 'dd/MM/yyyy');

where userdate will be your date string. See if this helps.

Make note of the lowercase for date and year :

d- date
M- month
y-year

EDIT

You have to pass locale string as an argument to DatePipe, in latest angular. I have tested in angular 4.x

For Example:

var datePipe = new DatePipe('en-US');

Maximum number of records in a MySQL database table

According to Scalability and Limits section in http://dev.mysql.com/doc/refman/5.6/en/features.html, MySQL support for large databases. They use MySQL Server with databases that contain 50 million records. Some users use MySQL Server with 200,000 tables and about 5,000,000,000 rows.

PHP preg replace only allow numbers

Try this:

return preg_replace("/[^0-9]/", "",$c);

How to convert string to date to string in Swift iOS?

//String to Date Convert

var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)


//CONVERT FROM NSDate to String  

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" 
var dateString = dateFormatter.stringFromDate(date)
println(dateString)  

Get the POST request body from HttpServletRequest

In Java 8, you can do it in a simpler and clean way :

if ("POST".equalsIgnoreCase(request.getMethod())) 
{
   test = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
}

Difference between hamiltonian path and euler path

I'll use a common example in biology; reconstructing a genome by making DNA samples.

De-novo assembly

To construct a genome from short reads, it's necessary to construct a graph of those reads. We do it by breaking the reads into k-mers and assemble them into a graph.

enter image description here

We can reconstruct the genome by visiting each node once as in the diagram. This is known as Hamiltonian path.

Unfortunately, constructing such path is NP-hard. It's not possible to derive an efficient algorithm for solving it. Instead, in bioinformatics we construct a Eulerian cycle where an edge represents an overlap.

enter image description here

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

I'm running SQL Developer 17.2.0.188 build 188.1159 which does indeed contain data modeling capability. I just created a relational model diagram via the menu: File->Data Modeler->Import->Data Dictionary....

I also have the stand-alone Data Modeler, which does the same thing.

As the Data Modeler tutorial states:

Figure 4: Relational model and diagram for HR

The diagram you’ve generated is not an ERD. Logical models are higher abstractions. An ERD represents entities and their attributes and relations, whereas a relational or physical model represents tables, columns, and foreign keys."

How to check if a windows form is already open, and close it if it is?

this will word definitely. i use this function for myself as well.

  public static bool isFormOpen(Form formm)
    {

        foreach (Form OpenForm in Application.OpenForms)
        {
            if (OpenForm.Name == formm.Name)
            {
                return true;
            }
        }

        return false;
    }

How can you run a command in bash over and over until success?

You can use an infinite loop to achieve this:

while true
do
  read -p "Enter password" passwd
  case "$passwd" in
    <some good condition> ) break;;
  esac
done

Removing All Items From A ComboBox?

If you want to simply remove the value in the combo box:

me.combobox = ""

If you want to remove the recordset of the combobox, the easiest way is:

me.combobox.recordset = ""
me.combobox.requery

Xcode 8 shows error that provisioning profile doesn't include signing certificate

The issue seems to start happening in Xcode 11.

  • Go to Apple Developer
  • Find the right provision profile
  • Press Edit in the right upper corner
  • Choose the (Distribution) option in Certificates. (I think it's a new option/certificate type that apple introduced though I couldn't find any documentation)
  • Optional: Delete all you provision profiles in (~/Library/MobileDevice/Provisioning Profiles/)
    go to Xcode ->Preferences->Accounts->Download Manual Profiles

enter image description here

xcode library not found

In XCode 10.1, I had to set "Library Search Paths" to something like $(PROJECT_DIR)/.../path/to/your/library

Bitbucket git credentials if signed up with Google

One way to skip this is by creating a specific app password variable.

  1. Settings
  2. App passwords
  3. Create app password

And you can use that generated password to access or to push commits from your terminal, when using a Google Account to sign in into Bitbucket.

Is there a way to detect if a browser window is not currently active?

Using : Page Visibility API

document.addEventListener( 'visibilitychange' , function() {
    if (document.hidden) {
        console.log('bye');
    } else {
        console.log('well back');
    }
}, false );

Can i use ? http://caniuse.com/#feat=pagevisibility

What are the file limits in Git (number and size)?

There is no real limit -- everything is named with a 160-bit name. The size of the file must be representable in a 64 bit number so no real limit there either.

There is a practical limit, though. I have a repository that's ~8GB with >880,000 files and git gc takes a while. The working tree is rather large so operations that inspect the entire working directory take quite a while. This repo is only used for data storage, though, so it's just a bunch of automated tools that handle it. Pulling changes from the repo is much, much faster than rsyncing the same data.

%find . -type f | wc -l
791887
%time git add .
git add .  6.48s user 13.53s system 55% cpu 36.121 total
%time git status
# On branch master
nothing to commit (working directory clean)
git status  0.00s user 0.01s system 0% cpu 47.169 total
%du -sh .
29G     .
%cd .git
%du -sh .
7.9G    .

Using variables inside strings

Use the following methods

1: Method one

var count = 123;
var message = $"Rows count is: {count}";

2: Method two

var count = 123;
var message = "Rows count is:" + count;

3: Method three

var count = 123;
var message = string.Format("Rows count is:{0}", count);

4: Method four

var count = 123;
var message = @"Rows
                count
                is:{0}" + count;

5: Method five

var count = 123;
var message = $@"Rows 
                 count 
                 is: {count}";

How to "grep" out specific line ranges of a file

The following command will do what you asked for "extract the lines between 1234 and 5555" in someFile.

sed -n '1234,5555p' someFile

How can I create a correlation matrix in R?

You could use 'corrplot' package.

d <- data.frame(x1=rnorm(10),
                 x2=rnorm(10),
                 x3=rnorm(10))
M <- cor(d) # get correlations

library('corrplot') #package corrplot
corrplot(M, method = "circle") #plot matrix

enter image description here

More information here: http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html

executing shell command in background from script

Leave off the quotes

$cmd &
$othercmd &

eg:

nicholas@nick-win7 /tmp
$ cat test
#!/bin/bash

cmd="ls -la"

$cmd &


nicholas@nick-win7 /tmp
$ ./test

nicholas@nick-win7 /tmp
$ total 6
drwxrwxrwt+ 1 nicholas root    0 2010-09-10 20:44 .
drwxr-xr-x+ 1 nicholas root 4096 2010-09-10 14:40 ..
-rwxrwxrwx  1 nicholas None   35 2010-09-10 20:44 test
-rwxr-xr-x  1 nicholas None   41 2010-09-10 20:43 test~

Adding a newline into a string in C#

as others have said new line char will give you a new line in a text file in windows. try the following:

using System;
using System.IO;

static class Program
{
    static void Main()
    {
        WriteToFile
        (
        @"C:\test.txt",
        "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@",
        "@"
        );

        /*
        output in test.txt in windows =
        fkdfdsfdflkdkfk@
        dfsdfjk72388389@
        kdkfkdfkkl@
        jkdjkfjd@
        jjjk@ 
        */
    }

    public static void WriteToFile(string filename, string text, string newLineDelim)
    {
        bool equal = Environment.NewLine == "\r\n";

        //Environment.NewLine == \r\n = True
        Console.WriteLine("Environment.NewLine == \\r\\n = {0}", equal);

        //replace newLineDelim with newLineDelim + a new line
        //trim to get rid of any new lines chars at the end of the file
        string filetext = text.Replace(newLineDelim, newLineDelim + Environment.NewLine).Trim();

        using (StreamWriter sw = new StreamWriter(File.OpenWrite(filename)))
        {
            sw.Write(filetext);
        }
    }
}

Length of a JavaScript object

Like most JavaScript problems, there are many solutions. You could extend the Object that for better or worse works like many other languages' Dictionary (+ first class citizens). Nothing wrong with that, but another option is to construct a new Object that meets your specific needs.

function uberject(obj){
    this._count = 0;
    for(var param in obj){
        this[param] = obj[param];
        this._count++;
    }
}

uberject.prototype.getLength = function(){
    return this._count;
};

var foo = new uberject({bar:123,baz:456});
alert(foo.getLength());

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

use this

<div id="date">23/05/2013</div>
<script type="text/javascript">
$(document).ready(function(){
  var x = $("#date").text();
    x.text(x.substring(0, 2) + '<br />'+x.substring(3));     
});
</script>

How to list only files and not directories of a directory Bash?

  • carlpett's find-based answer (find . -maxdepth 1 -type f) works in principle, but is not quite the same as using ls: you get a potentially unsorted list of filenames all prefixed with ./, and you lose the ability to apply ls's many options;
    also find invariably finds hidden items too, whereas ls' behavior depends on the presence or absence of the -a or -A options.

    • An improvement, suggested by Alex Hall in a comment on the question is to combine shell globbing with find:

          find * -maxdepth 0 -type f  # find -L * ... includes symlinks to files
      
      • However, while this addresses the prefix problem and gives you alphabetically sorted output, you still have neither (inline) control over inclusion of hidden items nor access to ls's many other sorting / output-format options.
  • Hans Roggeman's ls + grep answer is pragmatic, but locks you into using long (-l) output format.


To address these limitations I wrote the fls (filtering ls) utility,

  • a utility that provides the output flexibility of ls while also providing type-filtering capability,
  • simply by placing type-filtering characters such as f for files, d for directories, and l for symlinks before a list of ls arguments (run fls --help or fls --man to learn more).

Examples:

fls f        # list all files in current dir.
fls d -tA ~  #  list dirs. in home dir., including hidden ones, most recent first
fls f^l /usr/local/bin/c* # List matches that are files, but not (^) symlinks (l)

Installation

Supported platforms

  • When installing from the npm registry: Linux and macOS
  • When installing manually: any Unix-like platform with Bash

From the npm registry

Note: Even if you don't use Node.js, its package manager, npm, works across platforms and is easy to install; try
curl -L https://git.io/n-install | bash

With Node.js installed, install as follows:

[sudo] npm install fls -g

Note:

  • Whether you need sudo depends on how you installed Node.js / io.js and whether you've changed permissions later; if you get an EACCES error, try again with sudo.

  • The -g ensures global installation and is needed to put fls in your system's $PATH.

Manual installation

  • Download this bash script as fls.
  • Make it executable with chmod +x fls.
  • Move it or symlink it to a folder in your $PATH, such as /usr/local/bin (macOS) or /usr/bin (Linux).

How do I execute a program using Maven?

With the global configuration that you have defined for the exec-maven-plugin:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4.0</version>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

invoking mvn exec:java on the command line will invoke the plugin which is configured to execute the class org.dhappy.test.NeoTraverse.

So, to trigger the plugin from the command line, just run:

mvn exec:java

Now, if you want to execute the exec:java goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase to which you want to bind the goal in the execution element:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <id>my-execution</id>
      <phase>package</phase>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

With this example, your class would be executed during the package phase. This is just an example, adapt it to suit your needs. Works also with plugin version 1.1.

How do I add python3 kernel to jupyter (IPython)

I was getting same error with python-2. I wanted to run python-2 jupyter notebook session but by default I was getting python-3. So easiest work around is open Anaconda terminal for python-2 and type 'jupyter notebook' , it will launch jupyter-notebook session without any problem. Similary it could be tried with python-3

Inline list initialization in VB.NET

Collection initializers are only available in VB.NET 2010, released 2010-04-12:

Dim theVar = New List(Of String) From { "one", "two", "three" }

Select row and element in awk

To print the second line:

awk 'FNR == 2 {print}'

To print the second field:

awk '{print $2}'

To print the third field of the fifth line:

awk 'FNR == 5 {print $3}'

Here's an example with a header line and (redundant) field descriptions:

awk 'BEGIN {print "Name\t\tAge"}  FNR == 5 {print "Name: "$3"\tAge: "$2}'

There are better ways to align columns than "\t\t" by the way.

Use exit to stop as soon as you've printed the desired record if there's no reason to process the whole file:

awk 'FNR == 2 {print; exit}'

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

I would go through the packet capture and see if there are any records that I know I should be seeing to validate that the filter is working properly and to assuage any doubts.

That said, please try the following filter and see if you're getting the entries that you think you should be getting:

dns and ip.dst==159.25.78.7 or dns and ip.src==159.57.78.7

Module not found: Error: Can't resolve 'core-js/es6'

I found possible answer. You have core-js version 3.0, and this version doesn't have separate folders for ES6 and ES7; that's why the application cannot find correct paths.

To resolve this error, you can downgrade the core-js version to 2.5.7. This version produces correct catalogs structure, with separate ES6 and ES7 folders.

To downgrade the version, simply run:

npm i -S [email protected]

In my case, with Angular, this works ok.

What does <a href="#" class="view"> mean?

Don't forget to look at the Javascript as well. My guess is that there is custom Javascript code getting executed when you click on the link and it's that Javascript that is generating the URL and navigating to it.

How do I print debug messages in the Google Chrome JavaScript Console?

console.debug("");

Using this method prints out the text in a bright blue color in the console.

enter image description here

Git says remote ref does not exist when I delete remote branch

A handy one-liner to delete branches other than 'master' from origin:

git branch --remotes | grep -v 'origin/master' | sed "s/origin\///" | xargs -i{foo} git push origin --delete {foo}

Be sure you understand the implications of running this before doing so!

How do I find the width & height of a terminal window?

  • tput cols tells you the number of columns.
  • tput lines tells you the number of rows.

AttributeError: 'module' object has no attribute 'urlretrieve'

As you're using Python 3, there is no urllib module anymore. It has been split into several modules.

This would be equivalent to urlretrieve:

import urllib.request
data = urllib.request.urlretrieve("http://...")

urlretrieve behaves exactly the same way as it did in Python 2.x, so it'll work just fine.

Basically:

  • urlretrieve saves the file to a temporary file and returns a tuple (filename, headers)
  • urlopen returns a Request object whose read method returns a bytestring containing the file contents

Sorting Characters Of A C++ String

You can use sort() function. sort() exists in algorithm header file

        #include<bits/stdc++.h>
        using namespace std;


        int main()
        {
            ios::sync_with_stdio(false);
            string str = "sharlock";

            sort(str.begin(), str.end());
            cout<<str<<endl;

            return 0;
        }

Output:

achklors

Looping through all the properties of object php

Before you run the $object through a foreach loop you have to convert it to an array:

$array = (array) $object;  

 foreach($array as $key=>$val){
      echo "$key: $val";
      echo "<br>";
 }

Compare two Byte Arrays? (Java)

Java doesn't overload operators, so you'll usually need a method for non-basic types. Try the Arrays.equals() method.

Best way to parse RSS/Atom feeds with PHP

If feed isn't well-formed XML, you're supposed to reject it, no exceptions. You're entitled to call feed creator a bozo.

Otherwise you're paving way to mess that HTML ended up in.

Get safe area inset top and bottom heights

safeAreaLayoutGuide When the view is visible onscreen, this guide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor views. (In tvOS, the safe area reflects the area not covered the screen's bezel.) If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide edges are equal to the edges of the view.

Then to get the height of the red arrow in the screenshot it's:

self.safeAreaLayoutGuide.layoutFrame.size.height

Regex to get string between curly braces

Here's a simple solution using javascript replace

var st = '{getThis}';

st = st.replace(/\{|\}/gi,''); // "getThis"

As the accepted answer above points out the original problem is easily solved with substring, but using replace can solve the more complicated use cases

If you have a string like "randomstring999[fieldname]" You use a slightly different pattern to get fieldname

var nameAttr = "randomstring999[fieldname]";

var justName = nameAttr.replace(/.*\[|\]/gi,''); // "fieldname"

How to have multiple colors in a Windows batch file?

Several methods are covered in
"51} How can I echo lines in different colors in NT scripts?"
http://www.netikka.net/tsneti/info/tscmd051.htm

One of the alternatives: If you can get hold of QBASIC, using colors is relatively easy:

  @echo off & setlocal enableextensions
  for /f "tokens=*" %%f in ("%temp%") do set temp_=%%~sf
  set skip=
  findstr "'%skip%QB" "%~f0" > %temp_%\tmp$$$.bas
  qbasic /run %temp_%\tmp$$$.bas
  for %%f in (%temp_%\tmp$$$.bas) do if exist %%f del %%f
  endlocal & goto :EOF
  ::
  CLS 'QB
  COLOR 14,0 'QB
  PRINT "A simple "; 'QB
  COLOR 13,0 'QB
  PRINT "color "; 'QB
  COLOR 14,0 'QB
  PRINT "demonstration" 'QB
  PRINT "By Prof. (emer.) Timo Salmi" 'QB
  PRINT 'QB
  FOR j = 0 TO 7 'QB
    FOR i = 0 TO 15 'QB
      COLOR i, j 'QB
      PRINT LTRIM$(STR$(i)); " "; LTRIM$(STR$(j)); 'QB
      COLOR 1, 0 'QB
      PRINT " "; 'QB
    NEXT i 'QB
    PRINT 'QB
  NEXT j 'QB
  SYSTEM 'QB

How can I loop through all rows of a table? (MySQL)

Since the suggestion of a loop implies the request for a procedure type solution. Here is mine.

Any query which works on any single record taken from a table can be wrapped in a procedure to make it run through each row of a table like so:

First delete any existing procedure with the same name, and change the delimiter so your SQL doesn't try to run each line as you're trying to write the procedure.

DROP PROCEDURE IF EXISTS ROWPERROW;
DELIMITER ;;

Then here's the procedure as per your example (table_A and table_B used for clarity)

CREATE PROCEDURE ROWPERROW()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM table_A INTO n;
SET i=0;
WHILE i<n DO 
  INSERT INTO table_B(ID, VAL) SELECT (ID, VAL) FROM table_A LIMIT i,1;
  SET i = i + 1;
END WHILE;
End;
;;

Then dont forget to reset the delimiter

DELIMITER ;

And run the new procedure

CALL ROWPERROW();

You can do whatever you like at the "INSERT INTO" line which I simply copied from your example request.

Note CAREFULLY that the "INSERT INTO" line used here mirrors the line in the question. As per the comments to this answer you need to ensure that your query is syntactically correct for which ever version of SQL you are running.

In the simple case where your ID field is incremented and starts at 1 the line in the example could become:

INSERT INTO table_B(ID, VAL) VALUES(ID, VAL) FROM table_A WHERE ID=i;

Replacing the "SELECT COUNT" line with

SET n=10;

Will let you test your query on the first 10 record in table_A only.

One last thing. This process is also very easy to nest across different tables and was the only way I could carry out a process on one table which dynamically inserted different numbers of records into a new table from each row of a parent table.

If you need it to run faster then sure try to make it set based, if not then this is fine. You could also rewrite the above in cursor form but it may not improve performance. eg:

DROP PROCEDURE IF EXISTS cursor_ROWPERROW;
DELIMITER ;;

CREATE PROCEDURE cursor_ROWPERROW()
BEGIN
  DECLARE cursor_ID INT;
  DECLARE cursor_VAL VARCHAR;
  DECLARE done INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT ID,VAL FROM table_A;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO cursor_ID, cursor_VAL;
    IF done THEN
      LEAVE read_loop;
    END IF;
    INSERT INTO table_B(ID, VAL) VALUES(cursor_ID, cursor_VAL);
  END LOOP;
  CLOSE cursor_i;
END;
;;

Remember to declare the variables you will use as the same type as those from the queried tables.

My advise is to go with setbased queries when you can, and only use simple loops or cursors if you have to.

Find all stored procedures that reference a specific column in some table

You can use ApexSQL Search, it's a free SSMS and Visual Studio add-in and it can list all objects that reference a specific table column. It can also find data stored in tables and views. You can easily filter the results to show a specific database object type that references the column

enter image description here

Disclaimer: I work for ApexSQL as a Support Engineer

Add class to an element in Angular 4

If you want to set only one specific class, you might write a TypeScript function returning a boolean to determine when the class should be appended.

TypeScript

function hideThumbnail():boolean{
    if (/* Your criteria here */)
        return true;
}

CSS:

.request-card-hidden {
    display: none;
}

HTML:

<ion-note [class.request-card-hidden]="hideThumbnail()"></ion-note>

how to check and set max_allowed_packet mysql variable

The following PHP worked for me (using mysqli extension but queries should be the same for other extensions):

$db = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
// to get the max_allowed_packet
$maxp = $db->query( 'SELECT @@global.max_allowed_packet' )->fetch_array();
echo $maxp[ 0 ];
// to set the max_allowed_packet to 500MB
$db->query( 'SET @@global.max_allowed_packet = ' . 500 * 1024 * 1024 );

So if you've got a query you expect to be pretty long, you can make sure that mysql will accept it with something like:

$sql = "some really long sql query...";
$db->query( 'SET @@global.max_allowed_packet = ' . strlen( $sql ) + 1024 );
$db->query( $sql );

Notice that I added on an extra 1024 bytes to the length of the string because according to the manual,

The value should be a multiple of 1024; nonmultiples are rounded down to the nearest multiple.

That should hopefully set the max_allowed_packet size large enough to handle your query. I haven't tried this on a shared host, so the same caveat as @Glebushka applies.

Showing alert in angularjs when user leaves a page

Lets seperate your question, you are asking about two different things:

1.

I'm trying to write a validation which alerts the user when he tries to close the browser window.

2.

I want to pop up a message when the user clicks on v1 that "he's about to leave from v1, if he wishes to continue" and same on clicking on v2.

For the first question, do it this way:

window.onbeforeunload = function (event) {
  var message = 'Sure you want to leave?';
  if (typeof event == 'undefined') {
    event = window.event;
  }
  if (event) {
    event.returnValue = message;
  }
  return message;
}

And for the second question, do it this way:

You should handle the $locationChangeStart event in order to hook up to view transition event, so use this code to handle the transition validation in your controller/s:

function MyCtrl1($scope) {
    $scope.$on('$locationChangeStart', function(event) {
        var answer = confirm("Are you sure you want to leave this page?")
        if (!answer) {
            event.preventDefault();
        }
    });
}

How to make Firefox headless programmatically in Selenium with Python?

from selenium.webdriver.firefox.options import Options

if __name__ == "__main__":
    options = Options()
    options.add_argument('-headless')
    driver = Firefox(executable_path='geckodriver', firefox_options=options) 
    wait = WebDriverWait(driver, timeout=10)
    driver.get('http://www.google.com')

Tested, works as expected and this is from Official - Headless Mode | Mozilla

Source file not compiled Dev C++

This maybe because the c compiler is designed to work in linux.I had this problem too and to fix it go to tools and select compiler options.In the box click on programs

Now you will see a tab with gcc and make and the respective path to it.Edit the gcc and make path to use mingw32-c++.exe and mingw32-make.exe respectively.Now it will work.

The Answer

The reason was that you were using compilers built for linux.

Cross-Domain Cookies

The smartest solution is to follow facebook's path on this. How does facebook know who you are when you visit any domain? It's actually very simple:

The Like button actually allows Facebook to track all visitors of the external site, no matter if they click it or not. Facebook can do that because they use an iframe to display the button. An iframe is something like an embedded browser window within a page. The difference between using an iframe and a simple image for the button is that the iframe contains a complete web page – from Facebook. There is not much going on on this page, except for the button and the information about how many people have liked the current page.

So when you see a like button on cnn.com, you are actually visiting a Facebook page at the same time. That allows Facebook to read a cookie on your computer, which it has created the last time you’ve logged in to Facebook.

A fundamental security rule in every browser is that only the website that has created a cookie can read it later on. And that is the advantage of the iframe: it allows Facebook to read your Facebook-cookie even when you are visiting a different website. That’s how they recognize you on cnn.com and display your friends there.

Source:

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.

After importing PDFKit, you should initialize a PDFView with a local or a remote URL and display it in your view.

if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
    let pdfView = PDFView(frame: view.frame)
    pdfView.document = PDFDocument(url: url)
    view.addSubview(pdfView)
}

Read more about PDFKit in the Apple Developer documentation.

How to use (install) dblink in PostgreSQL?

Installing modules usually requires you to run an sql script that is included with the database installation.

Assuming linux-like OS

find / -name dblink.sql

Verify the location and run it

Return a string method in C#

You forgot the () at the end. It is not a variable, but a function and when there are not parameters, you still need the () at the end.

For future coding practices, I would highly recommend reforming the code a little bit as this can become frustrating to read:

 public string LastName
 { get { return lastName; } set { lastName = value; } }

If there is any kind of processing which happens in here (thankfully doesn't happen here), it will become very confusing. If you're going to pass your code onto someone else, I would recommend:

public string LastName
{
  get
  {
     return lastName;
  }
  set
  {
     lastName = value;
  }
}

It's a lot longer, but it's much easier to read when glancing at a huge section of code.

How to fix a Div to top of page with CSS only

You can simply make the top div fixed:

#top { position: fixed; top: 20px; left: 20px; }

Warning about SSL connection when connecting to MySQL database

the new versions of mysql-connector establish SSL connection by default ...to solve it:

Download the older version of mysql-connector such as mysql-connector-java-5.0.8.zip

. . or . . Download OpenSSL for Windows and follow the instructions how to set it

For Restful API, can GET method use json data?

To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode). However, considering your reason for doing this is due to the length of the URI, using JSON will be self-defeating (introducing more characters than required).

I suggest you send your parameters in body of a POST request, either in regular CGI style (param1=val1&param2=val2) or JSON (parsed by your API upon receipt)

Distinct pair of values SQL

What you mean is either

SELECT DISTINCT a, b FROM pairs;

or

SELECT a, b FROM pairs GROUP BY a, b;

What causes a Python segmentation fault?

Google search found me this article, and I did not see the following "personal solution" discussed.


My recent annoyance with Python 3.7 on Windows Subsystem for Linux is that: on two machines with the same Pandas library, one gives me segmentation fault and the other reports warning. It was not clear which one was newer, but "re-installing" pandas solves the problem.

Command that I ran on the buggy machine.

conda install pandas

More details: I was running identical scripts (synced through Git), and both are Windows 10 machine with WSL + Anaconda. Here go the screenshots to make the case. Also, on the machine where command-line python will complain about Segmentation fault (core dumped), Jupyter lab simply restarts the kernel every single time. Worse still, no warning was given at all.

enter image description here


Updates a few months later: I quit hosting Jupyter servers on Windows machine. I now use WSL on Windows to fetch remote ports opened on a Linux server and run all my jobs on the remote Linux machine. I have never experienced any execution error for a good number of months :)

golang why don't we have a set datastructure

Partly, because Go doesn't have generics (so you would need one set-type for every type, or fall back on reflection, which is rather inefficient).

Partly, because if all you need is "add/remove individual elements to a set" and "relatively space-efficient", you can get a fair bit of that simply by using a map[yourtype]bool (and set the value to true for any element in the set) or, for more space efficiency, you can use an empty struct as the value and use _, present = the_setoid[key] to check for presence.

How do I auto size a UIScrollView to fit its content

Because a scrollView can have other scrollViews or different inDepth subViews tree, run in depth recursively is preferable. enter image description here

Swift 2

extension UIScrollView {
    //it will block the mainThread
    func recalculateVerticalContentSize_synchronous () {
        let unionCalculatedTotalRect = recursiveUnionInDepthFor(self)
        self.contentSize = CGRectMake(0, 0, self.frame.width, unionCalculatedTotalRect.height).size;
    }

    private func recursiveUnionInDepthFor (view: UIView) -> CGRect {
        var totalRect = CGRectZero
        //calculate recursevly for every subView
        for subView in view.subviews {
            totalRect =  CGRectUnion(totalRect, recursiveUnionInDepthFor(subView))
        }
        //return the totalCalculated for all in depth subViews.
        return CGRectUnion(totalRect, view.frame)
    }
}

Usage

scrollView.recalculateVerticalContentSize_synchronous()

Difference between 2 dates in SQLite

Difference In Days

Select Cast ((
    JulianDay(ToDate) - JulianDay(FromDate)
) As Integer)

Difference In Hours

Select Cast ((
    JulianDay(ToDate) - JulianDay(FromDate)
) * 24 As Integer)

Difference In Minutes

Select Cast ((
    JulianDay(ToDate) - JulianDay(FromDate)
) * 24 * 60 As Integer)

Difference In Seconds

Select Cast ((
    JulianDay(ToDate) - JulianDay(FromDate)
) * 24 * 60 * 60 As Integer)

Firebase Storage How to store and Retrieve images

You can also use a service called Filepicker which will store your image to their servers and Filepicker which is now called Filestack, will provide you with a url to the image. You can than store the url to Firebase.

Handling identity columns in an "Insert Into TABLE Values()" statement?

set identity_insert customer on
insert into Customer(id,Name,city,Salary) values(8,'bcd','Amritsar',1234)

where 'customer' is table name

How to use particular CSS styles based on screen size / device

@media queries serve this purpose. Here's an example:

@media only screen and (max-width: 991px) and (min-width: 769px){
 /* CSS that should be displayed if width is equal to or less than 991px and larger 
  than 768px goes here */
}

@media only screen and (max-width: 991px){
 /* CSS that should be displayed if width is equal to or less than 991px goes here */
}

fatal: The current branch master has no upstream branch

Well, I was having the same trouble while uploading and I resolved it by doing the same thing which it says to do: Earlier I was trying to push through terminal to my repository in linux by https like

git push https://github.com/SiddharthChoudhary/ClientServerCloudComputing.git

But was not getting any result and hence I went down deeper and tried:

git push --set-upstream https://github.com/SiddharthChoudhary/ClientServerCloudComputing.git master

And it worked. Thus then you will get prompted with username and password. I also generated a token and instead of Password I pasted the token and thus, being done successfully.

  1. To generate a token go to your Github account and in Developer Settings and then create another token.
  2. After getting that, copy that token and paste in the password prompt when it's been asked.

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

Turn off deprecated errors in PHP 5.3

You have to edit the PHP configuration file. Find the line

error_reporting = E_ALL

and replace it with:

error_reporting = E_ALL ^ E_DEPRECATED

If you don't have access to the configuration file you can add this line to the PHP WordPress file (maybe headers.php):

error_reporting(E_ALL ^ E_DEPRECATED);

XMLHttpRequest module not defined/found

Since the last update of the xmlhttprequest module was around 2 years ago, in some cases it does not work as expected.

So instead, you can use the xhr2 module. In other words:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

becomes:

var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();

But ... of course, there are more popular modules like Axios, because -for example- uses promises:

// Make a request for a user with a given ID
axios.get('/user?ID=12345').then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

How to make a HTML list appear horizontally instead of vertically using CSS only?

Using display: inline-flex

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  display: inline-flex_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using display: inline-block

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
#menu li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get temporary folder for current user

DO NOT use this:

System.Environment.GetEnvironmentVariable("TEMP")

Environment variables can be overridden, so the TEMP variable is not necessarily the directory.

The correct way is to use System.IO.Path.GetTempPath() as in the accepted answer.

HTML5 video - show/hide controls programmatically

<video id="myvideo">
  <source src="path/to/movie.mp4" />
</video>

<p onclick="toggleControls();">Toggle</p>

<script>
var video = document.getElementById("myvideo");

function toggleControls() {
  if (video.hasAttribute("controls")) {
     video.removeAttribute("controls")   
  } else {
     video.setAttribute("controls","controls")   
  }
}
</script>

See it working on jsFiddle: http://jsfiddle.net/dgLds/

Localhost : 404 not found

If your server is still listening on port 80, check the permission on the DocumentRoot folder and if DirectoryIndex file existed.

How to delete from multiple tables in MySQL?

To anyone reading this in 2017, this is how I've done something similar.

DELETE pets, pets_activities FROM pets inner join pets_activities
on pets_activities.id = pets.id WHERE pets.`order` > :order AND 
pets.`pet_id` = :pet_id

Generally, to delete rows from multiple tables, the syntax I follow is given below. The solution is based on an assumption that there is some relation between the two tables.

DELETE table1, table2 FROM table1 inner join table2 on table2.id = table1.id
WHERE [conditions]

Handling very large numbers in Python

You could do this for the fun of it, but other than that it's not a good idea. It would not speed up anything I can think of.

  • Getting the cards in a hand will be an integer factoring operation which is much more expensive than just accessing an array.

  • Adding cards would be multiplication, and removing cards division, both of large multi-word numbers, which are more expensive operations than adding or removing elements from lists.

  • The actual numeric value of a hand will tell you nothing. You will need to factor the primes and follow the Poker rules to compare two hands. h1 < h2 for such hands means nothing.

Matplotlib tight_layout() doesn't take into account figure suptitle

An alternative and simple to use solution is to adjust the coordinates of the suptitle text in the figure using the y argument in the call of suptitle (see the docs):

import numpy as np
import matplotlib.pyplot as plt

f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure()
fig.suptitle('Long Suptitle', y=1.05, fontsize=24)
plt.subplot(121)
plt.plot(f)
plt.title('Very Long Title 1', fontsize=20)
plt.subplot(122)
plt.plot(g)
plt.title('Very Long Title 2', fontsize=20)
plt.show()

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

If you support IE, for versions of Internet Explorer 8 and above, this:

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />

Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.

If you separate with semi-colon, it sets compatibility levels for different versions. For example:

<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />

Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:

<meta http-equiv="X-UA-Compatible" content="IE=8" />

This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

For this:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

It forces the browser the render at whatever the most recent version's standards are.

For more information, there is plenty to read about on MSDN,

How do I redirect output to a variable in shell?

Use the $( ... ) construct:

hash=$(genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5)

Comparing two files in linux terminal

You can also use:

sdiff file1 file2

To display differences side by side within your terminal!

Find the least number of coins required that can make any change from 1 to 99 cents

Example Program:

#include<stdio.h> 

    #define LEN 9 // array length
    int main(){
        int coins[LEN]={0,0,0,0,0,0,0,0,0}; // coin count
        int cointypes[LEN]={1000,500,100,50,20,10,5,2,1}; // declare your coins and note here {ASC order}   
        int sum =0; //temp variable for sum
        int inc=0; // for loop
        int amount=0; // for total amount
        printf("Enter Amount :");
        scanf("%d",&amount);
        while(sum<amount){
            if((sum+cointypes[inc])<=amount){
                   sum = sum+  cointypes[inc];
                    //printf("%d[1] - %d\n",cointypes[inc],sum);
                    //switch case to count number of notes and coin
                   switch(cointypes[inc]){
                    case 1000:
                           coins[0]++;
                           break;
                    case 500:
                           coins[1]++;
                           break;
                    case 100:
                           coins[2]++;
                           break;
                    case 50:
                           coins[3]++;
                           break;               
                    case 20:
                           coins[4]++; 
                           break;
                    case 10:
                           coins[5]++;
                           break;
                    case 5:
                           coins[6]++;
                           break;
                    case 2:
                           coins[7]++;
                           break;
                    case 1:
                           coins[8]++;
                           break;
                       }
                }else{
                   inc++;
                }
            }
        printf("note for %d in\n note 1000 * %d\n note 500 * %d\n note 100 * %d\n note 50 * %d\n note 20 * %d\n note 10 * %d\n coin 5 * %d\n coin 2 * %d\n coin 1 * %d\n",amount,coins[0],coins[1],coins[2],coins[3],coins[4],coins[5],coins[6],coins[7],coins[8]); 

    }

How do I edit SSIS package files?

Additional answer for Visual Studio 2012:

You can open .dtsx along with their corresponding .dtproj project files with the SQL Server Data Tools Business Intelligence (SSDT-BI) add-in:

http://blogs.msdn.com/b/mattm/archive/2013/03/07/sql-server-data-tools-business-intelligence-for-visual-studio-2012-released-online.aspx

http://www.microsoft.com/download/details.aspx?id=36843

If the projects were created with an earlier version they will require an upgrade.

I did have some hang ups installing this - the install would spin on "Install_VSTA2012_CPU32_Action" and similar steps. It wasn't until I did a repair inside of the same installer did it install completely.

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

Can't install nuget package because of "Failed to initialize the PowerShell host"

Had the same problem and this solved it for me (Powershell as admin):

Set-ItemProperty -Path HKLM:\Software\Policies\Microsoft\Windows\PowerShell -Name ExecutionPolicy -Value ByPass 

What does %s mean in a python format string?

%s indicates a conversion type of string when using python's string formatting capabilities. More specifically, %s converts a specified value to a string using the str() function. Compare this with the %r conversion type that uses the repr() function for value conversion.

Take a look at the docs for string formatting.

How do I implement a progress bar in C#?

The idea behind reporting progress with the background worker is through sending a 'percent completed' event. You are yourself responsible for determining somehow 'how much' work has been completed. Unfortunately this is often the most difficult part.

In your case, the bulk of the work is database-related. There is to my knowledge no way to get progress information from the DB directly. What you can try to do however, is split up the work dynamically. E.g., if you need to read a lot of data, a naive way to implement this could be.

  • Determine how many rows are to be retrieved (SELECT COUNT(*) FROM ...)
  • Divide the actual reading in smaller chunks, reporting progress every time one chunk is completed:

    for (int i = 0; i < count; i++)
    {
        bgWorker.ReportProgress((100 * i) / count);
        // ... (read data for step i)
    }
    

How to check if an element exists in the xml using xpath?

take look at my example

<tocheading language="EN"> 
     <subj-group> 
         <subject>Editors Choice</subject> 
         <subject>creative common</subject> 
     </subj-group> 
</tocheading> 

now how to check if creative common is exist

tocheading/subj-group/subject/text() = 'creative common'

hope this help you

How to search a list of tuples in Python

Just another way.

zip(*a)[0].index(53)

What is a regular expression for a MAC Address?

As a MAC address can be 6 or 20 bytes (infiniband, ...) the correct answer is:

^([0-9A-Fa-f]{2}:){5}(([0-9A-Fa-f]{2}:){14})?([0-9A-Fa-f]{2})$

you can replace : with [:-.]? if you want different separators or none.

Using jQuery, Restricting File Size Before Uploading

This is a copy from my answers in a very similar question: How to check file input size with jQuery?


You actually don't have access to the filesystem (for example reading and writing local files). However, due to the HTML5 File API specification, there are some file properties that you do have access to, and the file size is one of them.

For this HTML:

<input type="file" id="myFile" />

try the following:

//binds to onchange event of your input field
$('#myFile').bind('change', function() {
  //this.files[0].size gets the size of your file.
  alert(this.files[0].size);
});

As it is a part of the HTML5 specification, it will only work for modern browsers (v10 required for IE) and I added here more details and links about other file information you should know: http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/


Old browsers support

Be aware that old browsers will return a null value for the previous this.files call, so accessing this.files[0] will raise an exception and you should check for File API support before using it

LINQ: Select where object does not contain items from list

I have not tried this, so I am not guarantueeing anything, however

foreach Bar f in filterBars
{
     search(f)
}
Foo search(Bar b)
{
    fooSelect = (from f in fooBunch
                 where !(from b in f.BarList select b.BarId).Contains(b.ID)
                 select f).ToList();

    return fooSelect;
}

JSON order mixed up

Just add the order with this tag

@JsonPropertyOrder({ "property1", "property2"})

Android: textview hyperlink

This is my working implementation

private void showMessage()
    {

        lblMessage.setText("");

        List<String> messages = db.getAllGCMMessages();

        for (int k = messages.size() - 1; k >= 0; --k)
         {

            String message  =  messages.get(k).toString();
            lblMessage.append(message + "\n\n");

         }
     Linkify.addLinks(lblMessage, Linkify.ALL);
  }

and to change color of hyperlinks , i editted my xml for textview -

 android:textColorLink="#69463d"

Xcode source automatic formatting

You can also have a look at https://github.com/octo-online/Xcode-formatter which is a formatter based on Uncrustify and integrated into Xcode. Works like a charm.

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

Working fiddle:

http://jsfiddle.net/repjt/

$.ajax({
    url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
    dataType: 'JSONP',
    jsonpCallback: 'callback',
    type: 'GET',
    success: function (data) {
        console.log(data);
    }
});

I had to manually set the callback to callback, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.

Android: How do I prevent the soft keyboard from pushing my view up?

None of them worked for me, try this one

 private void scrollingWhileKeyboard() {
    drawerlayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

            Rect r = new Rect();
            try {
                drawerlayout.getWindowVisibleDisplayFrame(r);
                int screenHeight = drawerlayout.getRootView().getHeight();
                int keypadHeight = screenHeight - r.bottom;
                if (keypadHeight > screenHeight * 0.15) {
                    tabLayout.setVisibility(View.GONE);
                } else {
                    tabLayout.setVisibility(View.VISIBLE);
                }
            } catch (NullPointerException e) {

            }
        }
    });

}

converting multiple columns from character to numeric format in r

I realize this is an old thread but wanted to post a solution similar to your request for a function (just ran into the similar issue myself trying to format an entire table to percentage labels).

Assume you have a df with 5 character columns you want to convert. First, I create a table containing the names of the columns I want to manipulate:

col_to_convert <- data.frame(nrow = 1:5
                            ,col = c("col1","col2","col3","col4","col5"))

for (i in 1:max(cal_to_convert$row))
  {
    colname <- col_to_convert$col[i]
    colnum <- which(colnames(df) == colname)
        for (j in 1:nrow(df))
          {
           df[j,colnum] <- as.numericdf(df[j,colnum])
          }
  }

This is not ideal for large tables as it goes cell by cell, but it would get the job done.

How to dynamic new Anonymous Class?

Of cause it's possible to create dynamic classes using very cool ExpandoObject class. But recently I worked on project and faced that Expando Object is serealized in not the same format on xml as an simple Anonymous class, it was pity =( , that is why I decided to create my own class and share it with you. It's using reflection and dynamic directive , builds Assembly, Class and Instance truly dynamicly. You can add, remove and change properties that is included in your class on fly Here it is :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using static YourNamespace.DynamicTypeBuilderTest;

namespace YourNamespace
{

    /// This class builds Dynamic Anonymous Classes

    public class DynamicTypeBuilderTest
    {    
        ///   
        /// Create instance based on any Source class as example based on PersonalData
        ///
        public static object CreateAnonymousDynamicInstance(PersonalData personalData, Type dynamicType, List<ClassDescriptorKeyValue> classDescriptionList)
        {
            var obj = Activator.CreateInstance(dynamicType);

            var propInfos = dynamicType.GetProperties();

            classDescriptionList.ForEach(x => SetValueToProperty(obj, propInfos, personalData, x));

            return obj;
        }

        private static void SetValueToProperty(object obj, PropertyInfo[] propInfos, PersonalData aisMessage, ClassDescriptorKeyValue description)
        {
            propInfos.SingleOrDefault(x => x.Name == description.Name)?.SetValue(obj, description.ValueGetter(aisMessage), null);
        }

        public static dynamic CreateAnonymousDynamicType(string entityName, List<ClassDescriptorKeyValue> classDescriptionList)
        {
            AssemblyName asmName = new AssemblyName();
            asmName.Name = $"{entityName}Assembly";
            AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndCollect);

            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule($"{asmName.Name}Module");

            TypeBuilder typeBuilder = moduleBuilder.DefineType($"{entityName}Dynamic", TypeAttributes.Public);

            classDescriptionList.ForEach(x => CreateDynamicProperty(typeBuilder, x));

            return typeBuilder.CreateTypeInfo().AsType();
        }

        private static void CreateDynamicProperty(TypeBuilder typeBuilder, ClassDescriptorKeyValue description)
        {
            CreateDynamicProperty(typeBuilder, description.Name, description.Type);
        }

        ///
        ///Creation Dynamic property (from MSDN) with some Magic
        ///
        public static void CreateDynamicProperty(TypeBuilder typeBuilder, string name, Type propType)
        {
            FieldBuilder fieldBuider = typeBuilder.DefineField($"{name.ToLower()}Field",
                                                            propType,
                                                            FieldAttributes.Private);

            PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(name,
                                                             PropertyAttributes.HasDefault,
                                                             propType,
                                                             null);

            MethodAttributes getSetAttr =
                MethodAttributes.Public | MethodAttributes.SpecialName |
                    MethodAttributes.HideBySig;

            MethodBuilder methodGetBuilder =
                typeBuilder.DefineMethod($"get_{name}",
                                           getSetAttr,
                                           propType,
                                           Type.EmptyTypes);

            ILGenerator methodGetIL = methodGetBuilder.GetILGenerator();

            methodGetIL.Emit(OpCodes.Ldarg_0);
            methodGetIL.Emit(OpCodes.Ldfld, fieldBuider);
            methodGetIL.Emit(OpCodes.Ret);

            MethodBuilder methodSetBuilder =
                typeBuilder.DefineMethod($"set_{name}",
                                           getSetAttr,
                                           null,
                                           new Type[] { propType });

            ILGenerator methodSetIL = methodSetBuilder.GetILGenerator();

            methodSetIL.Emit(OpCodes.Ldarg_0);
            methodSetIL.Emit(OpCodes.Ldarg_1);
            methodSetIL.Emit(OpCodes.Stfld, fieldBuider);
            methodSetIL.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(methodGetBuilder);
            propertyBuilder.SetSetMethod(methodSetBuilder);

        }

        public class ClassDescriptorKeyValue
        {
            public ClassDescriptorKeyValue(string name, Type type, Func<PersonalData, object> valueGetter)
            {
                Name = name;
                ValueGetter = valueGetter;
                Type = type;
            }

            public string Name;
            public Type Type;
            public Func<PersonalData, object> ValueGetter;
        }

        ///
        ///Your Custom class description based on any source class for example
        /// PersonalData
        public static IEnumerable<ClassDescriptorKeyValue> GetAnonymousClassDescription(bool includeAddress, bool includeFacebook)
        {
            yield return new ClassDescriptorKeyValue("Id", typeof(string), x => x.Id);
            yield return new ClassDescriptorKeyValue("Name", typeof(string), x => x.FirstName);
            yield return new ClassDescriptorKeyValue("Surname", typeof(string), x => x.LastName);
            yield return new ClassDescriptorKeyValue("Country", typeof(string), x => x.Country);
            yield return new ClassDescriptorKeyValue("Age", typeof(int?), x => x.Age);
            yield return new ClassDescriptorKeyValue("IsChild", typeof(bool), x => x.Age < 21);

            if (includeAddress)
                yield return new ClassDescriptorKeyValue("Address", typeof(string), x => x?.Contacts["Address"]);
            if (includeFacebook)
                yield return new ClassDescriptorKeyValue("Facebook", typeof(string), x => x?.Contacts["Facebook"]);
        }

        ///
        ///Source Data Class for example
        /// of cause you can use any other class
        public class PersonalData
        { 
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Country { get; set; }
            public int Age { get; set; }

            public Dictionary<string, string> Contacts { get; set; }
        }

    }
}

It is also very simple to use DynamicTypeBuilder, you just need put few lines like this:

    public class ExampleOfUse
    {
        private readonly bool includeAddress;
        private readonly bool includeFacebook;
        private readonly dynamic dynamicType;
        private readonly List<ClassDescriptorKeyValue> classDiscriptionList;
        public ExampleOfUse(bool includeAddress = false, bool includeFacebook = false)
        {
            this.includeAddress = includeAddress;
            this.includeFacebook = includeFacebook;
            this.classDiscriptionList = DynamicTypeBuilderTest.GetAnonymousClassDescription(includeAddress, includeFacebook).ToList();
            this.dynamicType = DynamicTypeBuilderTest.CreateAnonymousDynamicType("VeryPrivateData", this.classDiscriptionList);
        }

        public object Map(PersonalData privateInfo)
        {
            object dynamicObject = DynamicTypeBuilderTest.CreateAnonymousDynamicInstance(privateInfo, this.dynamicType, classDiscriptionList);

            return dynamicObject;
        }

    }

I hope that this code snippet help somebody =) Enjoy!

How can I get a Dialog style activity window to fill the screen?

I found the solution:

In your activity which has the Theme.Dialog style set, do this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.your_layout);

    getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

It's important that you call Window.setLayout() after you call setContentView(), otherwise it won't work.

How can you create multiple cursors in Visual Studio Code

There is no binding for exactly what you want.

The only thing that comes close is Ctrl+F2 which will select all of them at once.

You can bind it to Ctrl+D doing the following:

  • Click on File > Preferences > Keyboard Shortcuts
    You should see a pane full of the current bindings and on the right a list of custom bindings
  • In the current bindings, search for Ctrl+F2 and copy that whole line and paste it into the right pane.
  • You might have to remove the comma at the end and then change Ctrl+F2 to Ctrl+D and then save the file.

It should look something like this:

// Place your key bindings in this file to overwrite the defaults
[
{ "key": "ctrl+d",               "command": "editor.action.changeAll",
                                    "when": "editorTextFocus" }
]

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

I have a project in React Native and suddenly this error appeared. I was doing something with homebrew beforehand and this solved the issue for me:

brew update
brew upgrade
brew cleanup

How do I sort a Set to a List in Java?

There's no single method to do that. Use this:

@SuppressWarnings("unchecked")
public static <T extends Comparable> List<T> asSortedList(Collection<T> collection) {
  T[] array = collection.toArray(
    (T[])new Comparable[collection.size()]);
  Arrays.sort(array);
  return Arrays.asList(array);
}

Best practices with STDIN in Ruby?

I'll add that in order to use ARGF with parameters, you need to clear ARGV before calling ARGF.each. This is because ARGF will treat anything in ARGV as a filename and read lines from there first.

Here's an example 'tee' implementation:

File.open(ARGV[0], 'w') do |file|
  ARGV.clear

  ARGF.each do |line|
    puts line
    file.write(line)
  end
end

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

Yes there is one and it is inside the SQLServer management studio. Unlike the previous versions I think. Follow these simple steps.

1)Right click on a database in the Object explorer 2)Selected New Query from the popup menu 3)Query Analyzer will be opened.

Enjoy work.

jQuery validation plugin: accept only alphabetical characters?

Be careful,

jQuery.validator.addMethod("lettersonly", function(value, element) 
{
return this.optional(element) || /^[a-z," "]+$/i.test(value);
}, "Letters and spaces only please"); 

[a-z, " "] by adding the comma and quotation marks, you are allowing spaces, commas and quotation marks into the input box.

For spaces + text, just do this:

jQuery.validator.addMethod("lettersonly", function(value, element) 
{
return this.optional(element) || /^[a-z ]+$/i.test(value);
}, "Letters and spaces only please");

[a-z ] this allows spaces aswell as text only.

............................................................................

also the message "Letters and spaces only please" is not required, if you already have a message in messages:

messages:{
        firstname:{
        required: "Enter your first name",
        minlength: jQuery.format("Enter at least (2) characters"),
        maxlength:jQuery.format("First name too long more than (80) characters"),
        lettersonly:jQuery.format("letters only mate")
        },

Adam

Jquery: how to trigger click event on pressing enter key

$('#txtSearchProdAssign').keypress(function (e) {
  if (e.which == 13) {
    $('input[name = butAssignProd]').click();
    return false;  
  }
});

I also just found Submitting a form on 'Enter' which covers most of the issues comprehensively.

android lollipop toolbar: how to hide/show the toolbar while scrolling?

As far as I know there is nothing build in that does this for you. However you could have a look at the Google IO sourcecode, especially the BaseActivity. Search for "auto hide" or look at onMainContentScrolled

In order to hide the Toolbar your can just do something like this:

toolbar.animate().translationY(-toolbar.getBottom()).setInterpolator(new AccelerateInterpolator()).start();

If you want to show it again you call:

toolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator()).start();

Interface naming in Java

Is this a broader naming convention in any real sense? I'm more on the C++ side, and not really up on Java and descendants. How many language communities use the I convention?

If you have a language-independent shop standard naming convention here, use it. If not, go with the language naming convention.

How can I stage and commit all files, including newly added files, using a single command?

I use this function:

gcaa() { git add --all && git commit -m "$*" }

In my zsh config file, so i can just do:

> gcaa This is the commit message

To automatically stage and commit all files.

Sorting rows in a data table

This will help you...

DataTable dt = new DataTable();         
dt.DefaultView.Sort = "Column_name desc";
dt = dt.DefaultView.ToTable();

How to set the width of a RaisedButton in Flutter?

match_parent (Full width):

SizedBox(
  width: double.infinity, // <-- match_parent
  child: RaisedButton(...)
)

Specific width:

SizedBox(
  width: 100, // <-- Your width
  child: RaisedButton(...)
)

Set new id with jQuery

Use .val() not attr('value').

Convert varchar to uniqueidentifier in SQL Server

SELECT CONVERT(uniqueidentifier,STUFF(STUFF(STUFF(STUFF('B33D42A3AC5A4D4C81DD72F3D5C49025',9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-'))

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

Adding to what deceze said above. This is a parse error, so in order to debug a parse error, create a new file in the root named debugSyntax.php. Put this in it:

<?php

///////    SYNTAX ERROR CHECK    ////////////
error_reporting(E_ALL);
ini_set('display_errors','On');

//replace "pageToTest.php" with the file path that you want to test. 
include('pageToTest.php'); 

?>

Run the debugSyntax.php page and it will display parse errors from the page that you chose to test.

time data does not match format

No need to use datetime library. Using the dateutil library there is no need of any format:

>>> from dateutil import parser
>>> s= '25 April, 2020, 2:50, pm, IST'
>>> parser.parse(s)
datetime.datetime(2020, 4, 25, 14, 50)

What does the restrict keyword mean in C++?

In his paper, Memory Optimization, Christer Ericson says that while restrict is not part of the C++ standard yet, that it is supported by many compilers and he recommends it's usage when available:

restrict keyword

! New to 1999 ANSI/ISO C standard

! Not in C++ standard yet, but supported by many C++ compilers

! A hint only, so may do nothing and still be conforming

A restrict-qualified pointer (or reference)...

! ...is basically a promise to the compiler that for the scope of the pointer, the target of the pointer will only be accessed through that pointer (and pointers copied from it).

In C++ compilers that support it it should probably behave the same as in C.

See this SO post for details: Realistic usage of the C99 ‘restrict’ keyword?

Take half an hour to skim through Ericson's paper, it's interesting and worth the time.

Edit

I also found that IBM's AIX C/C++ compiler supports the __restrict__ keyword.

g++ also seems to support this as the following program compiles cleanly on g++:

#include <stdio.h>

int foo(int * __restrict__ a, int * __restrict__ b) {
    return *a + *b;
}

int main(void) {
    int a = 1, b = 1, c;

    c = foo(&a, &b);

    printf("c == %d\n", c);

    return 0;
}

I also found a nice article on the use of restrict:

Demystifying The Restrict Keyword

Edit2

I ran across an article which specifically discusses the use of restrict in C++ programs:

Load-hit-stores and the __restrict keyword

Also, Microsoft Visual C++ also supports the __restrict keyword.

How to Get a Sublist in C#

You want List::GetRange(firstIndex, count). See http://msdn.microsoft.com/en-us/library/21k0e39c.aspx

// I have a List called list
List sublist = list.GetRange(5, 5); // (gets elements 5,6,7,8,9)
List anotherSublist = list.GetRange(0, 4); // gets elements 0,1,2,3)

Is that what you're after?

If you're looking to delete the sublist items from the original list, you can then do:

// list is our original list
// sublist is our (newly created) sublist built from GetRange()
foreach (Type t in sublist)
{
    list.Remove(t);
}

Java LinkedHashMap get first or last entry

For first element use entrySet().iterator().next() and stop iterating after 1 iteration. For last one the easiest way is to preserve the key in a variable whenever you do a map.put.

Saving an Excel sheet in a current directory with VBA

Taking this one step further, to save a file to a relative directory, you can use the replace function. Say you have your workbook saved in: c:\property\california\sacramento\workbook.xlsx, use this to move the property to berkley:

workBookPath = Replace(ActiveWorkBook.path, "sacramento", "berkley")
myWorkbook.SaveAs(workBookPath & "\" & "newFileName.xlsx"

Only works if your file structure contains one instance of the text used to replace. YMMV.

What Does This Mean in PHP -> or =>

-> is used to call a method, or access a property, on the object of a class

=> is used to assign values to the keys of an array

E.g.:

    $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34, 1=>2); 

And since PHP 7.4+ the operator => is used too for the added arrow functions, a more concise syntax for anonymous functions.

How do you parse and process HTML/XML in PHP?

Just use DOMDocument->loadHTML() and be done with it. libxml's HTML parsing algorithm is quite good and fast, and contrary to popular belief, does not choke on malformed HTML.

Get only specific attributes with from Laravel Collection

this seems to work, but not sure if it's optimized for performance or not.

$request->user()->get(['id'])->groupBy('id')->keys()->all();

output:

array:2 [
  0 => 4
  1 => 1
]

What is the "right" JSON date format?

it is work for me with parse Server

{
    "ContractID": "203-17-DC0101-00003-10011",
    "Supplier":"Sample Co., Ltd",
    "Value":12345.80,
    "Curency":"USD",
    "StartDate": {
                "__type": "Date",
                "iso": "2017-08-22T06:11:00.000Z"
            }
}

UDP vs TCP, how much faster is it?

Which protocol performs better (in terms of throughput) - UDP or TCP - really depends on the network characteristics and the network traffic. Robert S. Barnes, for example, points out a scenario where TCP performs better (small-sized writes). Now, consider a scenario in which the network is congested and has both TCP and UDP traffic. Senders in the network that are using TCP, will sense the 'congestion' and cut down on their sending rates. However, UDP doesn't have any congestion avoidance or congestion control mechanisms, and senders using UDP would continue to pump in data at the same rate. Gradually, TCP senders would reduce their sending rates to bare minimum and if UDP senders have enough data to be sent over the network, they would hog up the majority of bandwidth available. So, in such a case, UDP senders will have greater throughput, as they get the bigger pie of the network bandwidth. In fact, this is an active research topic - How to improve TCP throughput in presence of UDP traffic. One way, that I know of, using which TCP applications can improve throughput is by opening multiple TCP connections. That way, even though, each TCP connection's throughput might be limited, the sum total of the throughput of all TCP connections may be greater than the throughput for an application using UDP.

text-align: right on <select> or <option>

The following CSS will right-align both the arrow and the options:

_x000D_
_x000D_
select { text-align-last: right; }_x000D_
option { direction: rtl; }
_x000D_
<!-- example usage -->_x000D_
Choose one: <select>_x000D_
  <option>The first option</option>_x000D_
  <option>A second, fairly long option</option>_x000D_
  <option>Last</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Undefined reference to pthread_create in Linux

You need to use the option -lpthread with gcc.

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

Changing Font Size For UITableView Section Headers

While mosca1337's answer is a correct solution, be careful with that method. For a header with text longer than one line, you will have to perform the calculations of the height of the header in tableView:heightForHeaderInSection: which can be cumbersome.

A much preferred method is to use the appearance API:

[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setFont:[UIFont boldSystemFontOfSize:28]];

This will change the font, while still leaving the table to manage the heights itself.

For optimal results, subclass the table view, and add it to the containment chain (in appearanceWhenContainedIn:) to make sure the font is only changed for the specific table views.

Cross-Origin Read Blocking (CORB)

 dataType:'jsonp',

You are making a JSONP request, but the server is responding with JSON.

The browser is refusing to try to treat the JSON as JSONP because it would be a security risk. (If the browser did try to treat the JSON as JSONP then it would, at best, fail).

See this question for more details on what JSONP is. Note that is a nasty hack to work around the Same Origin Policy that was used before CORS was available. CORS is a much cleaner, safer, and more powerful solution to the problem.


It looks like you are trying to make a cross-origin request and are throwing everything you can think of at it in one massive pile of conflicting instructions.

You need to understand how the Same Origin policy works.

See this question for an in-depth guide.


Now a few notes about your code:

contentType: 'application/json',
  • This is ignored when you use JSONP
  • You are making a GET request. There is no request body to describe the type of.
  • This will make a cross-origin request non-simple, meaning that as well as basic CORS permissions, you also need to deal with a pre-flight.

Remove that.

 dataType:'jsonp',
  • The server is not responding with JSONP.

Remove this. (You could make the server respond with JSONP instead, but CORS is better).

responseType:'application/json',

This is not an option supported by jQuery.ajax. Remove this.

xhrFields: { withCredentials: false },

This is the default. Unless you are setting it to true with ajaxSetup, remove this.

  headers: {
    'Access-Control-Allow-Credentials' : true,
    'Access-Control-Allow-Origin':'*',
    'Access-Control-Allow-Methods':'GET',
    'Access-Control-Allow-Headers':'application/json',
  },
  • These are response headers. They belong on the response, not the request.
  • This will make a cross-origin request non-simple, meaning that as well as basic CORS permissions, you also need to deal with a pre-flight.

How can I update NodeJS and NPM to the next versions?

When it comes to Linux I suggest an Update Node Using a Package Manager:

Node comes with npm pre-installed, but the manager is updated more frequently than Node. Run npm -v to see which version you have, then npm install npm@latest -g to install the newest npm update. Run npm -v again if you want to make sure npm updated correctly.

To update NodeJS, you’ll need npm’s handy n module. Run this code to clear npm’s cache, install n, and install the latest stable version of Node:

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

To install the latest release, use n latest. Alternatively, you can run n #.#.# to get a specific Node version.


When it comes to Windows/ macOS I suggest using Installers on Nodejs.org

The Node.js downloads page includes binary packages for Windows and macOS — but why make your life more difficult? The pre-made installers — .msi for Windows and .pkg for macOS — make the installation process unbelievably efficient and understandable. Download and run the file, and let the installation wizard take care of the rest. With each downloaded update, the newer versions of Node and npm will replace the older version.

Alternatively, macOS users can use the npm and n instructions above.


When it comes to updating your node_modules dependencies folder, I suggest skipping all the things that could cause you a headache and just go to your specific project and re-run npm install again.

Before anyone does that, I suggest first checking your package.json file for the following:

As a user of NodeJS packages, you can specify which kinds of updates your app can accept in the package.json file. For example, if you were starting with a package version 1.0.4, this is how you could specify the allowed update version ranges in three basic ways:

To Allow Patch Releases: 1.0 or 1.0.x or ~1.0.4
To Allow Minor Releases: 1 or 1.x or ^1.0.4
To Allow Major Releases: * or x

Explanation:

MAJOR version for when there are incompatible API changes. --> ~

MINOR version for when functionality is added in a backwards compatible manner. --> ^

PATCH version for when backward compatible bug fixes are done. --> *

Understanding Spring @Autowired usage

TL;DR

The @Autowired annotation spares you the need to do the wiring by yourself in the XML file (or any other way) and just finds for you what needs to be injected where and does that for you.

Full explanation

The @Autowired annotation allows you to skip configurations elsewhere of what to inject and just does it for you. Assuming your package is com.mycompany.movies you have to put this tag in your XML (application context file):

<context:component-scan base-package="com.mycompany.movies" />

This tag will do an auto-scanning. Assuming each class that has to become a bean is annotated with a correct annotation like @Component (for simple bean) or @Controller (for a servlet control) or @Repository (for DAO classes) and these classes are somewhere under the package com.mycompany.movies, Spring will find all of these and create a bean for each one. This is done in 2 scans of the classes - the first time it just searches for classes that need to become a bean and maps the injections it needs to be doing, and on the second scan it injects the beans. Of course, you can define your beans in the more traditional XML file or with an @Configuration class (or any combination of the three).

The @Autowired annotation tells Spring where an injection needs to occur. If you put it on a method setMovieFinder it understands (by the prefix set + the @Autowired annotation) that a bean needs to be injected. In the second scan, Spring searches for a bean of type MovieFinder, and if it finds such bean, it injects it to this method. If it finds two such beans you will get an Exception. To avoid the Exception, you can use the @Qualifier annotation and tell it which of the two beans to inject in the following manner:

@Qualifier("redBean")
class Red implements Color {
   // Class code here
}

@Qualifier("blueBean")
class Blue implements Color {
   // Class code here
}

Or if you prefer to declare the beans in your XML, it would look something like this:

<bean id="redBean" class="com.mycompany.movies.Red"/>

<bean id="blueBean" class="com.mycompany.movies.Blue"/>

In the @Autowired declaration, you need to also add the @Qualifier to tell which of the two color beans to inject:

@Autowired
@Qualifier("redBean")
public void setColor(Color color) {
  this.color = color;
}

If you don't want to use two annotations (the @Autowired and @Qualifier) you can use @Resource to combine these two:

@Resource(name="redBean")
public void setColor(Color color) {
  this.color = color;
}

The @Resource (you can read some extra data about it in the first comment on this answer) spares you the use of two annotations and instead, you only use one.

I'll just add two more comments:

  1. Good practice would be to use @Inject instead of @Autowired because it is not Spring-specific and is part of the JSR-330 standard.
  2. Another good practice would be to put the @Inject / @Autowired on a constructor instead of a method. If you put it on a constructor, you can validate that the injected beans are not null and fail fast when you try to start the application and avoid a NullPointerException when you need to actually use the bean.

Update: To complete the picture, I created a new question about the @Configuration class.

How do I combine the first character of a cell with another cell in Excel?

=CONCATENATE(LEFT(A1,1), B1)

Assuming A1 holds 1st names; B1 Last names

Create zip file and ignore directory structure

Using -j won't work along with the -r option.
So the work-around for it can be this:

cd path/to/parent/dir/;
zip -r complete/path/to/name.zip ./* ;
cd -;

Or in-line version

cd path/to/parent/dir/ && zip -r complete/path/to/name.zip ./* && cd -

you can direct the output to /dev/null if you don't want the cd - output to appear on screen

How do I vertically center text with CSS?

You can easily do this by adding the following piece of CSS code:

display: table-cell;
vertical-align: middle;

That means your CSS finally looks like:

_x000D_
_x000D_
#box {_x000D_
  height: 90px;_x000D_
  width: 270px;_x000D_
  background: #000;_x000D_
  font-size: 48px;_x000D_
  font-style: oblique;_x000D_
  color: #FFF;_x000D_
  text-align: center;_x000D_
  margin-top: 20px;_x000D_
  margin-left: 5px;_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<div id="box">_x000D_
  Some text_x000D_
</div>
_x000D_
_x000D_
_x000D_

Getting index value on razor foreach

Is there a reason you're not using CSS selectors to style the first and last elements instead of trying to attach a custom class to them? Instead of styling based on alpha or omega, use first-child and last-child.

http://www.quirksmode.org/css/firstchild.html

Sending simple message body + file attachment using Linux Mailx

Try this it works for me:

(echo "Hello XYX" ; uuencode /export/home/TOTAL_SI_COUNT_10042016.csv TOTAL_SI_COUNT_10042016.csv ) | mailx -s 'Script test' [email protected]

How to get a view table query (code) in SQL Server 2008 Management Studio

Additionally, if you have restricted access to the database (IE: Can't use "Script Function as > CREATE To"), there is another option to get this query.

Find your View > right click > "Design".

This will give you the query you are looking for.

How can I select item with class within a DIV?

You'll do it the same way you would apply a css selector. For instanse you can do

$("#mydiv > .myclass")

or

$("#mydiv .myclass")

The last one will match every myclass inside myDiv, including myclass inside myclass.

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

Yes, thats right.

You can get an idea by the usage of these two.

If you need to tell that you are finished with some work and other (threads) waiting for this can now proceed, you should use ManualResetEvent.

If you need to have mutual exclusive access to any resource, you should use AutoResetEvent.

Update records in table from CTE

WITH CTE_DocTotal (DocTotal, InvoiceNumber)
AS
(
    SELECT  InvoiceNumber,
            SUM(Sale + VAT) AS DocTotal
    FROM    PEDI_InvoiceDetail
    GROUP BY InvoiceNumber
)    
UPDATE PEDI_InvoiceDetail
SET PEDI_InvoiceDetail.DocTotal = CTE_DocTotal.DocTotal
FROM CTE_DocTotal
INNER JOIN PEDI_InvoiceDetail ON ...