Programs & Examples On #Efpocoadapter

How to trim a string to N chars in Javascript?

Copying Will's comment into an answer, because I found it useful:

var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ? 
                    string.substring(0, length - 3) + "..." : 
                    string;

Thanks Will.

And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)

Docker - Container is not running

docker run -it --entrypoint /bin/bash <imageid>

This was posted by L0j1k in the below post and worked for me.

How do I get into a Docker container's shell?

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

I think you have Two ways to solve this problem

01. Set Properties

  • Set Java Build Path as jdk

Right click project ->Java Build Path ->Select Libraries tab ->Select JRE System Library ->Click Edit button ->Click Installed JREs-> add tick to box ->click Edit ->Click Directory->Select jdk

  • Specifi which kind of jdk version you installed

Right click project ->Project Facets ->tick java and select java version->Apply ->Ok

  • Update project

Right-click on "project"->Go to Maven->Update

02.Delete .m2 file

If you can't solve your problem using above two topic get this action Close your project. Delete your full .m2 folder

How to fined .m2 file(windows)

Go to Local Disk(C) ->Users ->Select your PC name ->.m2 file

How to delete columns in pyspark dataframe

Adding to @Patrick's answer, you can use the following to drop multiple columns

columns_to_drop = ['id', 'id_copy']
df = df.drop(*columns_to_drop)

Adding hours to JavaScript Date object?

This is a easy way to get incremented or decremented data value.

const date = new Date()
const inc = 1000 * 60 * 60 // an hour
const dec = (1000 * 60 * 60) * -1 // an hour

const _date = new Date(date)
return new Date( _date.getTime() + inc )
return new Date( _date.getTime() + dec )

Self-reference for cell, column and row in worksheet functions

where F13 is the cell you need to reference:

=CELL("Row",F13)  yields 13; its row number

=CELL("Col",F13)  yields 6; its column number;  

=SUBSTITUTE(ADDRESS(1,COLUMN(F13)*1,4),"1","") yields F; its column letter

How does the FetchMode work in Spring Data JPA

I elaborated on dream83619 answer to make it handle nested Hibernate @Fetch annotations. I used recursive method to find annotations in nested associated classes.

So you have to implement custom repository and override getQuery(spec, domainClass, sort) method. Unfortunately you also have to copy all referenced private methods :(.

Here is the code, copied private methods are omitted.
EDIT: Added remaining private methods.

@NoRepositoryBean
public class EntityGraphRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> {

    private final EntityManager em;
    protected JpaEntityInformation<T, ?> entityInformation;

    public EntityGraphRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
        super(entityInformation, entityManager);
        this.em = entityManager;
        this.entityInformation = entityInformation;
    }

    @Override
    protected <S extends T> TypedQuery<S> getQuery(Specification<S> spec, Class<S> domainClass, Sort sort) {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<S> query = builder.createQuery(domainClass);

        Root<S> root = applySpecificationToCriteria(spec, domainClass, query);

        query.select(root);
        applyFetchMode(root);

        if (sort != null) {
            query.orderBy(toOrders(sort, root, builder));
        }

        return applyRepositoryMethodMetadata(em.createQuery(query));
    }

    private Map<String, Join<?, ?>> joinCache;

    private void applyFetchMode(Root<? extends T> root) {
        joinCache = new HashMap<>();
        applyFetchMode(root, getDomainClass(), "");
    }

    private void applyFetchMode(FetchParent<?, ?> root, Class<?> clazz, String path) {
        for (Field field : clazz.getDeclaredFields()) {
            Fetch fetch = field.getAnnotation(Fetch.class);

            if (fetch != null && fetch.value() == FetchMode.JOIN) {
                FetchParent<?, ?> descent = root.fetch(field.getName(), JoinType.LEFT);
                String fieldPath = path + "." + field.getName();
                joinCache.put(path, (Join) descent);

                applyFetchMode(descent, field.getType(), fieldPath);
            }
        }
    }

    /**
     * Applies the given {@link Specification} to the given {@link CriteriaQuery}.
     *
     * @param spec can be {@literal null}.
     * @param domainClass must not be {@literal null}.
     * @param query must not be {@literal null}.
     * @return
     */
    private <S, U extends T> Root<U> applySpecificationToCriteria(Specification<U> spec, Class<U> domainClass,
        CriteriaQuery<S> query) {

        Assert.notNull(query);
        Assert.notNull(domainClass);
        Root<U> root = query.from(domainClass);

        if (spec == null) {
            return root;
        }

        CriteriaBuilder builder = em.getCriteriaBuilder();
        Predicate predicate = spec.toPredicate(root, query, builder);

        if (predicate != null) {
            query.where(predicate);
        }

        return root;
    }

    private <S> TypedQuery<S> applyRepositoryMethodMetadata(TypedQuery<S> query) {
        if (getRepositoryMethodMetadata() == null) {
            return query;
        }

        LockModeType type = getRepositoryMethodMetadata().getLockModeType();
        TypedQuery<S> toReturn = type == null ? query : query.setLockMode(type);

        applyQueryHints(toReturn);

        return toReturn;
    }

    private void applyQueryHints(Query query) {
        for (Map.Entry<String, Object> hint : getQueryHints().entrySet()) {
            query.setHint(hint.getKey(), hint.getValue());
        }
    }

    public Class<T> getEntityType() {
        return entityInformation.getJavaType();
    }

    public EntityManager getEm() {
        return em;
    }
}

How to uninstall mini conda? python

In order to uninstall miniconda, simply remove the miniconda folder,

rm -r ~/miniconda/

As for avoiding conflicts between different Python environments, you can use virtual environments. In particular, with Miniconda, the following workflow could be used,

$ wget https://repo.continuum.io/miniconda/Miniconda3-3.7.0-Linux-x86_64.sh -O ~/miniconda.sh
$ bash miniconda
$ conda env remove --yes -n new_env    # remove the environement new_env if it exists (optional)
$ conda create --yes -n new_env pip numpy pandas scipy matplotlib scikit-learn nltk ipython-notebook seaborn python=2
$ activate new_env
$ # pip install modules if needed, run python scripts, etc
  # everything will be installed in the new_env
  # located in ~/miniconda/envs/new_env
$ deactivate

Inverse of matrix in R

solve(c) does give the correct inverse. The issue with your code is that you are using the wrong operator for matrix multiplication. You should use solve(c) %*% c to invoke matrix multiplication in R.

R performs element by element multiplication when you invoke solve(c) * c.

How to specify jdk path in eclipse.ini on windows 8 when path contains space

Even if your %JAVA_HOME% contains spaces, you can directly put entire string over there.

-vm
C:\Program Files (x86)\Java\jdk1.8.0_162\bin

Also, you don't have to specify javaw.exe in the path, just mention it till bin it will find javaw.exe in bin folder by itself. Just keep one thing in mind that the jdk version you provide should match with the eclipse version you are using.

If you are using a 64 bit java then download 64 bit Eclipse. If you are using a 32 bit java then download 32 bit Eclipse.

Replace all occurrences of a string in a data frame

If you are only looking to replace all occurrences of "< " (with space) with "<" (no space), then you can do an lapply over the data frame, with a gsub for replacement:

> data <- data.frame(lapply(data, function(x) {
+                  gsub("< ", "<", x)
+              }))
> data
  name var1 var2
1    a   <2   <3
2    a   <2   <3
3    a   <2   <3
4    b   <2   <3
5    b   <2   <3
6    b   <2   <3
7    c   <2   <3
8    c   <2   <3
9    c   <2   <3

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

In my case the issue resolved on commenting the tomcat dependencies exclusion from spring-boot-starte-web

     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <!-- <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions> -->
    </dependency> 

How to validate Google reCAPTCHA v3 on server side?

Here you have simple example. Just remember to provide secretKey and siteKey from google api.

<?php
$siteKey = 'Provide element from google';
$secretKey = 'Provide element from google';

if($_POST['submit']){
    $username = $_POST['username'];
    $responseKey = $_POST['g-recaptcha-response'];
    $userIP = $_SERVER['REMOTE_ADDR'];
    $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
    $response = file_get_contents($url);
    $response = json_decode($response);
    if($response->success){
        echo "Verification is correct. Your name is $username";
    } else {
        echo "Verification failed";
    }
} ?>

<html>
<meta>
    <title>Google ReCaptcha</title>
</meta>
<body>
    <form action="index.php" method="post">
        <input type="text" name="username" placeholder="Write your name"/>
        <div class="g-recaptcha" data-sitekey="<?= $siteKey ?>"></div>
        <input type="submit" name="submit" value="send"/>
    </form>
    <script src='https://www.google.com/recaptcha/api.js'></script>
</body>

Finding the index of an item in a list

Simply you can go with

a = [['hand', 'head'], ['phone', 'wallet'], ['lost', 'stock']]
b = ['phone', 'lost']

res = [[x[0] for x in a].index(y) for y in b]

Configure cron job to run every 15 minutes on Jenkins

1) Your cron is wrong. If you want to run job every 15 mins on Jenkins use this:

H/15 * * * *

2) Warning from Jenkins Spread load evenly by using ‘...’ rather than ‘...’ came with JENKINS-17311:

To allow periodically scheduled tasks to produce even load on the system, the symbol H (for “hash”) should be used wherever possible. For example, using 0 0 * * * for a dozen daily jobs will cause a large spike at midnight. In contrast, using H H * * * would still execute each job once a day, but not all at the same time, better using limited resources.

Examples:

  • H/15 * * * * - every fifteen minutes (perhaps at :07, :22, :37, :52):
  • H(0-29)/10 * * * * - every ten minutes in the first half of every hour (three times, perhaps at :04, :14, :24)
  • H 9-16/2 * * 1-5 - once every two hours every weekday (perhaps at 10:38 AM, 12:38 PM, 2:38 PM, 4:38 PM)
  • H H 1,15 1-11 * - once a day on the 1st and 15th of every month except December

How to get the contents of a webpage in a shell variable?

You can use curl or wget to retrieve the raw data, or you can use w3m -dump to have a nice text representation of a web page.

$ foo=$(w3m -dump http://www.example.com/); echo $foo
You have reached this web page by typing "example.com", "example.net","example.org" or "example.edu" into your web browser. These domain names are reserved for use in documentation and are not available for registration. See RFC 2606, Section 3.

xls to csv converter

First read your excel spreadsheet into pandas, below code will import your excel spreadsheet into pandas as a OrderedDict type which contain all of your worksheet as dataframes. Then simply use worksheet_name as a key to access specific worksheet as a dataframe and save only required worksheet as csv file by using df.to_csv(). Hope this will workout in your case.

import pandas as pd
df = pd.read_excel('YourExcel.xlsx', sheet_name=None)
df['worksheet_name'].to_csv('YourCsv.csv')  

If your Excel file contain only one worksheet then simply use below code:

import pandas as pd
df = pd.read_excel('YourExcel.xlsx')
df.to_csv('YourCsv.csv') 

If someone want to convert all the excel worksheets from single excel workbook to the different csv files, try below code:

import pandas as pd
def excelTOcsv(filename):
    df = pd.read_excel(filename, sheet_name=None)  
    for key, value in df.items(): 
        return df[key].to_csv('%s.csv' %key)

This function is working as a multiple Excel sheet of same excel workbook to multiple csv file converter. Where key is the sheet name and value is the content inside sheet.

Laravel eloquent update record without loading from database

You can simply use Query Builder rather than Eloquent, this code directly update your data in the database :) This is a sample:

DB::table('post')
            ->where('id', 3)
            ->update(['title' => "Updated Title"]);

You can check the documentation here for more information: http://laravel.com/docs/5.0/queries#updates

Android activity life cycle - what are all these methods for?

Adding some more info on top of highly rated answer (Added additional section of KILLABLE and next set of methods, which are going to be called in the life cycle):

Source: developer.android.com

enter image description here

Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed.

Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created.

Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

I would like to add few more methods. These are not listed as life cycle methods but they will be called during life cycle depending on some conditions. Depending on your requirement, you may have to implement these methods in your application for proper handling of state.

onPostCreate(Bundle savedInstanceState)

Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called).

onPostResume()

Called when activity resume is complete (after onResume() has been called).

onSaveInstanceState(Bundle outState)

Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

onRestoreInstanceState(Bundle savedInstanceState)

This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState.

My application code using all these methods:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText txtUserName;
    private EditText txtPassword;
    Button  loginButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("Ravi","Main OnCreate");
        txtUserName=(EditText) findViewById(R.id.username);
        txtPassword=(EditText) findViewById(R.id.password);
        loginButton =  (Button)  findViewById(R.id.login);
        loginButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        Log.d("Ravi", "Login processing initiated");
        Intent intent = new Intent(this,LoginActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("userName",txtUserName.getText().toString());
        bundle.putString("password",txtPassword.getText().toString());
        intent.putExtras(bundle);
        startActivityForResult(intent,1);
       // IntentFilter
    }
    public void onActivityResult(int requestCode, int resultCode, Intent resIntent){
        Log.d("Ravi back result:", "start");
        String result = resIntent.getStringExtra("result");
        Log.d("Ravi back result:", result);
        TextView txtView = (TextView)findViewById(R.id.txtView);
        txtView.setText(result);

        Intent sendIntent = new Intent();
        //sendIntent.setPackage("com.whatsapp");
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, "Message...");
        sendIntent.setType("text/plain");
        startActivity(sendIntent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Ravi","Main Start");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Ravi","Main ReStart");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Ravi","Main Pause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Ravi","Main Resume");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Ravi","Main Stop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Ravi","Main OnDestroy");
    }

    @Override
    public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onPostCreate(savedInstanceState, persistentState);
        Log.d("Ravi","Main onPostCreate");
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        Log.d("Ravi","Main PostResume");
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }
}

Login Activity:

public class LoginActivity extends AppCompatActivity {

    private TextView txtView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        txtView = (TextView) findViewById(R.id.Result);
        Log.d("Ravi","Login OnCreate");
        Bundle bundle = getIntent().getExtras();
        txtView.setText(bundle.getString("userName")+":"+bundle.getString("password"));
        //Intent  intent = new Intent(this,MainActivity.class);
        Intent  intent = new Intent();
        intent.putExtra("result","Success");
        setResult(1,intent);
       // finish();
    }
}

output: ( Before pause)

D/Ravi: Main OnCreate
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume

output: ( After resume from pause)

D/Ravi: Main ReStart
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume

Note that onPostResume() is invoked even though it's not quoted as life cycle method.

Comparing two hashmaps for equal values and same key sets?

public boolean compareMap(Map<String, String> map1, Map<String, String> map2) {

    if (map1 == null || map2 == null)
        return false;

    for (String ch1 : map1.keySet()) {
        if (!map1.get(ch1).equalsIgnoreCase(map2.get(ch1)))
            return false;

    }
    for (String ch2 : map2.keySet()) {
        if (!map2.get(ch2).equalsIgnoreCase(map1.get(ch2)))
            return false;

    }

    return true;
}

How to Clear Console in Java?

If you are using windows and are interested in clearing the screen before running the program, you can compile the file call it from a .bat file. for example:


cls

java "what ever the name of the compiles class is"


Save as "etc".bat and then running by calling it in the command prompt or double clicking the file

Convert a String representation of a Dictionary to a dictionary?

To OP's example:

s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"

We can use Yaml to deal with this kind of non-standard json in string:

>>> import yaml
>>> s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
>>> s
"{'muffin' : 'lolz', 'foo' : 'kitty'}"
>>> yaml.load(s)
{'muffin': 'lolz', 'foo': 'kitty'}

How to open my files in data_folder with pandas using relative path?

With python or pandas when you use read_csv or pd.read_csv, both of them look into current working directory, by default where the python process have started. So you need to use os module to chdir() and take it from there.

import pandas as pd 
import os
print(os.getcwd())
os.chdir("D:/01Coding/Python/data_sets/myowndata")
print(os.getcwd())
df = pd.read_csv('data.csv',nrows=10)
print(df.head())

Stack Memory vs Heap Memory

Stack memory is specifically the range of memory that is accessible via the Stack register of the CPU. The Stack was used as a way to implement the "Jump-Subroutine"-"Return" code pattern in assembly language, and also as a means to implement hardware-level interrupt handling. For instance, during an interrupt, the Stack was used to store various CPU registers, including Status (which indicates the results of an operation) and Program Counter (where was the CPU in the program when the interrupt occurred).

Stack memory is very much the consequence of usual CPU design. The speed of its allocation/deallocation is fast because it is strictly a last-in/first-out design. It is a simple matter of a move operation and a decrement/increment operation on the Stack register.

Heap memory was simply the memory that was left over after the program was loaded and the Stack memory was allocated. It may (or may not) include global variable space (it's a matter of convention).

Modern pre-emptive multitasking OS's with virtual memory and memory-mapped devices make the actual situation more complicated, but that's Stack vs Heap in a nutshell.

How to Copy Text to Clip Board in Android?

In Kotlin I have an extension for this

fun Context.copyToClipboard(text: String) {
  val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
  val clip =
    ClipData.newPlainText(getString(R.string.copy_clipboard_label, getString(R.string.app_name)),text)
  clipboard.setPrimaryClip(clip)
}

python modify item in list, save back in list

For Python 3:

ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
    ListOfStrings[idx] = "bar"

Make div 100% Width of Browser Window

If width:100% works in any cases, just use that, otherwise you can use vw in this case which is relative to 1% of the width of the viewport.

That means if you want to cover off the width, just use 100vw.

Look at the image I draw for you here:

enter image description here

Try the snippet I created for you as below:

_x000D_
_x000D_
.full-width {_x000D_
  width: 100vw;_x000D_
  height: 100px;_x000D_
  margin-bottom: 40px;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.one-vw-width {_x000D_
  width: 1vw;_x000D_
  height: 100px;_x000D_
  background-color: red;_x000D_
}
_x000D_
<div class="full-width"></div>_x000D_
<div class="one-vw-width"></div>
_x000D_
_x000D_
_x000D_

Reversing an Array in Java

Collections.reverse() can do that job for you if you put your numbers in a List of Integers.

List<Integer> list = Arrays.asList(1, 4, 9, 16, 9, 7, 4, 9, 11);
System.out.println(list);
Collections.reverse(list);
System.out.println(list);

Output:

[1, 4, 9, 16, 9, 7, 4, 9, 11]
[11, 9, 4, 7, 9, 16, 9, 4, 1]

what's the correct way to send a file from REST web service to client?

Since youre using JSON, I would Base64 Encode it before sending it across the wire.

If the files are large, try to look at BSON, or some other format that is better with binary transfers.

You could also zip the files, if they compress well, before base64 encoding them.

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

<p:commandXxx process> <p:ajax process> <f:ajax execute>

The process attribute is server side and can only affect UIComponents implementing EditableValueHolder (input fields) or ActionSource (command fields). The process attribute tells JSF, using a space-separated list of client IDs, which components exactly must be processed through the entire JSF lifecycle upon (partial) form submit.

JSF will then apply the request values (finding HTTP request parameter based on component's own client ID and then either setting it as submitted value in case of EditableValueHolder components or queueing a new ActionEvent in case of ActionSource components), perform conversion, validation and updating the model values (EditableValueHolder components only) and finally invoke the queued ActionEvent (ActionSource components only). JSF will skip processing of all other components which are not covered by process attribute. Also, components whose rendered attribute evaluates to false during apply request values phase will also be skipped as part of safeguard against tampered requests.

Note that it's in case of ActionSource components (such as <p:commandButton>) very important that you also include the component itself in the process attribute, particularly if you intend to invoke the action associated with the component. So the below example which intends to process only certain input component(s) when a certain command component is invoked ain't gonna work:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="foo" action="#{bean.action}" />

It would only process the #{bean.foo} and not the #{bean.action}. You'd need to include the command component itself as well:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@this foo" action="#{bean.action}" />

Or, as you apparently found out, using @parent if they happen to be the only components having a common parent:

<p:panel><!-- Type doesn't matter, as long as it's a common parent. -->
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@parent" action="#{bean.action}" />
</p:panel>

Or, if they both happen to be the only components of the parent UIForm component, then you can also use @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@form" action="#{bean.action}" />
</h:form>

This is sometimes undesirable if the form contains more input components which you'd like to skip in processing, more than often in cases when you'd like to update another input component(s) or some UI section based on the current input component in an ajax listener method. You namely don't want that validation errors on other input components are preventing the ajax listener method from being executed.

Then there's the @all. This has no special effect in process attribute, but only in update attribute. A process="@all" behaves exactly the same as process="@form". HTML doesn't support submitting multiple forms at once anyway.

There's by the way also a @none which may be useful in case you absolutely don't need to process anything, but only want to update some specific parts via update, particularly those sections whose content doesn't depend on submitted values or action listeners.

Noted should be that the process attribute has no influence on the HTTP request payload (the amount of request parameters). Meaning, the default HTML behavior of sending "everything" contained within the HTML representation of the <h:form> will be not be affected. In case you have a large form, and want to reduce the HTTP request payload to only these absolutely necessary in processing, i.e. only these covered by process attribute, then you can set the partialSubmit attribute in PrimeFaces Ajax components as in <p:commandXxx ... partialSubmit="true"> or <p:ajax ... partialSubmit="true">. You can also configure this 'globally' by editing web.xml and add

<context-param>
    <param-name>primefaces.SUBMIT</param-name>
    <param-value>partial</param-value>
</context-param>

Alternatively, you can also use <o:form> of OmniFaces 3.0+ which defaults to this behavior.

The standard JSF equivalent to the PrimeFaces specific process is execute from <f:ajax execute>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Also, it may be useful to know that <p:commandXxx process> defaults to @form while <p:ajax process> and <f:ajax execute> defaults to @this. Finally, it's also useful to know that process supports the so-called "PrimeFaces Selectors", see also How do PrimeFaces Selectors as in update="@(.myClass)" work?


<p:commandXxx update> <p:ajax update> <f:ajax render>

The update attribute is client side and can affect the HTML representation of all UIComponents. The update attribute tells JavaScript (the one responsible for handling the ajax request/response), using a space-separated list of client IDs, which parts in the HTML DOM tree need to be updated as response to the form submit.

JSF will then prepare the right ajax response for that, containing only the requested parts to update. JSF will skip all other components which are not covered by update attribute in the ajax response, hereby keeping the response payload small. Also, components whose rendered attribute evaluates to false during render response phase will be skipped. Note that even though it would return true, JavaScript cannot update it in the HTML DOM tree if it was initially false. You'd need to wrap it or update its parent instead. See also Ajax update/render does not work on a component which has rendered attribute.

Usually, you'd like to update only the components which really need to be "refreshed" in the client side upon (partial) form submit. The example below updates the entire parent form via @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@form" />
</h:form>

(note that process attribute is omitted as that defaults to @form already)

Whilst that may work fine, the update of input and command components is in this particular example unnecessary. Unless you change the model values foo and bar inside action method (which would in turn be unintuitive in UX perspective), there's no point of updating them. The message components are the only which really need to be updated:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="foo_m bar_m" />
</h:form>

However, that gets tedious when you have many of them. That's one of the reasons why PrimeFaces Selectors exist. Those message components have in the generated HTML output a common style class of ui-message, so the following should also do:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@(.ui-message)" />
</h:form>

(note that you should keep the IDs on message components, otherwise @(...) won't work! Again, see How do PrimeFaces Selectors as in update="@(.myClass)" work? for detail)

The @parent updates only the parent component, which thus covers the current component and all siblings and their children. This is more useful if you have separated the form in sane groups with each its own responsibility. The @this updates, obviously, only the current component. Normally, this is only necessary when you need to change one of the component's own HTML attributes in the action method. E.g.

<p:commandButton action="#{bean.action}" update="@this" 
    oncomplete="doSomething('#{bean.value}')" />

Imagine that the oncomplete needs to work with the value which is changed in action, then this construct wouldn't have worked if the component isn't updated, for the simple reason that oncomplete is part of generated HTML output (and thus all EL expressions in there are evaluated during render response).

The @all updates the entire document, which should be used with care. Normally, you'd like to use a true GET request for this instead by either a plain link (<a> or <h:link>) or a redirect-after-POST by ?faces-redirect=true or ExternalContext#redirect(). In effects, process="@form" update="@all" has exactly the same effect as a non-ajax (non-partial) submit. In my entire JSF career, the only sensible use case I encountered for @all is to display an error page in its entirety in case an exception occurs during an ajax request. See also What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?

The standard JSF equivalent to the PrimeFaces specific update is render from <f:ajax render>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Both update and render defaults to @none (which is, "nothing").


See also:

How to resolve /var/www copy/write permission denied?

You just have to write sudo instead of su.

Then just copy the PHP file to the var/www/ directory.

Then go to the browser, and write local host/test.php or whatever the .php filename is.

How can I use mySQL replace() to replace strings in multiple records?

This will help you.

UPDATE play_school_data SET title= REPLACE(title, "&#39;", "'") WHERE title = "Elmer&#39;s Parade";

Result:

title = Elmer's Parade

Nodejs cannot find installed module on Windows

For me worked on Windows 10 npm config set prefix %AppData%\npm\node_modules

Multiple selector chaining in jQuery?

There are already very good answers here, but in some other cases (not this in particular) using map could be the "only" solution.

Specially when we want to use regexps, other than the standard ones.

For this case it would look like this:

 $('.myClass').filter(function(index, elem) {
    var jElem = $(elem);

    return jElem.closest('#Create').length > 0 || 
           jElem.closest('#Edit').length > 0;

}).plugin(...);

As I said before, here this solution could be useless, but for further problems, is a very good option

SQL Server Operating system error 5: "5(Access is denied.)"

For me it was solved in the following way with SQL Server Management studio -Log in as admin (I logged in as windows authentication) -Attach the mdf file (right click Database | attach | Add ) -Log out as admin -Log in as normal user

CSS Styling for a Button: Using <input type="button> instead of <button>

In your .button CSS, try display:inline-block. See this JSFiddle

Regular Expression to match only alphabetic characters

You may use any of these 2 variants:

/^[A-Z]+$/i
/^[A-Za-z]+$/

to match an input string of ASCII alphabets.

  • [A-Za-z] will match all the alphabets (both lowercase and uppercase).
  • ^ and $ will make sure that nothing but these alphabets will be matched.

Code:

preg_match('/^[A-Z]+$/i', "abcAbc^Xyz", $m);
var_dump($m);

Output:

array(0) {
}

Test case is for OP's comment that he wants to match only if there are 1 or more alphabets present in the input. As you can see in the test case that matches failed because there was ^ in the input string abcAbc^Xyz.

Note: Please note that the above answer only matches ASCII alphabets and doesn't match Unicode characters. If you want to match Unicode letters then use:

/^\p{L}+$/u

Here, \p{L} matches any kind of letter from any language

How to set a default entity property value with Hibernate

what about just setting a default value for the field?

private String _foo = "default";

//property here
public String Foo

if they pass a value, then it will be overwritten, otherwise, you have a default.

node.js - request - How to "emitter.setMaxListeners()"?

This is how I solved the problem:

In main.js of the 'request' module I added one line:

Request.prototype.request = function () {
  var self = this
  self.setMaxListeners(0); // Added line

This defines unlimited listeners http://nodejs.org/docs/v0.4.7/api/events.html#emitter.setMaxListeners

In my code I set the 'maxRedirects' value explicitly:

var options = {uri:headingUri, headers:headerData, maxRedirects:100};

Select default option value from typescript angular 6

First or all you are using ng-model which is considered to be an angularjs syntax. Use [(ngModel)] instead with the default value

App.component.html

<select [(ngModel)]='nrSelect' class='form-control'>
    <option value='47'>47</option>
    <option value='46'>46</option>
    <option value='45'>45</option>
</select>

App.component.ts

import { Component } from '@angular/core'; 
@Component({ 
    selector: 'my-app', 
    templateUrl: './app.component.html', 
    styleUrls: [ './app.component.css' ] 
}) 

export class AppComponent { 
    nrSelect:string = "47" 
}

How to make the tab character 4 spaces instead of 8 spaces in nano?

If you use nano with a language like python (as in your example) it's also a good idea to convert tabs to spaces.

Edit your ~/.nanorc file (or create it) and add:

set tabsize 4
set tabstospaces

If you already got a file with tabs and want to convert them to spaces i recommend the expandcommand (shell):

expand -4 input.py > output.py

Send Email Intent

This is the proper way to send the e-mail intent according to the Android Developer Official Documentation

Add these lines of code to your app:

Intent intent = new Intent(Intent.ACTION_SEND);//common intent 
intent.setData(Uri.parse("mailto:")); // only email apps should handle this

Optional: Add the body and subject, like this

intent.putExtra(Intent.EXTRA_SUBJECT, "Your Subject Here");
intent.putExtra(Intent.EXTRA_TEXT, "E-mail body" );

You already added this line in your question

intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});

This will be the recipient's address, meaning the user will send you (the developer) an e-mail.

Temporarily disable all foreign key constraints

There is a easy way to this.

-- Disable all the constraint in database
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'

-- Enable all the constraint in database
EXEC sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'

Reference SQL SERVER – Disable All the Foreign Key Constraint in Database – Enable All the Foreign Key Constraint in Database

How to sort a list of objects based on an attribute of the objects?

from operator import attrgetter
ut.sort(key = attrgetter('count'), reverse = True)

'Source code does not match the bytecode' when debugging on a device

Android Studio takes source version equal to Target Version in your application. Compilation performed with source version equal to above mentioned Compile Version. So, take care that in your project Compile Version == Target Version (adjust module's build.gradle file).

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

$resource("../rest/api"}).get();

returns an object.

$resource("../rest/api").query();

returns an array.

You must use :

return $resource('../rest/api.php?method=getTask&q=*').query();

How can I make my string property nullable?

C# 8.0 is published now so you can make reference types nullable too. For this you have to add

#nullable enable

Feature over your namespace. It is detailed here

For example something like this will work:

#nullable enable
namespace TestCSharpEight
{
  public class Developer
  {
    public string FullName { get; set; }
    public string UserName { get; set; }

    public Developer(string fullName)
    {
        FullName = fullName;
        UserName = null;
    }
}}

Also you can have a look this nice article from John Skeet that explains details.

How do I convert hex to decimal in Python?

If by "hex data" you mean a string of the form

s = "6a48f82d8e828ce82b82"

you can use

i = int(s, 16)

to convert it to an integer and

str(i)

to convert it to a decimal string.

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

This error because mysql is trying to connect via wrong socket file

try this command for MAMP servers

cd /var/mysql && sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock

or

cd /tmp && sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock

and this commands for XAMPP servers

    cd /var/mysql && sudo ln -s /Applications/XAMPP/tmp/mysql/mysql.sock

or

    cd /tmp && sudo ln -s /Applications/XAMPP/tmp/mysql/mysql.sock

How to get PID by process name?

Complete example based on the excellent @Hackaholic's answer:

def get_process_id(name):
    """Return process ids found by (partial) name or regex.

    >>> get_process_id('kthreadd')
    [2]
    >>> get_process_id('watchdog')
    [10, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61]  # ymmv
    >>> get_process_id('non-existent process')
    []
    """
    child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
    response = child.communicate()[0]
    return [int(pid) for pid in response.split()]

Makefile: How to correctly include header file and its directory?

These lines in your makefile,

INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)
DEPS = split.h

and this line in your .cpp file,

#include "StdCUtil/split.h"

are in conflict.

With your makefile in your source directory and with that -I option you should be using #include "split.h" in your source file, and your dependency should be ../StdCUtil/split.h.

Another option:

INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)/..  # Ugly!
DEPS = $(INC_DIR)/split.h

With this your #include directive would remain as #include "StdCUtil/split.h".

Yet another option is to place your makefile in the parent directory:

root
  |____Makefile
  |
  |___Core
  |     |____DBC.cpp
  |     |____Lock.cpp
  |     |____Trace.cpp
  |
  |___StdCUtil
        |___split.h

With this layout it is common to put the object files (and possibly the executable) in a subdirectory that is parallel to your Core and StdCUtil directories. Object, for example. With this, your makefile becomes:

INC_DIR = StdCUtil
SRC_DIR = Core
OBJ_DIR = Object
CFLAGS  = -c -Wall -I.
SRCS = $(SRC_DIR)/Lock.cpp $(SRC_DIR)/DBC.cpp $(SRC_DIR)/Trace.cpp
OBJS = $(OBJ_DIR)/Lock.o $(OBJ_DIR)/DBC.o $(OBJ_DIR)/Trace.o
# Note: The above will soon get unwieldy.
# The wildcard and patsubt commands will come to your rescue.

DEPS = $(INC_DIR)/split.h
# Note: The above will soon get unwieldy.
# You will soon want to use an automatic dependency generator.


all: $(OBJS)

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
  $(CC) $(CFLAGS) -c $< -o $@

$(OBJ_DIR)/Trace.o: $(DEPS)

System.BadImageFormatException: Could not load file or assembly

Try to configure the setting of your projects, it is usually due to x86/x64 architecture problems:

Go and set your choice as shown:

CSS filter: make color image with transparency white

To my knowledge, there is sadly no CSS filter to colorise an element (perhaps with the use of some SVG filter magic, but I'm somewhat unfamiliar with that) and even if that wasn't the case, filters are basically only supported by webkit browsers.

With that said, you could still work around this and use a canvas to modify your image. Basically, you can draw an image element onto a canvas and then loop through the pixels, modifying the respective RGBA values to the colour you want.

However, canvases do come with some restrictions. Most importantly, you have to make sure that the image src comes from the same domain as the page. Otherwise the browser won't allow you to read or modify the pixel data of the canvas.

Here's a JSFiddle changing the colour of the JSFiddle logo.

_x000D_
_x000D_
//Base64 source, but any local source will work_x000D_
var src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAgCAYAAACGhPFEAAAABGdBTUEAALGPC/xhBQAABzhJREFUWAnNWAtwXFUZ/v9zs4GUJJu+k7tb5DFAGWO1aal1sJUiY3FQQaWidqgPLAMqYzd9CB073VodhCa7KziiFgWhzvAYQCiCD5yK4gOTDnZK2ymdZoruppu0afbu0pBs7p7f7yy96W662aw2QO/Mzj2P//Gd/5z/+89dprfzubnTN332Re+xiKawllxWucm+9O4eCi9xT8ctn45yKd3AXX1BPsu3XIiuY+K5kDmrUA7jORb5m2baLm7uscNrJr9eOF9Je8JAz9ySnFHlq9nEpG6CYx+RdJDQDtKymxT1iWZLFDUy0/kkfDUxzYVzV0hvHZLs946Gph+uBLCRmRDQdjTVwmw9DZCNMPi4KzqWbPX/sxwIu71vlrKq10HnZizwTSFZngj5f1NOx5s7bdB2LHWDEusBOD487LrX9qyd8qpnvJL3zGjqAh+pR4W4RVhu715Vv2U8PTWeQLn5YHvms4qsR4TpH/ImLfhfARvbPaGGrrjTtwjH5hFFfHcgkv5SOZ9mbvxIgwGaZl+8ULGcJ8zOsJa9R1r9B2d8v2eGb1KNieqBhLNz8ekyAoV3VAX985+FvSXEenF8lf9lA7DUUxa0HUl/RTG1EfOUQmUwwCtggDewiHmc1R+Ir/MfKJz/f9tTwn31Nf7qVxlHLR6qXwg7cHXqU/p4hPdUB6Lp55TiXwDYTsrpG12dbdY5t0WLrCSRSVjIItG0dqIAG2jHwlPTmvQdsL3Ajjg3nAq3zIgdS98ZiGV0MJZeWVJs2WNWIJK5hcLh0osuqVTxIAdi6X3w/0LFGoa+AtFMzo5kflix0gQLBiLOZmAYro84RcfSc3NKpFAcliM9eYDdjZ7QO/1mRc+CTapqFX+4lO9TQEPoUpz//anQ5FQphXdizB1QXXk/moOl/JUC7aLMDpQSHj02PdxbG9xybM60u47UjZ4bq290Zm451ky3HSi6kxTKJ9fXHQVvZJm1XTjutYsozw53T1L+2ufBGPMTe/c30M/mD3uChW+c+6tQttthuBnbqMBLKGbydI54/eFQ3b5CWa/dGMl8xFJ0D/rvg1Pjdxil+2XK5b6ZWD15lyfnvYOxTBYs9TrY5NbuUENRUo5EGtGyVUNtBwBfDjA/IDtTkiNRsdYD8O+NcVN2KUfXo3UnukvA6Z3I+mWeY++NpNoAwDvAv1Uiss7oiNBmYD+XraoO0NvnPVnvrbUsA4CcYusPgajzY2/cvN+KtOFl/6w/IWrvdTV/Ktla92KhkNcOxpwPCqm/IgLbEvteW1m4E2/d8iY9AZOXQ/7WxKq6nxq9YNT5OLF6DmAfTHT13EL3XjTk2csXk4bqX2OXWiQ73Jz49tS4N5d/oxoHLr14EzPfAf1IIlS/2oznIx1omLURhL5Qa1oxFuC8EeHb8U6I88bXCwGbuZ61jb2Jgz1XYUHb0b0vEHNWmHE9lNsjWrcmnMhNhYDNnCkmNJSFHFdzte82M1b04HgC6HrYbAPw1pFdNOc4GE334wz9qkihRAdK/0HBub/E1MkhJBiq6V8gq7Htm05OjN2C/z/jCP1xbAlCwcnsAsbdkGHF/trPIcoNrtbjFRNmoama6EgZ42SimRG5FjLHWakNwWjmirLyZpLpKH7TysghZ00OUHNTxFmK2yDNQSKlx7u0Q0GQeLtQdy4rY5zMzqVb/ccoJ/OQMEmoPWW3988to4NY8DxYf6WMDCW6ktuRvFqxmqewgguhdLCcwsic0DMA8lE7kvrYyFhBw446X2B/nRNo739/YnX9azKUXYCg9CtlvdAUyywuEB1p4gh9AzbPZc0mF8Z+sINgn0MIwiVgKcAG6rGlT86AMdqw2n8ppR63o+mveQXCFAxzX2BWD0P6pcT+g3uNlmEDV3JX4iOh1xICdWU2gGXOMXN5HfRhK4IoPxlfXQfmKf+Ajh1I+MEeHMcKzqvoxoZsHsoOXgP+fEkxbw1e2JhB0h2q9tc4OL/fAVdsdd3jnyhklmRo8qGBQXchIvMMKPW7Pt85/SM66CNmDw1mh75cHu6JWZFZxNLNSJTPIM5PuJquKEt3o6zmqyJZH4LTC7CIfTonO5Jr/B2jxIq6jW3OZVYVX4edDSD6e1BAXqwgl/I2miKp+ZayOkT0CjaJww21/2bhznio7uoiL2dQB8HdhoV++ri4AdUdtgfw789mRHspzulXzyCcI1BMVQXgL5LodnP7zFfE+N9/9yOUyedxTn/SFHWWj0ifAY1ANHUleOJRlPqdCUmbO85J1jjxUfkUkgVCsg1/uGw0n/fvFm67LT2NLTLfi98Cke8dpMGl3r9QxVRnPuPrWzaIUmsAtgas0okd6ETh7AYt5d7+BeCbhfKVcQ6CtwgJjjoiP3fdgVbcbY57/otBnxidfndvo6/67BtxUf4kztJsbMg0CJaU9QxN2FskhePQBWr7La6wvzRFarTtyoBgB4hm5M//aAMT2+/Vlfzp81/vywLMWSBN1QAAAABJRU5ErkJggg==";_x000D_
var canvas = document.getElementById("theCanvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image;_x000D_
_x000D_
//wait for the image to load_x000D_
img.onload = function() {_x000D_
    //Draw the original image so that you can fetch the colour data_x000D_
    ctx.drawImage(img,0,0);_x000D_
    var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);_x000D_
    _x000D_
    /*_x000D_
    imgData.data is a one-dimensional array which contains _x000D_
    the respective RGBA values for every pixel _x000D_
    in the selected region of the context _x000D_
    (note i+=4 in the loop)_x000D_
    */_x000D_
    _x000D_
    for (var i = 0; i < imgData.data.length; i+=4) {_x000D_
   imgData.data[i] = 255; //Red, 0-255_x000D_
   imgData.data[i+1] = 255; //Green, 0-255_x000D_
   imgData.data[i+2] = 255; //Blue, 0-255_x000D_
   /* _x000D_
   imgData.data[i+3] contains the alpha value_x000D_
   which we are going to ignore and leave_x000D_
   alone with its original value_x000D_
   */_x000D_
    }_x000D_
    ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the original image_x000D_
    ctx.putImageData(imgData, 0, 0); //paint the new colorised image_x000D_
}_x000D_
_x000D_
//Load the image!_x000D_
img.src = src;
_x000D_
body {_x000D_
    background: green;_x000D_
}
_x000D_
<canvas id="theCanvas"></canvas>
_x000D_
_x000D_
_x000D_

How do I link to Google Maps with a particular longitude and latitude?

As of today (1st November, 2020), Google provided a provision of Universal URL which works quite efficiently on cross-platforms and thus, Google recommends this method.

Syntax: https://www.google.com/maps/search/?api=1&query=<lat>,<lng>

Example : https://www.google.com/maps/search/?api=1&query=28.6139,77.2090 (New Delhi, India)

Documentation/Source.

Correct Semantic tag for copyright info - html5

The <footer> tag seems like a good candidate:

<footer>&copy; 2011 Some copyright message</footer>

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

How about adding this to your pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>${jackson.version}</version>
</dependency>

Plot width settings in ipython notebook

This is way I did it:

%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (12, 9) # (w, h)

You can define your own sizes.

How to add form validation pattern in Angular 2?

You could build your form using FormBuilder as it let you more flexible way to configure form.

export class MyComp {
  form: ControlGroup;

  constructor(@Inject()fb: FormBuilder) {  
    this.form = fb.group({  
      foo: ['', MyValidators.regex(/^(?!\s|.*\s$).*$/)]  
    });  
  }

Then in your template :

<input type="text" ngControl="foo" />
<div *ngIf="!form.foo.valid">Please correct foo entry !</div> 

You can also customize ng-invalid CSS class.

As there is actually no validators for regex, you have to write your own. It is a simple function that takes a control in input, and return null if valid or a StringMap if invalid.

export class MyValidators {
  static regex(pattern: string): Function {
    return (control: Control): {[key: string]: any} => {
      return control.value.match(pattern) ? null : {pattern: true};
    };
  }
}

Hope that it help you.

Using jQuery how to get click coordinates on the target element

Are you trying to get the position of mouse pointer relative to element ( or ) simply the mouse pointer location

Try this Demo : http://jsfiddle.net/AMsK9/


Edit :

1) event.pageX, event.pageY gives you the mouse position relative document !

Ref : http://api.jquery.com/event.pageX/
http://api.jquery.com/event.pageY/

2) offset() : It gives the offset position of an element

Ref : http://api.jquery.com/offset/

3) position() : It gives you the relative Position of an element i.e.,

consider an element is embedded inside another element

example :

<div id="imParent">
   <div id="imchild" />
</div>

Ref : http://api.jquery.com/position/

HTML

<body>
   <div id="A" style="left:100px;"> Default    <br /> mouse<br/>position </div>
   <div id="B" style="left:300px;"> offset()   <br /> mouse<br/>position </div>
   <div id="C" style="left:500px;"> position() <br /> mouse<br/>position </div>
</body>

JavaScript

$(document).ready(function (e) {

    $('#A').click(function (e) { //Default mouse Position 
        alert(e.pageX + ' , ' + e.pageY);
    });

    $('#B').click(function (e) { //Offset mouse Position
        var posX = $(this).offset().left,
            posY = $(this).offset().top;
        alert((e.pageX - posX) + ' , ' + (e.pageY - posY));
    });

    $('#C').click(function (e) { //Relative ( to its parent) mouse position 
        var posX = $(this).position().left,
            posY = $(this).position().top;
        alert((e.pageX - posX) + ' , ' + (e.pageY - posY));
    });
});

How to match all occurrences of a regex

Using scan should do the trick:

string.scan(/regex/)

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

Try wrapping your dates in single quotes, like this:

'15-6-2005'

It should be able to parse the date this way.

How can I debug my JavaScript code?

I used to use Firebug, until Internet Explorer 8 came out. I'm not a huge fan of Internet Explorer, but after spending some time with the built-in developer tools, which includes a really nice debugger, it seems pointless to use anything else. I have to tip my hat to Microsoft they did a fantastic job on this tool.

'No JUnit tests found' in Eclipse

If none of the other answers work for you, here's what worked for me.

Restart eclipse

I had source folder configured correctly, and unit tests correctly annotated but was still getting "No JUnit tests found", for one project. After a restart it worked. I was using STS 3.6.2 based of eclipse Luna 4.4.1

What is the best way to generate a unique and short file name in Java

Why not use synchronized to process multi thread. here is my solution,It's can generate a short file name , and it's unique.

private static synchronized String generateFileName(){
    String name = make(index);
    index ++;
    return name;
}
private static String make(int index) {
    if(index == 0) return "";
    return String.valueOf(chars[index % chars.length]) + make(index / chars.length);
}
private static int index = 1;
private static char[] chars = {'a','b','c','d','e','f','g',
        'h','i','j','k','l','m','n',
        'o','p','q','r','s','t',
        'u','v','w','x','y','z'};

blew is main function for test , It's work.

public static void main(String[] args) {
    List<String> names = new ArrayList<>();
    List<Thread> threads = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    String name = generateFileName();
                    names.add(name);
                }
            }
        });
        thread.run();
        threads.add(thread);
    }

    for (int i = 0; i < 10; i++) {
        try {
            threads.get(i).join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    System.out.println(names);
    System.out.println(names.size());

}

Wrapping text inside input type="text" element HTML/CSS

Word Break will mimic some of the intent

_x000D_
_x000D_
    input[type=text] {
        word-wrap: break-word;
        word-break: break-all;
        height: 80px;
    }
_x000D_
<input type="text" value="The quick brown fox jumped over the lazy dog" />
_x000D_
_x000D_
_x000D_

As a workaround, this solution lost its effectiveness on some browsers. Please check the demo: http://cssdesk.com/dbCSQ

How do you uninstall MySQL from Mac OS X?

You should also check /var/db/receipts and remove all entries that contain com.mysql.*

Using sudo rm -rf /var/db/receipts/com.mysql.* didn't work for me. I had to go into var/db/receipts and delete each one seperately.

Adjust plot title (main) position

Try this:

par(adj = 0)
plot(1, 1, main = "Title")

or equivalent:

plot(1, 1, main = "Title", adj = 0)

adj = 0 produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1] is allowed.

However, the issue is that this will also change the position of the label of the x-axis and y-axis.

JSON serialization/deserialization in ASP.Net Core

You can use Newtonsoft.Json, it's a dependency of Microsoft.AspNet.Mvc.ModelBinding which is a dependency of Microsoft.AspNet.Mvc. So, you don't need to add a dependency in your project.json.

#using Newtonsoft.Json
....
JsonConvert.DeserializeObject(json);

Note, using a WebAPI controller you don't need to deal with JSON.

UPDATE ASP.Net Core 3.0

Json.NET has been removed from the ASP.NET Core 3.0 shared framework.

You can use the new JSON serializer layers on top of the high-performance Utf8JsonReader and Utf8JsonWriter. It deserializes objects from JSON and serializes objects to JSON. Memory allocations are kept minimal and includes support for reading and writing JSON with Stream asynchronously.

To get started, use the JsonSerializer class in the System.Text.Json.Serialization namespace. See the documentation for information and samples.

To use Json.NET in an ASP.NET Core 3.0 project:

    services.AddMvc()
        .AddNewtonsoftJson();

Read Json.NET support in Migrate from ASP.NET Core 2.2 to 3.0 Preview 2 for more information.

proper way to sudo over ssh

The best way is ssh -t user@server "sudo <scriptname>", for example ssh -t user@server "sudo reboot". It will prompt for password for user first and then root(since we are running the script or command with root privilege.

I hope it helped and cleared your doubt.

Sorting dropdown alphabetically in AngularJS

var module = angular.module("example", []);

module.controller("orderByController", function ($scope) {
    $scope.orderByValue = function (value) {
        return value;
    };

    $scope.items = ["c", "b", "a"];
    $scope.objList = [
        {
            "name": "c"
        }, {
            "name": "b"
        }, {
            "name": "a"
        }];
        $scope.item = "b";
    });

http://jsfiddle.net/Nfv42/65/

Inserting the iframe into react component

You can use property dangerouslySetInnerHTML, like this

_x000D_
_x000D_
const Component = React.createClass({_x000D_
  iframe: function () {_x000D_
    return {_x000D_
      __html: this.props.iframe_x000D_
    }_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe> tag and pass it to new <iframe> tag, like that

_x000D_
_x000D_
/**_x000D_
 * getAttrs_x000D_
 * returns all attributes from TAG string_x000D_
 * @return Object_x000D_
 */_x000D_
const getAttrs = (iframeTag) => {_x000D_
  var doc = document.createElement('div');_x000D_
  doc.innerHTML = iframeTag;_x000D_
_x000D_
  const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
  return [].slice_x000D_
    .call(iframe.attributes)_x000D_
    .reduce((attrs, element) => {_x000D_
      attrs[element.name] = element.value;_x000D_
      return attrs;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <iframe {...getAttrs(this.props.iframe) } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
_x000D_
_x000D_

Conditional formatting, entire row based

Use the "indirect" function on conditional formatting.

  1. Select Conditional Formatting
  2. Select New Rule
  3. Select "Use a Formula to determine which cells to format"
  4. Enter the Formula, =INDIRECT("g"&ROW())="X"
  5. Enter the Format you want (text color, fill color, etc).
  6. Select OK to save the new format
  7. Open "Manage Rules" in Conditional Formatting
  8. Select "This Worksheet" if you can't see your new rule.
  9. In the "Applies to" box of your new rule, enter =$A$1:$Z$1500 (or however wide/long you want the conditional formatting to extend depending on your worksheet)

For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.

You can repeat this to do multiple row formatting depending on a column value. Just change either the g column or x specific text in the formula and set different formats.

For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR", then it will format every row that has CAR in the H Column as the format you specified.

Detecting installed programs via registry

You could use MSI API to enumerate everything installed by Windows Installer but that won't list all the software available on a machine. Without knowing more about what you need I think the concept of "installed" is a little vague. There are many ways to deploy software to a system ranging from big complicated installers to ZIP files and everything in between.

Bootstrap modal not displaying

If you are using angular and trying to create a directive that has a custom modal in it, the modal backdrop will show but the modal itself will not unless you set replace: true on your directive.

Typescript Directive:

export class myModalDirective implements ng.IDirective {
    static Register = () => {
        angular.module('app').directive('myModal', () => { return new myModalDirective () });
    }
    templateUrl = 'mymodal.html'    
restrict = 'E';
    replace = true;
    scope = {
        show: '='
    }
    link = (scope: any, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ctrl: any) => {
        var vm = this;
        scope.$watch(function () { return scope.show; }, function (vis) {
            if (vis) {
                $(element).modal('show');
            } else {
                $(element).modal('hide');
            }
        });

    }
    constructor () {
    }
}

Modal HTML

<div class="modal fade" data-keyboard="false" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Modal Title</h4>
                </div>
                <div class="modal-body">
                </div>
        </div>
    </div>
</div>

Update statement using with clause

The WITH syntax appears to be valid in an inline view, e.g.

UPDATE (WITH comp AS ...
        SELECT SomeColumn, ComputedValue FROM t INNER JOIN comp ...)
   SET SomeColumn=ComputedValue;

But in the quick tests I did this always failed with ORA-01732: data manipulation operation not legal on this view, although it succeeded if I rewrote to eliminate the WITH clause. So the refactoring may interfere with Oracle's ability to guarantee key-preservation.

You should be able to use a MERGE, though. Using the simple example you've posted this doesn't even require a WITH clause:

MERGE INTO mytable t
USING (select *, 42 as ComputedValue from mytable where id = 1) comp
ON (t.id = comp.id)
WHEN MATCHED THEN UPDATE SET SomeColumn=ComputedValue;

But I understand you have a more complex subquery you want to factor out. I think that you will be able to make the subquery in the USING clause arbitrarily complex, incorporating multiple WITH clauses.

How can I use optional parameters in a T-SQL stored procedure?

Five years late to the party.

It is mentioned in the provided links of the accepted answer, but I think it deserves an explicit answer on SO - dynamically building the query based on provided parameters. E.g.:

Setup

-- drop table Person
create table Person
(
    PersonId INT NOT NULL IDENTITY(1, 1) CONSTRAINT PK_Person PRIMARY KEY,
    FirstName NVARCHAR(64) NOT NULL,
    LastName NVARCHAR(64) NOT NULL,
    Title NVARCHAR(64) NULL
)
GO

INSERT INTO Person (FirstName, LastName, Title)
VALUES ('Dick', 'Ormsby', 'Mr'), ('Serena', 'Kroeger', 'Ms'), 
    ('Marina', 'Losoya', 'Mrs'), ('Shakita', 'Grate', 'Ms'), 
    ('Bethann', 'Zellner', 'Ms'), ('Dexter', 'Shaw', 'Mr'),
    ('Zona', 'Halligan', 'Ms'), ('Fiona', 'Cassity', 'Ms'),
    ('Sherron', 'Janowski', 'Ms'), ('Melinda', 'Cormier', 'Ms')
GO

Procedure

ALTER PROCEDURE spDoSearch
    @FirstName varchar(64) = null,
    @LastName varchar(64) = null,
    @Title varchar(64) = null,
    @TopCount INT = 100
AS
BEGIN
    DECLARE @SQL NVARCHAR(4000) = '
        SELECT TOP ' + CAST(@TopCount AS VARCHAR) + ' *
        FROM Person
        WHERE 1 = 1'

    PRINT @SQL

    IF (@FirstName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @FirstName'
    IF (@LastName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @LastName'
    IF (@Title IS NOT NULL) SET @SQL = @SQL + ' AND Title = @Title'

    EXEC sp_executesql @SQL, N'@TopCount INT, @FirstName varchar(25), @LastName varchar(25), @Title varchar(64)', 
         @TopCount, @FirstName, @LastName, @Title
END
GO

Usage

exec spDoSearch @TopCount = 3
exec spDoSearch @FirstName = 'Dick'

Pros:

  • easy to write and understand
  • flexibility - easily generate the query for trickier filterings (e.g. dynamic TOP)

Cons:

  • possible performance problems depending on provided parameters, indexes and data volume

Not direct answer, but related to the problem aka the big picture

Usually, these filtering stored procedures do not float around, but are being called from some service layer. This leaves the option of moving away business logic (filtering) from SQL to service layer.

One example is using LINQ2SQL to generate the query based on provided filters:

    public IList<SomeServiceModel> GetServiceModels(CustomFilter filters)
    {
        var query = DataAccess.SomeRepository.AllNoTracking;

        // partial and insensitive search 
        if (!string.IsNullOrWhiteSpace(filters.SomeName))
            query = query.Where(item => item.SomeName.IndexOf(filters.SomeName, StringComparison.OrdinalIgnoreCase) != -1);
        // filter by multiple selection
        if ((filters.CreatedByList?.Count ?? 0) > 0)
            query = query.Where(item => filters.CreatedByList.Contains(item.CreatedById));
        if (filters.EnabledOnly)
            query = query.Where(item => item.IsEnabled);

        var modelList = query.ToList();
        var serviceModelList = MappingService.MapEx<SomeDataModel, SomeServiceModel>(modelList);
        return serviceModelList;
    }

Pros:

  • dynamically generated query based on provided filters. No parameter sniffing or recompile hints needed
  • somewhat easier to write for those in the OOP world
  • typically performance friendly, since "simple" queries will be issued (appropriate indexes are still needed though)

Cons:

  • LINQ2QL limitations may be reached and forcing a downgrade to LINQ2Objects or going back to pure SQL solution depending on the case
  • careless writing of LINQ might generate awful queries (or many queries, if navigation properties loaded)

How to check if an app is installed from a web-page on an iPhone?

As far as I know you can not, from a browser, check if an app is installed or not.

But you can try redirecting the phone to the app, and if nothing happens redirect the phone to a specified page, like this:

setTimeout(function () { window.location = "https://itunes.apple.com/appdir"; }, 25);
window.location = "appname://";

If the second line of code gives a result then the first row is never executed.

Hope this helps!

Similar question:

How do I add an "Add to Favorites" button or link on my website?

I have faced some problems with rel="sidebar". when I add it in link tag bookmarking will work on FF but stop working in other browser. so I fix that by adding rel="sidebar" dynamic by code:

jQuery('.bookmarkMeLink').click(function() {
    if (window.sidebar && window.sidebar.addPanel) { 
        // Mozilla Firefox Bookmark
        window.sidebar.addPanel(document.title,window.location.href,'');
    }
    else if(window.sidebar && jQuery.browser.mozilla){
        //for other version of FF add rel="sidebar" to link like this:
        //<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
        jQuery(this).attr('rel', 'sidebar');
    }
    else if(window.external && ('AddFavorite' in window.external)) { 
        // IE Favorite
        window.external.AddFavorite(location.href,document.title); 
    } else if(window.opera && window.print) { 
        // Opera Hotlist
        this.title=document.title;
        return true;
    } else { 
        // webkit - safari/chrome
        alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');

    }
});

How to get the HTML's input element of "file" type to only accept pdf files?

Not with the HTML file control, no. A flash file uploader can do that for you though. You could use some client-side code to check for the PDF extension after they select, but you cannot directly control what they can select.

Does Java have something like C#'s ref and out keywords?

Actually there is neither ref nor out keyword equivalent in Java language as far as I know. However I've just transformed a C# code into Java that uses out parameter and will advise what I've just done. You should wrap whatever object into a wrapper class and pass the values wrapped in wrapper object instance as follows;

A Simple Example For Using Wrapper

Here is the Wrapper Class;

public class Wrapper {
    public Object ref1; // use this as ref
    public Object ref2; // use this as out

    public Wrapper(Object ref1) {
        this.ref1 = ref1;
    }
}

And here is the test code;

public class Test {

    public static void main(String[] args) {
        String abc = "abc";
        changeString(abc);
        System.out.println("Initial object: " + abc); //wont print "def"

        Wrapper w = new Wrapper(abc);
        changeStringWithWrapper(w);
        System.out.println("Updated object: " + w.ref1);
        System.out.println("Out     object: " + w.ref2);
    }

    // This won't work
    public static void changeString(String str) {
        str = "def";
    }

    // This will work
    public static void changeStringWithWrapper(Wrapper w) {
        w.ref1 = "def";
        w.ref2 = "And this should be used as out!";
    }

}

A Real World Example

A C#.NET method using out parameter

Here there is a C#.NET method that is using out keyword;

public bool Contains(T value)
{
    BinaryTreeNode<T> parent;
    return FindWithParent(value, out parent) != null;
}

private BinaryTreeNode<T> FindWithParent(T value, out BinaryTreeNode<T> parent)
{
    BinaryTreeNode<T> current = _head;
    parent = null;

    while(current != null)
    {
        int result = current.CompareTo(value);

        if (result > 0)
        {
            parent = current;
            current = current.Left;
        }
        else if (result < 0)
        {
            parent = current;
            current = current.Right;
        }
        else
        {
            break;
        }
    }

    return current;
}

Java Equivalent of the C# code that is using the out parameter

And the Java equivalent of this method with the help of wrapper class is as follows;

public boolean contains(T value) {
    BinaryTreeNodeGeneration<T> result = findWithParent(value);

    return (result != null);
}

private BinaryTreeNodeGeneration<T> findWithParent(T value) {
    BinaryTreeNode<T> current = head;
    BinaryTreeNode<T> parent = null;
    BinaryTreeNodeGeneration<T> resultGeneration = new BinaryTreeNodeGeneration<T>();
    resultGeneration.setParentNode(null);

    while(current != null) {
        int result = current.compareTo(value);

        if(result >0) {
            parent = current;
            current = current.left;
        } else if(result < 0) {
            parent = current;
            current = current.right;
        } else {
            break;
        }
    }

    resultGeneration.setChildNode(current);
    resultGeneration.setParentNode(parent);

    return resultGeneration;
}

Wrapper Class

And the wrapper class used in this Java code is as below;

public class BinaryTreeNodeGeneration<TNode extends Comparable<TNode>>  {

    private BinaryTreeNode<TNode>   parentNode;
    private BinaryTreeNode<TNode>   childNode;

    public BinaryTreeNodeGeneration() {
        this.parentNode = null;
        this.childNode = null;
    }

    public BinaryTreeNode<TNode> getParentNode() {
        return parentNode;
    }

    public void setParentNode(BinaryTreeNode<TNode> parentNode) {
        this.parentNode = parentNode;
    }

    public BinaryTreeNode<TNode> getChildNode() {
        return childNode;
    }

    public void setChildNode(BinaryTreeNode<TNode> childNode) {
        this.childNode = childNode;
    }

}

How to open an elevated cmd using command line for Windows?

I don't have enough reputation to add a comment to the top answer, but with the power of aliases you can get away with just typing the following:

powershell "start cmd -v runAs"

This is just a shorter version of user3018703 excellent solution:

powershell -Command "Start-Process cmd -Verb RunAs"

Convert timestamp to date in MySQL query

To just get a date you can cast it

cast(user.registration as date)

and to get a specific format use date_format

date_format(registration, '%Y-%m-%d')

SQLFiddle demo

What is the difference between a candidate key and a primary key?

Primary key -> Any column or set of columns that can uniquely identify a record in the table is a primary key. (There can be only one Primary key in the table) and the candidate key-> the same as Primary key but the Primary Key chosen by DB administrator's prospective for example(the primary key the least candidate key in size)

How can I add a box-shadow on one side of an element?

What I do is create a vertical block for the shadow, and place it next to where my block element should be. The two blocks are then wrapped into another block:

<div id="wrapper">
    <div id="shadow"></div>  
    <div id="content">CONTENT</div>  
</div>

<style>

div#wrapper {
  width:200px;
  height:258px;      
}

div#wrapper > div#shadow {
  display:inline-block;
  width:1px;
  height:100%;
  box-shadow: -3px 0px 5px 0px rgba(0,0,0,0.8)
}

div#wrapper > div#content {
  display:inline-block;
  height:100%;
  vertical-align:top;
}

</style>

jsFiddle example here.

How to use breakpoints in Eclipse

Put breakpoints - double click on the margin. Run > Debug > Yes (if dialog appears), then use commands from Run menu or shortcuts - F5, F6, F7, F8.

e.printStackTrace equivalent in python

import traceback
traceback.print_exc()

When doing this inside an except ...: block it will automatically use the current exception. See http://docs.python.org/library/traceback.html for more information.

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

I experienced a similar issue with android studio 2.2. Re-installing a new system image didnt resolve for me. Then found this solution on this link.

unchecking the Enable ADB Integration option and checking it back seem to resolve it for me. I hope this helps someone out there.

How to add click event to a iframe with JQuery

There's no 'onclick' event for an iframe, but you can try to catch the click event of the document in the iframe:

document.getElementById("iframe_id").contentWindow.document.body.onclick = 
function() {
  alert("iframe clicked");
}

EDIT Though this doesn't solve your cross site problem, FYI jQuery has been updated to play well with iFrames:

$('#iframe_id').on('click', function(event) { });

Update 1/2015 The link to the iframe explanation has been removed as it's no longer available.

Note The code above will not work if the iframe is from different domain than the host page. You can still try to use hacks mentioned in comments.

How can I get a resource content from a static context?

My Kotlin solution is to use a static Application context:

class App : Application() {
    companion object {
        lateinit var instance: App private set
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
    }
}

And the Strings class, that I use everywhere:

object Strings {
    fun get(@StringRes stringRes: Int, vararg formatArgs: Any = emptyArray()): String {
        return App.instance.getString(stringRes, *formatArgs)
    }
}

So you can have a clean way of getting resource strings

Strings.get(R.string.some_string)
Strings.get(R.string.some_string_with_arguments, "Some argument")

Please don't delete this answer, let me keep one.

Count the number of Occurrences of a Word in a String

using indexOf...

public static int count(String string, String substr) {
    int i;
    int last = 0;
    int count = 0;
    do {
        i = string.indexOf(substr, last);
        if (i != -1) count++;
        last = i+substr.length();
    } while(i != -1);
    return count;
}

public static void main (String[] args ){
    System.out.println(count("i have a male cat. the color of male cat is Black", "male cat"));
}

That will show: 2

Another implementation for count(), in just 1 line:

public static int count(String string, String substr) {
    return (string.length() - string.replaceAll(substr, "").length()) / substr.length() ;
}

Text in HTML Field to disappear when clicked?

This is as simple I think the solution that should solve all your problems:

<input name="myvalue" id="valueText" type="text" value="ENTER VALUE">

This is your submit button:

<input type="submit" id= "submitBtn" value="Submit">

then put this small jQuery in a js file:

//this will submit only if the value is not default
$("#submitBtn").click(function () {
    if ($("#valueText").val() === "ENTER VALUE")
    {
        alert("please insert a valid value");
        return false;
    }
});

//this will put default value if the field is empty
$("#valueText").blur(function () {
    if(this.value == ''){ 
        this.value = 'ENTER VALUE';
    }
}); 

 //this will empty the field is the value is the default one
 $("#valueText").focus(function () {
    if (this.value == 'ENTER VALUE') {
        this.value = ''; 
    }
});

And it works also in older browsers. Plus it can easily be converted to normal javascript if you need.

How to prevent auto-closing of console after the execution of batch file

Possibility 1: Just make 2 .bat files and write into the first:

start <filename> // name of 2nd batch file
exit

Batch file 2 is the file that wont close in the end. So now when you open batch nr.1 It will start the 2nd and cloe itself. When the 2nd finishes it will not close entirely (as long as you wont put exit at the end)

Possibility 2: Batch file 1:

call <filename>
cls
echo End of file
pause
<any code you want>

When the 2nd file ends then it will proceed to file 1 again and output the rest of it. With that you can even make error handlers. If nr.1 crashes it goes into nr.2 and displays it

How to print a linebreak in a python function?

\n is an escape sequence, denoted by the backslash. A normal forward slash, such as /n will not do the job. In your code you are using /n instead of \n.

Best practice: PHP Magic Methods __set and __get

I vote for a third solution. I use this in my projects and Symfony uses something like this too:

public function __call($val, $x) {
    if(substr($val, 0, 3) == 'get') {
        $varname = strtolower(substr($val, 3));
    }
    else {
        throw new Exception('Bad method.', 500);
    }
    if(property_exists('Yourclass', $varname)) {
        return $this->$varname;
    } else {
        throw new Exception('Property does not exist: '.$varname, 500);
    }
}

This way you have automated getters (you can write setters too), and you only have to write new methods if there is a special case for a member variable.

How do I clear only a few specific objects from the workspace?

  1. In RStudio, ensure the Environment tab is in Grid (not List) mode.

  2. Tick the object(s) you want to remove from the environment.

  3. Click the broom icon.

How to properly override clone method?

You can implement protected copy constructors like so:

/* This is a protected copy constructor for exclusive use by .clone() */
protected MyObject(MyObject that) {
    this.myFirstMember = that.getMyFirstMember(); //To clone primitive data
    this.mySecondMember = that.getMySecondMember().clone(); //To clone complex objects
    // etc
}

public MyObject clone() {
    return new MyObject(this);
}

How to step through Python code to help debug issues?

Python Tutor is an online single-step debugger meant for novices. You can put in code on the edit page then click "Visualize Execution" to start it running.

Among other things, it supports:

However it also doesn't support a lot of things, for example:

  • Reading/writing files - use io.StringIO and io.BytesIO instead: demo
  • Code that is too large, runs too long, or defines too many variables or objects
  • Command-line arguments
  • Lots of standard library modules like argparse, csv, enum, html, os, struct, weakref...

How to create a pivot query in sql server without aggregate function

SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
    MAX([Value])
    FOR [Period] IN ([2000], [2001], [2002])
) as pvt

Another way,

SELECT ACCOUNT,
      MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
      MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
      MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account

Running a command as Administrator using PowerShell?

I am using the solution below. It handles stdout/stderr via transcript feature and passes exit code correctly to parent process. You need to adjust transcript path/filename.

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{ 
  echo "* Respawning PowerShell child process with elevated privileges"
  $pinfo = New-Object System.Diagnostics.ProcessStartInfo
  $pinfo.FileName = "powershell"
  $pinfo.Arguments = "& '" + $myinvocation.mycommand.definition + "'"
  $pinfo.Verb = "RunAs"
  $pinfo.RedirectStandardError = $false
  $pinfo.RedirectStandardOutput = $false
  $pinfo.UseShellExecute = $true
  $p = New-Object System.Diagnostics.Process
  $p.StartInfo = $pinfo
  $p.Start() | Out-Null
  $p.WaitForExit()
  echo "* Child process finished"
  type "C:/jenkins/transcript.txt"
  Remove-Item "C:/jenkins/transcript.txt"
  Exit $p.ExitCode
} Else {
  echo "Child process starting with admin privileges"
  Start-Transcript -Path "C:/jenkins/transcript.txt"
}

# Rest of your script goes here, it will be executed with elevated privileges

Remove Android App Title Bar

If you use AppCompat v7, v21

getSupportActionBar().setDisplayShowTitleEnabled(false);

Printing PDFs from Windows Command Line

@ECHO off set "dir1=C:\TicketDownload" 
FOR %%X in ("%dir1%*.pdf") DO ( "C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe" /t "%%~dpnX.pdf" "Microsoft XPS Document Writer" ) 
FOR %%X in ("%dir1%*.pdf") DO (move "%%~dpnX.pdf" p/)

Try this..May be u have some other version of Reader so that is the problem..

What Scala web-frameworks are available?

I'm very interested in Scala, but I have not used it yet, so with that caveat, the frameworks I am aware of that are not mentioned in HRJ's answer (Lift, Sweet, Slinky) are:

Move textfield when keyboard appears swift

I modified @Simpa solution a little bit.........

override func viewDidLoad() 
{

    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("makeSpaceForKeyboard:"), name:UIKeyboardWillShowNotification, object: nil);
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("makeSpaceForKeyboard:"), name:UIKeyboardWillHideNotification, object: nil);
}

deinit{
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

var keyboardIsVisible = false
override func makeSpaceForKeyboard(notification: NSNotification) {

    let info = notification.userInfo!
    let keyboardHeight:CGFloat = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().size.height
    let duration:Double = info[UIKeyboardAnimationDurationUserInfoKey] as! Double

    if notification.name == UIKeyboardWillShowNotification && keyboardIsVisible == false{

        keyboardIsVisible = true

        UIView.animateWithDuration(duration, animations: { () -> Void in
            var frame = self.view.frame
            frame.size.height = frame.size.height - keyboardHeight
            self.view.frame = frame
        })

    } else if keyboardIsVisible == true && notification.name == UIKeyboardWillShowNotification{

    }else {
        keyboardIsVisible = false

        UIView.animateWithDuration(duration, animations: { () -> Void in
            var frame = self.view.frame
            frame.size.height = frame.size.height + keyboardHeight
            self.view.frame = frame
        })
    }
}

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

From your stack trace, EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) occurred because dispatch_group_t was released while it was still locking (waiting for dispatch_group_leave).

According to what you found, this was what happened :

  • dispatch_group_t group was created. group's retain count = 1.
  • -[self webservice:onCompletion:] captured the group. group's retain count = 2.
  • dispatch_async(...., ^{ dispatch_group_wait(group, ...) ... }); captured the group again. group's retain count = 3.
  • Exit the current scope. group was released. group's retain count = 2.
  • dispatch_group_leave was never called.
  • dispatch_group_wait was timeout. The dispatch_async block was completed. group was released. group's retain count = 1.
  • You called this method again. When -[self webservice:onCompletion:] was called again, the old onCompletion block was replaced with the new one. So, the old group was released. group's retain count = 0. group was deallocated. That resulted to EXC_BAD_INSTRUCTION.

To fix this, I suggest you should find out why -[self webservice:onCompletion:] didn't call onCompletion block, and fix it. Then make sure the next call to the method will happen after the previous call did finish.


In case you allow the method to be called many times whether the previous calls did finish or not, you might find someone to hold group for you :

  • You can change the timeout from 2 seconds to DISPATCH_TIME_FOREVER or a reasonable amount of time that all -[self webservice:onCompletion] should call their onCompletion blocks by the time. So that the block in dispatch_async(...) will hold it for you.
    OR
  • You can add group into a collection, such as NSMutableArray.

I think it is the best approach to create a dedicate class for this action. When you want to make calls to webservice, you then create an object of the class, call the method on it with the completion block passing to it that will release the object. In the class, there is an ivar of dispatch_group_t or dispatch_semaphore_t.

What are the date formats available in SimpleDateFormat class?

check the formats here http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

main

System.out.println("date  : " + new classname().getMyDate("2014-01-09 14:06", "dd-MMM-yyyy E hh:mm a z", "yyyy-MM-dd HH:mm"));

method

 public String getMyDate(String myDate, String returnFormat, String myFormat)
            {
                DateFormat dateFormat = new SimpleDateFormat(returnFormat);
                Date date=null;
                String returnValue="";
                try {
                    date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
                    returnValue = dateFormat.format(date);
                } catch (ParseException e) {
                    returnValue= myDate;
                    System.out.println("failed");
                    e.printStackTrace();
                }

            return returnValue;
            }

Proper way to handle multiple forms on one page in Django

view:

class AddProductView(generic.TemplateView):
template_name = 'manager/add_product.html'

    def get(self, request, *args, **kwargs):
    form = ProductForm(self.request.GET or None, prefix="sch")
    sub_form = ImageForm(self.request.GET or None, prefix="loc")
    context = super(AddProductView, self).get_context_data(**kwargs)
    context['form'] = form
    context['sub_form'] = sub_form
    return self.render_to_response(context)

def post(self, request, *args, **kwargs):
    form = ProductForm(request.POST,  prefix="sch")
    sub_form = ImageForm(request.POST, prefix="loc")
    ...

template:

{% block container %}
<div class="container">
    <br/>
    <form action="{% url 'manager:add_product' %}" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        {{ sub_form.as_p }}
        <p>
            <button type="submit">Submit</button>
        </p>
    </form>
</div>
{% endblock %}

NSURLErrorDomain error codes description

The NSURLErrorDomain error codes are listed here https://developer.apple.com/documentation/foundation/1508628-url_loading_system_error_codes

However, 400 is just the http status code (http://www.w3.org/Protocols/HTTP/HTRESP.html) being returned which means you've got something wrong with your request.

How can I determine whether a specific file is open in Windows?

Try Unlocker.

The Unlocker site has a nifty chart (scroll down after following the link) that shows a comparison to other tools. Obviously such comparisons are usually biased since they are typically written by the tool author, but the chart at least lists the alternatives so that you can try them for yourself.

Rounded corners for <input type='text' /> using border-radius.htc for IE

if you are using for certain text field then use the class

<style>
  .inputForm{
      border-radius:5px;
      -moz-border-radius:5px;
      -webkit-border-radius:5px;
   }
</style>

and in html code use

 <input type="text" class="inputForm">

or if u want to do this for all the input type text field means use

<style>
    input[type="text"]{
      border-radius:5px;
      -moz-border-radius:5px;
      -webkit-border-radius:5px;
    }
 </style>

and in html code

<input type="text" name="name">

Use xml.etree.ElementTree to print nicely formatted xml files

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

Overlaying histograms with ggplot2 in R

Your current code:

ggplot(histogram, aes(f0, fill = utt)) + geom_histogram(alpha = 0.2)

is telling ggplot to construct one histogram using all the values in f0 and then color the bars of this single histogram according to the variable utt.

What you want instead is to create three separate histograms, with alpha blending so that they are visible through each other. So you probably want to use three separate calls to geom_histogram, where each one gets it's own data frame and fill:

ggplot(histogram, aes(f0)) + 
    geom_histogram(data = lowf0, fill = "red", alpha = 0.2) + 
    geom_histogram(data = mediumf0, fill = "blue", alpha = 0.2) +
    geom_histogram(data = highf0, fill = "green", alpha = 0.2) +

Here's a concrete example with some output:

dat <- data.frame(xx = c(runif(100,20,50),runif(100,40,80),runif(100,0,30)),yy = rep(letters[1:3],each = 100))

ggplot(dat,aes(x=xx)) + 
    geom_histogram(data=subset(dat,yy == 'a'),fill = "red", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'b'),fill = "blue", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'c'),fill = "green", alpha = 0.2)

which produces something like this:

enter image description here

Edited to fix typos; you wanted fill, not colour.

Determine Whether Integer Is Between Two Other Integers?

The condition should be,

if number == 10000 and number <= 30000:
     print("5% tax payable")

reason for using number == 10000 is that if number's value is 50000 and if we use number >= 10000 the condition will pass, which is not what you want.

MySQL add days to a date

 DATE_ADD(FROM_DATE_HERE, INTERVAL INTERVAL_TIME_HERE DAY) 

will give the Date after adjusting the INTERVAL

eg.

DATE_ADD(NOW(), INTERVAL -1 DAY) for deducting 1 DAY from current Day
DATE_ADD(NOW(), INTERVAL 2 DAY)  for adding 2 Days

You can use like

UPDATE classes WHERE date=(DATE_ADD(date, INTERVAL 1 DAY)) WHERE id=161

Skip over a value in the range function in python

In addition to the Python 2 approach here are the equivalents for Python 3:

# Create a range that does not contain 50
for i in [x for x in range(100) if x != 50]:
    print(i)

# Create 2 ranges [0,49] and [51, 100]
from itertools import chain
concatenated = chain(range(50), range(51, 100))
for i in concatenated:
    print(i)

# Create a iterator and skip 50
xr = iter(range(100))
for i in xr:
    print(i)
    if i == 49:
        next(xr)

# Simply continue in the loop if the number is 50
for i in range(100):
    if i == 50:
        continue
    print(i)

Ranges are lists in Python 2 and iterators in Python 3.

SET versus SELECT when assigning variables?

Aside from the one being ANSI and speed etc., there is a very important difference that always matters to me; more than ANSI and speed. The number of bugs I have fixed due to this important overlook is large. I look for this during code reviews all the time.

-- Arrange
create table Employee (EmployeeId int);
insert into dbo.Employee values (1);
insert into dbo.Employee values (2);
insert into dbo.Employee values (3);

-- Act
declare @employeeId int;
select @employeeId = e.EmployeeId from dbo.Employee e;

-- Assert
-- This will print 3, the last EmployeeId from the query (an arbitrary value)
-- Almost always, this is not what the developer was intending. 
print @employeeId; 

Almost always, that is not what the developer is intending. In the above, the query is straight forward but I have seen queries that are quite complex and figuring out whether it will return a single value or not, is not trivial. The query is often more complex than this and by chance it has been returning single value. During developer testing all is fine. But this is like a ticking bomb and will cause issues when the query returns multiple results. Why? Because it will simply assign the last value to the variable.

Now let's try the same thing with SET:

 -- Act
 set @employeeId = (select e.EmployeeId from dbo.Employee e);

You will receive an error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

That is amazing and very important because why would you want to assign some trivial "last item in result" to the @employeeId. With select you will never get any error and you will spend minutes, hours debugging.

Perhaps, you are looking for a single Id and SET will force you to fix your query. Thus you may do something like:

-- Act
-- Notice the where clause
set @employeeId = (select e.EmployeeId from dbo.Employee e where e.EmployeeId = 1);
print @employeeId;

Cleanup

drop table Employee;

In conclusion, use:

  • SET: When you want to assign a single value to a variable and your variable is for a single value.
  • SELECT: When you want to assign multiple values to a variable. The variable may be a table, temp table or table variable etc.

Equivalent of SQL ISNULL in LINQ?

Since aa is the set/object that might be null, can you check aa == null ?

(aa / xx might be interchangeable (a typo in the question); the original question talks about xx but only defines aa)

i.e.

select new {
    AssetID = x.AssetID,
    Status = aa == null ? (bool?)null : aa.Online; // a Nullable<bool>
}

or if you want the default to be false (not null):

select new {
    AssetID = x.AssetID,
    Status = aa == null ? false : aa.Online;
}

Update; in response to the downvote, I've investigated more... the fact is, this is the right approach! Here's an example on Northwind:

        using(var ctx = new DataClasses1DataContext())
        {
            ctx.Log = Console.Out;
            var qry = from boss in ctx.Employees
                      join grunt in ctx.Employees
                          on boss.EmployeeID equals grunt.ReportsTo into tree
                      from tmp in tree.DefaultIfEmpty()
                      select new
                             {
                                 ID = boss.EmployeeID,
                                 Name = tmp == null ? "" : tmp.FirstName
                        };
            foreach(var row in qry)
            {
                Console.WriteLine("{0}: {1}", row.ID, row.Name);
            }
        }

And here's the TSQL - pretty much what we want (it isn't ISNULL, but it is close enough):

SELECT [t0].[EmployeeID] AS [ID],
    (CASE
        WHEN [t2].[test] IS NULL THEN CONVERT(NVarChar(10),@p0)
        ELSE [t2].[FirstName]
     END) AS [Name]
FROM [dbo].[Employees] AS [t0]
LEFT OUTER JOIN (
    SELECT 1 AS [test], [t1].[FirstName], [t1].[ReportsTo]
    FROM [dbo].[Employees] AS [t1]
    ) AS [t2] ON ([t0].[EmployeeID]) = [t2].[ReportsTo]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

QED?

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

In my case, it was Blend SDK missed out on TeamCity machine. This caused the error due incorrect way of assembly resolving then.

How can I get the class name from a C++ object?

Do you want [classname] to be 'one' and [objectname] to be 'A'?

If so, this is not possible. These names are only abstractions for the programmer, and aren't actually used in the binary code that is generated. You could give the class a static variable classname, which you set to 'one' and a normal variable objectname which you would assign either directly, through a method or the constructor. You can then query these methods for the class and object names.

Prevent wrapping of span or div

Try this:

_x000D_
_x000D_
.slideContainer {_x000D_
    overflow-x: scroll;_x000D_
    white-space: nowrap;_x000D_
}_x000D_
.slide {_x000D_
    display: inline-block;_x000D_
    width: 600px;_x000D_
    white-space: normal;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
    <span class="slide">Some content</span>_x000D_
    <span class="slide">More content. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>_x000D_
    <span class="slide">Even more content!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note that you can omit .slideContainer { overflow-x: scroll; } (which browsers may or may not support when you read this), and you'll get a scrollbar on the window instead of on this container.

The key here is display: inline-block. This has decent cross-browser support nowadays, but as usual, it's worth testing in all target browsers to be sure.

What is the difference between `Enum.name()` and `Enum.toString()`?

Use toString() when you want to present information to a user (including a developer looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overridden.

how to make UITextView height dynamic according to text length?

Declaration here

    fileprivate weak var textView: UITextView!

Call your setupview here

    override func viewDidLoad() {
        super.viewDidLoad()

         setupViews()
    }

Setup here

    fileprivate func setupViews() {

    let textView = UITextView()
    textView.translatesAutoresizingMaskIntoConstraints = false
    textView.text = "your text here"
    textView.font = UIFont.poppinsMedium(size: 14)
    textView.textColor = UIColor.brownishGrey
    textView.textAlignment = .left
    textView.isEditable = false
    textView.isScrollEnabled = false
    textView.textContainerInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)

   self.view.addSubview(textView)

   self.textView = textView

   setupConstraints()

   }

Setup constraints here

   fileprivate func setupConstraints() {

    NSLayoutConstraint.activate([

        textView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
        textView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20),
        textView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20),
        textView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
        textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 150),
        ])
  }

How can I determine whether a 2D Point is within a Polygon?

.Net port:

    static void Main(string[] args)
    {

        Console.Write("Hola");
        List<double> vertx = new List<double>();
        List<double> verty = new List<double>();

        int i, j, c = 0;

        vertx.Add(1);
        vertx.Add(2);
        vertx.Add(1);
        vertx.Add(4);
        vertx.Add(4);
        vertx.Add(1);

        verty.Add(1);
        verty.Add(2);
        verty.Add(4);
        verty.Add(4);
        verty.Add(1);
        verty.Add(1);

        int nvert = 6;  //Vértices del poligono

        double testx = 2;
        double testy = 5;


        for (i = 0, j = nvert - 1; i < nvert; j = i++)
        {
            if (((verty[i] > testy) != (verty[j] > testy)) &&
             (testx < (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i]))
                c = 1;
        }
    }

How to get all enum values in Java?

Enums are just like Classes in that they are typed. Your current code just checks if it is an Enum without specifying what type of Enum it is a part of.

Because you haven't specified the type of the enum, you will have to use reflection to find out what the list of enum values is.

You can do it like so:

enumValue.getDeclaringClass().getEnumConstants() 

This will return an array of Enum objects, with each being one of the available options.

Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies

I had this same problem - some users could pull from git and everything ran fine. Some would pull and get a very similar exception:

Could not load file or assembly '..., Version=..., Culture=neutral, PublicKeyToken=...' or one of its dependencies. The system cannot find the file specified.

In my particular case it was AjaxMin, so the actual error looked like this but the details don't matter:

Could not load file or assembly 'AjaxMin, Version=4.95.4924.12383, Culture=neutral, PublicKeyToken=21ef50ce11b5d80f' or one of its dependencies. The system cannot find the file specified.

It turned out to be a result of the following actions on a Solution:

  1. NuGet Package Restore was turned on for the Solution.

  2. A Project was added, and a Nuget package was installed into it (AjaxMin in this case).

  3. The Project was moved to different folder in the Solution.

  4. The Nuget package was updated to a newer version.

And slowly but surely this bug started showing up for some users.

The reason was the Solution-level packages/respositories.config kept the old Project reference, and now had a new, second entry for the moved Project. In other words it had this before the reorg:

  <repository path="..\Old\packages.config" />

And this after the reorg:

  <repository path="..\Old\packages.config" />
  <repository path="..\New\packages.config" />

So the first line now refers to a Project that, while on disk, is no longer part of my Solution.

With Nuget Package Restore on, both packages.config files were being read, which each pointed to their own list of Nuget packages and package versions. Until a Nuget package was updated to a newer version however, there weren't any conflicts.

Once a Nuget package was updated, however, only active Projects had their repositories listings updated. NuGet Package Restore chose to download just one version of the library - the first one it encountered in repositories.config, which was the older one. The compiler and IDE proceeded as though it chose the newer one. The result was a run-time exception saying the DLL was missing.

The answer obviously is to delete any lines from this file that referenced Projects that aren't in your Solution.

How can you create pop up messages in a batch script?

msg * "Enter Your Message"

Does this help ?

How to $http Synchronous call with AngularJS

Not currently. If you look at the source code (from this point in time Oct 2012), you'll see that the call to XHR open is actually hard-coded to be asynchronous (the third parameter is true):

 xhr.open(method, url, true);

You'd need to write your own service that did synchronous calls. Generally that's not something you'll usually want to do because of the nature of JavaScript execution you'll end up blocking everything else.

... but.. if blocking everything else is actually desired, maybe you should look into promises and the $q service. It allows you to wait until a set of asynchronous actions are done, and then execute something once they're all complete. I don't know what your use case is, but that might be worth a look.

Outside of that, if you're going to roll your own, more information about how to make synchronous and asynchronous ajax calls can be found here.

I hope that is helpful.

how can I set visible back to true in jquery

The problem is that since you are using ASP.NET controls with a runat attribute, the ID of the control is not actually "test1". It's "test1" with a long string attached to it.

Indexes of all occurrences of character in a string

I had this problem as well, until I came up with this method.

public static int[] indexesOf(String s, String flag) {
    int flagLen = flag.length();
    String current = s;
    int[] res = new int[s.length()];
    int count = 0;
    int base = 0;
    while(current.contains(flag)) {
        int index = current.indexOf(flag);
        res[count] = index + base;
        base += index + flagLen;
        current = current.substring(current.indexOf(flag) + flagLen, current.length());
        ++ count;
    }
    return Arrays.copyOf(res, count);
}

This method can be used to find indexes of any flag of any length in a string, for example:

public class Main {

    public static void main(String[] args) {
        int[] indexes = indexesOf("Hello, yellow jello", "ll");

        // Prints [2, 9, 16]
        System.out.println(Arrays.toString(indexes));
    }

    public static int[] indexesOf(String s, String flag) {
        int flagLen = flag.length();
        String current = s;
        int[] res = new int[s.length()];
        int count = 0;
        int base = 0;
        while(current.contains(flag)) {
            int index = current.indexOf(flag);
            res[count] = index + base;
            base += index + flagLen;
            current = current.substring(current.indexOf(flag) + flagLen, current.length());
            ++ count;
        }
        return Arrays.copyOf(res, count);
    }
}

How to get substring from string in c#?

string text = "Retrieves a substring from this instance. The substring starts at a specified character position. Some other text";

string result = text.Substring(text.IndexOf('.') + 1,text.LastIndexOf('.')-text.IndexOf('.'))

This will cut the part of string which lays between the special characters.

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

another way is to use certutil.exe save your username and password in a file e.g. in.txt as username:password

certutil -encode in.txt out.txt

Now you should be able to use auth value from out.txt

$headers = @{ Authorization = "Basic $((get-content out.txt)[1])" }
Invoke-WebRequest -Uri 'https://whatever' -Headers $Headers

Refresh image with a new one at the same url

Try adding a cachebreaker at the end of the url:

newImage.src = "http://localhost/image.jpg?" + new Date().getTime();

This will append the current timestamp automatically when you are creating the image, and it will make the browser look again for the image instead of retrieving the one in the cache.

What's the proper way to install pip, virtualenv, and distribute for Python?

If you follow the steps advised in several tutorials I linked in this answer, you can get the desired effect without the somewhat complicated "manual" steps in Walker's and Vinay's answers. If you're on Ubuntu:

sudo apt-get install python-pip python-dev

The equivalent is achieved in OS X by using homebrew to install python (more details here).

brew install python

With pip installed, you can use it to get the remaining packages (you can omit sudo in OS X, as you're using your local python installation).

sudo pip install virtualenvwrapper

(these are the only packages you need installed globally and I doubt that it will clash with anything system-level from the OS. If you want to be super-safe, you can keep the distro's versions sudo apt-get install virtualenvwrapper)

Note: in Ubuntu 14.04 I receive some errors with pip install, so I use pip3 install virtualenv virtualenvwrapper and add VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 to my .bashrc/.zshrc file.

You then append to your .bashrc file

export WORKON_HOME
source /usr/local/bin/virtualenvwrapper.sh

and source it

. ~/.bashrc

This is basically it. Now the only decision is whether you want to create a virtualenv to include system-level packages

mkvirtualenv --system-site-packages foo

where your existing system packages don't have to be reinstalled, they are symlinked to the system interpreter's versions. Note: you can still install new packages and upgrade existing included-from-system packages without sudo - I tested it and it works without any disruptions of the system interpreter.

kermit@hocus-pocus:~$ sudo apt-get install python-pandas
kermit@hocus-pocus:~$ mkvirtualenv --system-site-packages s
(s)kermit@hocus-pocus:~$ pip install --upgrade pandas
(s)kermit@hocus-pocus:~$ python -c "import pandas; print(pandas.__version__)"
0.10.1
(s)kermit@hocus-pocus:~$ deactivate
kermit@hocus-pocus:~$ python -c "import pandas; print(pandas.__version__)"
0.8.0

The alternative, if you want a completely separated environment, is

mkvirtualenv --no-site-packages bar

or given that this is the default option, simply

mkvirtualenv bar

The result is that you have a new virtualenv where you can freely and sudolessly install your favourite packages

pip install flask

Bash script and /bin/bash^M: bad interpreter: No such file or directory

I was able to resolve the issue by opening the script in Gedit and saving it with the proper Line Ending option:

File > Save As...

In the bottom left of the Save As prompt, there are drop-down menus for Character Encoding and Line Ending. Change the Line Ending from Windows to Unix/Linux then Save.

gedit "Save As" prompt]

Access Google's Traffic Data through a Web Service

Maybe you should have a look at Mapquests Traffic API: http://www.mapquestapi.com/traffic/

The webservice is unfortunately only available for some citys in the US, I think. But probably it solves your problem.

Can I replace groups in Java regex?

Use $n (where n is a digit) to refer to captured subsequences in replaceFirst(...). I'm assuming you wanted to replace the first group with the literal string "number" and the second group with the value of the first group.

Pattern p = Pattern.compile("(\\d)(.*)(\\d)");
String input = "6 example input 4";
Matcher m = p.matcher(input);
if (m.find()) {
    // replace first number with "number" and second number with the first
    String output = m.replaceFirst("number $3$1");  // number 46
}

Consider (\D+) for the second group instead of (.*). * is a greedy matcher, and will at first consume the last digit. The matcher will then have to backtrack when it realizes the final (\d) has nothing to match, before it can match to the final digit.

What does asterisk * mean in Python?

A single star means that the variable 'a' will be a tuple of extra parameters that were supplied to the function. The double star means the variable 'kw' will be a variable-size dictionary of extra parameters that were supplied with keywords.

Although the actual behavior is spec'd out, it still sometimes can be very non-intuitive. Writing some sample functions and calling them with various parameter styles may help you understand what is allowed and what the results are.

def f0(a)
def f1(*a)
def f2(**a)
def f3(*a, **b)
etc...

Can't update: no tracked branch

I got the same error but in PyCharm because I accidentally deleted my VCS origin. After re-adding my origin I ran:

git fetch

which reloaded all of my branches. I then clicked the button to update the project, and I was back to normal.

Get names of all keys in the collection

I think the best way do this as mentioned here is in mongod 3.4.4+ but without using the $unwind operator and using only two stages in the pipeline. Instead we can use the $mergeObjects and $objectToArray operators.

In the $group stage, we use the $mergeObjects operator to return a single document where key/value are from all documents in the collection.

Then comes the $project where we use $map and $objectToArray to return the keys.

let allTopLevelKeys =  [
    {
        "$group": {
            "_id": null,
            "array": {
                "$mergeObjects": "$$ROOT"
            }
        }
    },
    {
        "$project": {
            "keys": {
                "$map": {
                    "input": { "$objectToArray": "$array" },
                    "in": "$$this.k"
                }
            }
        }
    }
];

Now if we have a nested documents and want to get the keys as well, this is doable. For simplicity, let consider a document with simple embedded document that look like this:

{field1: {field2: "abc"}, field3: "def"}
{field1: {field3: "abc"}, field4: "def"}

The following pipeline yield all keys (field1, field2, field3, field4).

let allFistSecondLevelKeys = [
    {
        "$group": {
            "_id": null,
            "array": {
                "$mergeObjects": "$$ROOT"
            }
        }
    },
    {
        "$project": {
            "keys": {
                "$setUnion": [
                    {
                        "$map": {
                            "input": {
                                "$reduce": {
                                    "input": {
                                        "$map": {
                                            "input": {
                                                "$objectToArray": "$array"
                                            },
                                            "in": {
                                                "$cond": [
                                                    {
                                                        "$eq": [
                                                            {
                                                                "$type": "$$this.v"
                                                            },
                                                            "object"
                                                        ]
                                                    },
                                                    {
                                                        "$objectToArray": "$$this.v"
                                                    },
                                                    [
                                                        "$$this"
                                                    ]
                                                ]
                                            }
                                        }
                                    },
                                    "initialValue": [

                                    ],
                                    "in": {
                                        "$concatArrays": [
                                            "$$this",
                                            "$$value"
                                        ]
                                    }
                                }
                            },
                            "in": "$$this.k"
                        }
                    }
                ]
            }
        }
    }
]

With a little effort, we can get the key for all subdocument in an array field where the elements are object as well.

Error: Uncaught SyntaxError: Unexpected token <

I got this error while using the web app with firebase. It was due to not including the desired libraries in the index.html

To fix this in the development environment, I added following line of code in the index.html

<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase.js"></script>

Use the necessary libraries instead of importing all the js sdk when you are planning to deploy for production.

Extracting columns from text file with different delimiters in Linux

If the command should work with both tabs and spaces as the delimiter I would use awk:

awk '{print $100,$101,$102,$103,$104,$105}' myfile > outfile

As long as you just need to specify 5 fields it is imo ok to just type them, for longer ranges you can use a for loop:

awk '{for(i=100;i<=105;i++)print $i}' myfile > outfile

If you want to use cut, you need to use the -f option:

cut -f100-105 myfile > outfile

If the field delimiter is different from TAB you need to specify it using -d:

cut -d' ' -f100-105 myfile > outfile

Check the man page for more info on the cut command.

Python List vs. Array - when to use?

It's a trade off !

pros of each one :

list

  • flexible
  • can be heterogeneous

array (ex: numpy array)

  • array of uniform values
  • homogeneous
  • compact (in size)
  • efficient (functionality and speed)
  • convenient

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

To check online you can use

http://codebeautify.org/base64-to-image-converter

You can convert string to image like this way

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView image =(ImageView)findViewById(R.id.image);

        //encode image to base64 string
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

        //decode base64 string to image
        imageBytes = Base64.decode(imageString, Base64.DEFAULT);
        Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        image.setImageBitmap(decodedImage);
    }
}

http://www.thecrazyprogrammer.com/2016/10/android-convert-image-base64-string-base64-string-image.html

How to post pictures to instagram using API

For users who find this question, you can pass photos to the instagram sharing flow (from your app to the filters screen) on iPhone using iPhone hooks: http://help.instagram.com/355896521173347 Other than that, there is currently no way in version 1 of the api.

Android changing Floating Action Button color

add colors in color.xml file

add colors in color.xml file and then add this line of code... floatingActionButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.fab2_color)));

Rotate a div using javascript

To rotate a DIV we can add some CSS that, well, rotates the DIV using CSS transform rotate.

To toggle the rotation we can keep a flag, a simple variable with a boolean value that tells us what way to rotate.

var rotated = false;

document.getElementById('button').onclick = function() {
    var div = document.getElementById('div'),
        deg = rotated ? 0 : 66;

    div.style.webkitTransform = 'rotate('+deg+'deg)'; 
    div.style.mozTransform    = 'rotate('+deg+'deg)'; 
    div.style.msTransform     = 'rotate('+deg+'deg)'; 
    div.style.oTransform      = 'rotate('+deg+'deg)'; 
    div.style.transform       = 'rotate('+deg+'deg)'; 

    rotated = !rotated;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

To add some animation to the rotation all we have to do is add CSS transitions

div {
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

Another way to do it is using classes, and setting all the styles in a stylesheet, thus keeping them out of the javascript

document.getElementById('button').onclick = function() {
    document.getElementById('div').classList.toggle('rotated');
}

_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    document.getElementById('div').classList.toggle('rotated');_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}_x000D_
_x000D_
#div.rotated {_x000D_
    -webkit-transform : rotate(66deg); _x000D_
    -moz-transform : rotate(66deg); _x000D_
    -ms-transform : rotate(66deg); _x000D_
    -o-transform : rotate(66deg); _x000D_
    transform : rotate(66deg); _x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

Eliminating NAs from a ggplot

Not sure if you have solved the problem. For this issue, you can use the "filter" function in the dplyr package. The idea is to filter the observations/rows whose values of the variable of your interest is not NA. Next, you make the graph with these filtered observations. You can find my codes below, and note that all the name of the data frame and variable is copied from the prompt of your question. Also, I assume you know the pipe operators.

library(tidyverse) 

MyDate %>%
   filter(!is.na(the_variable)) %>%
     ggplot(aes(x= the_variable, fill=the_variable)) + 
        geom_bar(stat="bin") 

You should be able to remove the annoying NAs on your plot. Hope this works :)

Bootstrap modal: is not a function

jQuery should be the first:

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>

Where is a log file with logs from a container?

To see the size of logs per container, you can use this bash command :

for cont_id in $(docker ps -aq); do cont_name=$(docker ps | grep $cont_id | awk '{ print $NF }') && cont_size=$(docker inspect --format='{{.LogPath}}' $cont_id | xargs sudo ls -hl | awk '{ print $5 }') && echo "$cont_name ($cont_id): $cont_size"; done

Example output:

container_name (6eed984b29da): 13M
elegant_albattani (acd8f73aa31e): 2.3G

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

MaxLength Attribute not generating client-side validation attributes

Try using the [StringLength] attribute:

[Required(ErrorMessage = "Name is required.")]
[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }

That's for validation purposes. If you want to set for example the maxlength attribute on the input you could write a custom data annotations metadata provider as shown in this post and customize the default templates.

List attributes of an object

Inspect module:

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.


Using getmembers() you can see all attributes of your class, along with their value. To exclude private or protected attributes use .startswith('_'). To exclude methods or functions use inspect.ismethod() or inspect.isfunction().

import inspect


class NewClass(object):
    def __init__(self, number):
        self.multi = int(number) * 2
        self.str = str(number)

    def func_1(self):
        pass


a = NewClass(2)

for i in inspect.getmembers(a):
    # Ignores anything starting with underscore 
    # (that is, private and protected attributes)
    if not i[0].startswith('_'):
        # Ignores methods
        if not inspect.ismethod(i[1]):
            print(i)

Note that ismethod() is used on the second element of i since the first is simply a string (its name).

Offtopic: Use CamelCase for class names.

Delete all records in a table of MYSQL in phpMyAdmin

write the query: truncate 'Your_table_name';

Want to show/hide div based on dropdown box selection

try this which is working for me in my test demo

<script>
$(document).ready(function(){
$('#dropdown').change(function() 
{ 
//  var selectedValue = parseInt(jQuery(this).val());
var text = $('#dropdown').val();
//alert("text");
    //Depend on Value i.e. 0 or 1 respective function gets called. 
    switch(text){
        case 'Reporting':
          // alert("hello1");
   $("#td1").hide();
            break;
        case 'Buyer':
      //alert("hello");
     $("#td1").show();   
            break;
        //etc... 
        default:
            alert("catch default");
            break;
    }
});
});

</script>

how to overlap two div in css?

add to second div bottomDiv

and add this to css.

 .bottomDiv{
       position:relative;
       bottom:150px;
       left:150px;
    }

http://jsfiddle.net/aw8RD/1/

Lock down Microsoft Excel macro

Generate a protected application for Mac or Windows from your Excel spreadsheet using OfficeProtect with either AppProtect or QuickLicense/AddLicense. There is a demonstation video called "Protect Excel Spreedsheet" at www.excelsoftware.com/videos.

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

To answer this question, we have to look at how indexing a multidimensional array works in Numpy. Let's first say you have the array x from your question. The buffer assigned to x will contain 16 ascending integers from 0 to 15. If you access one element, say x[i,j], NumPy has to figure out the memory location of this element relative to the beginning of the buffer. This is done by calculating in effect i*x.shape[1]+j (and multiplying with the size of an int to get an actual memory offset).

If you extract a subarray by basic slicing like y = x[0:2,0:2], the resulting object will share the underlying buffer with x. But what happens if you acces y[i,j]? NumPy can't use i*y.shape[1]+j to calculate the offset into the array, because the data belonging to y is not consecutive in memory.

NumPy solves this problem by introducing strides. When calculating the memory offset for accessing x[i,j], what is actually calculated is i*x.strides[0]+j*x.strides[1] (and this already includes the factor for the size of an int):

x.strides
(16, 4)

When y is extracted like above, NumPy does not create a new buffer, but it does create a new array object referencing the same buffer (otherwise y would just be equal to x.) The new array object will have a different shape then x and maybe a different starting offset into the buffer, but will share the strides with x (in this case at least):

y.shape
(2,2)
y.strides
(16, 4)

This way, computing the memory offset for y[i,j] will yield the correct result.

But what should NumPy do for something like z=x[[1,3]]? The strides mechanism won't allow correct indexing if the original buffer is used for z. NumPy theoretically could add some more sophisticated mechanism than the strides, but this would make element access relatively expensive, somehow defying the whole idea of an array. In addition, a view wouldn't be a really lightweight object anymore.

This is covered in depth in the NumPy documentation on indexing.

Oh, and nearly forgot about your actual question: Here is how to make the indexing with multiple lists work as expected:

x[[[1],[3]],[1,3]]

This is because the index arrays are broadcasted to a common shape. Of course, for this particular example, you can also make do with basic slicing:

x[1::2, 1::2]

Connecting to SQL Server using windows authentication

Your connection string is wrong

<connectionStrings>
   <add name="ConnStringDb1" connectionString="Data Source=localhost\SQLSERVER;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

Note: the solution in this and other answers involves disabling safety measures that are there to fix arbitrary code execution vulnerabilities. See for instance this ghostscript-related and this ubuntu-related announcement. Only go forward with these solutions if the input to convert comes from a trusted source.

I use ImageMagick in php (v.7.1) to slice PDF file to images.

First I got errors like:

Exception type: ImagickException

Exception message: not authorized ..... @ error/constitute.c/ReadImage/412

After some changes in /etc/ImageMagick-6/policy.xml I start getting erroes like:

Exception type: ImagickException

Exception message: unable to create temporary file ..... Permission denied @ error/pdf.c/ReadPDFImage/465

My fix:

In file /etc/ImageMagick-6/policy.xml (or /etc/ImageMagick/policy.xml)

  1. comment line

    <!-- <policy domain="coder" rights="none" pattern="MVG" /> -->
    
  2. change line

    <policy domain="coder" rights="none" pattern="PDF" />
    

    to

    <policy domain="coder" rights="read|write" pattern="PDF" />
    
  3. add line

    <policy domain="coder" rights="read|write" pattern="LABEL" />
    

Then restart your web server (nginx, apache).

Java String import

import java.lang.String;

This is an unnecessary import. java.lang classes are always implicitly imported. This means that you do not have to import them manually (explicitly).

How do I align spans or divs horizontally?

My answer:

<style>
 #whatever div {
  display: inline;
  margin: 0 1em 0 1em;
  width: 30%;
}
</style>

<div id="whatever">
 <div>content</div>
 <div>content</div>
 <div>content</div>
</div>

Why?

Technically, a Span is an inline element, however it can have width, you just need to set their display property to block first. However, in this context, a div is probably more appropriate, as I'm guessing you want to fill these divs with content.

One thing you definitely don't want to do is have clear:both set on the divs. Setting it like that will mean that the browser will not allow any elements to sit on the same line as them. The result, your elements will stack up.

Note, the use of display:inline. This deals with the ie6 margin-doubling bug. You could tackle this in other ways if necessary, for example conditional stylesheets.

I've added a wrapper (#whatever) as I'm guessing these won't be the only elements on page, so you'll almost certainly need to segregate them from the other page elements.

Anyway, I hope that's helpful.

php random x digit number

Following is simple method to generate specific length verification code. Length can be specified, by default, it generates 4 digit code.

function get_sms_token($length = 4) {

    return rand(
        ((int) str_pad(1, $length, 0, STR_PAD_RIGHT)),
        ((int) str_pad(9, $length, 9, STR_PAD_RIGHT))
    );
}

echo get_sms_token(6);

How to check encoding of a CSV file

Use chardet https://github.com/chardet/chardet (documentation is short and easy to read).

Install python, then pip install chardet, at last use the command line command.

I tested under GB2312 and it's pretty accurate. (Make sure you have at least a few characters, sample with only 1 character may fail easily).

file is not reliable as you can see.

enter image description here

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

Yes, presumably it wants the path to the javadoc command line tool that comes with the JDK (in the bin directory, same as java and javac).

Eclipse should be able to find it automatically; are you perhaps running it on a JRE? That would explain the request.

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

Adding null values to arraylist

You can add nulls to the ArrayList, and you will have to check for nulls in the loop:

for(Item i : itemList) {
   if (i != null) {

   }
}

itemsList.size(); would take the null into account.

 List<Integer> list = new ArrayList<Integer>();
 list.add(null);
 list.add (5);
 System.out.println (list.size());
 for (Integer value : list) {
   if (value == null)
       System.out.println ("null value");
   else 
       System.out.println (value);
 }

Output :

2
null value
5

How to set gradle home while importing existing project in Android studio

On Linux Mint 17 it was

/usr/share/gradle

for me

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

'method' is the object-oriented word for 'function'. That's pretty much all there is to it (ie., no real difference).

Unfortunately, I think a lot of the answers here are perpetuating or advancing the idea that there's some complex, meaningful difference.

Really - there isn't all that much to it, just different words for the same thing.

[late addition]


In fact, as Brian Neal pointed out in a comment to this question, the C++ standard never uses the term 'method' when refering to member functions. Some people may take that as an indication that C++ isn't really an object-oriented language; however, I prefer to take it as an indication that a pretty smart group of people didn't think there was a particularly strong reason to use a different term.

How do I view the SQL generated by the Entity Framework?

In my case for EF 6+, instead of using this in the Immediate Window to find the query string:

var sql = ((System.Data.Entity.Core.Objects.ObjectQuery)query).ToTraceString();

I ended up having to use this to get the generated SQL command:

var sql = ((System.Data.Entity.Infrastructure.DbQuery<<>f__AnonymousType3<string,string,string,short,string>>)query).ToString();

Of course your anonymous type signature might be different.

HTH.

What is the difference between a field and a property?

Properties have the primary advantage of allowing you to change the way data on an object is accessed without breaking it's public interface. For example, if you need to add extra validation, or to change a stored field into a calculated you can do so easily if you initially exposed the field as a property. If you just exposed a field directly, then you would have to change the public interface of your class to add the new functionality. That change would break existing clients, requiring them to be recompiled before they could use the new version of your code.

If you write a class library designed for wide consumption (like the .NET Framework, which is used by millions of people), that can be a problem. However, if you are writing a class used internally inside a small code base (say <= 50 K lines), it's really not a big deal, because no one would be adversely affected by your changes. In that case it really just comes down to personal preference.

Why is volatile needed in C?

Volatile is also useful, when you want to force the compiler not to optimize a specific code sequence (e.g. for writing a micro-benchmark).

How to map and remove nil values in Ruby

One more way to accomplish it will be as shown below. Here, we use Enumerable#each_with_object to collect values, and make use of Object#tap to get rid of temporary variable that is otherwise needed for nil check on result of process_x method.

items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}

Complete example for illustration:

items = [1,2,3,4,5]
def process x
    rand(10) > 5 ? nil : x
end

items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}

Alternate approach:

By looking at the method you are calling process_x url, it is not clear what is the purpose of input x in that method. If I assume that you are going to process the value of x by passing it some url and determine which of the xs really get processed into valid non-nil results - then, may be Enumerabble.group_by is a better option than Enumerable#map.

h = items.group_by {|x| (process x).nil? ? "Bad" : "Good"}
#=> {"Bad"=>[1, 2], "Good"=>[3, 4, 5]}

h["Good"]
#=> [3,4,5]

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

The limitation relates to the simplified CommonJS syntax vs. the normal callback syntax:

Loading a module is inherently an asynchronous process due to the unknown timing of downloading it. However, RequireJS in emulation of the server-side CommonJS spec tries to give you a simplified syntax. When you do something like this:

var foomodule = require('foo');
// do something with fooModule

What's happening behind the scenes is that RequireJS is looking at the body of your function code and parsing out that you need 'foo' and loading it prior to your function execution. However, when a variable or anything other than a simple string, such as your example...

var module = require(path); // Call RequireJS require

...then Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax;

var moduleName = 'foo';
require([moduleName], function(fooModule){
    // do something with fooModule
})

Given the above, here is one possible rewrite of your 2nd example to use the standard syntax:

define(['dyn_modules'], function (dynModules) {
    require(dynModules, function(){
        // use arguments since you don't know how many modules you're getting in the callback
        for (var i = 0; i < arguments.length; i++){
            var mymodule = arguments[i];
            // do something with mymodule...
        }
    });

});

EDIT: From your own answer, I see you're using underscore/lodash, so using _.values and _.object can simplify the looping through arguments array as above.

adding text to an existing text element in javascript via DOM

Instead of appending element you can just do.

 document.getElementById("p").textContent += " this has just been added";

_x000D_
_x000D_
document.getElementById("p").textContent += " this has just been added";
_x000D_
<p id ="p">This is some text</p>
_x000D_
_x000D_
_x000D_

Default argument values in JavaScript functions

function func(a, b)
{
  if (typeof a == 'undefined')
    a = 10;
  if (typeof b == 'undefined')
    b = 20;
  // do what you want ... for example
  alert(a + ',' + b);
}

in shorthand

function func(a, b)
{
  a = (typeof a == 'undefined')?10:a;
  b = (typeof b == 'undefined')?20:b;

  // do what you want ... for example
  alert(a + ',' + b);
}

What does it mean when Statement.executeUpdate() returns -1?

For executeUpdate statements against a DB2 for z/OS server, the value that is returned depends on the type of SQL statement that is being executed:

For an SQL statement that can have an update count, such as an INSERT, UPDATE, or DELETE statement, the returned value is the number of affected rows. It can be:

A positive number, if a positive number of rows are affected by the operation, and the operation is not a mass delete on a segmented table space.

0, if no rows are affected by the operation.

-1, if the operation is a mass delete on a segmented table space.

For a DB2 CALL statement, a value of -1 is returned, because the DB2 database server cannot determine the number of affected rows. Calls to getUpdateCount or getMoreResults for a CALL statement also return -1. For any other SQL statement, a value of -1 is returned.

MySQL pivot table query with dynamic columns

The only way in MySQL to do this dynamically is with Prepared statements. Here is a good article about them:

Dynamic pivot tables (transform rows to columns)

Your code would look like this:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(pa.fieldname = ''',
      fieldname,
      ''', pa.fieldvalue, NULL)) AS ',
      fieldname
    )
  ) INTO @sql
FROM product_additional;

SET @sql = CONCAT('SELECT p.id
                    , p.name
                    , p.description, ', @sql, ' 
                   FROM product p
                   LEFT JOIN product_additional AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

See Demo

NOTE: GROUP_CONCAT function has a limit of 1024 characters. See parameter group_concat_max_len

Is Laravel really this slow?

I know this is a little old question, but things changed. Laravel isn't that slow. It's, as mentioned, synced folders are slow. However, on Windows 10 I wasn't able to use rsync. I tried both cygwin and minGW. It seems like rsync is incompatible with git for windows's version of ssh.

Here is what worked for me: NFS.

Vagrant docs says:

NFS folders do not work on Windows hosts. Vagrant will ignore your request for NFS synced folders on Windows.

This isn't true anymore. We can use vagrant-winnfsd plugin nowadays. It's really simple to install:

  1. Execute vagrant plugin install vagrant-winnfsd
  2. Change in your Vagrantfile: config.vm.synced_folder ".", "/vagrant", type: "nfs"
  3. Add to Vagrantfile: config.vm.network "private_network", type: "dhcp"

That's all I needed to make NFS work. Laravel response time decreased from 500ms to 100ms for me.

Filtering DataSet

The above were really close. Here's my solution:

Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
    Dim i As Integer

    outClone = inClone.Clone
    Dim dv As DataView = inClone.Tables(0).DefaultView
    dv.RowFilter = matchStr
    Dim dt As New DataTable
    dt = dv.ToTable
    For i = 0 To dv.Count - 1
        outClone.Tables(0).ImportRow(dv.Item(i).Row)
    Next
End Sub

MySQL WHERE IN ()

You have wrong database design and you should take a time to read something about database normalization (wikipedia / stackoverflow).

I assume your table looks somewhat like this

TABLE
================================
| group_id | user_ids | name   |
--------------------------------
| 1        | 1,4,6    | group1 |
--------------------------------
| 2        | 4,5,1    | group2 |    

so in your table of user groups, each row represents one group and in user_ids column you have set of user ids assigned to that group.

Normalized version of this table would look like this

GROUP
=====================
| id       | name   |
---------------------
| 1        | group1 |
---------------------
| 2        | group2 |    

GROUP_USER_ASSIGNMENT
======================
| group_id | user_id |
----------------------
| 1        | 1       |
----------------------
| 1        | 4       |
----------------------
| 1        | 6       |
----------------------
| 2        | 4       |
----------------------
| ...      

Then you can easily select all users with assigned group, or all users in group, or all groups of user, or whatever you can think of. Also, your sql query will work:

/* Your query to select assignments */
SELECT * FROM `group_user_assignment` WHERE user_id IN (1,2,3,4);

/* Select only some users */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE user_id IN (1,4);

/* Select all groups of user */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`user_id` = 1;

/* Select all users of group */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`group_id` = 1;

/* Count number of groups user is in */
SELECT COUNT(*) AS `groups_count` FROM `group_user_assignment` WHERE `user_id` = 1;

/* Count number of users in group */
SELECT COUNT(*) AS `users_count` FROM `group_user_assignment` WHERE `group_id` = 1;

This way it will be also easier to update database, when you would like to add new assignment, you just simply insert new row in group_user_assignment, when you want to remove assignment you just delete row in group_user_assignment.

In your database design, to update assignments, you would have to get your assignment set from database, process it and update and then write back to database.

Here is sqlFiddle to play with.

Validation of file extension before uploading file

When you want to validate browse button and file extension, use this code:

function fileValidate(){ 
var docVal=document.forms[0].fileUploaded.value;
var extension = docVal.substring(docVal.lastIndexOf(".")+1,docVal.length);
if(extension.toLowerCase() != 'pdf')
alert("Please enter file  in .pdf extension ");

return false;
}

Render HTML to PDF in Django site

https://github.com/nigma/django-easy-pdf

Template:

{% extends "easy_pdf/base.html" %}

{% block content %}
    <div id="content">
        <h1>Hi there!</h1>
    </div>
{% endblock %}

View:

from easy_pdf.views import PDFTemplateView

class HelloPDFView(PDFTemplateView):
    template_name = "hello.html"

If you want to use django-easy-pdf on Python 3 check the solution suggested here.

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

Using a scanner to accept String input and storing in a String Array

//go through this code I have made several changes in it//

import java.util.Scanner;

public class addContact {
public static void main(String [] args){

//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
int i=0;
String name = "0";
String phone = "0";
String add1 = "0";
String add2 = "0";
//method of taken input
Scanner input = new Scanner(System.in);

//while name field is empty display prompt etc.
while (i<11)
{
    i++;
System.out.println("Enter contacts name: "+ i);
name = input.nextLine();
name += contactName[i];
}


while (i<12)
{
    i++;
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[i];
}

while (i<12)
{
    i++;
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[i];
}

while (i<12)
{
    i++;
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[i];
}

}   
}

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

If you use vagrant, try this:

First remove config.php in current/vendor.

Run these command:

php artisan config:clear
php artisan clear-compiled
php artisan optimize

NOT RUN php artisan config:cache.

Hope this help.

Call a child class method from a parent class object

Why don't you just write an empty method in Person and override it in the children classes? And call it, when it needs to be:

void caluculate(Person p){
  p.dotheCalculate();
}

This would mean you have to have the same method in both children classes, but i don't see why this would be a problem at all.

How to get row index number in R?

rownames(dataframe)

This will give you the index of dataframe

undefined offset PHP error

Undefined offset means there's an empty array key for example:

$a = array('Felix','Jon','Java');

// This will result in an "Undefined offset" because the size of the array
// is three (3), thus, 0,1,2 without 3
echo $a[3];

You can solve the problem using a loop (while):

$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
    // Increase count by 1, thus, $i=1
    $i++;

    $groupname[$i] = base64_decode(base64_decode($row['groupname']));

    // Set the first position of the array to null or empty
    $groupname[0] = "";
}

Why is Java's SimpleDateFormat not thread-safe?

Release 3.2 of commons-lang will have FastDateParser class that is a thread-safe substitute of SimpleDateFormat for Gregorian calendar. See LANG-909 for more information.

phpexcel to download

Instead of saving it to a file, save it to php://output­Docs:

$objWriter->save('php://output');

This will send it AS-IS to the browser.

You want to add some headers­Docs first, like it's common with file downloads, so the browser knows which type that file is and how it should be named (the filename):

// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');

// It will be called file.xls
header('Content-Disposition: attachment; filename="file.xls"');

// Write file to the browser
$objWriter->save('php://output');

First do the headers, then the save. For the excel headers see as well the following question: Setting mime type for excel document.

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

A similar error appears while pulling the changes from the origin. If you are trying in Intellij from the menu options, the pull might not work directly.

Go to terminal and type this command and this should work out: git pull origin master

How to loop through all the files in a directory in c # .net?

You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.

http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori

Java - Access is denied java.io.FileNotFoundException

Not exactly the case of this question but can be helpful. I got this exception when i call mkdirs() on new file instead of its parent

File file = new java.io.File(path);
//file.mkdirs(); // wrong! 
file.getParentFile().mkdirs(); // correct!
if (!file.exists()) {
    file.createNewFile();
} 

Select current date by default in ASP.Net Calendar control

I have tried above with above code but not working ,Here is solution to set current date selected in asp.net calendar control

dtpStartDate.SelectedDate = Convert.ToDateTime(DateTime.Now.Date);
dtpStartDate.VisibleDate = Convert.ToDateTime(DateTime.Now.ToString());

How to echo or print an array in PHP?

Human readable: (eg. can be log to text file..)

print_r( $arr_name , TRUE);

How to set the From email address for mailx command?

On debian where bsd-mailx is installed by default, the -r option does not work. However you can use mailx -s subject [email protected] -- -f [email protected] instead. According to man page, you can specify sendmail options after --.

How do I write output in same place on the console?

For Python 3xx:

import time
for i in range(10):
    time.sleep(0.2) 
    print ("\r Loading... {}".format(i)+str(i), end="")

Check if string contains only digits

_x000D_
_x000D_
var str='1232323a.1';
var reg=/^[0-9]*[.]?[0-9]*$/;

console.log(reg.test(str))
_x000D_
_x000D_
_x000D_

Converting JSON String to Dictionary Not List

I am working with a Python code for a REST API, so this is for those who are working on similar projects.

I extract data from an URL using a POST request and the raw output is JSON. For some reason the output is already a dictionary, not a list, and I'm able to refer to the nested dictionary keys right away, like this:

datapoint_1 = json1_data['datapoints']['datapoint_1']

where datapoint_1 is inside the datapoints dictionary.